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 depenencies 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; //tigthly packed
  2041. buffer_image_copy.bufferImageHeight = 0; //tigthly 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 Destionation 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 Destionation 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. VkAttachmentDescription description;
  2613. description.flags = 0;
  2614. ERR_FAIL_INDEX_V(p_format[i].format, DATA_FORMAT_MAX, VK_NULL_HANDLE);
  2615. description.format = vulkan_formats[p_format[i].format];
  2616. ERR_FAIL_INDEX_V(p_format[i].samples, TEXTURE_SAMPLES_MAX, VK_NULL_HANDLE);
  2617. description.samples = rasterization_sample_count[p_format[i].samples];
  2618. //anything below does not really matter, as vulkan just ignores it when creating a pipeline
  2619. 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)), VK_NULL_HANDLE,
  2620. "Texture format for index (" + itos(i) + ") requires an attachment (depth, stencil or resolve) bit set.");
  2621. bool is_depth_stencil = p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  2622. bool is_sampled = p_format[i].usage_flags & TEXTURE_USAGE_SAMPLING_BIT;
  2623. bool is_storage = p_format[i].usage_flags & TEXTURE_USAGE_STORAGE_BIT;
  2624. switch (is_depth_stencil ? p_initial_depth_action : p_initial_color_action) {
  2625. case INITIAL_ACTION_CLEAR: {
  2626. description.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  2627. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  2628. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2629. } break;
  2630. case INITIAL_ACTION_KEEP: {
  2631. if (p_format[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2632. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2633. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  2634. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2635. } else if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2636. description.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  2637. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2638. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  2639. } else {
  2640. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2641. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2642. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2643. }
  2644. } break;
  2645. case INITIAL_ACTION_DROP: {
  2646. if (p_format[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2647. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2648. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  2649. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2650. } else if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2651. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2652. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2653. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2654. } else {
  2655. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2656. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2657. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2658. }
  2659. } break;
  2660. case INITIAL_ACTION_CONTINUE: {
  2661. if (p_format[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2662. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2663. description.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  2664. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2665. } else if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2666. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2667. description.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; //don't care what is there
  2668. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2669. } else {
  2670. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2671. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2672. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2673. }
  2674. } break;
  2675. default: {
  2676. ERR_FAIL_V(VK_NULL_HANDLE); //should never reach here
  2677. }
  2678. }
  2679. switch (is_depth_stencil ? p_final_depth_action : p_final_color_action) {
  2680. case FINAL_ACTION_READ: {
  2681. if (p_format[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2682. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  2683. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  2684. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  2685. } else if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2686. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  2687. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
  2688. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  2689. } else {
  2690. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2691. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2692. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2693. }
  2694. } break;
  2695. case FINAL_ACTION_DISCARD: {
  2696. if (p_format[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2697. description.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  2698. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  2699. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  2700. } else if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2701. description.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  2702. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  2703. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  2704. } else {
  2705. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2706. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2707. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2708. }
  2709. } break;
  2710. case FINAL_ACTION_CONTINUE: {
  2711. if (p_format[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2712. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  2713. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  2714. description.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  2715. } else if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2716. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  2717. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
  2718. description.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  2719. } else {
  2720. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2721. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2722. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2723. }
  2724. } break;
  2725. default: {
  2726. ERR_FAIL_V(VK_NULL_HANDLE); //should never reach here
  2727. }
  2728. }
  2729. attachments.push_back(description);
  2730. VkAttachmentReference reference;
  2731. reference.attachment = i;
  2732. if (p_format[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2733. reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  2734. color_references.push_back(reference);
  2735. } else if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2736. reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  2737. depth_stencil_references.push_back(reference);
  2738. } else if (p_format[i].usage_flags & TEXTURE_USAGE_RESOLVE_ATTACHMENT_BIT) {
  2739. reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  2740. resolve_references.push_back(reference);
  2741. } else {
  2742. 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.");
  2743. }
  2744. }
  2745. ERR_FAIL_COND_V_MSG(depth_stencil_references.size() > 1, VK_NULL_HANDLE,
  2746. "Formats can only have one depth/stencil attachment, supplied (" + itos(depth_stencil_references.size()) + ").");
  2747. ERR_FAIL_COND_V_MSG(resolve_references.size() > 1, VK_NULL_HANDLE,
  2748. "Formats can only have one resolve attachment, supplied (" + itos(resolve_references.size()) + ").");
  2749. VkSubpassDescription subpass;
  2750. subpass.flags = 0;
  2751. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  2752. subpass.inputAttachmentCount = 0; //unsupported for now
  2753. subpass.pInputAttachments = nullptr;
  2754. subpass.colorAttachmentCount = color_references.size();
  2755. subpass.pColorAttachments = color_references.ptr();
  2756. subpass.pDepthStencilAttachment = depth_stencil_references.ptr();
  2757. subpass.pResolveAttachments = resolve_references.ptr();
  2758. subpass.preserveAttachmentCount = 0;
  2759. subpass.pPreserveAttachments = nullptr;
  2760. VkRenderPassCreateInfo render_pass_create_info;
  2761. render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  2762. render_pass_create_info.pNext = nullptr;
  2763. render_pass_create_info.flags = 0;
  2764. render_pass_create_info.attachmentCount = attachments.size();
  2765. render_pass_create_info.pAttachments = attachments.ptr();
  2766. render_pass_create_info.subpassCount = 1;
  2767. render_pass_create_info.pSubpasses = &subpass;
  2768. render_pass_create_info.dependencyCount = 0;
  2769. render_pass_create_info.pDependencies = nullptr;
  2770. VkRenderPass render_pass;
  2771. VkResult res = vkCreateRenderPass(device, &render_pass_create_info, nullptr, &render_pass);
  2772. ERR_FAIL_COND_V_MSG(res, VK_NULL_HANDLE, "vkCreateRenderPass failed with error " + itos(res) + ".");
  2773. if (r_color_attachment_count) {
  2774. *r_color_attachment_count = color_references.size();
  2775. }
  2776. return render_pass;
  2777. }
  2778. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create(const Vector<AttachmentFormat> &p_format) {
  2779. _THREAD_SAFE_METHOD_
  2780. FramebufferFormatKey key;
  2781. key.attachments = p_format;
  2782. const Map<FramebufferFormatKey, FramebufferFormatID>::Element *E = framebuffer_format_cache.find(key);
  2783. if (E) {
  2784. //exists, return
  2785. return E->get();
  2786. }
  2787. int color_references;
  2788. 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
  2789. if (render_pass == VK_NULL_HANDLE) { //was likely invalid
  2790. return INVALID_ID;
  2791. }
  2792. FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT));
  2793. E = framebuffer_format_cache.insert(key, id);
  2794. FramebufferFormat fb_format;
  2795. fb_format.E = E;
  2796. fb_format.color_attachments = color_references;
  2797. fb_format.render_pass = render_pass;
  2798. fb_format.samples = p_format[0].samples;
  2799. framebuffer_formats[id] = fb_format;
  2800. return id;
  2801. }
  2802. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create_empty(const Size2i &p_size) {
  2803. ERR_FAIL_COND_V(p_size.width <= 0 || p_size.height <= 0, INVALID_FORMAT_ID);
  2804. FramebufferFormatKey key;
  2805. key.empty_size = p_size;
  2806. const Map<FramebufferFormatKey, FramebufferFormatID>::Element *E = framebuffer_format_cache.find(key);
  2807. if (E) {
  2808. //exists, return
  2809. return E->get();
  2810. }
  2811. VkSubpassDescription subpass;
  2812. subpass.flags = 0;
  2813. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  2814. subpass.inputAttachmentCount = 0; //unsupported for now
  2815. subpass.pInputAttachments = nullptr;
  2816. subpass.colorAttachmentCount = 0;
  2817. subpass.pColorAttachments = nullptr;
  2818. subpass.pDepthStencilAttachment = nullptr;
  2819. subpass.pResolveAttachments = nullptr;
  2820. subpass.preserveAttachmentCount = 0;
  2821. subpass.pPreserveAttachments = nullptr;
  2822. VkRenderPassCreateInfo render_pass_create_info;
  2823. render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  2824. render_pass_create_info.pNext = nullptr;
  2825. render_pass_create_info.flags = 0;
  2826. render_pass_create_info.attachmentCount = 0;
  2827. render_pass_create_info.pAttachments = nullptr;
  2828. render_pass_create_info.subpassCount = 1;
  2829. render_pass_create_info.pSubpasses = &subpass;
  2830. render_pass_create_info.dependencyCount = 0;
  2831. render_pass_create_info.pDependencies = nullptr;
  2832. VkRenderPass render_pass;
  2833. VkResult res = vkCreateRenderPass(device, &render_pass_create_info, nullptr, &render_pass);
  2834. ERR_FAIL_COND_V_MSG(res, VK_NULL_HANDLE, "vkCreateRenderPass for empty fb failed with error " + itos(res) + ".");
  2835. if (render_pass == VK_NULL_HANDLE) { //was likely invalid
  2836. return INVALID_ID;
  2837. }
  2838. FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT));
  2839. E = framebuffer_format_cache.insert(key, id);
  2840. FramebufferFormat fb_format;
  2841. fb_format.E = E;
  2842. fb_format.color_attachments = 0;
  2843. fb_format.render_pass = render_pass;
  2844. fb_format.samples = TEXTURE_SAMPLES_1;
  2845. framebuffer_formats[id] = fb_format;
  2846. return id;
  2847. }
  2848. RenderingDevice::TextureSamples RenderingDeviceVulkan::framebuffer_format_get_texture_samples(FramebufferFormatID p_format) {
  2849. Map<FramebufferFormatID, FramebufferFormat>::Element *E = framebuffer_formats.find(p_format);
  2850. ERR_FAIL_COND_V(!E, TEXTURE_SAMPLES_1);
  2851. return E->get().samples;
  2852. }
  2853. /***********************/
  2854. /**** RENDER TARGET ****/
  2855. /***********************/
  2856. RID RenderingDeviceVulkan::framebuffer_create_empty(const Size2i &p_size, FramebufferFormatID p_format_check) {
  2857. _THREAD_SAFE_METHOD_
  2858. Framebuffer framebuffer;
  2859. framebuffer.format_id = framebuffer_format_create_empty(p_size);
  2860. ERR_FAIL_COND_V(p_format_check != INVALID_FORMAT_ID && framebuffer.format_id != p_format_check, RID());
  2861. framebuffer.size = p_size;
  2862. return framebuffer_owner.make_rid(framebuffer);
  2863. }
  2864. RID RenderingDeviceVulkan::framebuffer_create(const Vector<RID> &p_texture_attachments, FramebufferFormatID p_format_check) {
  2865. _THREAD_SAFE_METHOD_
  2866. Vector<AttachmentFormat> attachments;
  2867. Size2i size;
  2868. for (int i = 0; i < p_texture_attachments.size(); i++) {
  2869. Texture *texture = texture_owner.getornull(p_texture_attachments[i]);
  2870. ERR_FAIL_COND_V_MSG(!texture, RID(), "Texture index supplied for framebuffer (" + itos(i) + ") is not a valid texture.");
  2871. if (i == 0) {
  2872. size.width = texture->width;
  2873. size.height = texture->height;
  2874. } else {
  2875. ERR_FAIL_COND_V_MSG((uint32_t)size.width != texture->width || (uint32_t)size.height != texture->height, RID(),
  2876. "All textures in a framebuffer should be the same size.");
  2877. }
  2878. AttachmentFormat af;
  2879. af.format = texture->format;
  2880. af.samples = texture->samples;
  2881. af.usage_flags = texture->usage_flags;
  2882. attachments.push_back(af);
  2883. }
  2884. FramebufferFormatID format_id = framebuffer_format_create(attachments);
  2885. if (format_id == INVALID_ID) {
  2886. return RID();
  2887. }
  2888. ERR_FAIL_COND_V_MSG(p_format_check != INVALID_ID && format_id != p_format_check, RID(),
  2889. "The format used to check this framebuffer differs from the intended framebuffer format.");
  2890. Framebuffer framebuffer;
  2891. framebuffer.format_id = format_id;
  2892. framebuffer.texture_ids = p_texture_attachments;
  2893. framebuffer.size = size;
  2894. RID id = framebuffer_owner.make_rid(framebuffer);
  2895. for (int i = 0; i < p_texture_attachments.size(); i++) {
  2896. _add_dependency(id, p_texture_attachments[i]);
  2897. }
  2898. return id;
  2899. }
  2900. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_get_format(RID p_framebuffer) {
  2901. _THREAD_SAFE_METHOD_
  2902. Framebuffer *framebuffer = framebuffer_owner.getornull(p_framebuffer);
  2903. ERR_FAIL_COND_V(!framebuffer, INVALID_ID);
  2904. return framebuffer->format_id;
  2905. }
  2906. /*****************/
  2907. /**** SAMPLER ****/
  2908. /*****************/
  2909. RID RenderingDeviceVulkan::sampler_create(const SamplerState &p_state) {
  2910. _THREAD_SAFE_METHOD_
  2911. VkSamplerCreateInfo sampler_create_info;
  2912. sampler_create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  2913. sampler_create_info.pNext = nullptr;
  2914. sampler_create_info.flags = 0;
  2915. sampler_create_info.magFilter = p_state.mag_filter == SAMPLER_FILTER_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
  2916. sampler_create_info.minFilter = p_state.min_filter == SAMPLER_FILTER_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
  2917. sampler_create_info.mipmapMode = p_state.mip_filter == SAMPLER_FILTER_LINEAR ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST;
  2918. ERR_FAIL_INDEX_V(p_state.repeat_u, SAMPLER_REPEAT_MODE_MAX, RID());
  2919. sampler_create_info.addressModeU = address_modes[p_state.repeat_u];
  2920. ERR_FAIL_INDEX_V(p_state.repeat_v, SAMPLER_REPEAT_MODE_MAX, RID());
  2921. sampler_create_info.addressModeV = address_modes[p_state.repeat_v];
  2922. ERR_FAIL_INDEX_V(p_state.repeat_w, SAMPLER_REPEAT_MODE_MAX, RID());
  2923. sampler_create_info.addressModeW = address_modes[p_state.repeat_w];
  2924. sampler_create_info.mipLodBias = p_state.lod_bias;
  2925. sampler_create_info.anisotropyEnable = p_state.use_anisotropy;
  2926. sampler_create_info.maxAnisotropy = p_state.anisotropy_max;
  2927. sampler_create_info.compareEnable = p_state.enable_compare;
  2928. ERR_FAIL_INDEX_V(p_state.compare_op, COMPARE_OP_MAX, RID());
  2929. sampler_create_info.compareOp = compare_operators[p_state.compare_op];
  2930. sampler_create_info.minLod = p_state.min_lod;
  2931. sampler_create_info.maxLod = p_state.max_lod;
  2932. ERR_FAIL_INDEX_V(p_state.border_color, SAMPLER_BORDER_COLOR_MAX, RID());
  2933. sampler_create_info.borderColor = sampler_border_colors[p_state.border_color];
  2934. sampler_create_info.unnormalizedCoordinates = p_state.unnormalized_uvw;
  2935. VkSampler sampler;
  2936. VkResult res = vkCreateSampler(device, &sampler_create_info, nullptr, &sampler);
  2937. ERR_FAIL_COND_V_MSG(res, RID(), "vkCreateSampler failed with error " + itos(res) + ".");
  2938. return sampler_owner.make_rid(sampler);
  2939. }
  2940. /**********************/
  2941. /**** VERTEX ARRAY ****/
  2942. /**********************/
  2943. RID RenderingDeviceVulkan::vertex_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data) {
  2944. _THREAD_SAFE_METHOD_
  2945. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  2946. Buffer buffer;
  2947. _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);
  2948. if (p_data.size()) {
  2949. uint64_t data_size = p_data.size();
  2950. const uint8_t *r = p_data.ptr();
  2951. _buffer_update(&buffer, 0, r, data_size);
  2952. _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);
  2953. }
  2954. return vertex_buffer_owner.make_rid(buffer);
  2955. }
  2956. // 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
  2957. RenderingDevice::VertexFormatID RenderingDeviceVulkan::vertex_format_create(const Vector<VertexAttribute> &p_vertex_formats) {
  2958. _THREAD_SAFE_METHOD_
  2959. VertexDescriptionKey key;
  2960. key.vertex_formats = p_vertex_formats;
  2961. VertexFormatID *idptr = vertex_format_cache.getptr(key);
  2962. if (idptr) {
  2963. return *idptr;
  2964. }
  2965. //does not exist, create one and cache it
  2966. VertexDescriptionCache vdcache;
  2967. vdcache.bindings = memnew_arr(VkVertexInputBindingDescription, p_vertex_formats.size());
  2968. vdcache.attributes = memnew_arr(VkVertexInputAttributeDescription, p_vertex_formats.size());
  2969. Set<int> used_locations;
  2970. for (int i = 0; i < p_vertex_formats.size(); i++) {
  2971. ERR_CONTINUE(p_vertex_formats[i].format >= DATA_FORMAT_MAX);
  2972. ERR_FAIL_COND_V(used_locations.has(p_vertex_formats[i].location), INVALID_ID);
  2973. ERR_FAIL_COND_V_MSG(get_format_vertex_size(p_vertex_formats[i].format) == 0, INVALID_ID,
  2974. "Data format for attachment (" + itos(i) + ") is not valid for a vertex array.");
  2975. vdcache.bindings[i].binding = i;
  2976. vdcache.bindings[i].stride = p_vertex_formats[i].stride;
  2977. vdcache.bindings[i].inputRate = p_vertex_formats[i].frequency == VERTEX_FREQUENCY_INSTANCE ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX;
  2978. vdcache.attributes[i].binding = i;
  2979. vdcache.attributes[i].location = p_vertex_formats[i].location;
  2980. vdcache.attributes[i].format = vulkan_formats[p_vertex_formats[i].format];
  2981. vdcache.attributes[i].offset = p_vertex_formats[i].offset;
  2982. used_locations.insert(p_vertex_formats[i].location);
  2983. }
  2984. vdcache.create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  2985. vdcache.create_info.pNext = nullptr;
  2986. vdcache.create_info.flags = 0;
  2987. vdcache.create_info.vertexAttributeDescriptionCount = p_vertex_formats.size();
  2988. vdcache.create_info.pVertexAttributeDescriptions = vdcache.attributes;
  2989. vdcache.create_info.vertexBindingDescriptionCount = p_vertex_formats.size();
  2990. vdcache.create_info.pVertexBindingDescriptions = vdcache.bindings;
  2991. vdcache.vertex_formats = p_vertex_formats;
  2992. VertexFormatID id = VertexFormatID(vertex_format_cache.size()) | (VertexFormatID(ID_TYPE_VERTEX_FORMAT) << ID_BASE_SHIFT);
  2993. vertex_format_cache[key] = id;
  2994. vertex_formats[id] = vdcache;
  2995. return id;
  2996. }
  2997. RID RenderingDeviceVulkan::vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector<RID> &p_src_buffers) {
  2998. _THREAD_SAFE_METHOD_
  2999. ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID());
  3000. const VertexDescriptionCache &vd = vertex_formats[p_vertex_format];
  3001. ERR_FAIL_COND_V(vd.vertex_formats.size() != p_src_buffers.size(), RID());
  3002. for (int i = 0; i < p_src_buffers.size(); i++) {
  3003. ERR_FAIL_COND_V(!vertex_buffer_owner.owns(p_src_buffers[i]), RID());
  3004. }
  3005. VertexArray vertex_array;
  3006. vertex_array.vertex_count = p_vertex_count;
  3007. vertex_array.description = p_vertex_format;
  3008. vertex_array.max_instances_allowed = 0xFFFFFFFF; //by default as many as you want
  3009. for (int i = 0; i < p_src_buffers.size(); i++) {
  3010. Buffer *buffer = vertex_buffer_owner.getornull(p_src_buffers[i]);
  3011. //validate with buffer
  3012. {
  3013. const VertexAttribute &atf = vd.vertex_formats[i];
  3014. uint32_t element_size = get_format_vertex_size(atf.format);
  3015. ERR_FAIL_COND_V(element_size == 0, RID()); //should never happens since this was prevalidated
  3016. if (atf.frequency == VERTEX_FREQUENCY_VERTEX) {
  3017. //validate size for regular drawing
  3018. uint64_t total_size = uint64_t(atf.stride) * (p_vertex_count - 1) + atf.offset + element_size;
  3019. ERR_FAIL_COND_V_MSG(total_size > buffer->size, RID(),
  3020. "Attachment (" + itos(i) + ") will read past the end of the buffer.");
  3021. } else {
  3022. //validate size for instances drawing
  3023. uint64_t available = buffer->size - atf.offset;
  3024. ERR_FAIL_COND_V_MSG(available < element_size, RID(),
  3025. "Attachment (" + itos(i) + ") uses instancing, but it's just too small.");
  3026. uint32_t instances_allowed = available / atf.stride;
  3027. vertex_array.max_instances_allowed = MIN(instances_allowed, vertex_array.max_instances_allowed);
  3028. }
  3029. }
  3030. vertex_array.buffers.push_back(buffer->buffer);
  3031. vertex_array.offsets.push_back(0); //offset unused, but passing anyway
  3032. }
  3033. RID id = vertex_array_owner.make_rid(vertex_array);
  3034. for (int i = 0; i < p_src_buffers.size(); i++) {
  3035. _add_dependency(id, p_src_buffers[i]);
  3036. }
  3037. return id;
  3038. }
  3039. RID RenderingDeviceVulkan::index_buffer_create(uint32_t p_index_count, IndexBufferFormat p_format, const Vector<uint8_t> &p_data, bool p_use_restart_indices) {
  3040. _THREAD_SAFE_METHOD_
  3041. ERR_FAIL_COND_V(p_index_count == 0, RID());
  3042. IndexBuffer index_buffer;
  3043. index_buffer.index_type = (p_format == INDEX_BUFFER_FORMAT_UINT16) ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32;
  3044. index_buffer.supports_restart_indices = p_use_restart_indices;
  3045. index_buffer.index_count = p_index_count;
  3046. uint32_t size_bytes = p_index_count * ((p_format == INDEX_BUFFER_FORMAT_UINT16) ? 2 : 4);
  3047. #ifdef DEBUG_ENABLED
  3048. if (p_data.size()) {
  3049. index_buffer.max_index = 0;
  3050. ERR_FAIL_COND_V_MSG((uint32_t)p_data.size() != size_bytes, RID(),
  3051. "Default index buffer initializer array size (" + itos(p_data.size()) + ") does not match format required size (" + itos(size_bytes) + ").");
  3052. const uint8_t *r = p_data.ptr();
  3053. if (p_format == INDEX_BUFFER_FORMAT_UINT16) {
  3054. const uint16_t *index16 = (const uint16_t *)r;
  3055. for (uint32_t i = 0; i < p_index_count; i++) {
  3056. if (p_use_restart_indices && index16[i] == 0xFFFF) {
  3057. continue; //restart index, ingnore
  3058. }
  3059. index_buffer.max_index = MAX(index16[i], index_buffer.max_index);
  3060. }
  3061. } else {
  3062. const uint32_t *index32 = (const uint32_t *)r;
  3063. for (uint32_t i = 0; i < p_index_count; i++) {
  3064. if (p_use_restart_indices && index32[i] == 0xFFFFFFFF) {
  3065. continue; //restart index, ingnore
  3066. }
  3067. index_buffer.max_index = MAX(index32[i], index_buffer.max_index);
  3068. }
  3069. }
  3070. } else {
  3071. index_buffer.max_index = 0xFFFFFFFF;
  3072. }
  3073. #else
  3074. index_buffer.max_index = 0xFFFFFFFF;
  3075. #endif
  3076. _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);
  3077. if (p_data.size()) {
  3078. uint64_t data_size = p_data.size();
  3079. const uint8_t *r = p_data.ptr();
  3080. _buffer_update(&index_buffer, 0, r, data_size);
  3081. _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);
  3082. }
  3083. return index_buffer_owner.make_rid(index_buffer);
  3084. }
  3085. RID RenderingDeviceVulkan::index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count) {
  3086. _THREAD_SAFE_METHOD_
  3087. ERR_FAIL_COND_V(!index_buffer_owner.owns(p_index_buffer), RID());
  3088. IndexBuffer *index_buffer = index_buffer_owner.getornull(p_index_buffer);
  3089. ERR_FAIL_COND_V(p_index_count == 0, RID());
  3090. ERR_FAIL_COND_V(p_index_offset + p_index_count > index_buffer->index_count, RID());
  3091. IndexArray index_array;
  3092. index_array.max_index = index_buffer->max_index;
  3093. index_array.buffer = index_buffer->buffer;
  3094. index_array.offset = p_index_offset;
  3095. index_array.indices = p_index_count;
  3096. index_array.index_type = index_buffer->index_type;
  3097. index_array.supports_restart_indices = index_buffer->supports_restart_indices;
  3098. RID id = index_array_owner.make_rid(index_array);
  3099. _add_dependency(id, p_index_buffer);
  3100. return id;
  3101. }
  3102. /****************/
  3103. /**** SHADER ****/
  3104. /****************/
  3105. static const char *shader_stage_names[RenderingDevice::SHADER_STAGE_MAX] = {
  3106. "Vertex",
  3107. "Fragment",
  3108. "TesselationControl",
  3109. "TesselationEvaluation",
  3110. "Compute"
  3111. };
  3112. static const char *shader_uniform_names[RenderingDevice::UNIFORM_TYPE_MAX] = {
  3113. "Sampler", "CombinedSampler", "Texture", "Image", "TextureBuffer", "SamplerTextureBuffer", "ImageBuffer", "UniformBuffer", "StorageBuffer", "InputAttachment"
  3114. };
  3115. static VkShaderStageFlagBits shader_stage_masks[RenderingDevice::SHADER_STAGE_MAX] = {
  3116. VK_SHADER_STAGE_VERTEX_BIT,
  3117. VK_SHADER_STAGE_FRAGMENT_BIT,
  3118. VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT,
  3119. VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
  3120. VK_SHADER_STAGE_COMPUTE_BIT,
  3121. };
  3122. String RenderingDeviceVulkan::_shader_uniform_debug(RID p_shader, int p_set) {
  3123. String ret;
  3124. const Shader *shader = shader_owner.getornull(p_shader);
  3125. ERR_FAIL_COND_V(!shader, String());
  3126. for (int i = 0; i < shader->sets.size(); i++) {
  3127. if (p_set >= 0 && i != p_set) {
  3128. continue;
  3129. }
  3130. for (int j = 0; j < shader->sets[i].uniform_info.size(); j++) {
  3131. const UniformInfo &ui = shader->sets[i].uniform_info[j];
  3132. if (ret != String()) {
  3133. ret += "\n";
  3134. }
  3135. ret += "Set: " + itos(i) + " Binding: " + itos(ui.binding) + " Type: " + shader_uniform_names[ui.type] + " Length: " + itos(ui.length);
  3136. }
  3137. }
  3138. return ret;
  3139. }
  3140. #if 0
  3141. 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) {
  3142. VkDescriptorSetLayoutBinding layout_binding;
  3143. UniformInfo info;
  3144. switch (reflection.getType()->getBasicType()) {
  3145. case glslang::EbtSampler: {
  3146. //print_line("DEBUG: IsSampler");
  3147. if (reflection.getType()->getSampler().dim == glslang::EsdBuffer) {
  3148. //texture buffers
  3149. if (reflection.getType()->getSampler().isCombined()) {
  3150. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  3151. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER;
  3152. //print_line("DEBUG: SAMPLER: texel combined");
  3153. } else if (reflection.getType()->getSampler().isTexture()) {
  3154. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  3155. info.type = UNIFORM_TYPE_TEXTURE_BUFFER;
  3156. //print_line("DEBUG: SAMPLER: texel alone");
  3157. } else if (reflection.getType()->getSampler().isImage()) {
  3158. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  3159. info.type = UNIFORM_TYPE_IMAGE_BUFFER;
  3160. //print_line("DEBUG: SAMPLER: texel buffer");
  3161. } else {
  3162. if (r_error) {
  3163. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name.c_str() + "' is of unsupported buffer type.";
  3164. }
  3165. return false;
  3166. }
  3167. } else if (reflection.getType()->getSampler().isCombined()) {
  3168. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  3169. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
  3170. //print_line("DEBUG: SAMPLER: combined");
  3171. } else if (reflection.getType()->getSampler().isPureSampler()) {
  3172. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  3173. info.type = UNIFORM_TYPE_SAMPLER;
  3174. //print_line("DEBUG: SAMPLER: sampler");
  3175. } else if (reflection.getType()->getSampler().isTexture()) {
  3176. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  3177. info.type = UNIFORM_TYPE_TEXTURE;
  3178. //print_line("DEBUG: SAMPLER: image");
  3179. } else if (reflection.getType()->getSampler().isImage()) {
  3180. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  3181. info.type = UNIFORM_TYPE_IMAGE;
  3182. //print_line("DEBUG: SAMPLER: storage image");
  3183. } else {
  3184. //print_line("DEBUG: sampler unknown");
  3185. if (r_error) {
  3186. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name.c_str() + "' is of unsupported sampler type.";
  3187. }
  3188. return false;
  3189. }
  3190. if (reflection.getType()->isArray()) {
  3191. layout_binding.descriptorCount = reflection.getType()->getArraySizes()->getCumulativeSize();
  3192. //print_line("DEBUG: array of size: " + itos(layout_binding.descriptorCount));
  3193. } else {
  3194. layout_binding.descriptorCount = 1;
  3195. }
  3196. info.length = layout_binding.descriptorCount;
  3197. } break;
  3198. /*case glslang::EbtStruct: {
  3199. print_line("DEBUG: Struct");
  3200. } break;*/
  3201. case glslang::EbtBlock: {
  3202. //print_line("DEBUG: Block");
  3203. if (reflection.getType()->getQualifier().storage == glslang::EvqUniform) {
  3204. if (reflection.getType()->getQualifier().layoutPushConstant) {
  3205. uint32_t len = reflection.size;
  3206. if (push_constant.push_constant_size != 0 && push_constant.push_constant_size != len) {
  3207. *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.";
  3208. return false;
  3209. }
  3210. push_constant.push_constant_size = len;
  3211. push_constant.push_constants_vk_stage |= shader_stage_masks[p_stage];
  3212. return true;
  3213. }
  3214. //print_line("DEBUG: Uniform buffer");
  3215. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  3216. info.type = UNIFORM_TYPE_UNIFORM_BUFFER;
  3217. } else if (reflection.getType()->getQualifier().storage == glslang::EvqBuffer) {
  3218. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  3219. info.type = UNIFORM_TYPE_STORAGE_BUFFER;
  3220. //print_line("DEBUG: Storage buffer");
  3221. } else {
  3222. if (r_error) {
  3223. *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) + ").";
  3224. }
  3225. return false;
  3226. }
  3227. if (reflection.getType()->isArray()) {
  3228. layout_binding.descriptorCount = reflection.getType()->getArraySizes()->getCumulativeSize();
  3229. //print_line("DEBUG: array of size: " + itos(layout_binding.descriptorCount));
  3230. } else {
  3231. layout_binding.descriptorCount = 1;
  3232. }
  3233. info.length = reflection.size;
  3234. } break;
  3235. /*case glslang::EbtReference: {
  3236. } break;*/
  3237. /*case glslang::EbtAtomicUint: {
  3238. } break;*/
  3239. default: {
  3240. if (reflection.getType()->getQualifier().hasOffset() || reflection.name.find(".") != std::string::npos) {
  3241. //member of uniform block?
  3242. return true;
  3243. }
  3244. if (r_error) {
  3245. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name.c_str() + "' unsupported uniform type.";
  3246. }
  3247. return false;
  3248. }
  3249. }
  3250. if (!reflection.getType()->getQualifier().hasBinding()) {
  3251. if (r_error) {
  3252. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name.c_str() + "' lacks a binding number.";
  3253. }
  3254. return false;
  3255. }
  3256. uint32_t set = reflection.getType()->getQualifier().hasSet() ? reflection.getType()->getQualifier().layoutSet : 0;
  3257. if (set >= MAX_UNIFORM_SETS) {
  3258. if (r_error) {
  3259. *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) + ").";
  3260. }
  3261. return false;
  3262. }
  3263. if (set >= limits.maxBoundDescriptorSets) {
  3264. if (r_error) {
  3265. *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) + ").";
  3266. }
  3267. return false;
  3268. }
  3269. uint32_t binding = reflection.getType()->getQualifier().layoutBinding;
  3270. if (set < (uint32_t)bindings.size()) {
  3271. //check if this already exists
  3272. for (int i = 0; i < bindings[set].size(); i++) {
  3273. if (bindings[set][i].binding == binding) {
  3274. //already exists, verify that it's the same type
  3275. if (bindings[set][i].descriptorType != layout_binding.descriptorType) {
  3276. if (r_error) {
  3277. *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.";
  3278. }
  3279. return false;
  3280. }
  3281. //also, verify that it's the same size
  3282. if (bindings[set][i].descriptorCount != layout_binding.descriptorCount || uniform_infos[set][i].length != info.length) {
  3283. if (r_error) {
  3284. *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.";
  3285. }
  3286. return false;
  3287. }
  3288. //just append stage mask and return
  3289. bindings.write[set].write[i].stageFlags |= shader_stage_masks[p_stage];
  3290. uniform_infos.write[set].write[i].stages |= 1 << p_stage;
  3291. return true;
  3292. }
  3293. }
  3294. }
  3295. layout_binding.binding = binding;
  3296. layout_binding.stageFlags = shader_stage_masks[p_stage];
  3297. layout_binding.pImmutableSamplers = nullptr; //no support for this yet
  3298. info.stages = 1 << p_stage;
  3299. info.binding = binding;
  3300. if (set >= (uint32_t)bindings.size()) {
  3301. bindings.resize(set + 1);
  3302. uniform_infos.resize(set + 1);
  3303. }
  3304. #if 0
  3305. 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));
  3306. #endif
  3307. bindings.write[set].push_back(layout_binding);
  3308. uniform_infos.write[set].push_back(info);
  3309. return true;
  3310. }
  3311. #endif
  3312. RID RenderingDeviceVulkan::shader_create(const Vector<ShaderStageData> &p_stages) {
  3313. //descriptor layouts
  3314. Vector<Vector<VkDescriptorSetLayoutBinding>> set_bindings;
  3315. Vector<Vector<UniformInfo>> uniform_info;
  3316. Shader::PushConstant push_constant;
  3317. push_constant.push_constant_size = 0;
  3318. push_constant.push_constants_vk_stage = 0;
  3319. uint32_t vertex_input_mask = 0;
  3320. uint32_t fragment_outputs = 0;
  3321. uint32_t stages_processed = 0;
  3322. bool is_compute = false;
  3323. for (int i = 0; i < p_stages.size(); i++) {
  3324. if (p_stages[i].shader_stage == SHADER_STAGE_COMPUTE) {
  3325. is_compute = true;
  3326. ERR_FAIL_COND_V_MSG(p_stages.size() != 1, RID(),
  3327. "Compute shaders can only receive one stage, dedicated to compute.");
  3328. }
  3329. ERR_FAIL_COND_V_MSG(stages_processed & (1 << p_stages[i].shader_stage), RID(),
  3330. "Stage " + String(shader_stage_names[p_stages[i].shader_stage]) + " submitted more than once.");
  3331. {
  3332. SpvReflectShaderModule module;
  3333. const uint8_t *spirv = p_stages[i].spir_v.ptr();
  3334. SpvReflectResult result = spvReflectCreateShaderModule(p_stages[i].spir_v.size(), spirv, &module);
  3335. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, RID(),
  3336. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_stages[i].shader_stage]) + "' failed parsing shader.");
  3337. uint32_t binding_count = 0;
  3338. result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, nullptr);
  3339. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, RID(),
  3340. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_stages[i].shader_stage]) + "' failed enumerating descriptor bindings.");
  3341. uint32_t stage = p_stages[i].shader_stage;
  3342. if (binding_count > 0) {
  3343. //Parse bindings
  3344. Vector<SpvReflectDescriptorBinding *> bindings;
  3345. bindings.resize(binding_count);
  3346. result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, bindings.ptrw());
  3347. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, RID(),
  3348. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_stages[i].shader_stage]) + "' failed getting descriptor bindings.");
  3349. for (uint32_t j = 0; j < binding_count; j++) {
  3350. const SpvReflectDescriptorBinding &binding = *bindings[j];
  3351. VkDescriptorSetLayoutBinding layout_binding;
  3352. UniformInfo info;
  3353. bool need_array_dimensions = false;
  3354. bool need_block_size = false;
  3355. switch (binding.descriptor_type) {
  3356. case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLER: {
  3357. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  3358. info.type = UNIFORM_TYPE_SAMPLER;
  3359. need_array_dimensions = true;
  3360. } break;
  3361. case SPV_REFLECT_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: {
  3362. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  3363. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
  3364. need_array_dimensions = true;
  3365. } break;
  3366. case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLED_IMAGE: {
  3367. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  3368. info.type = UNIFORM_TYPE_TEXTURE;
  3369. need_array_dimensions = true;
  3370. } break;
  3371. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
  3372. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  3373. info.type = UNIFORM_TYPE_IMAGE;
  3374. need_array_dimensions = true;
  3375. } break;
  3376. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: {
  3377. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  3378. info.type = UNIFORM_TYPE_TEXTURE_BUFFER;
  3379. need_array_dimensions = true;
  3380. } break;
  3381. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: {
  3382. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  3383. info.type = UNIFORM_TYPE_IMAGE_BUFFER;
  3384. need_array_dimensions = true;
  3385. } break;
  3386. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER: {
  3387. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  3388. info.type = UNIFORM_TYPE_UNIFORM_BUFFER;
  3389. need_block_size = true;
  3390. } break;
  3391. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER: {
  3392. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  3393. info.type = UNIFORM_TYPE_STORAGE_BUFFER;
  3394. need_block_size = true;
  3395. } break;
  3396. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: {
  3397. ERR_PRINT("Dynamic uniform buffer not supported.");
  3398. continue;
  3399. } break;
  3400. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
  3401. ERR_PRINT("Dynamic storage buffer not supported.");
  3402. continue;
  3403. } break;
  3404. case SPV_REFLECT_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: {
  3405. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
  3406. info.type = UNIFORM_TYPE_INPUT_ATTACHMENT;
  3407. } break;
  3408. }
  3409. if (need_array_dimensions) {
  3410. if (binding.array.dims_count == 0) {
  3411. info.length = 1;
  3412. } else {
  3413. for (uint32_t k = 0; k < binding.array.dims_count; k++) {
  3414. if (k == 0) {
  3415. info.length = binding.array.dims[0];
  3416. } else {
  3417. info.length *= binding.array.dims[k];
  3418. }
  3419. }
  3420. }
  3421. layout_binding.descriptorCount = info.length;
  3422. } else if (need_block_size) {
  3423. info.length = binding.block.size;
  3424. layout_binding.descriptorCount = 1;
  3425. } else {
  3426. info.length = 0;
  3427. layout_binding.descriptorCount = 1;
  3428. }
  3429. info.binding = binding.binding;
  3430. uint32_t set = binding.set;
  3431. //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));
  3432. ERR_FAIL_COND_V_MSG(set >= MAX_UNIFORM_SETS, RID(),
  3433. "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) + ").");
  3434. ERR_FAIL_COND_V_MSG(set >= limits.maxBoundDescriptorSets, RID(),
  3435. "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) + ").");
  3436. if (set < (uint32_t)set_bindings.size()) {
  3437. //check if this already exists
  3438. bool exists = false;
  3439. for (int k = 0; k < set_bindings[set].size(); k++) {
  3440. if (set_bindings[set][k].binding == (uint32_t)info.binding) {
  3441. //already exists, verify that it's the same type
  3442. ERR_FAIL_COND_V_MSG(set_bindings[set][k].descriptorType != layout_binding.descriptorType, RID(),
  3443. "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.");
  3444. //also, verify that it's the same size
  3445. ERR_FAIL_COND_V_MSG(set_bindings[set][k].descriptorCount != layout_binding.descriptorCount || uniform_info[set][k].length != info.length, RID(),
  3446. "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.");
  3447. //just append stage mask and return
  3448. set_bindings.write[set].write[k].stageFlags |= shader_stage_masks[stage];
  3449. uniform_info.write[set].write[k].stages |= 1 << stage;
  3450. exists = true;
  3451. }
  3452. }
  3453. if (exists) {
  3454. continue; //merged
  3455. }
  3456. }
  3457. layout_binding.binding = info.binding;
  3458. layout_binding.stageFlags = shader_stage_masks[stage];
  3459. layout_binding.pImmutableSamplers = nullptr; //no support for this yet
  3460. info.stages = 1 << stage;
  3461. info.binding = info.binding;
  3462. if (set >= (uint32_t)set_bindings.size()) {
  3463. set_bindings.resize(set + 1);
  3464. uniform_info.resize(set + 1);
  3465. }
  3466. set_bindings.write[set].push_back(layout_binding);
  3467. uniform_info.write[set].push_back(info);
  3468. }
  3469. }
  3470. if (stage == SHADER_STAGE_VERTEX) {
  3471. uint32_t iv_count = 0;
  3472. result = spvReflectEnumerateInputVariables(&module, &iv_count, nullptr);
  3473. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, RID(),
  3474. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_stages[i].shader_stage]) + "' failed enumerating input variables.");
  3475. if (iv_count) {
  3476. Vector<SpvReflectInterfaceVariable *> input_vars;
  3477. input_vars.resize(iv_count);
  3478. result = spvReflectEnumerateInputVariables(&module, &iv_count, input_vars.ptrw());
  3479. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, RID(),
  3480. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_stages[i].shader_stage]) + "' failed obtaining input variables.");
  3481. for (uint32_t j = 0; j < iv_count; j++) {
  3482. if (input_vars[j] && input_vars[j]->decoration_flags == 0) { //regular input
  3483. vertex_input_mask |= (1 << uint32_t(input_vars[j]->location));
  3484. }
  3485. }
  3486. }
  3487. }
  3488. if (stage == SHADER_STAGE_FRAGMENT) {
  3489. uint32_t ov_count = 0;
  3490. result = spvReflectEnumerateOutputVariables(&module, &ov_count, nullptr);
  3491. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, RID(),
  3492. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_stages[i].shader_stage]) + "' failed enumerating output variables.");
  3493. if (ov_count) {
  3494. Vector<SpvReflectInterfaceVariable *> output_vars;
  3495. output_vars.resize(ov_count);
  3496. result = spvReflectEnumerateOutputVariables(&module, &ov_count, output_vars.ptrw());
  3497. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, RID(),
  3498. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_stages[i].shader_stage]) + "' failed obtaining output variables.");
  3499. for (uint32_t j = 0; j < ov_count; j++) {
  3500. if (output_vars[j]) {
  3501. fragment_outputs = MAX(fragment_outputs, output_vars[j]->location + 1);
  3502. }
  3503. }
  3504. }
  3505. }
  3506. uint32_t pc_count = 0;
  3507. result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, nullptr);
  3508. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, RID(),
  3509. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_stages[i].shader_stage]) + "' failed enumerating push constants.");
  3510. if (pc_count) {
  3511. ERR_FAIL_COND_V_MSG(pc_count > 1, RID(),
  3512. "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.");
  3513. Vector<SpvReflectBlockVariable *> pconstants;
  3514. pconstants.resize(pc_count);
  3515. result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, pconstants.ptrw());
  3516. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, RID(),
  3517. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_stages[i].shader_stage]) + "' failed obtaining push constants.");
  3518. #if 0
  3519. if (pconstants[0] == nullptr) {
  3520. FileAccess *f = FileAccess::open("res://popo.spv", FileAccess::WRITE);
  3521. f->store_buffer((const uint8_t *)&SpirV[0], SpirV.size() * sizeof(uint32_t));
  3522. memdelete(f);
  3523. }
  3524. #endif
  3525. ERR_FAIL_COND_V_MSG(push_constant.push_constant_size && push_constant.push_constant_size != pconstants[0]->size, RID(),
  3526. "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.");
  3527. push_constant.push_constant_size = pconstants[0]->size;
  3528. push_constant.push_constants_vk_stage |= shader_stage_masks[stage];
  3529. //print_line("Stage: " + String(shader_stage_names[stage]) + " push constant of size=" + itos(push_constant.push_constant_size));
  3530. }
  3531. // Destroy the reflection data when no longer required.
  3532. spvReflectDestroyShaderModule(&module);
  3533. }
  3534. stages_processed |= (1 << p_stages[i].shader_stage);
  3535. }
  3536. //all good, let's create modules
  3537. _THREAD_SAFE_METHOD_
  3538. Shader shader;
  3539. shader.vertex_input_mask = vertex_input_mask;
  3540. shader.fragment_outputs = fragment_outputs;
  3541. shader.push_constant = push_constant;
  3542. shader.is_compute = is_compute;
  3543. String error_text;
  3544. bool success = true;
  3545. for (int i = 0; i < p_stages.size(); i++) {
  3546. VkShaderModuleCreateInfo shader_module_create_info;
  3547. shader_module_create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  3548. shader_module_create_info.pNext = nullptr;
  3549. shader_module_create_info.flags = 0;
  3550. shader_module_create_info.codeSize = p_stages[i].spir_v.size();
  3551. const uint8_t *r = p_stages[i].spir_v.ptr();
  3552. shader_module_create_info.pCode = (const uint32_t *)r;
  3553. VkShaderModule module;
  3554. VkResult res = vkCreateShaderModule(device, &shader_module_create_info, nullptr, &module);
  3555. if (res) {
  3556. success = false;
  3557. error_text = "Error (" + itos(res) + ") creating shader module for stage: " + String(shader_stage_names[p_stages[i].shader_stage]);
  3558. break;
  3559. }
  3560. const VkShaderStageFlagBits shader_stage_bits[SHADER_STAGE_MAX] = {
  3561. VK_SHADER_STAGE_VERTEX_BIT,
  3562. VK_SHADER_STAGE_FRAGMENT_BIT,
  3563. VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT,
  3564. VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
  3565. VK_SHADER_STAGE_COMPUTE_BIT,
  3566. };
  3567. VkPipelineShaderStageCreateInfo shader_stage;
  3568. shader_stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  3569. shader_stage.pNext = nullptr;
  3570. shader_stage.flags = 0;
  3571. shader_stage.stage = shader_stage_bits[p_stages[i].shader_stage];
  3572. shader_stage.module = module;
  3573. shader_stage.pName = "main";
  3574. shader_stage.pSpecializationInfo = nullptr;
  3575. shader.pipeline_stages.push_back(shader_stage);
  3576. }
  3577. //proceed to create descriptor sets
  3578. if (success) {
  3579. for (int i = 0; i < set_bindings.size(); i++) {
  3580. //empty ones are fine if they were not used according to spec (binding count will be 0)
  3581. VkDescriptorSetLayoutCreateInfo layout_create_info;
  3582. layout_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  3583. layout_create_info.pNext = nullptr;
  3584. layout_create_info.flags = 0;
  3585. layout_create_info.bindingCount = set_bindings[i].size();
  3586. layout_create_info.pBindings = set_bindings[i].ptr();
  3587. VkDescriptorSetLayout layout;
  3588. VkResult res = vkCreateDescriptorSetLayout(device, &layout_create_info, nullptr, &layout);
  3589. if (res) {
  3590. error_text = "Error (" + itos(res) + ") creating descriptor set layout for set " + itos(i);
  3591. success = false;
  3592. break;
  3593. }
  3594. Shader::Set set;
  3595. set.descriptor_set_layout = layout;
  3596. set.uniform_info = uniform_info[i];
  3597. //sort and hash
  3598. set.uniform_info.sort();
  3599. uint32_t format = 0; //no format, default
  3600. if (set.uniform_info.size()) {
  3601. //has data, needs an actual format;
  3602. UniformSetFormat usformat;
  3603. usformat.uniform_info = set.uniform_info;
  3604. Map<UniformSetFormat, uint32_t>::Element *E = uniform_set_format_cache.find(usformat);
  3605. if (E) {
  3606. format = E->get();
  3607. } else {
  3608. format = uniform_set_format_cache.size() + 1;
  3609. uniform_set_format_cache.insert(usformat, format);
  3610. }
  3611. }
  3612. shader.sets.push_back(set);
  3613. shader.set_formats.push_back(format);
  3614. }
  3615. }
  3616. if (success) {
  3617. //create pipeline layout
  3618. VkPipelineLayoutCreateInfo pipeline_layout_create_info;
  3619. pipeline_layout_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  3620. pipeline_layout_create_info.pNext = nullptr;
  3621. pipeline_layout_create_info.flags = 0;
  3622. pipeline_layout_create_info.setLayoutCount = shader.sets.size();
  3623. Vector<VkDescriptorSetLayout> layouts;
  3624. layouts.resize(shader.sets.size());
  3625. for (int i = 0; i < layouts.size(); i++) {
  3626. layouts.write[i] = shader.sets[i].descriptor_set_layout;
  3627. }
  3628. pipeline_layout_create_info.pSetLayouts = layouts.ptr();
  3629. if (push_constant.push_constant_size) {
  3630. VkPushConstantRange push_constant_range;
  3631. push_constant_range.stageFlags = push_constant.push_constants_vk_stage;
  3632. push_constant_range.offset = 0;
  3633. push_constant_range.size = push_constant.push_constant_size;
  3634. pipeline_layout_create_info.pushConstantRangeCount = 1;
  3635. pipeline_layout_create_info.pPushConstantRanges = &push_constant_range;
  3636. } else {
  3637. pipeline_layout_create_info.pushConstantRangeCount = 0;
  3638. pipeline_layout_create_info.pPushConstantRanges = nullptr;
  3639. }
  3640. VkResult err = vkCreatePipelineLayout(device, &pipeline_layout_create_info, nullptr, &shader.pipeline_layout);
  3641. if (err) {
  3642. error_text = "Error (" + itos(err) + ") creating pipeline layout.";
  3643. success = false;
  3644. }
  3645. }
  3646. if (!success) {
  3647. //clean up if failed
  3648. for (int i = 0; i < shader.pipeline_stages.size(); i++) {
  3649. vkDestroyShaderModule(device, shader.pipeline_stages[i].module, nullptr);
  3650. }
  3651. for (int i = 0; i < shader.sets.size(); i++) {
  3652. vkDestroyDescriptorSetLayout(device, shader.sets[i].descriptor_set_layout, nullptr);
  3653. }
  3654. ERR_FAIL_V_MSG(RID(), error_text);
  3655. }
  3656. return shader_owner.make_rid(shader);
  3657. }
  3658. uint32_t RenderingDeviceVulkan::shader_get_vertex_input_attribute_mask(RID p_shader) {
  3659. _THREAD_SAFE_METHOD_
  3660. const Shader *shader = shader_owner.getornull(p_shader);
  3661. ERR_FAIL_COND_V(!shader, 0);
  3662. return shader->vertex_input_mask;
  3663. }
  3664. /******************/
  3665. /**** UNIFORMS ****/
  3666. /******************/
  3667. RID RenderingDeviceVulkan::uniform_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data) {
  3668. _THREAD_SAFE_METHOD_
  3669. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  3670. Buffer buffer;
  3671. 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);
  3672. ERR_FAIL_COND_V(err != OK, RID());
  3673. if (p_data.size()) {
  3674. uint64_t data_size = p_data.size();
  3675. const uint8_t *r = p_data.ptr();
  3676. _buffer_update(&buffer, 0, r, data_size);
  3677. _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);
  3678. }
  3679. return uniform_buffer_owner.make_rid(buffer);
  3680. }
  3681. RID RenderingDeviceVulkan::storage_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data, uint32_t p_usage) {
  3682. _THREAD_SAFE_METHOD_
  3683. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  3684. Buffer buffer;
  3685. buffer.usage = p_usage;
  3686. uint32_t flags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
  3687. if (p_usage & STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT) {
  3688. flags |= VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
  3689. }
  3690. Error err = _buffer_allocate(&buffer, p_size_bytes, flags, VMA_MEMORY_USAGE_GPU_ONLY);
  3691. ERR_FAIL_COND_V(err != OK, RID());
  3692. if (p_data.size()) {
  3693. uint64_t data_size = p_data.size();
  3694. const uint8_t *r = p_data.ptr();
  3695. _buffer_update(&buffer, 0, r, data_size);
  3696. _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);
  3697. }
  3698. return storage_buffer_owner.make_rid(buffer);
  3699. }
  3700. RID RenderingDeviceVulkan::texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector<uint8_t> &p_data) {
  3701. _THREAD_SAFE_METHOD_
  3702. uint32_t element_size = get_format_vertex_size(p_format);
  3703. ERR_FAIL_COND_V_MSG(element_size == 0, RID(), "Format requested is not supported for texture buffers");
  3704. uint64_t size_bytes = uint64_t(element_size) * p_size_elements;
  3705. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != size_bytes, RID());
  3706. TextureBuffer texture_buffer;
  3707. 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);
  3708. ERR_FAIL_COND_V(err != OK, RID());
  3709. if (p_data.size()) {
  3710. uint64_t data_size = p_data.size();
  3711. const uint8_t *r = p_data.ptr();
  3712. _buffer_update(&texture_buffer.buffer, 0, r, data_size);
  3713. _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);
  3714. }
  3715. VkBufferViewCreateInfo view_create_info;
  3716. view_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;
  3717. view_create_info.pNext = nullptr;
  3718. view_create_info.flags = 0;
  3719. view_create_info.buffer = texture_buffer.buffer.buffer;
  3720. view_create_info.format = vulkan_formats[p_format];
  3721. view_create_info.offset = 0;
  3722. view_create_info.range = size_bytes;
  3723. texture_buffer.view = VK_NULL_HANDLE;
  3724. VkResult res = vkCreateBufferView(device, &view_create_info, nullptr, &texture_buffer.view);
  3725. if (res) {
  3726. _buffer_free(&texture_buffer.buffer);
  3727. ERR_FAIL_V_MSG(RID(), "Unable to create buffer view, error " + itos(res) + ".");
  3728. }
  3729. //allocate the view
  3730. return texture_buffer_owner.make_rid(texture_buffer);
  3731. }
  3732. RenderingDeviceVulkan::DescriptorPool *RenderingDeviceVulkan::_descriptor_pool_allocate(const DescriptorPoolKey &p_key) {
  3733. if (!descriptor_pools.has(p_key)) {
  3734. descriptor_pools[p_key] = Set<DescriptorPool *>();
  3735. }
  3736. DescriptorPool *pool = nullptr;
  3737. for (Set<DescriptorPool *>::Element *E = descriptor_pools[p_key].front(); E; E = E->next()) {
  3738. if (E->get()->usage < max_descriptors_per_pool) {
  3739. pool = E->get();
  3740. break;
  3741. }
  3742. }
  3743. if (!pool) {
  3744. //create a new one
  3745. pool = memnew(DescriptorPool);
  3746. pool->usage = 0;
  3747. VkDescriptorPoolCreateInfo descriptor_pool_create_info;
  3748. descriptor_pool_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
  3749. descriptor_pool_create_info.pNext = nullptr;
  3750. descriptor_pool_create_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; // can't think how somebody may NOT need this flag..
  3751. descriptor_pool_create_info.maxSets = max_descriptors_per_pool;
  3752. Vector<VkDescriptorPoolSize> sizes;
  3753. //here comes more vulkan API strangeness
  3754. if (p_key.uniform_type[UNIFORM_TYPE_SAMPLER]) {
  3755. VkDescriptorPoolSize s;
  3756. s.type = VK_DESCRIPTOR_TYPE_SAMPLER;
  3757. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_SAMPLER] * max_descriptors_per_pool;
  3758. sizes.push_back(s);
  3759. }
  3760. if (p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE]) {
  3761. VkDescriptorPoolSize s;
  3762. s.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  3763. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE] * max_descriptors_per_pool;
  3764. sizes.push_back(s);
  3765. }
  3766. if (p_key.uniform_type[UNIFORM_TYPE_TEXTURE]) {
  3767. VkDescriptorPoolSize s;
  3768. s.type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  3769. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_TEXTURE] * max_descriptors_per_pool;
  3770. sizes.push_back(s);
  3771. }
  3772. if (p_key.uniform_type[UNIFORM_TYPE_IMAGE]) {
  3773. VkDescriptorPoolSize s;
  3774. s.type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  3775. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_IMAGE] * max_descriptors_per_pool;
  3776. sizes.push_back(s);
  3777. }
  3778. if (p_key.uniform_type[UNIFORM_TYPE_TEXTURE_BUFFER] || p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER]) {
  3779. VkDescriptorPoolSize s;
  3780. s.type = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  3781. s.descriptorCount = (p_key.uniform_type[UNIFORM_TYPE_TEXTURE_BUFFER] + p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER]) * max_descriptors_per_pool;
  3782. sizes.push_back(s);
  3783. }
  3784. if (p_key.uniform_type[UNIFORM_TYPE_IMAGE_BUFFER]) {
  3785. VkDescriptorPoolSize s;
  3786. s.type = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  3787. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_IMAGE_BUFFER] * max_descriptors_per_pool;
  3788. sizes.push_back(s);
  3789. }
  3790. if (p_key.uniform_type[UNIFORM_TYPE_UNIFORM_BUFFER]) {
  3791. VkDescriptorPoolSize s;
  3792. s.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  3793. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_UNIFORM_BUFFER] * max_descriptors_per_pool;
  3794. sizes.push_back(s);
  3795. }
  3796. if (p_key.uniform_type[UNIFORM_TYPE_STORAGE_BUFFER]) {
  3797. VkDescriptorPoolSize s;
  3798. s.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  3799. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_STORAGE_BUFFER] * max_descriptors_per_pool;
  3800. sizes.push_back(s);
  3801. }
  3802. if (p_key.uniform_type[UNIFORM_TYPE_INPUT_ATTACHMENT]) {
  3803. VkDescriptorPoolSize s;
  3804. s.type = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
  3805. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_INPUT_ATTACHMENT] * max_descriptors_per_pool;
  3806. sizes.push_back(s);
  3807. }
  3808. descriptor_pool_create_info.poolSizeCount = sizes.size();
  3809. descriptor_pool_create_info.pPoolSizes = sizes.ptr();
  3810. VkResult res = vkCreateDescriptorPool(device, &descriptor_pool_create_info, nullptr, &pool->pool);
  3811. if (res) {
  3812. memdelete(pool);
  3813. ERR_FAIL_COND_V_MSG(res, nullptr, "vkCreateDescriptorPool failed with error " + itos(res) + ".");
  3814. }
  3815. descriptor_pools[p_key].insert(pool);
  3816. }
  3817. pool->usage++;
  3818. return pool;
  3819. }
  3820. void RenderingDeviceVulkan::_descriptor_pool_free(const DescriptorPoolKey &p_key, DescriptorPool *p_pool) {
  3821. #ifdef DEBUG_ENABLED
  3822. ERR_FAIL_COND(!descriptor_pools[p_key].has(p_pool));
  3823. #endif
  3824. ERR_FAIL_COND(p_pool->usage == 0);
  3825. p_pool->usage--;
  3826. if (p_pool->usage == 0) {
  3827. vkDestroyDescriptorPool(device, p_pool->pool, nullptr);
  3828. descriptor_pools[p_key].erase(p_pool);
  3829. memdelete(p_pool);
  3830. if (descriptor_pools[p_key].empty()) {
  3831. descriptor_pools.erase(p_key);
  3832. }
  3833. }
  3834. }
  3835. RID RenderingDeviceVulkan::uniform_set_create(const Vector<Uniform> &p_uniforms, RID p_shader, uint32_t p_shader_set) {
  3836. _THREAD_SAFE_METHOD_
  3837. ERR_FAIL_COND_V(p_uniforms.size() == 0, RID());
  3838. Shader *shader = shader_owner.getornull(p_shader);
  3839. ERR_FAIL_COND_V(!shader, RID());
  3840. ERR_FAIL_COND_V_MSG(p_shader_set >= (uint32_t)shader->sets.size() || shader->sets[p_shader_set].uniform_info.size() == 0, RID(),
  3841. "Desired set (" + itos(p_shader_set) + ") not used by shader.");
  3842. //see that all sets in shader are satisfied
  3843. const Shader::Set &set = shader->sets[p_shader_set];
  3844. uint32_t uniform_count = p_uniforms.size();
  3845. const Uniform *uniforms = p_uniforms.ptr();
  3846. uint32_t set_uniform_count = set.uniform_info.size();
  3847. const UniformInfo *set_uniforms = set.uniform_info.ptr();
  3848. Vector<VkWriteDescriptorSet> writes;
  3849. DescriptorPoolKey pool_key;
  3850. //to keep them alive until update call
  3851. List<Vector<VkDescriptorBufferInfo>> buffer_infos;
  3852. List<Vector<VkBufferView>> buffer_views;
  3853. List<Vector<VkDescriptorImageInfo>> image_infos;
  3854. //used for verification to make sure a uniform set does not use a framebuffer bound texture
  3855. Vector<RID> attachable_textures;
  3856. Vector<Texture *> mutable_sampled_textures;
  3857. Vector<Texture *> mutable_storage_textures;
  3858. for (uint32_t i = 0; i < set_uniform_count; i++) {
  3859. const UniformInfo &set_uniform = set_uniforms[i];
  3860. int uniform_idx = -1;
  3861. for (int j = 0; j < (int)uniform_count; j++) {
  3862. if (uniforms[j].binding == set_uniform.binding) {
  3863. uniform_idx = j;
  3864. }
  3865. }
  3866. ERR_FAIL_COND_V_MSG(uniform_idx == -1, RID(),
  3867. "All the shader bindings for the given set must be covered by the uniforms provided. Binding (" + itos(set_uniform.binding) + ") was not provided.");
  3868. const Uniform &uniform = uniforms[uniform_idx];
  3869. ERR_FAIL_COND_V_MSG(uniform.type != set_uniform.type, RID(),
  3870. "Mismatch uniform type for binding (" + itos(set_uniform.binding) + "). Expected '" + shader_uniform_names[set_uniform.type] + "', supplied: '" + shader_uniform_names[uniform.type] + "'.");
  3871. VkWriteDescriptorSet write; //common header
  3872. write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  3873. write.pNext = nullptr;
  3874. write.dstSet = VK_NULL_HANDLE; //will assign afterwards when everything is valid
  3875. write.dstBinding = set_uniform.binding;
  3876. write.dstArrayElement = 0;
  3877. write.descriptorCount = 0;
  3878. write.descriptorType = VK_DESCRIPTOR_TYPE_MAX_ENUM; //Invalid value.
  3879. write.pImageInfo = nullptr;
  3880. write.pBufferInfo = nullptr;
  3881. write.pTexelBufferView = nullptr;
  3882. uint32_t type_size = 1;
  3883. switch (uniform.type) {
  3884. case UNIFORM_TYPE_SAMPLER: {
  3885. if (uniform.ids.size() != set_uniform.length) {
  3886. if (set_uniform.length > 1) {
  3887. 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()) + ").");
  3888. } else {
  3889. ERR_FAIL_V_MSG(RID(), "Sampler (binding: " + itos(uniform.binding) + ") should provide one ID referencing a sampler (IDs provided: " + itos(uniform.ids.size()) + ").");
  3890. }
  3891. }
  3892. Vector<VkDescriptorImageInfo> image_info;
  3893. for (int j = 0; j < uniform.ids.size(); j++) {
  3894. VkSampler *sampler = sampler_owner.getornull(uniform.ids[j]);
  3895. ERR_FAIL_COND_V_MSG(!sampler, RID(), "Sampler (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid sampler.");
  3896. VkDescriptorImageInfo img_info;
  3897. img_info.sampler = *sampler;
  3898. img_info.imageView = VK_NULL_HANDLE;
  3899. img_info.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  3900. image_info.push_back(img_info);
  3901. }
  3902. write.dstArrayElement = 0;
  3903. write.descriptorCount = uniform.ids.size();
  3904. write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  3905. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  3906. write.pBufferInfo = nullptr;
  3907. write.pTexelBufferView = nullptr;
  3908. type_size = uniform.ids.size();
  3909. } break;
  3910. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {
  3911. if (uniform.ids.size() != set_uniform.length * 2) {
  3912. if (set_uniform.length > 1) {
  3913. 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()) + ").");
  3914. } else {
  3915. 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()) + ").");
  3916. }
  3917. }
  3918. Vector<VkDescriptorImageInfo> image_info;
  3919. for (int j = 0; j < uniform.ids.size(); j += 2) {
  3920. VkSampler *sampler = sampler_owner.getornull(uniform.ids[j + 0]);
  3921. ERR_FAIL_COND_V_MSG(!sampler, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler.");
  3922. Texture *texture = texture_owner.getornull(uniform.ids[j + 1]);
  3923. ERR_FAIL_COND_V_MSG(!texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  3924. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  3925. "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  3926. VkDescriptorImageInfo img_info;
  3927. img_info.sampler = *sampler;
  3928. img_info.imageView = texture->view;
  3929. if (texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_RESOLVE_ATTACHMENT_BIT)) {
  3930. attachable_textures.push_back(texture->owner.is_valid() ? texture->owner : uniform.ids[j + 1]);
  3931. }
  3932. if (texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  3933. //can also be used as storage, add to mutable sampled
  3934. mutable_sampled_textures.push_back(texture);
  3935. }
  3936. if (texture->owner.is_valid()) {
  3937. texture = texture_owner.getornull(texture->owner);
  3938. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  3939. }
  3940. img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  3941. image_info.push_back(img_info);
  3942. }
  3943. write.dstArrayElement = 0;
  3944. write.descriptorCount = uniform.ids.size() / 2;
  3945. write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  3946. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  3947. write.pBufferInfo = nullptr;
  3948. write.pTexelBufferView = nullptr;
  3949. type_size = uniform.ids.size() / 2;
  3950. } break;
  3951. case UNIFORM_TYPE_TEXTURE: {
  3952. if (uniform.ids.size() != set_uniform.length) {
  3953. if (set_uniform.length > 1) {
  3954. 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()) + ").");
  3955. } else {
  3956. ERR_FAIL_V_MSG(RID(), "Texture (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.ids.size()) + ").");
  3957. }
  3958. }
  3959. Vector<VkDescriptorImageInfo> image_info;
  3960. for (int j = 0; j < uniform.ids.size(); j++) {
  3961. Texture *texture = texture_owner.getornull(uniform.ids[j]);
  3962. ERR_FAIL_COND_V_MSG(!texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  3963. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  3964. "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  3965. VkDescriptorImageInfo img_info;
  3966. img_info.sampler = VK_NULL_HANDLE;
  3967. img_info.imageView = texture->view;
  3968. if (texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_RESOLVE_ATTACHMENT_BIT)) {
  3969. attachable_textures.push_back(texture->owner.is_valid() ? texture->owner : uniform.ids[j]);
  3970. }
  3971. if (texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  3972. //can also be used as storage, add to mutable sampled
  3973. mutable_sampled_textures.push_back(texture);
  3974. }
  3975. if (texture->owner.is_valid()) {
  3976. texture = texture_owner.getornull(texture->owner);
  3977. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  3978. }
  3979. img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  3980. image_info.push_back(img_info);
  3981. }
  3982. write.dstArrayElement = 0;
  3983. write.descriptorCount = uniform.ids.size();
  3984. write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  3985. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  3986. write.pBufferInfo = nullptr;
  3987. write.pTexelBufferView = nullptr;
  3988. type_size = uniform.ids.size();
  3989. } break;
  3990. case UNIFORM_TYPE_IMAGE: {
  3991. if (uniform.ids.size() != set_uniform.length) {
  3992. if (set_uniform.length > 1) {
  3993. 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()) + ").");
  3994. } else {
  3995. ERR_FAIL_V_MSG(RID(), "Image (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.ids.size()) + ").");
  3996. }
  3997. }
  3998. Vector<VkDescriptorImageInfo> image_info;
  3999. for (int j = 0; j < uniform.ids.size(); j++) {
  4000. Texture *texture = texture_owner.getornull(uniform.ids[j]);
  4001. ERR_FAIL_COND_V_MSG(!texture, RID(),
  4002. "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  4003. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), RID(),
  4004. "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_STORAGE_BIT usage flag set in order to be used as uniform.");
  4005. VkDescriptorImageInfo img_info;
  4006. img_info.sampler = VK_NULL_HANDLE;
  4007. img_info.imageView = texture->view;
  4008. if (texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT) {
  4009. //can also be used as storage, add to mutable sampled
  4010. mutable_storage_textures.push_back(texture);
  4011. }
  4012. if (texture->owner.is_valid()) {
  4013. texture = texture_owner.getornull(texture->owner);
  4014. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  4015. }
  4016. img_info.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
  4017. image_info.push_back(img_info);
  4018. }
  4019. write.dstArrayElement = 0;
  4020. write.descriptorCount = uniform.ids.size();
  4021. write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  4022. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  4023. write.pBufferInfo = nullptr;
  4024. write.pTexelBufferView = nullptr;
  4025. type_size = uniform.ids.size();
  4026. } break;
  4027. case UNIFORM_TYPE_TEXTURE_BUFFER: {
  4028. if (uniform.ids.size() != set_uniform.length) {
  4029. if (set_uniform.length > 1) {
  4030. 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()) + ").");
  4031. } else {
  4032. ERR_FAIL_V_MSG(RID(), "Buffer (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture buffer (IDs provided: " + itos(uniform.ids.size()) + ").");
  4033. }
  4034. }
  4035. Vector<VkDescriptorBufferInfo> buffer_info;
  4036. Vector<VkBufferView> buffer_view;
  4037. for (int j = 0; j < uniform.ids.size(); j++) {
  4038. TextureBuffer *buffer = texture_buffer_owner.getornull(uniform.ids[j]);
  4039. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Texture Buffer (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture buffer.");
  4040. buffer_info.push_back(buffer->buffer.buffer_info);
  4041. buffer_view.push_back(buffer->view);
  4042. }
  4043. write.dstArrayElement = 0;
  4044. write.descriptorCount = uniform.ids.size();
  4045. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  4046. write.pImageInfo = nullptr;
  4047. write.pBufferInfo = buffer_infos.push_back(buffer_info)->get().ptr();
  4048. write.pTexelBufferView = buffer_views.push_back(buffer_view)->get().ptr();
  4049. type_size = uniform.ids.size();
  4050. } break;
  4051. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {
  4052. if (uniform.ids.size() != set_uniform.length * 2) {
  4053. if (set_uniform.length > 1) {
  4054. 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()) + ").");
  4055. } else {
  4056. 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()) + ").");
  4057. }
  4058. }
  4059. Vector<VkDescriptorImageInfo> image_info;
  4060. Vector<VkDescriptorBufferInfo> buffer_info;
  4061. Vector<VkBufferView> buffer_view;
  4062. for (int j = 0; j < uniform.ids.size(); j += 2) {
  4063. VkSampler *sampler = sampler_owner.getornull(uniform.ids[j + 0]);
  4064. ERR_FAIL_COND_V_MSG(!sampler, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler.");
  4065. TextureBuffer *buffer = texture_buffer_owner.getornull(uniform.ids[j + 1]);
  4066. VkDescriptorImageInfo img_info;
  4067. img_info.sampler = *sampler;
  4068. img_info.imageView = VK_NULL_HANDLE;
  4069. img_info.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  4070. image_info.push_back(img_info);
  4071. ERR_FAIL_COND_V_MSG(!buffer, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid texture buffer.");
  4072. buffer_info.push_back(buffer->buffer.buffer_info);
  4073. buffer_view.push_back(buffer->view);
  4074. }
  4075. write.dstArrayElement = 0;
  4076. write.descriptorCount = uniform.ids.size() / 2;
  4077. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  4078. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  4079. write.pBufferInfo = buffer_infos.push_back(buffer_info)->get().ptr();
  4080. write.pTexelBufferView = buffer_views.push_back(buffer_view)->get().ptr();
  4081. type_size = uniform.ids.size() / 2;
  4082. } break;
  4083. case UNIFORM_TYPE_IMAGE_BUFFER: {
  4084. //todo
  4085. } break;
  4086. case UNIFORM_TYPE_UNIFORM_BUFFER: {
  4087. ERR_FAIL_COND_V_MSG(uniform.ids.size() != 1, RID(),
  4088. "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.ids.size()) + " provided).");
  4089. Buffer *buffer = uniform_buffer_owner.getornull(uniform.ids[0]);
  4090. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") is invalid.");
  4091. ERR_FAIL_COND_V_MSG(buffer->size != (uint32_t)set_uniform.length, RID(),
  4092. "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " does not match size of shader uniform: (" + itos(set_uniform.length) + ").");
  4093. write.dstArrayElement = 0;
  4094. write.descriptorCount = 1;
  4095. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  4096. write.pImageInfo = nullptr;
  4097. write.pBufferInfo = &buffer->buffer_info;
  4098. write.pTexelBufferView = nullptr;
  4099. } break;
  4100. case UNIFORM_TYPE_STORAGE_BUFFER: {
  4101. ERR_FAIL_COND_V_MSG(uniform.ids.size() != 1, RID(),
  4102. "Storage buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.ids.size()) + " provided).");
  4103. Buffer *buffer = storage_buffer_owner.getornull(uniform.ids[0]);
  4104. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Storage buffer supplied (binding: " + itos(uniform.binding) + ") is invalid.");
  4105. //if 0, then its sized on link time
  4106. ERR_FAIL_COND_V_MSG(set_uniform.length > 0 && buffer->size != (uint32_t)set_uniform.length, RID(),
  4107. "Storage buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " does not match size of shader uniform: (" + itos(set_uniform.length) + ").");
  4108. write.dstArrayElement = 0;
  4109. write.descriptorCount = 1;
  4110. write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  4111. write.pImageInfo = nullptr;
  4112. write.pBufferInfo = &buffer->buffer_info;
  4113. write.pTexelBufferView = nullptr;
  4114. } break;
  4115. case UNIFORM_TYPE_INPUT_ATTACHMENT: {
  4116. } break;
  4117. default: {
  4118. }
  4119. }
  4120. writes.push_back(write);
  4121. ERR_FAIL_COND_V_MSG(pool_key.uniform_type[set_uniform.type] == MAX_DESCRIPTOR_POOL_ELEMENT, RID(),
  4122. "Uniform set reached the limit of bindings for the same type (" + itos(MAX_DESCRIPTOR_POOL_ELEMENT) + ").");
  4123. pool_key.uniform_type[set_uniform.type] += type_size;
  4124. }
  4125. //need a descriptor pool
  4126. DescriptorPool *pool = _descriptor_pool_allocate(pool_key);
  4127. ERR_FAIL_COND_V(!pool, RID());
  4128. VkDescriptorSetAllocateInfo descriptor_set_allocate_info;
  4129. descriptor_set_allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
  4130. descriptor_set_allocate_info.pNext = nullptr;
  4131. descriptor_set_allocate_info.descriptorPool = pool->pool;
  4132. descriptor_set_allocate_info.descriptorSetCount = 1;
  4133. descriptor_set_allocate_info.pSetLayouts = &shader->sets[p_shader_set].descriptor_set_layout;
  4134. VkDescriptorSet descriptor_set;
  4135. VkResult res = vkAllocateDescriptorSets(device, &descriptor_set_allocate_info, &descriptor_set);
  4136. if (res) {
  4137. _descriptor_pool_free(pool_key, pool); // meh
  4138. ERR_FAIL_V_MSG(RID(), "Cannot allocate descriptor sets, error " + itos(res) + ".");
  4139. }
  4140. UniformSet uniform_set;
  4141. uniform_set.pool = pool;
  4142. uniform_set.pool_key = pool_key;
  4143. uniform_set.descriptor_set = descriptor_set;
  4144. uniform_set.format = shader->set_formats[p_shader_set];
  4145. uniform_set.attachable_textures = attachable_textures;
  4146. uniform_set.mutable_sampled_textures = mutable_sampled_textures;
  4147. uniform_set.mutable_storage_textures = mutable_storage_textures;
  4148. uniform_set.shader_set = p_shader_set;
  4149. uniform_set.shader_id = p_shader;
  4150. RID id = uniform_set_owner.make_rid(uniform_set);
  4151. //add dependencies
  4152. _add_dependency(id, p_shader);
  4153. for (uint32_t i = 0; i < uniform_count; i++) {
  4154. const Uniform &uniform = uniforms[i];
  4155. int id_count = uniform.ids.size();
  4156. const RID *ids = uniform.ids.ptr();
  4157. for (int j = 0; j < id_count; j++) {
  4158. _add_dependency(id, ids[j]);
  4159. }
  4160. }
  4161. //write the contents
  4162. if (writes.size()) {
  4163. for (int i = 0; i < writes.size(); i++) {
  4164. writes.write[i].dstSet = descriptor_set;
  4165. }
  4166. vkUpdateDescriptorSets(device, writes.size(), writes.ptr(), 0, nullptr);
  4167. }
  4168. return id;
  4169. }
  4170. bool RenderingDeviceVulkan::uniform_set_is_valid(RID p_uniform_set) {
  4171. return uniform_set_owner.owns(p_uniform_set);
  4172. }
  4173. Error RenderingDeviceVulkan::buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, bool p_sync_with_draw) {
  4174. _THREAD_SAFE_METHOD_
  4175. ERR_FAIL_COND_V_MSG(draw_list && p_sync_with_draw, ERR_INVALID_PARAMETER,
  4176. "Updating buffers in 'sync to draw' mode is forbidden during creation of a draw list");
  4177. VkPipelineStageFlags dst_stage_mask;
  4178. VkAccessFlags dst_access;
  4179. Buffer *buffer = nullptr;
  4180. if (vertex_buffer_owner.owns(p_buffer)) {
  4181. dst_stage_mask = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  4182. dst_access = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
  4183. buffer = vertex_buffer_owner.getornull(p_buffer);
  4184. } else if (index_buffer_owner.owns(p_buffer)) {
  4185. dst_stage_mask = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  4186. dst_access = VK_ACCESS_INDEX_READ_BIT;
  4187. buffer = index_buffer_owner.getornull(p_buffer);
  4188. } else if (uniform_buffer_owner.owns(p_buffer)) {
  4189. dst_stage_mask = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  4190. dst_access = VK_ACCESS_UNIFORM_READ_BIT;
  4191. buffer = uniform_buffer_owner.getornull(p_buffer);
  4192. } else if (texture_buffer_owner.owns(p_buffer)) {
  4193. dst_stage_mask = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  4194. dst_access = VK_ACCESS_SHADER_READ_BIT;
  4195. buffer = &texture_buffer_owner.getornull(p_buffer)->buffer;
  4196. } else if (storage_buffer_owner.owns(p_buffer)) {
  4197. dst_stage_mask = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  4198. dst_access = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  4199. buffer = storage_buffer_owner.getornull(p_buffer);
  4200. } else {
  4201. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type.");
  4202. }
  4203. ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER,
  4204. "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end.");
  4205. Error err = _buffer_update(buffer, p_offset, (uint8_t *)p_data, p_size, p_sync_with_draw);
  4206. if (err) {
  4207. return err;
  4208. }
  4209. _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);
  4210. #ifdef FORCE_FULL_BARRIER
  4211. _full_barrier(p_sync_with_draw);
  4212. #else
  4213. _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);
  4214. #endif
  4215. return err;
  4216. }
  4217. Vector<uint8_t> RenderingDeviceVulkan::buffer_get_data(RID p_buffer) {
  4218. _THREAD_SAFE_METHOD_
  4219. Buffer *buffer = nullptr;
  4220. if (vertex_buffer_owner.owns(p_buffer)) {
  4221. buffer = vertex_buffer_owner.getornull(p_buffer);
  4222. } else if (index_buffer_owner.owns(p_buffer)) {
  4223. buffer = index_buffer_owner.getornull(p_buffer);
  4224. } else if (texture_buffer_owner.owns(p_buffer)) {
  4225. buffer = &texture_buffer_owner.getornull(p_buffer)->buffer;
  4226. } else if (storage_buffer_owner.owns(p_buffer)) {
  4227. buffer = storage_buffer_owner.getornull(p_buffer);
  4228. } else {
  4229. 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.");
  4230. }
  4231. VkCommandBuffer command_buffer = frames[frame].setup_command_buffer;
  4232. Buffer tmp_buffer;
  4233. _buffer_allocate(&tmp_buffer, buffer->size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_CPU_ONLY);
  4234. VkBufferCopy region;
  4235. region.srcOffset = 0;
  4236. region.dstOffset = 0;
  4237. region.size = buffer->size;
  4238. 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..
  4239. //flush everything so memory can be safely mapped
  4240. _flush(true);
  4241. void *buffer_mem;
  4242. VkResult vkerr = vmaMapMemory(allocator, tmp_buffer.allocation, &buffer_mem);
  4243. ERR_FAIL_COND_V_MSG(vkerr, Vector<uint8_t>(), "vmaMapMemory failed with error " + itos(vkerr) + ".");
  4244. Vector<uint8_t> buffer_data;
  4245. {
  4246. buffer_data.resize(buffer->size);
  4247. uint8_t *w = buffer_data.ptrw();
  4248. copymem(w, buffer_mem, buffer->size);
  4249. }
  4250. vmaUnmapMemory(allocator, tmp_buffer.allocation);
  4251. _buffer_free(&tmp_buffer);
  4252. return buffer_data;
  4253. }
  4254. /*************************/
  4255. /**** RENDER PIPELINE ****/
  4256. /*************************/
  4257. 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) {
  4258. _THREAD_SAFE_METHOD_
  4259. //needs a shader
  4260. Shader *shader = shader_owner.getornull(p_shader);
  4261. ERR_FAIL_COND_V(!shader, RID());
  4262. ERR_FAIL_COND_V_MSG(shader->is_compute, RID(),
  4263. "Compute shaders can't be used in render pipelines");
  4264. if (p_framebuffer_format == INVALID_ID) {
  4265. //if nothing provided, use an empty one (no attachments)
  4266. p_framebuffer_format = framebuffer_format_create(Vector<AttachmentFormat>());
  4267. }
  4268. ERR_FAIL_COND_V(!framebuffer_formats.has(p_framebuffer_format), RID());
  4269. const FramebufferFormat &fb_format = framebuffer_formats[p_framebuffer_format];
  4270. { //validate shader vs framebuffer
  4271. ERR_FAIL_COND_V_MSG(shader->fragment_outputs != fb_format.color_attachments, RID(),
  4272. "Mismatch fragment output bindings (" + itos(shader->fragment_outputs) + ") and framebuffer color buffers (" + itos(fb_format.color_attachments) + ") when binding both in render pipeline.");
  4273. }
  4274. //vertex
  4275. VkPipelineVertexInputStateCreateInfo pipeline_vertex_input_state_create_info;
  4276. if (p_vertex_format != INVALID_ID) {
  4277. //uses vertices, else it does not
  4278. ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID());
  4279. const VertexDescriptionCache &vd = vertex_formats[p_vertex_format];
  4280. pipeline_vertex_input_state_create_info = vd.create_info;
  4281. //validate with inputs
  4282. for (uint32_t i = 0; i < 32; i++) {
  4283. if (!(shader->vertex_input_mask & (1 << i))) {
  4284. continue;
  4285. }
  4286. bool found = false;
  4287. for (int j = 0; j < vd.vertex_formats.size(); j++) {
  4288. if (vd.vertex_formats[j].location == i) {
  4289. found = true;
  4290. }
  4291. }
  4292. ERR_FAIL_COND_V_MSG(!found, RID(),
  4293. "Shader vertex input location (" + itos(i) + ") not provided in vertex input description for pipeline creation.");
  4294. }
  4295. } else {
  4296. //does not use vertices
  4297. pipeline_vertex_input_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  4298. pipeline_vertex_input_state_create_info.pNext = nullptr;
  4299. pipeline_vertex_input_state_create_info.flags = 0;
  4300. pipeline_vertex_input_state_create_info.vertexBindingDescriptionCount = 0;
  4301. pipeline_vertex_input_state_create_info.pVertexBindingDescriptions = nullptr;
  4302. pipeline_vertex_input_state_create_info.vertexAttributeDescriptionCount = 0;
  4303. pipeline_vertex_input_state_create_info.pVertexAttributeDescriptions = nullptr;
  4304. ERR_FAIL_COND_V_MSG(shader->vertex_input_mask != 0, RID(),
  4305. "Shader contains vertex inputs, but no vertex input description was provided for pipeline creation.");
  4306. }
  4307. //input assembly
  4308. ERR_FAIL_INDEX_V(p_render_primitive, RENDER_PRIMITIVE_MAX, RID());
  4309. VkPipelineInputAssemblyStateCreateInfo input_assembly_create_info;
  4310. input_assembly_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  4311. input_assembly_create_info.pNext = nullptr;
  4312. input_assembly_create_info.flags = 0;
  4313. static const VkPrimitiveTopology topology_list[RENDER_PRIMITIVE_MAX] = {
  4314. VK_PRIMITIVE_TOPOLOGY_POINT_LIST,
  4315. VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
  4316. VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY,
  4317. VK_PRIMITIVE_TOPOLOGY_LINE_STRIP,
  4318. VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY,
  4319. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
  4320. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY,
  4321. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
  4322. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY,
  4323. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
  4324. VK_PRIMITIVE_TOPOLOGY_PATCH_LIST
  4325. };
  4326. input_assembly_create_info.topology = topology_list[p_render_primitive];
  4327. input_assembly_create_info.primitiveRestartEnable = (p_render_primitive == RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX);
  4328. //tesselation
  4329. VkPipelineTessellationStateCreateInfo tesselation_create_info;
  4330. tesselation_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO;
  4331. tesselation_create_info.pNext = nullptr;
  4332. tesselation_create_info.flags = 0;
  4333. ERR_FAIL_COND_V(p_rasterization_state.patch_control_points < 1 || p_rasterization_state.patch_control_points > limits.maxTessellationPatchSize, RID());
  4334. tesselation_create_info.patchControlPoints = p_rasterization_state.patch_control_points;
  4335. VkPipelineViewportStateCreateInfo viewport_state_create_info;
  4336. viewport_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  4337. viewport_state_create_info.pNext = nullptr;
  4338. viewport_state_create_info.flags = 0;
  4339. viewport_state_create_info.viewportCount = 1; //if VR extensions are supported at some point, this will have to be customizable in the framebuffer format
  4340. viewport_state_create_info.pViewports = nullptr;
  4341. viewport_state_create_info.scissorCount = 1;
  4342. viewport_state_create_info.pScissors = nullptr;
  4343. //rasterization
  4344. VkPipelineRasterizationStateCreateInfo rasterization_state_create_info;
  4345. rasterization_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  4346. rasterization_state_create_info.pNext = nullptr;
  4347. rasterization_state_create_info.flags = 0;
  4348. rasterization_state_create_info.depthClampEnable = p_rasterization_state.enable_depth_clamp;
  4349. rasterization_state_create_info.rasterizerDiscardEnable = p_rasterization_state.discard_primitives;
  4350. rasterization_state_create_info.polygonMode = (p_rasterization_state.wireframe ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL);
  4351. static VkCullModeFlags cull_mode[3] = {
  4352. VK_CULL_MODE_NONE,
  4353. VK_CULL_MODE_FRONT_BIT,
  4354. VK_CULL_MODE_BACK_BIT
  4355. };
  4356. ERR_FAIL_INDEX_V(p_rasterization_state.cull_mode, 3, RID());
  4357. rasterization_state_create_info.cullMode = cull_mode[p_rasterization_state.cull_mode];
  4358. rasterization_state_create_info.frontFace = (p_rasterization_state.front_face == POLYGON_FRONT_FACE_CLOCKWISE ? VK_FRONT_FACE_CLOCKWISE : VK_FRONT_FACE_COUNTER_CLOCKWISE);
  4359. rasterization_state_create_info.depthBiasEnable = p_rasterization_state.depth_bias_enable;
  4360. rasterization_state_create_info.depthBiasConstantFactor = p_rasterization_state.depth_bias_constant_factor;
  4361. rasterization_state_create_info.depthBiasClamp = p_rasterization_state.depth_bias_clamp;
  4362. rasterization_state_create_info.depthBiasSlopeFactor = p_rasterization_state.depth_bias_slope_factor;
  4363. rasterization_state_create_info.lineWidth = p_rasterization_state.line_width;
  4364. //multisample
  4365. VkPipelineMultisampleStateCreateInfo multisample_state_create_info;
  4366. multisample_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  4367. multisample_state_create_info.pNext = nullptr;
  4368. multisample_state_create_info.flags = 0;
  4369. multisample_state_create_info.rasterizationSamples = rasterization_sample_count[p_multisample_state.sample_count];
  4370. multisample_state_create_info.sampleShadingEnable = p_multisample_state.enable_sample_shading;
  4371. multisample_state_create_info.minSampleShading = p_multisample_state.min_sample_shading;
  4372. Vector<VkSampleMask> sample_mask;
  4373. if (p_multisample_state.sample_mask.size()) {
  4374. //use sample mask
  4375. int rasterization_sample_mask_expected_size[TEXTURE_SAMPLES_MAX] = {
  4376. 1, 2, 4, 8, 16, 32, 64
  4377. };
  4378. ERR_FAIL_COND_V(rasterization_sample_mask_expected_size[p_multisample_state.sample_count] != p_multisample_state.sample_mask.size(), RID());
  4379. sample_mask.resize(p_multisample_state.sample_mask.size());
  4380. for (int i = 0; i < p_multisample_state.sample_mask.size(); i++) {
  4381. VkSampleMask mask = p_multisample_state.sample_mask[i];
  4382. sample_mask.push_back(mask);
  4383. }
  4384. multisample_state_create_info.pSampleMask = sample_mask.ptr();
  4385. } else {
  4386. multisample_state_create_info.pSampleMask = nullptr;
  4387. }
  4388. multisample_state_create_info.alphaToCoverageEnable = p_multisample_state.enable_alpha_to_coverage;
  4389. multisample_state_create_info.alphaToOneEnable = p_multisample_state.enable_alpha_to_one;
  4390. //depth stencil
  4391. VkPipelineDepthStencilStateCreateInfo depth_stencil_state_create_info;
  4392. depth_stencil_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  4393. depth_stencil_state_create_info.pNext = nullptr;
  4394. depth_stencil_state_create_info.flags = 0;
  4395. depth_stencil_state_create_info.depthTestEnable = p_depth_stencil_state.enable_depth_test;
  4396. depth_stencil_state_create_info.depthWriteEnable = p_depth_stencil_state.enable_depth_write;
  4397. ERR_FAIL_INDEX_V(p_depth_stencil_state.depth_compare_operator, COMPARE_OP_MAX, RID());
  4398. depth_stencil_state_create_info.depthCompareOp = compare_operators[p_depth_stencil_state.depth_compare_operator];
  4399. depth_stencil_state_create_info.depthBoundsTestEnable = p_depth_stencil_state.enable_depth_range;
  4400. depth_stencil_state_create_info.stencilTestEnable = p_depth_stencil_state.enable_stencil;
  4401. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.fail, STENCIL_OP_MAX, RID());
  4402. depth_stencil_state_create_info.front.failOp = stencil_operations[p_depth_stencil_state.front_op.fail];
  4403. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.pass, STENCIL_OP_MAX, RID());
  4404. depth_stencil_state_create_info.front.passOp = stencil_operations[p_depth_stencil_state.front_op.pass];
  4405. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.depth_fail, STENCIL_OP_MAX, RID());
  4406. depth_stencil_state_create_info.front.depthFailOp = stencil_operations[p_depth_stencil_state.front_op.depth_fail];
  4407. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.compare, COMPARE_OP_MAX, RID());
  4408. depth_stencil_state_create_info.front.compareOp = compare_operators[p_depth_stencil_state.front_op.compare];
  4409. depth_stencil_state_create_info.front.compareMask = p_depth_stencil_state.front_op.compare_mask;
  4410. depth_stencil_state_create_info.front.writeMask = p_depth_stencil_state.front_op.write_mask;
  4411. depth_stencil_state_create_info.front.reference = p_depth_stencil_state.front_op.reference;
  4412. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.fail, STENCIL_OP_MAX, RID());
  4413. depth_stencil_state_create_info.back.failOp = stencil_operations[p_depth_stencil_state.back_op.fail];
  4414. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.pass, STENCIL_OP_MAX, RID());
  4415. depth_stencil_state_create_info.back.passOp = stencil_operations[p_depth_stencil_state.back_op.pass];
  4416. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.depth_fail, STENCIL_OP_MAX, RID());
  4417. depth_stencil_state_create_info.back.depthFailOp = stencil_operations[p_depth_stencil_state.back_op.depth_fail];
  4418. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.compare, COMPARE_OP_MAX, RID());
  4419. depth_stencil_state_create_info.back.compareOp = compare_operators[p_depth_stencil_state.back_op.compare];
  4420. depth_stencil_state_create_info.back.compareMask = p_depth_stencil_state.back_op.compare_mask;
  4421. depth_stencil_state_create_info.back.writeMask = p_depth_stencil_state.back_op.write_mask;
  4422. depth_stencil_state_create_info.back.reference = p_depth_stencil_state.back_op.reference;
  4423. depth_stencil_state_create_info.minDepthBounds = p_depth_stencil_state.depth_range_min;
  4424. depth_stencil_state_create_info.maxDepthBounds = p_depth_stencil_state.depth_range_max;
  4425. //blend state
  4426. VkPipelineColorBlendStateCreateInfo color_blend_state_create_info;
  4427. color_blend_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  4428. color_blend_state_create_info.pNext = nullptr;
  4429. color_blend_state_create_info.flags = 0;
  4430. color_blend_state_create_info.logicOpEnable = p_blend_state.enable_logic_op;
  4431. ERR_FAIL_INDEX_V(p_blend_state.logic_op, LOGIC_OP_MAX, RID());
  4432. color_blend_state_create_info.logicOp = logic_operations[p_blend_state.logic_op];
  4433. ERR_FAIL_COND_V(fb_format.color_attachments != p_blend_state.attachments.size(), RID());
  4434. Vector<VkPipelineColorBlendAttachmentState> attachment_states;
  4435. for (int i = 0; i < p_blend_state.attachments.size(); i++) {
  4436. VkPipelineColorBlendAttachmentState state;
  4437. state.blendEnable = p_blend_state.attachments[i].enable_blend;
  4438. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_color_blend_factor, BLEND_FACTOR_MAX, RID());
  4439. state.srcColorBlendFactor = blend_factors[p_blend_state.attachments[i].src_color_blend_factor];
  4440. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_color_blend_factor, BLEND_FACTOR_MAX, RID());
  4441. state.dstColorBlendFactor = blend_factors[p_blend_state.attachments[i].dst_color_blend_factor];
  4442. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].color_blend_op, BLEND_OP_MAX, RID());
  4443. state.colorBlendOp = blend_operations[p_blend_state.attachments[i].color_blend_op];
  4444. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_alpha_blend_factor, BLEND_FACTOR_MAX, RID());
  4445. state.srcAlphaBlendFactor = blend_factors[p_blend_state.attachments[i].src_alpha_blend_factor];
  4446. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_alpha_blend_factor, BLEND_FACTOR_MAX, RID());
  4447. state.dstAlphaBlendFactor = blend_factors[p_blend_state.attachments[i].dst_alpha_blend_factor];
  4448. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].alpha_blend_op, BLEND_OP_MAX, RID());
  4449. state.alphaBlendOp = blend_operations[p_blend_state.attachments[i].alpha_blend_op];
  4450. state.colorWriteMask = 0;
  4451. if (p_blend_state.attachments[i].write_r) {
  4452. state.colorWriteMask |= VK_COLOR_COMPONENT_R_BIT;
  4453. }
  4454. if (p_blend_state.attachments[i].write_g) {
  4455. state.colorWriteMask |= VK_COLOR_COMPONENT_G_BIT;
  4456. }
  4457. if (p_blend_state.attachments[i].write_b) {
  4458. state.colorWriteMask |= VK_COLOR_COMPONENT_B_BIT;
  4459. }
  4460. if (p_blend_state.attachments[i].write_a) {
  4461. state.colorWriteMask |= VK_COLOR_COMPONENT_A_BIT;
  4462. }
  4463. attachment_states.push_back(state);
  4464. };
  4465. color_blend_state_create_info.attachmentCount = attachment_states.size();
  4466. color_blend_state_create_info.pAttachments = attachment_states.ptr();
  4467. color_blend_state_create_info.blendConstants[0] = p_blend_state.blend_constant.r;
  4468. color_blend_state_create_info.blendConstants[1] = p_blend_state.blend_constant.g;
  4469. color_blend_state_create_info.blendConstants[2] = p_blend_state.blend_constant.b;
  4470. color_blend_state_create_info.blendConstants[3] = p_blend_state.blend_constant.a;
  4471. //dynamic state
  4472. VkPipelineDynamicStateCreateInfo dynamic_state_create_info;
  4473. dynamic_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
  4474. dynamic_state_create_info.pNext = nullptr;
  4475. dynamic_state_create_info.flags = 0;
  4476. Vector<VkDynamicState> dynamic_states; //vulkan is weird..
  4477. dynamic_states.push_back(VK_DYNAMIC_STATE_VIEWPORT); //viewport and scissor are always dynamic
  4478. dynamic_states.push_back(VK_DYNAMIC_STATE_SCISSOR);
  4479. if (p_dynamic_state_flags & DYNAMIC_STATE_LINE_WIDTH) {
  4480. dynamic_states.push_back(VK_DYNAMIC_STATE_LINE_WIDTH);
  4481. }
  4482. if (p_dynamic_state_flags & DYNAMIC_STATE_DEPTH_BIAS) {
  4483. dynamic_states.push_back(VK_DYNAMIC_STATE_DEPTH_BIAS);
  4484. }
  4485. if (p_dynamic_state_flags & DYNAMIC_STATE_BLEND_CONSTANTS) {
  4486. dynamic_states.push_back(VK_DYNAMIC_STATE_BLEND_CONSTANTS);
  4487. }
  4488. if (p_dynamic_state_flags & DYNAMIC_STATE_DEPTH_BOUNDS) {
  4489. dynamic_states.push_back(VK_DYNAMIC_STATE_DEPTH_BOUNDS);
  4490. }
  4491. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_COMPARE_MASK) {
  4492. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK);
  4493. }
  4494. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_WRITE_MASK) {
  4495. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_WRITE_MASK);
  4496. }
  4497. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_REFERENCE) {
  4498. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_REFERENCE);
  4499. }
  4500. dynamic_state_create_info.dynamicStateCount = dynamic_states.size();
  4501. dynamic_state_create_info.pDynamicStates = dynamic_states.ptr();
  4502. //finally, pipeline create info
  4503. VkGraphicsPipelineCreateInfo graphics_pipeline_create_info;
  4504. graphics_pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  4505. graphics_pipeline_create_info.pNext = nullptr;
  4506. graphics_pipeline_create_info.flags = 0;
  4507. graphics_pipeline_create_info.stageCount = shader->pipeline_stages.size();
  4508. graphics_pipeline_create_info.pStages = shader->pipeline_stages.ptr();
  4509. graphics_pipeline_create_info.pVertexInputState = &pipeline_vertex_input_state_create_info;
  4510. graphics_pipeline_create_info.pInputAssemblyState = &input_assembly_create_info;
  4511. graphics_pipeline_create_info.pTessellationState = &tesselation_create_info;
  4512. graphics_pipeline_create_info.pViewportState = &viewport_state_create_info;
  4513. graphics_pipeline_create_info.pRasterizationState = &rasterization_state_create_info;
  4514. graphics_pipeline_create_info.pMultisampleState = &multisample_state_create_info;
  4515. graphics_pipeline_create_info.pDepthStencilState = &depth_stencil_state_create_info;
  4516. graphics_pipeline_create_info.pColorBlendState = &color_blend_state_create_info;
  4517. graphics_pipeline_create_info.pDynamicState = &dynamic_state_create_info;
  4518. graphics_pipeline_create_info.layout = shader->pipeline_layout;
  4519. graphics_pipeline_create_info.renderPass = fb_format.render_pass;
  4520. graphics_pipeline_create_info.subpass = 0;
  4521. graphics_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE;
  4522. graphics_pipeline_create_info.basePipelineIndex = 0;
  4523. RenderPipeline pipeline;
  4524. VkResult err = vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &graphics_pipeline_create_info, nullptr, &pipeline.pipeline);
  4525. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateGraphicsPipelines failed with error " + itos(err) + ".");
  4526. pipeline.set_formats = shader->set_formats;
  4527. pipeline.push_constant_stages = shader->push_constant.push_constants_vk_stage;
  4528. pipeline.pipeline_layout = shader->pipeline_layout;
  4529. pipeline.shader = p_shader;
  4530. pipeline.push_constant_size = shader->push_constant.push_constant_size;
  4531. #ifdef DEBUG_ENABLED
  4532. pipeline.validation.dynamic_state = p_dynamic_state_flags;
  4533. pipeline.validation.framebuffer_format = p_framebuffer_format;
  4534. pipeline.validation.vertex_format = p_vertex_format;
  4535. pipeline.validation.uses_restart_indices = input_assembly_create_info.primitiveRestartEnable;
  4536. static const uint32_t primitive_divisor[RENDER_PRIMITIVE_MAX] = {
  4537. 1, 2, 1, 1, 1, 3, 1, 1, 1, 1, 1
  4538. };
  4539. pipeline.validation.primitive_divisor = primitive_divisor[p_render_primitive];
  4540. static const uint32_t primitive_minimum[RENDER_PRIMITIVE_MAX] = {
  4541. 1,
  4542. 2,
  4543. 2,
  4544. 2,
  4545. 2,
  4546. 3,
  4547. 3,
  4548. 3,
  4549. 3,
  4550. 3,
  4551. 1,
  4552. };
  4553. pipeline.validation.primitive_minimum = primitive_minimum[p_render_primitive];
  4554. #endif
  4555. //create ID to associate with this pipeline
  4556. RID id = render_pipeline_owner.make_rid(pipeline);
  4557. //now add aall the dependencies
  4558. _add_dependency(id, p_shader);
  4559. return id;
  4560. }
  4561. bool RenderingDeviceVulkan::render_pipeline_is_valid(RID p_pipeline) {
  4562. _THREAD_SAFE_METHOD_
  4563. return render_pipeline_owner.owns(p_pipeline);
  4564. }
  4565. /**************************/
  4566. /**** COMPUTE PIPELINE ****/
  4567. /**************************/
  4568. RID RenderingDeviceVulkan::compute_pipeline_create(RID p_shader) {
  4569. _THREAD_SAFE_METHOD_
  4570. //needs a shader
  4571. Shader *shader = shader_owner.getornull(p_shader);
  4572. ERR_FAIL_COND_V(!shader, RID());
  4573. ERR_FAIL_COND_V_MSG(!shader->is_compute, RID(),
  4574. "Non-compute shaders can't be used in compute pipelines");
  4575. //finally, pipeline create info
  4576. VkComputePipelineCreateInfo compute_pipeline_create_info;
  4577. compute_pipeline_create_info.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
  4578. compute_pipeline_create_info.pNext = nullptr;
  4579. compute_pipeline_create_info.flags = 0;
  4580. compute_pipeline_create_info.stage = shader->pipeline_stages[0];
  4581. compute_pipeline_create_info.layout = shader->pipeline_layout;
  4582. compute_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE;
  4583. compute_pipeline_create_info.basePipelineIndex = 0;
  4584. ComputePipeline pipeline;
  4585. VkResult err = vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute_pipeline_create_info, nullptr, &pipeline.pipeline);
  4586. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateComputePipelines failed with error " + itos(err) + ".");
  4587. pipeline.set_formats = shader->set_formats;
  4588. pipeline.push_constant_stages = shader->push_constant.push_constants_vk_stage;
  4589. pipeline.pipeline_layout = shader->pipeline_layout;
  4590. pipeline.shader = p_shader;
  4591. pipeline.push_constant_size = shader->push_constant.push_constant_size;
  4592. //create ID to associate with this pipeline
  4593. RID id = compute_pipeline_owner.make_rid(pipeline);
  4594. //now add aall the dependencies
  4595. _add_dependency(id, p_shader);
  4596. return id;
  4597. }
  4598. bool RenderingDeviceVulkan::compute_pipeline_is_valid(RID p_pipeline) {
  4599. return compute_pipeline_owner.owns(p_pipeline);
  4600. }
  4601. /****************/
  4602. /**** SCREEN ****/
  4603. /****************/
  4604. int RenderingDeviceVulkan::screen_get_width(DisplayServer::WindowID p_screen) const {
  4605. _THREAD_SAFE_METHOD_
  4606. ERR_FAIL_COND_V_MSG(local_device.is_valid(), -1, "Local devices have no screen");
  4607. return context->window_get_width(p_screen);
  4608. }
  4609. int RenderingDeviceVulkan::screen_get_height(DisplayServer::WindowID p_screen) const {
  4610. _THREAD_SAFE_METHOD_
  4611. ERR_FAIL_COND_V_MSG(local_device.is_valid(), -1, "Local devices have no screen");
  4612. return context->window_get_height(p_screen);
  4613. }
  4614. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::screen_get_framebuffer_format() const {
  4615. _THREAD_SAFE_METHOD_
  4616. ERR_FAIL_COND_V_MSG(local_device.is_valid(), INVALID_ID, "Local devices have no screen");
  4617. //very hacky, but not used often per frame so I guess ok
  4618. VkFormat vkformat = context->get_screen_format();
  4619. DataFormat format = DATA_FORMAT_MAX;
  4620. for (int i = 0; i < DATA_FORMAT_MAX; i++) {
  4621. if (vkformat == vulkan_formats[i]) {
  4622. format = DataFormat(i);
  4623. break;
  4624. }
  4625. }
  4626. ERR_FAIL_COND_V(format == DATA_FORMAT_MAX, INVALID_ID);
  4627. AttachmentFormat attachment;
  4628. attachment.format = format;
  4629. attachment.samples = TEXTURE_SAMPLES_1;
  4630. attachment.usage_flags = TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  4631. Vector<AttachmentFormat> screen_attachment;
  4632. screen_attachment.push_back(attachment);
  4633. return const_cast<RenderingDeviceVulkan *>(this)->framebuffer_format_create(screen_attachment);
  4634. }
  4635. /*******************/
  4636. /**** DRAW LIST ****/
  4637. /*******************/
  4638. RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_begin_for_screen(DisplayServer::WindowID p_screen, const Color &p_clear_color) {
  4639. _THREAD_SAFE_METHOD_
  4640. ERR_FAIL_COND_V_MSG(local_device.is_valid(), INVALID_ID, "Local devices have no screen");
  4641. ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  4642. ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  4643. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  4644. draw_list = memnew(DrawList);
  4645. draw_list->command_buffer = command_buffer;
  4646. #ifdef DEBUG_ENABLED
  4647. draw_list->validation.framebuffer_format = screen_get_framebuffer_format();
  4648. #endif
  4649. draw_list_count = 0;
  4650. draw_list_split = false;
  4651. VkRenderPassBeginInfo render_pass_begin;
  4652. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  4653. render_pass_begin.pNext = nullptr;
  4654. render_pass_begin.renderPass = context->window_get_render_pass(p_screen);
  4655. render_pass_begin.framebuffer = context->window_get_framebuffer(p_screen);
  4656. render_pass_begin.renderArea.extent.width = context->window_get_width(p_screen);
  4657. render_pass_begin.renderArea.extent.height = context->window_get_height(p_screen);
  4658. render_pass_begin.renderArea.offset.x = 0;
  4659. render_pass_begin.renderArea.offset.y = 0;
  4660. render_pass_begin.clearValueCount = 1;
  4661. VkClearValue clear_value;
  4662. clear_value.color.float32[0] = p_clear_color.r;
  4663. clear_value.color.float32[1] = p_clear_color.g;
  4664. clear_value.color.float32[2] = p_clear_color.b;
  4665. clear_value.color.float32[3] = p_clear_color.a;
  4666. render_pass_begin.pClearValues = &clear_value;
  4667. vkCmdBeginRenderPass(command_buffer, &render_pass_begin, VK_SUBPASS_CONTENTS_INLINE);
  4668. uint32_t size_x = screen_get_width(p_screen);
  4669. uint32_t size_y = screen_get_height(p_screen);
  4670. VkViewport viewport;
  4671. viewport.x = 0;
  4672. viewport.y = 0;
  4673. viewport.width = size_x;
  4674. viewport.height = size_y;
  4675. viewport.minDepth = 0;
  4676. viewport.maxDepth = 1.0;
  4677. vkCmdSetViewport(command_buffer, 0, 1, &viewport);
  4678. VkRect2D scissor;
  4679. scissor.offset.x = 0;
  4680. scissor.offset.y = 0;
  4681. scissor.extent.width = size_x;
  4682. scissor.extent.height = size_y;
  4683. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  4684. return ID_TYPE_DRAW_LIST;
  4685. }
  4686. 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) {
  4687. Framebuffer::VersionKey vk;
  4688. vk.initial_color_action = p_initial_color_action;
  4689. vk.final_color_action = p_final_color_action;
  4690. vk.initial_depth_action = p_initial_depth_action;
  4691. vk.final_depth_action = p_final_depth_action;
  4692. if (!p_framebuffer->framebuffers.has(vk)) {
  4693. //need to create this version
  4694. Framebuffer::Version version;
  4695. 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);
  4696. VkFramebufferCreateInfo framebuffer_create_info;
  4697. framebuffer_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  4698. framebuffer_create_info.pNext = nullptr;
  4699. framebuffer_create_info.flags = 0;
  4700. framebuffer_create_info.renderPass = version.render_pass;
  4701. Vector<VkImageView> attachments;
  4702. for (int i = 0; i < p_framebuffer->texture_ids.size(); i++) {
  4703. Texture *texture = texture_owner.getornull(p_framebuffer->texture_ids[i]);
  4704. ERR_FAIL_COND_V(!texture, ERR_BUG);
  4705. attachments.push_back(texture->view);
  4706. ERR_FAIL_COND_V(texture->width != p_framebuffer->size.width, ERR_BUG);
  4707. ERR_FAIL_COND_V(texture->height != p_framebuffer->size.height, ERR_BUG);
  4708. }
  4709. framebuffer_create_info.attachmentCount = attachments.size();
  4710. framebuffer_create_info.pAttachments = attachments.ptr();
  4711. framebuffer_create_info.width = p_framebuffer->size.width;
  4712. framebuffer_create_info.height = p_framebuffer->size.height;
  4713. framebuffer_create_info.layers = 1;
  4714. VkResult err = vkCreateFramebuffer(device, &framebuffer_create_info, nullptr, &version.framebuffer);
  4715. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vkCreateFramebuffer failed with error " + itos(err) + ".");
  4716. p_framebuffer->framebuffers.insert(vk, version);
  4717. }
  4718. const Framebuffer::Version &version = p_framebuffer->framebuffers[vk];
  4719. *r_framebuffer = version.framebuffer;
  4720. *r_render_pass = version.render_pass;
  4721. return OK;
  4722. }
  4723. 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) {
  4724. VkRenderPassBeginInfo render_pass_begin;
  4725. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  4726. render_pass_begin.pNext = nullptr;
  4727. render_pass_begin.renderPass = render_pass;
  4728. render_pass_begin.framebuffer = vkframebuffer;
  4729. render_pass_begin.renderArea.extent.width = viewport_size.width;
  4730. render_pass_begin.renderArea.extent.height = viewport_size.height;
  4731. render_pass_begin.renderArea.offset.x = viewport_offset.x;
  4732. render_pass_begin.renderArea.offset.y = viewport_offset.y;
  4733. Vector<VkClearValue> clear_values;
  4734. clear_values.resize(framebuffer->texture_ids.size());
  4735. {
  4736. int color_index = 0;
  4737. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  4738. Texture *texture = texture_owner.getornull(framebuffer->texture_ids[i]);
  4739. VkClearValue clear_value;
  4740. if (color_index < p_clear_colors.size() && texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  4741. ERR_FAIL_INDEX_V(color_index, p_clear_colors.size(), ERR_BUG); //a bug
  4742. Color clear_color = p_clear_colors[color_index];
  4743. clear_value.color.float32[0] = clear_color.r;
  4744. clear_value.color.float32[1] = clear_color.g;
  4745. clear_value.color.float32[2] = clear_color.b;
  4746. clear_value.color.float32[3] = clear_color.a;
  4747. color_index++;
  4748. } else if (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  4749. clear_value.depthStencil.depth = p_clear_depth;
  4750. clear_value.depthStencil.stencil = p_clear_stencil;
  4751. } else {
  4752. clear_value.color.float32[0] = 0;
  4753. clear_value.color.float32[1] = 0;
  4754. clear_value.color.float32[2] = 0;
  4755. clear_value.color.float32[3] = 0;
  4756. }
  4757. clear_values.write[i] = clear_value;
  4758. }
  4759. }
  4760. render_pass_begin.clearValueCount = clear_values.size();
  4761. render_pass_begin.pClearValues = clear_values.ptr();
  4762. for (int i = 0; i < p_storage_textures.size(); i++) {
  4763. Texture *texture = texture_owner.getornull(p_storage_textures[i]);
  4764. ERR_CONTINUE_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), "Supplied storage texture " + itos(i) + " for draw list ist not set to be used for storage.");
  4765. if (texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT) {
  4766. //must change layout to general
  4767. VkImageMemoryBarrier image_memory_barrier;
  4768. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  4769. image_memory_barrier.pNext = nullptr;
  4770. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  4771. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  4772. image_memory_barrier.oldLayout = texture->layout;
  4773. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  4774. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  4775. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  4776. image_memory_barrier.image = texture->image;
  4777. image_memory_barrier.subresourceRange.aspectMask = texture->read_aspect_mask;
  4778. image_memory_barrier.subresourceRange.baseMipLevel = texture->base_mipmap;
  4779. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  4780. image_memory_barrier.subresourceRange.baseArrayLayer = texture->base_layer;
  4781. image_memory_barrier.subresourceRange.layerCount = texture->layers;
  4782. 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);
  4783. texture->layout = VK_IMAGE_LAYOUT_GENERAL;
  4784. draw_list_storage_textures.push_back(p_storage_textures[i]);
  4785. }
  4786. }
  4787. vkCmdBeginRenderPass(command_buffer, &render_pass_begin, subpass_contents);
  4788. //mark textures as bound
  4789. draw_list_bound_textures.clear();
  4790. draw_list_unbind_color_textures = p_final_color_action != FINAL_ACTION_CONTINUE;
  4791. draw_list_unbind_depth_textures = p_final_depth_action != FINAL_ACTION_CONTINUE;
  4792. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  4793. Texture *texture = texture_owner.getornull(framebuffer->texture_ids[i]);
  4794. texture->bound = true;
  4795. draw_list_bound_textures.push_back(framebuffer->texture_ids[i]);
  4796. }
  4797. return OK;
  4798. }
  4799. 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) {
  4800. Vector<VkClearAttachment> clear_attachments;
  4801. int color_index = 0;
  4802. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  4803. Texture *texture = texture_owner.getornull(framebuffer->texture_ids[i]);
  4804. VkClearAttachment clear_at;
  4805. if (p_clear_color && texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  4806. ERR_FAIL_INDEX(color_index, p_clear_colors.size()); //a bug
  4807. Color clear_color = p_clear_colors[color_index];
  4808. clear_at.clearValue.color.float32[0] = clear_color.r;
  4809. clear_at.clearValue.color.float32[1] = clear_color.g;
  4810. clear_at.clearValue.color.float32[2] = clear_color.b;
  4811. clear_at.clearValue.color.float32[3] = clear_color.a;
  4812. clear_at.colorAttachment = color_index++;
  4813. clear_at.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  4814. } else if (p_clear_depth && texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  4815. clear_at.clearValue.depthStencil.depth = p_depth;
  4816. clear_at.clearValue.depthStencil.stencil = p_stencil;
  4817. clear_at.colorAttachment = 0;
  4818. clear_at.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  4819. if (format_has_stencil(texture->format)) {
  4820. clear_at.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  4821. }
  4822. } else {
  4823. ERR_CONTINUE(true);
  4824. }
  4825. clear_attachments.push_back(clear_at);
  4826. }
  4827. VkClearRect cr;
  4828. cr.baseArrayLayer = 0;
  4829. cr.layerCount = 1;
  4830. cr.rect.offset.x = viewport_offset.x;
  4831. cr.rect.offset.y = viewport_offset.y;
  4832. cr.rect.extent.width = viewport_size.width;
  4833. cr.rect.extent.height = viewport_size.height;
  4834. vkCmdClearAttachments(draw_list->command_buffer, clear_attachments.size(), clear_attachments.ptr(), 1, &cr);
  4835. }
  4836. 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) {
  4837. _THREAD_SAFE_METHOD_
  4838. ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  4839. ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  4840. Framebuffer *framebuffer = framebuffer_owner.getornull(p_framebuffer);
  4841. ERR_FAIL_COND_V(!framebuffer, INVALID_ID);
  4842. Point2i viewport_offset;
  4843. Point2i viewport_size = framebuffer->size;
  4844. bool needs_clear_color = false;
  4845. bool needs_clear_depth = false;
  4846. if (p_region != Rect2() && p_region != Rect2(Vector2(), viewport_size)) { //check custom region
  4847. Rect2i viewport(viewport_offset, viewport_size);
  4848. Rect2i regioni = p_region;
  4849. if (!(regioni.position.x >= viewport.position.x) && (regioni.position.y >= viewport.position.y) &&
  4850. ((regioni.position.x + regioni.size.x) <= (viewport.position.x + viewport.size.x)) &&
  4851. ((regioni.position.y + regioni.size.y) <= (viewport.position.y + viewport.size.y))) {
  4852. ERR_FAIL_V_MSG(INVALID_ID, "When supplying a custom region, it must be contained within the framebuffer rectangle");
  4853. }
  4854. viewport_offset = regioni.position;
  4855. viewport_size = regioni.size;
  4856. if (p_initial_color_action == INITIAL_ACTION_CLEAR) {
  4857. needs_clear_color = true;
  4858. p_initial_color_action = INITIAL_ACTION_KEEP;
  4859. }
  4860. if (p_initial_depth_action == INITIAL_ACTION_CLEAR) {
  4861. needs_clear_depth = true;
  4862. p_initial_depth_action = INITIAL_ACTION_KEEP;
  4863. }
  4864. }
  4865. if (p_initial_color_action == INITIAL_ACTION_CLEAR) { //check clear values
  4866. int color_attachments = framebuffer_formats[framebuffer->format_id].color_attachments;
  4867. ERR_FAIL_COND_V_MSG(p_clear_color_values.size() != color_attachments, INVALID_ID,
  4868. "Clear color values supplied (" + itos(p_clear_color_values.size()) + ") differ from the amount required for framebuffer (" + itos(color_attachments) + ").");
  4869. }
  4870. VkFramebuffer vkframebuffer;
  4871. VkRenderPass render_pass;
  4872. 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);
  4873. ERR_FAIL_COND_V(err != OK, INVALID_ID);
  4874. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  4875. 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);
  4876. if (err != OK) {
  4877. return INVALID_ID;
  4878. }
  4879. draw_list = memnew(DrawList);
  4880. draw_list->command_buffer = command_buffer;
  4881. #ifdef DEBUG_ENABLED
  4882. draw_list->validation.framebuffer_format = framebuffer->format_id;
  4883. #endif
  4884. draw_list_count = 0;
  4885. draw_list_split = false;
  4886. if (needs_clear_color || needs_clear_depth) {
  4887. _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);
  4888. }
  4889. VkViewport viewport;
  4890. viewport.x = viewport_offset.x;
  4891. viewport.y = viewport_offset.y;
  4892. viewport.width = viewport_size.width;
  4893. viewport.height = viewport_size.height;
  4894. viewport.minDepth = 0;
  4895. viewport.maxDepth = 1.0;
  4896. vkCmdSetViewport(command_buffer, 0, 1, &viewport);
  4897. VkRect2D scissor;
  4898. scissor.offset.x = viewport_offset.x;
  4899. scissor.offset.y = viewport_offset.y;
  4900. scissor.extent.width = viewport_size.width;
  4901. scissor.extent.height = viewport_size.height;
  4902. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  4903. draw_list->viewport = Rect2i(viewport_offset, viewport_size);
  4904. return ID_TYPE_DRAW_LIST;
  4905. }
  4906. 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) {
  4907. _THREAD_SAFE_METHOD_
  4908. ERR_FAIL_COND_V(p_splits < 1, ERR_INVALID_DECLARATION);
  4909. Framebuffer *framebuffer = framebuffer_owner.getornull(p_framebuffer);
  4910. ERR_FAIL_COND_V(!framebuffer, ERR_INVALID_DECLARATION);
  4911. Point2i viewport_offset;
  4912. Point2i viewport_size = framebuffer->size;
  4913. bool needs_clear_color = false;
  4914. bool needs_clear_depth = false;
  4915. if (p_region != Rect2() && p_region != Rect2(Vector2(), viewport_size)) { //check custom region
  4916. Rect2i viewport(viewport_offset, viewport_size);
  4917. Rect2i regioni = p_region;
  4918. if (!(regioni.position.x >= viewport.position.x) && (regioni.position.y >= viewport.position.y) &&
  4919. ((regioni.position.x + regioni.size.x) <= (viewport.position.x + viewport.size.x)) &&
  4920. ((regioni.position.y + regioni.size.y) <= (viewport.position.y + viewport.size.y))) {
  4921. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "When supplying a custom region, it must be contained within the framebuffer rectangle");
  4922. }
  4923. viewport_offset = regioni.position;
  4924. viewport_size = regioni.size;
  4925. if (p_initial_color_action == INITIAL_ACTION_CLEAR) {
  4926. needs_clear_color = true;
  4927. p_initial_color_action = INITIAL_ACTION_KEEP;
  4928. }
  4929. if (p_initial_depth_action == INITIAL_ACTION_CLEAR) {
  4930. needs_clear_depth = true;
  4931. p_initial_depth_action = INITIAL_ACTION_KEEP;
  4932. }
  4933. }
  4934. if (p_initial_color_action == INITIAL_ACTION_CLEAR) { //check clear values
  4935. int color_attachments = framebuffer_formats[framebuffer->format_id].color_attachments;
  4936. ERR_FAIL_COND_V_MSG(p_clear_color_values.size() != color_attachments, ERR_INVALID_PARAMETER,
  4937. "Clear color values supplied (" + itos(p_clear_color_values.size()) + ") differ from the amount required for framebuffer (" + itos(color_attachments) + ").");
  4938. }
  4939. if (p_splits > (uint32_t)split_draw_list_allocators.size()) {
  4940. uint32_t from = split_draw_list_allocators.size();
  4941. split_draw_list_allocators.resize(p_splits);
  4942. for (uint32_t i = from; i < p_splits; i++) {
  4943. VkCommandPoolCreateInfo cmd_pool_info;
  4944. cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  4945. cmd_pool_info.pNext = nullptr;
  4946. cmd_pool_info.queueFamilyIndex = context->get_graphics_queue();
  4947. cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  4948. VkResult res = vkCreateCommandPool(device, &cmd_pool_info, nullptr, &split_draw_list_allocators.write[i].command_pool);
  4949. ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "vkCreateCommandPool failed with error " + itos(res) + ".");
  4950. for (int j = 0; j < frame_count; j++) {
  4951. VkCommandBuffer command_buffer;
  4952. VkCommandBufferAllocateInfo cmdbuf;
  4953. //no command buffer exists, create it.
  4954. cmdbuf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  4955. cmdbuf.pNext = nullptr;
  4956. cmdbuf.commandPool = split_draw_list_allocators[i].command_pool;
  4957. cmdbuf.level = VK_COMMAND_BUFFER_LEVEL_SECONDARY;
  4958. cmdbuf.commandBufferCount = 1;
  4959. VkResult err = vkAllocateCommandBuffers(device, &cmdbuf, &command_buffer);
  4960. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  4961. split_draw_list_allocators.write[i].command_buffers.push_back(command_buffer);
  4962. }
  4963. }
  4964. }
  4965. VkFramebuffer vkframebuffer;
  4966. VkRenderPass render_pass;
  4967. Error err = _draw_list_setup_framebuffer(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, &vkframebuffer, &render_pass);
  4968. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  4969. VkCommandBuffer frame_command_buffer = frames[frame].draw_command_buffer;
  4970. err = _draw_list_render_pass_begin(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, viewport_offset, viewport_size, vkframebuffer, render_pass, frame_command_buffer, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS, p_storage_textures);
  4971. if (err != OK) {
  4972. return ERR_CANT_CREATE;
  4973. }
  4974. draw_list = memnew_arr(DrawList, p_splits);
  4975. draw_list_count = p_splits;
  4976. draw_list_split = true;
  4977. for (uint32_t i = 0; i < p_splits; i++) {
  4978. //take a command buffer and initialize it
  4979. VkCommandBuffer command_buffer = split_draw_list_allocators[p_splits].command_buffers[frame];
  4980. VkCommandBufferInheritanceInfo inheritance_info;
  4981. inheritance_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO;
  4982. inheritance_info.pNext = nullptr;
  4983. inheritance_info.renderPass = render_pass;
  4984. inheritance_info.subpass = 0;
  4985. inheritance_info.framebuffer = vkframebuffer;
  4986. inheritance_info.occlusionQueryEnable = false;
  4987. inheritance_info.queryFlags = 0; //?
  4988. inheritance_info.pipelineStatistics = 0;
  4989. VkCommandBufferBeginInfo cmdbuf_begin;
  4990. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  4991. cmdbuf_begin.pNext = nullptr;
  4992. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT;
  4993. cmdbuf_begin.pInheritanceInfo = &inheritance_info;
  4994. VkResult res = vkResetCommandBuffer(command_buffer, 0);
  4995. if (res) {
  4996. memdelete_arr(draw_list);
  4997. draw_list = nullptr;
  4998. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "vkResetCommandBuffer failed with error " + itos(res) + ".");
  4999. }
  5000. res = vkBeginCommandBuffer(command_buffer, &cmdbuf_begin);
  5001. if (res) {
  5002. memdelete_arr(draw_list);
  5003. draw_list = nullptr;
  5004. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "vkBeginCommandBuffer failed with error " + itos(res) + ".");
  5005. }
  5006. draw_list[i].command_buffer = command_buffer;
  5007. #ifdef DEBUG_ENABLED
  5008. draw_list[i].validation.framebuffer_format = framebuffer->format_id;
  5009. #endif
  5010. if (i == 0 && (needs_clear_color || needs_clear_depth)) {
  5011. _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);
  5012. }
  5013. VkViewport viewport;
  5014. viewport.x = viewport_offset.x;
  5015. viewport.y = viewport_offset.y;
  5016. viewport.width = viewport_size.width;
  5017. viewport.height = viewport_size.height;
  5018. viewport.minDepth = 0;
  5019. viewport.maxDepth = 1.0;
  5020. vkCmdSetViewport(command_buffer, 0, 1, &viewport);
  5021. VkRect2D scissor;
  5022. scissor.offset.x = viewport_offset.x;
  5023. scissor.offset.y = viewport_offset.y;
  5024. scissor.extent.width = viewport_size.width;
  5025. scissor.extent.height = viewport_size.height;
  5026. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  5027. r_split_ids[i] = (DrawListID(1) << DrawListID(ID_TYPE_SPLIT_DRAW_LIST)) + i;
  5028. draw_list[i].viewport = Rect2i(viewport_offset, viewport_size);
  5029. }
  5030. return OK;
  5031. }
  5032. RenderingDeviceVulkan::DrawList *RenderingDeviceVulkan::_get_draw_list_ptr(DrawListID p_id) {
  5033. if (p_id < 0) {
  5034. return nullptr;
  5035. }
  5036. if (!draw_list) {
  5037. return nullptr;
  5038. } else if (p_id == ID_TYPE_DRAW_LIST) {
  5039. if (draw_list_split) {
  5040. return nullptr;
  5041. }
  5042. return draw_list;
  5043. } else if (p_id >> DrawListID(ID_BASE_SHIFT) == ID_TYPE_SPLIT_DRAW_LIST) {
  5044. if (!draw_list_split) {
  5045. return nullptr;
  5046. }
  5047. uint64_t index = p_id & ((DrawListID(1) << DrawListID(ID_BASE_SHIFT)) - 1); //mask
  5048. if (index >= draw_list_count) {
  5049. return nullptr;
  5050. }
  5051. return &draw_list[index];
  5052. } else {
  5053. return nullptr;
  5054. }
  5055. }
  5056. void RenderingDeviceVulkan::draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline) {
  5057. DrawList *dl = _get_draw_list_ptr(p_list);
  5058. ERR_FAIL_COND(!dl);
  5059. #ifdef DEBUG_ENABLED
  5060. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  5061. #endif
  5062. const RenderPipeline *pipeline = render_pipeline_owner.getornull(p_render_pipeline);
  5063. ERR_FAIL_COND(!pipeline);
  5064. #ifdef DEBUG_ENABLED
  5065. ERR_FAIL_COND(pipeline->validation.framebuffer_format != dl->validation.framebuffer_format);
  5066. #endif
  5067. if (p_render_pipeline == dl->state.pipeline) {
  5068. return; //redundant state, return.
  5069. }
  5070. dl->state.pipeline = p_render_pipeline;
  5071. dl->state.pipeline_layout = pipeline->pipeline_layout;
  5072. vkCmdBindPipeline(dl->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline);
  5073. if (dl->state.pipeline_shader != pipeline->shader) {
  5074. // shader changed, so descriptor sets may become incompatible.
  5075. //go through ALL sets, and unbind them (and all those above) if the format is different
  5076. uint32_t pcount = pipeline->set_formats.size(); //formats count in this pipeline
  5077. dl->state.set_count = MAX(dl->state.set_count, pcount);
  5078. const uint32_t *pformats = pipeline->set_formats.ptr(); //pipeline set formats
  5079. bool sets_valid = true; //once invalid, all above become invalid
  5080. for (uint32_t i = 0; i < pcount; i++) {
  5081. //if a part of the format is different, invalidate it (and the rest)
  5082. if (!sets_valid || dl->state.sets[i].pipeline_expected_format != pformats[i]) {
  5083. dl->state.sets[i].bound = false;
  5084. dl->state.sets[i].pipeline_expected_format = pformats[i];
  5085. sets_valid = false;
  5086. }
  5087. }
  5088. for (uint32_t i = pcount; i < dl->state.set_count; i++) {
  5089. //unbind the ones above (not used) if exist
  5090. dl->state.sets[i].bound = false;
  5091. }
  5092. dl->state.set_count = pcount; //update set count
  5093. if (pipeline->push_constant_size) {
  5094. dl->state.pipeline_push_constant_stages = pipeline->push_constant_stages;
  5095. #ifdef DEBUG_ENABLED
  5096. dl->validation.pipeline_push_constant_supplied = false;
  5097. #endif
  5098. }
  5099. dl->state.pipeline_shader = pipeline->shader;
  5100. }
  5101. #ifdef DEBUG_ENABLED
  5102. //update render pass pipeline info
  5103. dl->validation.pipeline_active = true;
  5104. dl->validation.pipeline_dynamic_state = pipeline->validation.dynamic_state;
  5105. dl->validation.pipeline_vertex_format = pipeline->validation.vertex_format;
  5106. dl->validation.pipeline_uses_restart_indices = pipeline->validation.uses_restart_indices;
  5107. dl->validation.pipeline_primitive_divisor = pipeline->validation.primitive_divisor;
  5108. dl->validation.pipeline_primitive_minimum = pipeline->validation.primitive_minimum;
  5109. dl->validation.pipeline_push_constant_size = pipeline->push_constant_size;
  5110. #endif
  5111. }
  5112. void RenderingDeviceVulkan::draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index) {
  5113. #ifdef DEBUG_ENABLED
  5114. ERR_FAIL_COND_MSG(p_index >= limits.maxBoundDescriptorSets || p_index > MAX_UNIFORM_SETS,
  5115. "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(limits.maxBoundDescriptorSets) + ").");
  5116. #endif
  5117. DrawList *dl = _get_draw_list_ptr(p_list);
  5118. ERR_FAIL_COND(!dl);
  5119. #ifdef DEBUG_ENABLED
  5120. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  5121. #endif
  5122. const UniformSet *uniform_set = uniform_set_owner.getornull(p_uniform_set);
  5123. ERR_FAIL_COND(!uniform_set);
  5124. if (p_index > dl->state.set_count) {
  5125. dl->state.set_count = p_index;
  5126. }
  5127. dl->state.sets[p_index].descriptor_set = uniform_set->descriptor_set; //update set pointer
  5128. dl->state.sets[p_index].bound = false; //needs rebind
  5129. dl->state.sets[p_index].uniform_set_format = uniform_set->format;
  5130. dl->state.sets[p_index].uniform_set = p_uniform_set;
  5131. #ifdef DEBUG_ENABLED
  5132. { //validate that textures bound are not attached as framebuffer bindings
  5133. uint32_t attachable_count = uniform_set->attachable_textures.size();
  5134. const RID *attachable_ptr = uniform_set->attachable_textures.ptr();
  5135. uint32_t bound_count = draw_list_bound_textures.size();
  5136. const RID *bound_ptr = draw_list_bound_textures.ptr();
  5137. for (uint32_t i = 0; i < attachable_count; i++) {
  5138. for (uint32_t j = 0; j < bound_count; j++) {
  5139. ERR_FAIL_COND_MSG(attachable_ptr[i] == bound_ptr[j],
  5140. "Attempted to use the same texture in framebuffer attachment and a uniform set, this is not allowed.");
  5141. }
  5142. }
  5143. }
  5144. #endif
  5145. }
  5146. void RenderingDeviceVulkan::draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array) {
  5147. DrawList *dl = _get_draw_list_ptr(p_list);
  5148. ERR_FAIL_COND(!dl);
  5149. #ifdef DEBUG_ENABLED
  5150. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  5151. #endif
  5152. const VertexArray *vertex_array = vertex_array_owner.getornull(p_vertex_array);
  5153. ERR_FAIL_COND(!vertex_array);
  5154. if (dl->state.vertex_array == p_vertex_array) {
  5155. return; //already set
  5156. }
  5157. dl->state.vertex_array = p_vertex_array;
  5158. #ifdef DEBUG_ENABLED
  5159. dl->validation.vertex_format = vertex_array->description;
  5160. dl->validation.vertex_max_instances_allowed = vertex_array->max_instances_allowed;
  5161. #endif
  5162. dl->validation.vertex_array_size = vertex_array->vertex_count;
  5163. vkCmdBindVertexBuffers(dl->command_buffer, 0, vertex_array->buffers.size(), vertex_array->buffers.ptr(), vertex_array->offsets.ptr());
  5164. }
  5165. void RenderingDeviceVulkan::draw_list_bind_index_array(DrawListID p_list, RID p_index_array) {
  5166. DrawList *dl = _get_draw_list_ptr(p_list);
  5167. ERR_FAIL_COND(!dl);
  5168. #ifdef DEBUG_ENABLED
  5169. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  5170. #endif
  5171. const IndexArray *index_array = index_array_owner.getornull(p_index_array);
  5172. ERR_FAIL_COND(!index_array);
  5173. if (dl->state.index_array == p_index_array) {
  5174. return; //already set
  5175. }
  5176. dl->state.index_array = p_index_array;
  5177. #ifdef DEBUG_ENABLED
  5178. dl->validation.index_array_max_index = index_array->max_index;
  5179. #endif
  5180. dl->validation.index_array_size = index_array->indices;
  5181. dl->validation.index_array_offset = index_array->offset;
  5182. vkCmdBindIndexBuffer(dl->command_buffer, index_array->buffer, index_array->offset, index_array->index_type);
  5183. }
  5184. void RenderingDeviceVulkan::draw_list_set_line_width(DrawListID p_list, float p_width) {
  5185. DrawList *dl = _get_draw_list_ptr(p_list);
  5186. ERR_FAIL_COND(!dl);
  5187. #ifdef DEBUG_ENABLED
  5188. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  5189. #endif
  5190. vkCmdSetLineWidth(dl->command_buffer, p_width);
  5191. }
  5192. void RenderingDeviceVulkan::draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size) {
  5193. DrawList *dl = _get_draw_list_ptr(p_list);
  5194. ERR_FAIL_COND(!dl);
  5195. #ifdef DEBUG_ENABLED
  5196. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  5197. #endif
  5198. #ifdef DEBUG_ENABLED
  5199. ERR_FAIL_COND_MSG(p_data_size != dl->validation.pipeline_push_constant_size,
  5200. "This render pipeline requires (" + itos(dl->validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");
  5201. #endif
  5202. vkCmdPushConstants(dl->command_buffer, dl->state.pipeline_layout, dl->state.pipeline_push_constant_stages, 0, p_data_size, p_data);
  5203. #ifdef DEBUG_ENABLED
  5204. dl->validation.pipeline_push_constant_supplied = true;
  5205. #endif
  5206. }
  5207. void RenderingDeviceVulkan::draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances, uint32_t p_procedural_vertices) {
  5208. DrawList *dl = _get_draw_list_ptr(p_list);
  5209. ERR_FAIL_COND(!dl);
  5210. #ifdef DEBUG_ENABLED
  5211. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  5212. #endif
  5213. #ifdef DEBUG_ENABLED
  5214. ERR_FAIL_COND_MSG(!dl->validation.pipeline_active,
  5215. "No render pipeline was set before attempting to draw.");
  5216. if (dl->validation.pipeline_vertex_format != INVALID_ID) {
  5217. //pipeline uses vertices, validate format
  5218. ERR_FAIL_COND_MSG(dl->validation.vertex_format == INVALID_ID,
  5219. "No vertex array was bound, and render pipeline expects vertices.");
  5220. //make sure format is right
  5221. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format != dl->validation.vertex_format,
  5222. "The vertex format used to create the pipeline does not match the vertex format bound.");
  5223. //make sure amount of instances is valid
  5224. ERR_FAIL_COND_MSG(p_instances > dl->validation.vertex_max_instances_allowed,
  5225. "Amount of instances requested (" + itos(p_instances) + " is larger than the maximum amount suported by the bound vertex array (" + itos(dl->validation.vertex_max_instances_allowed) + ").");
  5226. }
  5227. if (dl->validation.pipeline_push_constant_size > 0) {
  5228. //using push constants, check that they were supplied
  5229. ERR_FAIL_COND_MSG(!dl->validation.pipeline_push_constant_supplied,
  5230. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  5231. }
  5232. #endif
  5233. //Bind descriptor sets
  5234. for (uint32_t i = 0; i < dl->state.set_count; i++) {
  5235. if (dl->state.sets[i].pipeline_expected_format == 0) {
  5236. continue; //nothing expected by this pipeline
  5237. }
  5238. #ifdef DEBUG_ENABLED
  5239. if (dl->state.sets[i].pipeline_expected_format != dl->state.sets[i].uniform_set_format) {
  5240. if (dl->state.sets[i].uniform_set_format == 0) {
  5241. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  5242. } else if (uniform_set_owner.owns(dl->state.sets[i].uniform_set)) {
  5243. UniformSet *us = uniform_set_owner.getornull(dl->state.sets[i].uniform_set);
  5244. 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));
  5245. } else {
  5246. 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));
  5247. }
  5248. }
  5249. #endif
  5250. if (!dl->state.sets[i].bound) {
  5251. //All good, see if this requires re-binding
  5252. vkCmdBindDescriptorSets(dl->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, dl->state.pipeline_layout, i, 1, &dl->state.sets[i].descriptor_set, 0, nullptr);
  5253. dl->state.sets[i].bound = true;
  5254. }
  5255. }
  5256. if (p_use_indices) {
  5257. #ifdef DEBUG_ENABLED
  5258. ERR_FAIL_COND_MSG(p_procedural_vertices > 0,
  5259. "Procedural vertices can't be used together with indices.");
  5260. ERR_FAIL_COND_MSG(!dl->validation.index_array_size,
  5261. "Draw command requested indices, but no index buffer was set.");
  5262. if (dl->validation.pipeline_vertex_format != INVALID_ID) {
  5263. //uses vertices, do some vertex validations
  5264. ERR_FAIL_COND_MSG(dl->validation.vertex_array_size < dl->validation.index_array_max_index,
  5265. "Index array references (max index: " + itos(dl->validation.index_array_max_index) + ") indices beyond the vertex array size (" + itos(dl->validation.vertex_array_size) + ").");
  5266. }
  5267. ERR_FAIL_COND_MSG(dl->validation.pipeline_uses_restart_indices != dl->validation.index_buffer_uses_restart_indices,
  5268. "The usage of restart indices in index buffer does not match the render primitive in the pipeline.");
  5269. #endif
  5270. uint32_t to_draw = dl->validation.index_array_size;
  5271. #ifdef DEBUG_ENABLED
  5272. ERR_FAIL_COND_MSG(to_draw < dl->validation.pipeline_primitive_minimum,
  5273. "Too few indices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(dl->validation.pipeline_primitive_minimum) + ").");
  5274. ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0,
  5275. "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) + ").");
  5276. #endif
  5277. vkCmdDrawIndexed(dl->command_buffer, to_draw, p_instances, dl->validation.index_array_offset, 0, 0);
  5278. } else {
  5279. uint32_t to_draw;
  5280. if (p_procedural_vertices > 0) {
  5281. #ifdef DEBUG_ENABLED
  5282. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format != INVALID_ID,
  5283. "Procedural vertices requested, but pipeline expects a vertex array.");
  5284. #endif
  5285. to_draw = p_procedural_vertices;
  5286. } else {
  5287. #ifdef DEBUG_ENABLED
  5288. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format == INVALID_ID,
  5289. "Draw command lacks indices, but pipeline format does not use vertices.");
  5290. #endif
  5291. to_draw = dl->validation.vertex_array_size;
  5292. }
  5293. #ifdef DEBUG_ENABLED
  5294. ERR_FAIL_COND_MSG(to_draw < dl->validation.pipeline_primitive_minimum,
  5295. "Too few vertices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(dl->validation.pipeline_primitive_minimum) + ").");
  5296. ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0,
  5297. "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) + ").");
  5298. #endif
  5299. vkCmdDraw(dl->command_buffer, to_draw, p_instances, 0, 0);
  5300. }
  5301. }
  5302. void RenderingDeviceVulkan::draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect) {
  5303. DrawList *dl = _get_draw_list_ptr(p_list);
  5304. ERR_FAIL_COND(!dl);
  5305. #ifdef DEBUG_ENABLED
  5306. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  5307. #endif
  5308. Rect2i rect = p_rect;
  5309. rect.position += dl->viewport.position;
  5310. rect = dl->viewport.clip(rect);
  5311. if (rect.get_area() == 0) {
  5312. return;
  5313. }
  5314. VkRect2D scissor;
  5315. scissor.offset.x = rect.position.x;
  5316. scissor.offset.y = rect.position.y;
  5317. scissor.extent.width = rect.size.width;
  5318. scissor.extent.height = rect.size.height;
  5319. vkCmdSetScissor(dl->command_buffer, 0, 1, &scissor);
  5320. }
  5321. void RenderingDeviceVulkan::draw_list_disable_scissor(DrawListID p_list) {
  5322. DrawList *dl = _get_draw_list_ptr(p_list);
  5323. ERR_FAIL_COND(!dl);
  5324. #ifdef DEBUG_ENABLED
  5325. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  5326. #endif
  5327. VkRect2D scissor;
  5328. scissor.offset.x = dl->viewport.position.x;
  5329. scissor.offset.y = dl->viewport.position.y;
  5330. scissor.extent.width = dl->viewport.size.width;
  5331. scissor.extent.height = dl->viewport.size.height;
  5332. vkCmdSetScissor(dl->command_buffer, 0, 1, &scissor);
  5333. }
  5334. void RenderingDeviceVulkan::draw_list_end() {
  5335. _THREAD_SAFE_METHOD_
  5336. ERR_FAIL_COND_MSG(!draw_list, "Immediate draw list is already inactive.");
  5337. if (draw_list_split) {
  5338. //send all command buffers
  5339. VkCommandBuffer *command_buffers = (VkCommandBuffer *)alloca(sizeof(VkCommandBuffer) * draw_list_count);
  5340. for (uint32_t i = 0; i < draw_list_count; i++) {
  5341. vkEndCommandBuffer(draw_list->command_buffer);
  5342. command_buffers[i] = draw_list->command_buffer;
  5343. }
  5344. vkCmdExecuteCommands(frames[frame].draw_command_buffer, draw_list_count, command_buffers);
  5345. vkCmdEndRenderPass(frames[frame].draw_command_buffer);
  5346. memdelete_arr(draw_list);
  5347. draw_list = nullptr;
  5348. } else {
  5349. //just end the list
  5350. vkCmdEndRenderPass(draw_list->command_buffer);
  5351. memdelete(draw_list);
  5352. draw_list = nullptr;
  5353. }
  5354. for (int i = 0; i < draw_list_bound_textures.size(); i++) {
  5355. Texture *texture = texture_owner.getornull(draw_list_bound_textures[i]);
  5356. ERR_CONTINUE(!texture); //wtf
  5357. if (draw_list_unbind_color_textures && (texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) {
  5358. texture->bound = false;
  5359. }
  5360. if (draw_list_unbind_depth_textures && (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  5361. texture->bound = false;
  5362. }
  5363. }
  5364. draw_list_bound_textures.clear();
  5365. for (int i = 0; i < draw_list_storage_textures.size(); i++) {
  5366. Texture *texture = texture_owner.getornull(draw_list_storage_textures[i]);
  5367. VkImageMemoryBarrier image_memory_barrier;
  5368. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  5369. image_memory_barrier.pNext = nullptr;
  5370. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  5371. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  5372. image_memory_barrier.oldLayout = texture->layout;
  5373. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  5374. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  5375. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  5376. image_memory_barrier.image = texture->image;
  5377. image_memory_barrier.subresourceRange.aspectMask = texture->read_aspect_mask;
  5378. image_memory_barrier.subresourceRange.baseMipLevel = texture->base_mipmap;
  5379. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  5380. image_memory_barrier.subresourceRange.baseArrayLayer = texture->base_layer;
  5381. image_memory_barrier.subresourceRange.layerCount = texture->layers;
  5382. 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);
  5383. texture->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  5384. }
  5385. draw_list_storage_textures.clear();
  5386. // To ensure proper synchronization, we must make sure rendering is done before:
  5387. // * Some buffer is copied
  5388. // * Another render pass happens (since we may be done
  5389. #ifdef FORCE_FULL_BARRIER
  5390. _full_barrier(true);
  5391. #else
  5392. _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);
  5393. #endif
  5394. }
  5395. /***********************/
  5396. /**** COMPUTE LISTS ****/
  5397. /***********************/
  5398. RenderingDevice::ComputeListID RenderingDeviceVulkan::compute_list_begin() {
  5399. ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  5400. ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  5401. compute_list = memnew(ComputeList);
  5402. compute_list->command_buffer = frames[frame].draw_command_buffer;
  5403. return ID_TYPE_COMPUTE_LIST;
  5404. }
  5405. void RenderingDeviceVulkan::compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline) {
  5406. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  5407. ERR_FAIL_COND(!compute_list);
  5408. ComputeList *cl = compute_list;
  5409. const ComputePipeline *pipeline = compute_pipeline_owner.getornull(p_compute_pipeline);
  5410. ERR_FAIL_COND(!pipeline);
  5411. if (p_compute_pipeline == cl->state.pipeline) {
  5412. return; //redundant state, return.
  5413. }
  5414. cl->state.pipeline = p_compute_pipeline;
  5415. cl->state.pipeline_layout = pipeline->pipeline_layout;
  5416. vkCmdBindPipeline(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline->pipeline);
  5417. if (cl->state.pipeline_shader != pipeline->shader) {
  5418. // shader changed, so descriptor sets may become incompatible.
  5419. //go through ALL sets, and unbind them (and all those above) if the format is different
  5420. uint32_t pcount = pipeline->set_formats.size(); //formats count in this pipeline
  5421. cl->state.set_count = MAX(cl->state.set_count, pcount);
  5422. const uint32_t *pformats = pipeline->set_formats.ptr(); //pipeline set formats
  5423. bool sets_valid = true; //once invalid, all above become invalid
  5424. for (uint32_t i = 0; i < pcount; i++) {
  5425. //if a part of the format is different, invalidate it (and the rest)
  5426. if (!sets_valid || cl->state.sets[i].pipeline_expected_format != pformats[i]) {
  5427. cl->state.sets[i].bound = false;
  5428. cl->state.sets[i].pipeline_expected_format = pformats[i];
  5429. sets_valid = false;
  5430. }
  5431. }
  5432. for (uint32_t i = pcount; i < cl->state.set_count; i++) {
  5433. //unbind the ones above (not used) if exist
  5434. cl->state.sets[i].bound = false;
  5435. }
  5436. cl->state.set_count = pcount; //update set count
  5437. if (pipeline->push_constant_size) {
  5438. cl->state.pipeline_push_constant_stages = pipeline->push_constant_stages;
  5439. #ifdef DEBUG_ENABLED
  5440. cl->validation.pipeline_push_constant_supplied = false;
  5441. #endif
  5442. }
  5443. cl->state.pipeline_shader = pipeline->shader;
  5444. }
  5445. #ifdef DEBUG_ENABLED
  5446. //update compute pass pipeline info
  5447. cl->validation.pipeline_active = true;
  5448. cl->validation.pipeline_push_constant_size = pipeline->push_constant_size;
  5449. #endif
  5450. }
  5451. void RenderingDeviceVulkan::compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index) {
  5452. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  5453. ERR_FAIL_COND(!compute_list);
  5454. ComputeList *cl = compute_list;
  5455. #ifdef DEBUG_ENABLED
  5456. ERR_FAIL_COND_MSG(p_index >= limits.maxBoundDescriptorSets || p_index > MAX_UNIFORM_SETS,
  5457. "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(limits.maxBoundDescriptorSets) + ").");
  5458. #endif
  5459. #ifdef DEBUG_ENABLED
  5460. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  5461. #endif
  5462. UniformSet *uniform_set = uniform_set_owner.getornull(p_uniform_set);
  5463. ERR_FAIL_COND(!uniform_set);
  5464. if (p_index > cl->state.set_count) {
  5465. cl->state.set_count = p_index;
  5466. }
  5467. cl->state.sets[p_index].descriptor_set = uniform_set->descriptor_set; //update set pointer
  5468. cl->state.sets[p_index].bound = false; //needs rebind
  5469. cl->state.sets[p_index].uniform_set_format = uniform_set->format;
  5470. cl->state.sets[p_index].uniform_set = p_uniform_set;
  5471. uint32_t textures_to_sampled_count = uniform_set->mutable_sampled_textures.size();
  5472. Texture **textures_to_sampled = uniform_set->mutable_sampled_textures.ptrw();
  5473. for (uint32_t i = 0; i < textures_to_sampled_count; i++) {
  5474. if (textures_to_sampled[i]->layout != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
  5475. VkImageMemoryBarrier image_memory_barrier;
  5476. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  5477. image_memory_barrier.pNext = nullptr;
  5478. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  5479. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  5480. image_memory_barrier.oldLayout = textures_to_sampled[i]->layout;
  5481. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  5482. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  5483. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  5484. image_memory_barrier.image = textures_to_sampled[i]->image;
  5485. image_memory_barrier.subresourceRange.aspectMask = textures_to_sampled[i]->read_aspect_mask;
  5486. image_memory_barrier.subresourceRange.baseMipLevel = textures_to_sampled[i]->base_mipmap;
  5487. image_memory_barrier.subresourceRange.levelCount = textures_to_sampled[i]->mipmaps;
  5488. image_memory_barrier.subresourceRange.baseArrayLayer = textures_to_sampled[i]->base_layer;
  5489. image_memory_barrier.subresourceRange.layerCount = textures_to_sampled[i]->layers;
  5490. 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);
  5491. textures_to_sampled[i]->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  5492. cl->state.textures_to_sampled_layout.erase(textures_to_sampled[i]);
  5493. }
  5494. }
  5495. uint32_t textures_to_storage_count = uniform_set->mutable_storage_textures.size();
  5496. Texture **textures_to_storage = uniform_set->mutable_storage_textures.ptrw();
  5497. for (uint32_t i = 0; i < textures_to_storage_count; i++) {
  5498. if (textures_to_storage[i]->layout != VK_IMAGE_LAYOUT_GENERAL) {
  5499. VkImageMemoryBarrier image_memory_barrier;
  5500. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  5501. image_memory_barrier.pNext = nullptr;
  5502. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  5503. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  5504. image_memory_barrier.oldLayout = textures_to_storage[i]->layout;
  5505. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  5506. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  5507. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  5508. image_memory_barrier.image = textures_to_storage[i]->image;
  5509. image_memory_barrier.subresourceRange.aspectMask = textures_to_storage[i]->read_aspect_mask;
  5510. image_memory_barrier.subresourceRange.baseMipLevel = textures_to_storage[i]->base_mipmap;
  5511. image_memory_barrier.subresourceRange.levelCount = textures_to_storage[i]->mipmaps;
  5512. image_memory_barrier.subresourceRange.baseArrayLayer = textures_to_storage[i]->base_layer;
  5513. image_memory_barrier.subresourceRange.layerCount = textures_to_storage[i]->layers;
  5514. 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);
  5515. textures_to_storage[i]->layout = VK_IMAGE_LAYOUT_GENERAL;
  5516. cl->state.textures_to_sampled_layout.insert(textures_to_storage[i]); //needs to go back to sampled layout afterwards
  5517. }
  5518. }
  5519. #if 0
  5520. { //validate that textures bound are not attached as framebuffer bindings
  5521. uint32_t attachable_count = uniform_set->attachable_textures.size();
  5522. const RID *attachable_ptr = uniform_set->attachable_textures.ptr();
  5523. uint32_t bound_count = draw_list_bound_textures.size();
  5524. const RID *bound_ptr = draw_list_bound_textures.ptr();
  5525. for (uint32_t i = 0; i < attachable_count; i++) {
  5526. for (uint32_t j = 0; j < bound_count; j++) {
  5527. ERR_FAIL_COND_MSG(attachable_ptr[i] == bound_ptr[j],
  5528. "Attempted to use the same texture in framebuffer attachment and a uniform set, this is not allowed.");
  5529. }
  5530. }
  5531. }
  5532. #endif
  5533. }
  5534. void RenderingDeviceVulkan::compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size) {
  5535. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  5536. ERR_FAIL_COND(!compute_list);
  5537. ComputeList *cl = compute_list;
  5538. #ifdef DEBUG_ENABLED
  5539. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  5540. #endif
  5541. #ifdef DEBUG_ENABLED
  5542. ERR_FAIL_COND_MSG(p_data_size != cl->validation.pipeline_push_constant_size,
  5543. "This compute pipeline requires (" + itos(cl->validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");
  5544. #endif
  5545. vkCmdPushConstants(cl->command_buffer, cl->state.pipeline_layout, cl->state.pipeline_push_constant_stages, 0, p_data_size, p_data);
  5546. #ifdef DEBUG_ENABLED
  5547. cl->validation.pipeline_push_constant_supplied = true;
  5548. #endif
  5549. }
  5550. void RenderingDeviceVulkan::compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) {
  5551. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  5552. ERR_FAIL_COND(!compute_list);
  5553. ComputeList *cl = compute_list;
  5554. #ifdef DEBUG_ENABLED
  5555. ERR_FAIL_COND_MSG(p_x_groups > limits.maxComputeWorkGroupCount[0],
  5556. "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[0]) + ")");
  5557. ERR_FAIL_COND_MSG(p_y_groups > limits.maxComputeWorkGroupCount[1],
  5558. "Dispatch amount of Y compute groups (" + itos(p_x_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[0]) + ")");
  5559. ERR_FAIL_COND_MSG(p_z_groups > limits.maxComputeWorkGroupCount[2],
  5560. "Dispatch amount of Z compute groups (" + itos(p_x_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[0]) + ")");
  5561. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  5562. #endif
  5563. #ifdef DEBUG_ENABLED
  5564. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  5565. if (cl->validation.pipeline_push_constant_size > 0) {
  5566. //using push constants, check that they were supplied
  5567. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  5568. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  5569. }
  5570. #endif
  5571. //Bind descriptor sets
  5572. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  5573. if (cl->state.sets[i].pipeline_expected_format == 0) {
  5574. continue; //nothing expected by this pipeline
  5575. }
  5576. #ifdef DEBUG_ENABLED
  5577. if (cl->state.sets[i].pipeline_expected_format != cl->state.sets[i].uniform_set_format) {
  5578. if (cl->state.sets[i].uniform_set_format == 0) {
  5579. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  5580. } else if (uniform_set_owner.owns(cl->state.sets[i].uniform_set)) {
  5581. UniformSet *us = uniform_set_owner.getornull(cl->state.sets[i].uniform_set);
  5582. 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));
  5583. } else {
  5584. 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));
  5585. }
  5586. }
  5587. #endif
  5588. if (!cl->state.sets[i].bound) {
  5589. //All good, see if this requires re-binding
  5590. vkCmdBindDescriptorSets(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, cl->state.pipeline_layout, i, 1, &cl->state.sets[i].descriptor_set, 0, nullptr);
  5591. cl->state.sets[i].bound = true;
  5592. }
  5593. }
  5594. vkCmdDispatch(cl->command_buffer, p_x_groups, p_y_groups, p_z_groups);
  5595. }
  5596. void RenderingDeviceVulkan::compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset) {
  5597. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  5598. ERR_FAIL_COND(!compute_list);
  5599. ComputeList *cl = compute_list;
  5600. Buffer *buffer = storage_buffer_owner.getornull(p_buffer);
  5601. ERR_FAIL_COND(!buffer);
  5602. ERR_FAIL_COND_MSG(!(buffer->usage & STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT), "Buffer provided was not created to do indirect dispatch.");
  5603. ERR_FAIL_COND_MSG(p_offset + 12 > buffer->size, "Offset provided (+12) is past the end of buffer.");
  5604. #ifdef DEBUG_ENABLED
  5605. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  5606. #endif
  5607. #ifdef DEBUG_ENABLED
  5608. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  5609. if (cl->validation.pipeline_push_constant_size > 0) {
  5610. //using push constants, check that they were supplied
  5611. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  5612. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  5613. }
  5614. #endif
  5615. //Bind descriptor sets
  5616. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  5617. if (cl->state.sets[i].pipeline_expected_format == 0) {
  5618. continue; //nothing expected by this pipeline
  5619. }
  5620. #ifdef DEBUG_ENABLED
  5621. if (cl->state.sets[i].pipeline_expected_format != cl->state.sets[i].uniform_set_format) {
  5622. if (cl->state.sets[i].uniform_set_format == 0) {
  5623. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  5624. } else if (uniform_set_owner.owns(cl->state.sets[i].uniform_set)) {
  5625. UniformSet *us = uniform_set_owner.getornull(cl->state.sets[i].uniform_set);
  5626. 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));
  5627. } else {
  5628. 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));
  5629. }
  5630. }
  5631. #endif
  5632. if (!cl->state.sets[i].bound) {
  5633. //All good, see if this requires re-binding
  5634. vkCmdBindDescriptorSets(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, cl->state.pipeline_layout, i, 1, &cl->state.sets[i].descriptor_set, 0, nullptr);
  5635. cl->state.sets[i].bound = true;
  5636. }
  5637. }
  5638. vkCmdDispatchIndirect(cl->command_buffer, buffer->buffer, p_offset);
  5639. }
  5640. void RenderingDeviceVulkan::compute_list_add_barrier(ComputeListID p_list) {
  5641. #ifdef FORCE_FULL_BARRIER
  5642. _full_barrier(true);
  5643. #else
  5644. _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);
  5645. #endif
  5646. }
  5647. void RenderingDeviceVulkan::compute_list_end() {
  5648. ERR_FAIL_COND(!compute_list);
  5649. for (Set<Texture *>::Element *E = compute_list->state.textures_to_sampled_layout.front(); E; E = E->next()) {
  5650. VkImageMemoryBarrier image_memory_barrier;
  5651. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  5652. image_memory_barrier.pNext = nullptr;
  5653. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  5654. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  5655. image_memory_barrier.oldLayout = E->get()->layout;
  5656. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  5657. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  5658. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  5659. image_memory_barrier.image = E->get()->image;
  5660. image_memory_barrier.subresourceRange.aspectMask = E->get()->read_aspect_mask;
  5661. image_memory_barrier.subresourceRange.baseMipLevel = E->get()->base_mipmap;
  5662. image_memory_barrier.subresourceRange.levelCount = E->get()->mipmaps;
  5663. image_memory_barrier.subresourceRange.baseArrayLayer = E->get()->base_layer;
  5664. image_memory_barrier.subresourceRange.layerCount = E->get()->layers;
  5665. 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);
  5666. E->get()->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  5667. }
  5668. memdelete(compute_list);
  5669. compute_list = nullptr;
  5670. #ifdef FORCE_FULL_BARRIER
  5671. _full_barrier(true);
  5672. #else
  5673. _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);
  5674. #endif
  5675. }
  5676. void RenderingDeviceVulkan::full_barrier() {
  5677. #ifndef DEBUG_ENABLED
  5678. ERR_PRINT("Full barrier is debug-only, should not be used in production");
  5679. #endif
  5680. _full_barrier(true);
  5681. }
  5682. #if 0
  5683. 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) {
  5684. VkCommandBuffer frame_cmdbuf = frames[frame].frame_buffer;
  5685. ERR_FAIL_COND(!frame_cmdbuf);
  5686. VkRenderPassBeginInfo render_pass_begin;
  5687. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  5688. render_pass_begin.pNext = nullptr;
  5689. render_pass_begin.renderPass = context->get_render_pass();
  5690. render_pass_begin.framebuffer = context->get_frame_framebuffer(frame);
  5691. render_pass_begin.renderArea.extent.width = context->get_screen_width(p_screen);
  5692. render_pass_begin.renderArea.extent.height = context->get_screen_height(p_screen);
  5693. render_pass_begin.renderArea.offset.x = 0;
  5694. render_pass_begin.renderArea.offset.y = 0;
  5695. render_pass_begin.clearValueCount = 1;
  5696. VkClearValue clear_value;
  5697. clear_value.color.float32[0] = p_clear_color.r;
  5698. clear_value.color.float32[1] = p_clear_color.g;
  5699. clear_value.color.float32[2] = p_clear_color.b;
  5700. clear_value.color.float32[3] = p_clear_color.a;
  5701. render_pass_begin.pClearValues = &clear_value;
  5702. vkCmdBeginRenderPass(frame_cmdbuf, &render_pass_begin, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS);
  5703. ID screen_format = screen_get_framebuffer_format();
  5704. {
  5705. VkCommandBuffer *command_buffers = (VkCommandBuffer *)alloca(sizeof(VkCommandBuffer) * p_draw_list_count);
  5706. uint32_t command_buffer_count = 0;
  5707. for (uint32_t i = 0; i < p_draw_list_count; i++) {
  5708. DrawList *dl = _get_draw_list_ptr(p_draw_lists[i]);
  5709. ERR_CONTINUE_MSG(!dl, "Draw list index (" + itos(i) + ") is not a valid draw list ID.");
  5710. ERR_CONTINUE_MSG(dl->validation.framebuffer_format != p_format_check,
  5711. "Draw list index (" + itos(i) + ") is created with a framebuffer format incompatible with this render pass.");
  5712. if (dl->validation.active) {
  5713. //needs to be closed, so close it.
  5714. vkEndCommandBuffer(dl->command_buffer);
  5715. dl->validation.active = false;
  5716. }
  5717. command_buffers[command_buffer_count++] = dl->command_buffer;
  5718. }
  5719. print_line("to draw: " + itos(command_buffer_count));
  5720. vkCmdExecuteCommands(p_primary, command_buffer_count, command_buffers);
  5721. }
  5722. vkCmdEndRenderPass(frame_cmdbuf);
  5723. }
  5724. #endif
  5725. void RenderingDeviceVulkan::_free_internal(RID p_id) {
  5726. //push everything so it's disposed of next time this frame index is processed (means, it's safe to do it)
  5727. if (texture_owner.owns(p_id)) {
  5728. Texture *texture = texture_owner.getornull(p_id);
  5729. frames[frame].textures_to_dispose_of.push_back(*texture);
  5730. texture_owner.free(p_id);
  5731. } else if (framebuffer_owner.owns(p_id)) {
  5732. Framebuffer *framebuffer = framebuffer_owner.getornull(p_id);
  5733. frames[frame].framebuffers_to_dispose_of.push_back(*framebuffer);
  5734. framebuffer_owner.free(p_id);
  5735. } else if (sampler_owner.owns(p_id)) {
  5736. VkSampler *sampler = sampler_owner.getornull(p_id);
  5737. frames[frame].samplers_to_dispose_of.push_back(*sampler);
  5738. sampler_owner.free(p_id);
  5739. } else if (vertex_buffer_owner.owns(p_id)) {
  5740. Buffer *vertex_buffer = vertex_buffer_owner.getornull(p_id);
  5741. frames[frame].buffers_to_dispose_of.push_back(*vertex_buffer);
  5742. vertex_buffer_owner.free(p_id);
  5743. } else if (vertex_array_owner.owns(p_id)) {
  5744. vertex_array_owner.free(p_id);
  5745. } else if (index_buffer_owner.owns(p_id)) {
  5746. IndexBuffer *index_buffer = index_buffer_owner.getornull(p_id);
  5747. Buffer b;
  5748. b.allocation = index_buffer->allocation;
  5749. b.buffer = index_buffer->buffer;
  5750. b.size = index_buffer->size;
  5751. frames[frame].buffers_to_dispose_of.push_back(b);
  5752. index_buffer_owner.free(p_id);
  5753. } else if (index_array_owner.owns(p_id)) {
  5754. index_array_owner.free(p_id);
  5755. } else if (shader_owner.owns(p_id)) {
  5756. Shader *shader = shader_owner.getornull(p_id);
  5757. frames[frame].shaders_to_dispose_of.push_back(*shader);
  5758. shader_owner.free(p_id);
  5759. } else if (uniform_buffer_owner.owns(p_id)) {
  5760. Buffer *uniform_buffer = uniform_buffer_owner.getornull(p_id);
  5761. frames[frame].buffers_to_dispose_of.push_back(*uniform_buffer);
  5762. uniform_buffer_owner.free(p_id);
  5763. } else if (texture_buffer_owner.owns(p_id)) {
  5764. TextureBuffer *texture_buffer = texture_buffer_owner.getornull(p_id);
  5765. frames[frame].buffers_to_dispose_of.push_back(texture_buffer->buffer);
  5766. frames[frame].buffer_views_to_dispose_of.push_back(texture_buffer->view);
  5767. texture_buffer_owner.free(p_id);
  5768. } else if (storage_buffer_owner.owns(p_id)) {
  5769. Buffer *storage_buffer = storage_buffer_owner.getornull(p_id);
  5770. frames[frame].buffers_to_dispose_of.push_back(*storage_buffer);
  5771. storage_buffer_owner.free(p_id);
  5772. } else if (uniform_set_owner.owns(p_id)) {
  5773. UniformSet *uniform_set = uniform_set_owner.getornull(p_id);
  5774. frames[frame].uniform_sets_to_dispose_of.push_back(*uniform_set);
  5775. uniform_set_owner.free(p_id);
  5776. } else if (render_pipeline_owner.owns(p_id)) {
  5777. RenderPipeline *pipeline = render_pipeline_owner.getornull(p_id);
  5778. frames[frame].render_pipelines_to_dispose_of.push_back(*pipeline);
  5779. render_pipeline_owner.free(p_id);
  5780. } else if (compute_pipeline_owner.owns(p_id)) {
  5781. ComputePipeline *pipeline = compute_pipeline_owner.getornull(p_id);
  5782. frames[frame].compute_pipelines_to_dispose_of.push_back(*pipeline);
  5783. compute_pipeline_owner.free(p_id);
  5784. } else {
  5785. ERR_PRINT("Attempted to free invalid ID: " + itos(p_id.get_id()));
  5786. }
  5787. }
  5788. void RenderingDeviceVulkan::free(RID p_id) {
  5789. _THREAD_SAFE_METHOD_
  5790. _free_dependencies(p_id); //recursively erase dependencies first, to avoid potential API problems
  5791. _free_internal(p_id);
  5792. }
  5793. void RenderingDeviceVulkan::_finalize_command_bufers() {
  5794. if (draw_list) {
  5795. ERR_PRINT("Found open draw list at the end of the frame, this should never happen (further drawing will likely not work).");
  5796. }
  5797. if (compute_list) {
  5798. ERR_PRINT("Found open compute list at the end of the frame, this should never happen (further compute will likely not work).");
  5799. }
  5800. { //complete the setup buffer (that needs to be processed before anything else)
  5801. vkEndCommandBuffer(frames[frame].setup_command_buffer);
  5802. vkEndCommandBuffer(frames[frame].draw_command_buffer);
  5803. }
  5804. }
  5805. void RenderingDeviceVulkan::_begin_frame() {
  5806. //erase pending resources
  5807. _free_pending_resources(frame);
  5808. //create setup command buffer and set as the setup buffer
  5809. {
  5810. VkCommandBufferBeginInfo cmdbuf_begin;
  5811. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  5812. cmdbuf_begin.pNext = nullptr;
  5813. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  5814. cmdbuf_begin.pInheritanceInfo = nullptr;
  5815. VkResult err = vkResetCommandBuffer(frames[frame].setup_command_buffer, 0);
  5816. ERR_FAIL_COND_MSG(err, "vkResetCommandBuffer failed with error " + itos(err) + ".");
  5817. err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  5818. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  5819. err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  5820. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  5821. if (local_device.is_null()) {
  5822. context->append_command_buffer(frames[frame].draw_command_buffer);
  5823. context->set_setup_buffer(frames[frame].setup_command_buffer); //append now so it's added before everything else
  5824. }
  5825. }
  5826. //advance current frame
  5827. frames_drawn++;
  5828. //advance staging buffer if used
  5829. if (staging_buffer_used) {
  5830. staging_buffer_current = (staging_buffer_current + 1) % staging_buffer_blocks.size();
  5831. staging_buffer_used = false;
  5832. }
  5833. if (frames[frame].timestamp_count) {
  5834. 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);
  5835. SWAP(frames[frame].timestamp_names, frames[frame].timestamp_result_names);
  5836. SWAP(frames[frame].timestamp_cpu_values, frames[frame].timestamp_cpu_result_values);
  5837. }
  5838. frames[frame].timestamp_result_count = frames[frame].timestamp_count;
  5839. frames[frame].timestamp_count = 0;
  5840. frames[frame].index = Engine::get_singleton()->get_frames_drawn();
  5841. }
  5842. void RenderingDeviceVulkan::swap_buffers() {
  5843. ERR_FAIL_COND_MSG(local_device.is_valid(), "Local devices can't swap buffers.");
  5844. _THREAD_SAFE_METHOD_
  5845. _finalize_command_bufers();
  5846. screen_prepared = false;
  5847. //swap buffers
  5848. context->swap_buffers();
  5849. frame = (frame + 1) % frame_count;
  5850. _begin_frame();
  5851. }
  5852. void RenderingDeviceVulkan::submit() {
  5853. ERR_FAIL_COND_MSG(local_device.is_null(), "Only local devices can submit and sync.");
  5854. ERR_FAIL_COND_MSG(local_device_processing, "device already submitted, call sync to wait until done.");
  5855. _finalize_command_bufers();
  5856. VkCommandBuffer command_buffers[2] = { frames[frame].setup_command_buffer, frames[frame].draw_command_buffer };
  5857. context->local_device_push_command_buffers(local_device, command_buffers, 2);
  5858. local_device_processing = true;
  5859. }
  5860. void RenderingDeviceVulkan::sync() {
  5861. ERR_FAIL_COND_MSG(local_device.is_null(), "Only local devices can submit and sync.");
  5862. ERR_FAIL_COND_MSG(!local_device_processing, "sync can only be called after a submit");
  5863. context->local_device_sync(local_device);
  5864. _begin_frame();
  5865. local_device_processing = false;
  5866. }
  5867. void RenderingDeviceVulkan::_free_pending_resources(int p_frame) {
  5868. //free in dependency usage order, so nothing weird happens
  5869. //pipelines
  5870. while (frames[p_frame].render_pipelines_to_dispose_of.front()) {
  5871. RenderPipeline *pipeline = &frames[p_frame].render_pipelines_to_dispose_of.front()->get();
  5872. vkDestroyPipeline(device, pipeline->pipeline, nullptr);
  5873. frames[p_frame].render_pipelines_to_dispose_of.pop_front();
  5874. }
  5875. while (frames[p_frame].compute_pipelines_to_dispose_of.front()) {
  5876. ComputePipeline *pipeline = &frames[p_frame].compute_pipelines_to_dispose_of.front()->get();
  5877. vkDestroyPipeline(device, pipeline->pipeline, nullptr);
  5878. frames[p_frame].compute_pipelines_to_dispose_of.pop_front();
  5879. }
  5880. //uniform sets
  5881. while (frames[p_frame].uniform_sets_to_dispose_of.front()) {
  5882. UniformSet *uniform_set = &frames[p_frame].uniform_sets_to_dispose_of.front()->get();
  5883. vkFreeDescriptorSets(device, uniform_set->pool->pool, 1, &uniform_set->descriptor_set);
  5884. _descriptor_pool_free(uniform_set->pool_key, uniform_set->pool);
  5885. frames[p_frame].uniform_sets_to_dispose_of.pop_front();
  5886. }
  5887. //buffer views
  5888. while (frames[p_frame].buffer_views_to_dispose_of.front()) {
  5889. VkBufferView buffer_view = frames[p_frame].buffer_views_to_dispose_of.front()->get();
  5890. vkDestroyBufferView(device, buffer_view, nullptr);
  5891. frames[p_frame].buffer_views_to_dispose_of.pop_front();
  5892. }
  5893. //shaders
  5894. while (frames[p_frame].shaders_to_dispose_of.front()) {
  5895. Shader *shader = &frames[p_frame].shaders_to_dispose_of.front()->get();
  5896. //descriptor set layout for each set
  5897. for (int i = 0; i < shader->sets.size(); i++) {
  5898. vkDestroyDescriptorSetLayout(device, shader->sets[i].descriptor_set_layout, nullptr);
  5899. }
  5900. //pipeline layout
  5901. vkDestroyPipelineLayout(device, shader->pipeline_layout, nullptr);
  5902. //shaders themselves
  5903. for (int i = 0; i < shader->pipeline_stages.size(); i++) {
  5904. vkDestroyShaderModule(device, shader->pipeline_stages[i].module, nullptr);
  5905. }
  5906. frames[p_frame].shaders_to_dispose_of.pop_front();
  5907. }
  5908. //samplers
  5909. while (frames[p_frame].samplers_to_dispose_of.front()) {
  5910. VkSampler sampler = frames[p_frame].samplers_to_dispose_of.front()->get();
  5911. vkDestroySampler(device, sampler, nullptr);
  5912. frames[p_frame].samplers_to_dispose_of.pop_front();
  5913. }
  5914. //framebuffers
  5915. while (frames[p_frame].framebuffers_to_dispose_of.front()) {
  5916. Framebuffer *framebuffer = &frames[p_frame].framebuffers_to_dispose_of.front()->get();
  5917. for (Map<Framebuffer::VersionKey, Framebuffer::Version>::Element *E = framebuffer->framebuffers.front(); E; E = E->next()) {
  5918. //first framebuffer, then render pass because it depends on it
  5919. vkDestroyFramebuffer(device, E->get().framebuffer, nullptr);
  5920. vkDestroyRenderPass(device, E->get().render_pass, nullptr);
  5921. }
  5922. frames[p_frame].framebuffers_to_dispose_of.pop_front();
  5923. }
  5924. //textures
  5925. while (frames[p_frame].textures_to_dispose_of.front()) {
  5926. Texture *texture = &frames[p_frame].textures_to_dispose_of.front()->get();
  5927. if (texture->bound) {
  5928. WARN_PRINT("Deleted a texture while it was bound..");
  5929. }
  5930. vkDestroyImageView(device, texture->view, nullptr);
  5931. if (texture->owner.is_null()) {
  5932. //actually owns the image and the allocation too
  5933. vmaDestroyImage(allocator, texture->image, texture->allocation);
  5934. }
  5935. frames[p_frame].textures_to_dispose_of.pop_front();
  5936. }
  5937. //buffers
  5938. while (frames[p_frame].buffers_to_dispose_of.front()) {
  5939. _buffer_free(&frames[p_frame].buffers_to_dispose_of.front()->get());
  5940. frames[p_frame].buffers_to_dispose_of.pop_front();
  5941. }
  5942. }
  5943. void RenderingDeviceVulkan::prepare_screen_for_drawing() {
  5944. _THREAD_SAFE_METHOD_
  5945. context->prepare_buffers();
  5946. screen_prepared = true;
  5947. }
  5948. uint32_t RenderingDeviceVulkan::get_frame_delay() const {
  5949. return frame_count;
  5950. }
  5951. uint64_t RenderingDeviceVulkan::get_memory_usage() const {
  5952. VmaStats stats;
  5953. vmaCalculateStats(allocator, &stats);
  5954. return stats.total.usedBytes;
  5955. }
  5956. void RenderingDeviceVulkan::_flush(bool p_current_frame) {
  5957. if (local_device.is_valid() && !p_current_frame) {
  5958. return; //flushign previous frames has no effect with local device
  5959. }
  5960. //not doing this crashes RADV (undefined behavior)
  5961. if (p_current_frame) {
  5962. vkEndCommandBuffer(frames[frame].setup_command_buffer);
  5963. vkEndCommandBuffer(frames[frame].draw_command_buffer);
  5964. }
  5965. if (local_device.is_valid()) {
  5966. VkCommandBuffer command_buffers[2] = { frames[frame].setup_command_buffer, frames[frame].draw_command_buffer };
  5967. context->local_device_push_command_buffers(local_device, command_buffers, 2);
  5968. context->local_device_sync(local_device);
  5969. VkCommandBufferBeginInfo cmdbuf_begin;
  5970. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  5971. cmdbuf_begin.pNext = nullptr;
  5972. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  5973. cmdbuf_begin.pInheritanceInfo = nullptr;
  5974. VkResult err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  5975. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  5976. err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  5977. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  5978. } else {
  5979. context->flush(p_current_frame, p_current_frame);
  5980. //re-create the setup command
  5981. if (p_current_frame) {
  5982. VkCommandBufferBeginInfo cmdbuf_begin;
  5983. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  5984. cmdbuf_begin.pNext = nullptr;
  5985. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  5986. cmdbuf_begin.pInheritanceInfo = nullptr;
  5987. VkResult err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  5988. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  5989. context->set_setup_buffer(frames[frame].setup_command_buffer); //append now so it's added before everything else
  5990. }
  5991. if (p_current_frame) {
  5992. VkCommandBufferBeginInfo cmdbuf_begin;
  5993. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  5994. cmdbuf_begin.pNext = nullptr;
  5995. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  5996. cmdbuf_begin.pInheritanceInfo = nullptr;
  5997. VkResult err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  5998. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  5999. context->append_command_buffer(frames[frame].draw_command_buffer);
  6000. }
  6001. }
  6002. }
  6003. void RenderingDeviceVulkan::initialize(VulkanContext *p_context, bool p_local_device) {
  6004. context = p_context;
  6005. device = p_context->get_device();
  6006. if (p_local_device) {
  6007. frame_count = 1;
  6008. local_device = p_context->local_device_create();
  6009. device = p_context->local_device_get_vk_device(local_device);
  6010. } else {
  6011. 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.
  6012. }
  6013. limits = p_context->get_device_limits();
  6014. max_timestamp_query_elements = 256;
  6015. { //initialize allocator
  6016. VmaAllocatorCreateInfo allocatorInfo;
  6017. memset(&allocatorInfo, 0, sizeof(VmaAllocatorCreateInfo));
  6018. allocatorInfo.physicalDevice = p_context->get_physical_device();
  6019. allocatorInfo.device = device;
  6020. vmaCreateAllocator(&allocatorInfo, &allocator);
  6021. }
  6022. frames = memnew_arr(Frame, frame_count);
  6023. frame = 0;
  6024. //create setup and frame buffers
  6025. for (int i = 0; i < frame_count; i++) {
  6026. frames[i].index = 0;
  6027. { //create command pool, one per frame is recommended
  6028. VkCommandPoolCreateInfo cmd_pool_info;
  6029. cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  6030. cmd_pool_info.pNext = nullptr;
  6031. cmd_pool_info.queueFamilyIndex = p_context->get_graphics_queue();
  6032. cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  6033. VkResult res = vkCreateCommandPool(device, &cmd_pool_info, nullptr, &frames[i].command_pool);
  6034. ERR_FAIL_COND_MSG(res, "vkCreateCommandPool failed with error " + itos(res) + ".");
  6035. }
  6036. { //create command buffers
  6037. VkCommandBufferAllocateInfo cmdbuf;
  6038. //no command buffer exists, create it.
  6039. cmdbuf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  6040. cmdbuf.pNext = nullptr;
  6041. cmdbuf.commandPool = frames[i].command_pool;
  6042. cmdbuf.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  6043. cmdbuf.commandBufferCount = 1;
  6044. VkResult err = vkAllocateCommandBuffers(device, &cmdbuf, &frames[i].setup_command_buffer);
  6045. ERR_CONTINUE_MSG(err, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  6046. err = vkAllocateCommandBuffers(device, &cmdbuf, &frames[i].draw_command_buffer);
  6047. ERR_CONTINUE_MSG(err, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  6048. }
  6049. {
  6050. //create query pool
  6051. VkQueryPoolCreateInfo query_pool_create_info;
  6052. query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
  6053. query_pool_create_info.flags = 0;
  6054. query_pool_create_info.pNext = nullptr;
  6055. query_pool_create_info.queryType = VK_QUERY_TYPE_TIMESTAMP;
  6056. query_pool_create_info.queryCount = max_timestamp_query_elements;
  6057. query_pool_create_info.pipelineStatistics = 0;
  6058. vkCreateQueryPool(device, &query_pool_create_info, nullptr, &frames[i].timestamp_pool);
  6059. frames[i].timestamp_names = memnew_arr(String, max_timestamp_query_elements);
  6060. frames[i].timestamp_cpu_values = memnew_arr(uint64_t, max_timestamp_query_elements);
  6061. frames[i].timestamp_count = 0;
  6062. frames[i].timestamp_result_names = memnew_arr(String, max_timestamp_query_elements);
  6063. frames[i].timestamp_cpu_result_values = memnew_arr(uint64_t, max_timestamp_query_elements);
  6064. frames[i].timestamp_result_values = memnew_arr(uint64_t, max_timestamp_query_elements);
  6065. frames[i].timestamp_result_count = 0;
  6066. }
  6067. }
  6068. {
  6069. //begin the first command buffer for the first frame, so
  6070. //setting up things can be done in the meantime until swap_buffers(), which is called before advance.
  6071. VkCommandBufferBeginInfo cmdbuf_begin;
  6072. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  6073. cmdbuf_begin.pNext = nullptr;
  6074. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  6075. cmdbuf_begin.pInheritanceInfo = nullptr;
  6076. VkResult err = vkBeginCommandBuffer(frames[0].setup_command_buffer, &cmdbuf_begin);
  6077. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  6078. err = vkBeginCommandBuffer(frames[0].draw_command_buffer, &cmdbuf_begin);
  6079. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  6080. if (local_device.is_null()) {
  6081. context->set_setup_buffer(frames[0].setup_command_buffer); //append now so it's added before everything else
  6082. context->append_command_buffer(frames[0].draw_command_buffer);
  6083. }
  6084. }
  6085. staging_buffer_block_size = GLOBAL_DEF("rendering/vulkan/staging_buffer/block_size_kb", 256);
  6086. staging_buffer_block_size = MAX(4, staging_buffer_block_size);
  6087. staging_buffer_block_size *= 1024; //kb -> bytes
  6088. staging_buffer_max_size = GLOBAL_DEF("rendering/vulkan/staging_buffer/max_size_mb", 128);
  6089. staging_buffer_max_size = MAX(1, staging_buffer_max_size);
  6090. staging_buffer_max_size *= 1024 * 1024;
  6091. if (staging_buffer_max_size < staging_buffer_block_size * 4) {
  6092. //validate enough blocks
  6093. staging_buffer_max_size = staging_buffer_block_size * 4;
  6094. }
  6095. texture_upload_region_size_px = GLOBAL_DEF("rendering/vulkan/staging_buffer/texture_upload_region_size_px", 64);
  6096. texture_upload_region_size_px = nearest_power_of_2_templated(texture_upload_region_size_px);
  6097. frames_drawn = frame_count; //start from frame count, so everything else is immediately old
  6098. //ensure current staging block is valid and at least one per frame exists
  6099. staging_buffer_current = 0;
  6100. staging_buffer_used = false;
  6101. for (int i = 0; i < frame_count; i++) {
  6102. //staging was never used, create a block
  6103. Error err = _insert_staging_block();
  6104. ERR_CONTINUE(err != OK);
  6105. }
  6106. max_descriptors_per_pool = GLOBAL_DEF("rendering/vulkan/descriptor_pools/max_descriptors_per_pool", 64);
  6107. //check to make sure DescriptorPoolKey is good
  6108. static_assert(sizeof(uint64_t) * 3 >= UNIFORM_TYPE_MAX * sizeof(uint16_t));
  6109. draw_list = nullptr;
  6110. draw_list_count = 0;
  6111. draw_list_split = false;
  6112. compute_list = nullptr;
  6113. }
  6114. template <class T>
  6115. void RenderingDeviceVulkan::_free_rids(T &p_owner, const char *p_type) {
  6116. List<RID> owned;
  6117. p_owner.get_owned_list(&owned);
  6118. if (owned.size()) {
  6119. WARN_PRINT(itos(owned.size()) + " RIDs of type '" + p_type + "' were leaked.");
  6120. for (List<RID>::Element *E = owned.front(); E; E = E->next()) {
  6121. free(E->get());
  6122. }
  6123. }
  6124. }
  6125. void RenderingDeviceVulkan::capture_timestamp(const String &p_name, bool p_sync_to_draw) {
  6126. ERR_FAIL_COND(frames[frame].timestamp_count >= max_timestamp_query_elements);
  6127. {
  6128. VkMemoryBarrier memoryBarrier;
  6129. memoryBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  6130. memoryBarrier.pNext = nullptr;
  6131. memoryBarrier.srcAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  6132. VK_ACCESS_INDEX_READ_BIT |
  6133. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  6134. VK_ACCESS_UNIFORM_READ_BIT |
  6135. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  6136. VK_ACCESS_SHADER_READ_BIT |
  6137. VK_ACCESS_SHADER_WRITE_BIT |
  6138. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  6139. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  6140. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  6141. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  6142. VK_ACCESS_TRANSFER_READ_BIT |
  6143. VK_ACCESS_TRANSFER_WRITE_BIT |
  6144. VK_ACCESS_HOST_READ_BIT |
  6145. VK_ACCESS_HOST_WRITE_BIT;
  6146. memoryBarrier.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  6147. VK_ACCESS_INDEX_READ_BIT |
  6148. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  6149. VK_ACCESS_UNIFORM_READ_BIT |
  6150. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  6151. VK_ACCESS_SHADER_READ_BIT |
  6152. VK_ACCESS_SHADER_WRITE_BIT |
  6153. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  6154. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  6155. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  6156. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  6157. VK_ACCESS_TRANSFER_READ_BIT |
  6158. VK_ACCESS_TRANSFER_WRITE_BIT |
  6159. VK_ACCESS_HOST_READ_BIT |
  6160. VK_ACCESS_HOST_WRITE_BIT;
  6161. 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);
  6162. }
  6163. 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);
  6164. frames[frame].timestamp_names[frames[frame].timestamp_count] = p_name;
  6165. frames[frame].timestamp_cpu_values[frames[frame].timestamp_count] = OS::get_singleton()->get_ticks_usec();
  6166. frames[frame].timestamp_count++;
  6167. }
  6168. uint32_t RenderingDeviceVulkan::get_captured_timestamps_count() const {
  6169. return frames[frame].timestamp_result_count;
  6170. }
  6171. uint64_t RenderingDeviceVulkan::get_captured_timestamps_frame() const {
  6172. return frames[frame].index;
  6173. }
  6174. static void mult64to128(uint64_t u, uint64_t v, uint64_t &h, uint64_t &l) {
  6175. uint64_t u1 = (u & 0xffffffff);
  6176. uint64_t v1 = (v & 0xffffffff);
  6177. uint64_t t = (u1 * v1);
  6178. uint64_t w3 = (t & 0xffffffff);
  6179. uint64_t k = (t >> 32);
  6180. u >>= 32;
  6181. t = (u * v1) + k;
  6182. k = (t & 0xffffffff);
  6183. uint64_t w1 = (t >> 32);
  6184. v >>= 32;
  6185. t = (u1 * v) + k;
  6186. k = (t >> 32);
  6187. h = (u * v) + w1 + k;
  6188. l = (t << 32) + w3;
  6189. }
  6190. uint64_t RenderingDeviceVulkan::get_captured_timestamp_gpu_time(uint32_t p_index) const {
  6191. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0);
  6192. // this sucks because timestampPeriod multiplier is a float, while the timestamp is 64 bits nanosecs.
  6193. // so, in cases like nvidia which give you enormous numbers and 1 as multiplier, multiplying is next to impossible
  6194. // need to do 128 bits fixed point multiplication to get the rigth value
  6195. uint64_t shift_bits = 16;
  6196. uint64_t h, l;
  6197. mult64to128(frames[frame].timestamp_result_values[p_index], uint64_t(double(limits.timestampPeriod) * double(1 << shift_bits)), h, l);
  6198. l >>= shift_bits;
  6199. l |= h << (64 - shift_bits);
  6200. return l;
  6201. }
  6202. uint64_t RenderingDeviceVulkan::get_captured_timestamp_cpu_time(uint32_t p_index) const {
  6203. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0);
  6204. return frames[frame].timestamp_cpu_result_values[p_index];
  6205. }
  6206. String RenderingDeviceVulkan::get_captured_timestamp_name(uint32_t p_index) const {
  6207. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, String());
  6208. return frames[frame].timestamp_result_names[p_index];
  6209. }
  6210. int RenderingDeviceVulkan::limit_get(Limit p_limit) {
  6211. switch (p_limit) {
  6212. case LIMIT_MAX_BOUND_UNIFORM_SETS:
  6213. return limits.maxBoundDescriptorSets;
  6214. case LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS:
  6215. return limits.maxColorAttachments;
  6216. case LIMIT_MAX_TEXTURES_PER_UNIFORM_SET:
  6217. return limits.maxDescriptorSetSampledImages;
  6218. case LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET:
  6219. return limits.maxDescriptorSetSamplers;
  6220. case LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET:
  6221. return limits.maxDescriptorSetStorageBuffers;
  6222. case LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET:
  6223. return limits.maxDescriptorSetStorageImages;
  6224. case LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET:
  6225. return limits.maxDescriptorSetUniformBuffers;
  6226. case LIMIT_MAX_DRAW_INDEXED_INDEX:
  6227. return limits.maxDrawIndexedIndexValue;
  6228. case LIMIT_MAX_FRAMEBUFFER_HEIGHT:
  6229. return limits.maxFramebufferHeight;
  6230. case LIMIT_MAX_FRAMEBUFFER_WIDTH:
  6231. return limits.maxFramebufferWidth;
  6232. case LIMIT_MAX_TEXTURE_ARRAY_LAYERS:
  6233. return limits.maxImageArrayLayers;
  6234. case LIMIT_MAX_TEXTURE_SIZE_1D:
  6235. return limits.maxImageDimension1D;
  6236. case LIMIT_MAX_TEXTURE_SIZE_2D:
  6237. return limits.maxImageDimension2D;
  6238. case LIMIT_MAX_TEXTURE_SIZE_3D:
  6239. return limits.maxImageDimension3D;
  6240. case LIMIT_MAX_TEXTURE_SIZE_CUBE:
  6241. return limits.maxImageDimensionCube;
  6242. case LIMIT_MAX_TEXTURES_PER_SHADER_STAGE:
  6243. return limits.maxPerStageDescriptorSampledImages;
  6244. case LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE:
  6245. return limits.maxPerStageDescriptorSamplers;
  6246. case LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE:
  6247. return limits.maxPerStageDescriptorStorageBuffers;
  6248. case LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE:
  6249. return limits.maxPerStageDescriptorStorageImages;
  6250. case LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE:
  6251. return limits.maxPerStageDescriptorUniformBuffers;
  6252. case LIMIT_MAX_PUSH_CONSTANT_SIZE:
  6253. return limits.maxPushConstantsSize;
  6254. case LIMIT_MAX_UNIFORM_BUFFER_SIZE:
  6255. return limits.maxUniformBufferRange;
  6256. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET:
  6257. return limits.maxVertexInputAttributeOffset;
  6258. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES:
  6259. return limits.maxVertexInputAttributes;
  6260. case LIMIT_MAX_VERTEX_INPUT_BINDINGS:
  6261. return limits.maxVertexInputBindings;
  6262. case LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE:
  6263. return limits.maxVertexInputBindingStride;
  6264. case LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
  6265. return limits.minUniformBufferOffsetAlignment;
  6266. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X:
  6267. return limits.maxComputeWorkGroupCount[0];
  6268. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y:
  6269. return limits.maxComputeWorkGroupCount[1];
  6270. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z:
  6271. return limits.maxComputeWorkGroupCount[2];
  6272. case LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS:
  6273. return limits.maxComputeWorkGroupInvocations;
  6274. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X:
  6275. return limits.maxComputeWorkGroupSize[0];
  6276. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y:
  6277. return limits.maxComputeWorkGroupSize[1];
  6278. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z:
  6279. return limits.maxComputeWorkGroupSize[2];
  6280. default:
  6281. ERR_FAIL_V(0);
  6282. }
  6283. return 0;
  6284. }
  6285. void RenderingDeviceVulkan::finalize() {
  6286. //free all resources
  6287. _flush(false);
  6288. _free_rids(render_pipeline_owner, "Pipeline");
  6289. _free_rids(compute_pipeline_owner, "Compute");
  6290. _free_rids(uniform_set_owner, "UniformSet");
  6291. _free_rids(texture_buffer_owner, "TextureBuffer");
  6292. _free_rids(storage_buffer_owner, "StorageBuffer");
  6293. _free_rids(uniform_buffer_owner, "UniformBuffer");
  6294. _free_rids(shader_owner, "Shader");
  6295. _free_rids(index_array_owner, "IndexArray");
  6296. _free_rids(index_buffer_owner, "IndexBuffer");
  6297. _free_rids(vertex_array_owner, "VertexArray");
  6298. _free_rids(vertex_buffer_owner, "VertexBuffer");
  6299. _free_rids(framebuffer_owner, "Framebuffer");
  6300. _free_rids(sampler_owner, "Sampler");
  6301. {
  6302. //for textures it's a bit more difficult because they may be shared
  6303. List<RID> owned;
  6304. texture_owner.get_owned_list(&owned);
  6305. if (owned.size()) {
  6306. WARN_PRINT(itos(owned.size()) + " RIDs of type 'Texture' were leaked.");
  6307. //free shared first
  6308. for (List<RID>::Element *E = owned.front(); E;) {
  6309. List<RID>::Element *N = E->next();
  6310. if (texture_is_shared(E->get())) {
  6311. free(E->get());
  6312. owned.erase(E->get());
  6313. }
  6314. E = N;
  6315. }
  6316. //free non shared second, this will avoid an error trying to free unexisting textures due to dependencies.
  6317. for (List<RID>::Element *E = owned.front(); E; E = E->next()) {
  6318. free(E->get());
  6319. }
  6320. }
  6321. }
  6322. //free everything pending
  6323. for (int i = 0; i < frame_count; i++) {
  6324. int f = (frame + i) % frame_count;
  6325. _free_pending_resources(f);
  6326. vkDestroyCommandPool(device, frames[i].command_pool, nullptr);
  6327. vkDestroyQueryPool(device, frames[i].timestamp_pool, nullptr);
  6328. memdelete_arr(frames[i].timestamp_names);
  6329. memdelete_arr(frames[i].timestamp_cpu_values);
  6330. memdelete_arr(frames[i].timestamp_result_names);
  6331. memdelete_arr(frames[i].timestamp_result_values);
  6332. memdelete_arr(frames[i].timestamp_cpu_result_values);
  6333. }
  6334. for (int i = 0; i < split_draw_list_allocators.size(); i++) {
  6335. vkDestroyCommandPool(device, split_draw_list_allocators[i].command_pool, nullptr);
  6336. }
  6337. memdelete_arr(frames);
  6338. for (int i = 0; i < staging_buffer_blocks.size(); i++) {
  6339. vmaDestroyBuffer(allocator, staging_buffer_blocks[i].buffer, staging_buffer_blocks[i].allocation);
  6340. }
  6341. vmaDestroyAllocator(allocator);
  6342. while (vertex_formats.size()) {
  6343. Map<VertexFormatID, VertexDescriptionCache>::Element *temp = vertex_formats.front();
  6344. memdelete_arr(temp->get().bindings);
  6345. memdelete_arr(temp->get().attributes);
  6346. vertex_formats.erase(temp);
  6347. }
  6348. for (int i = 0; i < framebuffer_formats.size(); i++) {
  6349. vkDestroyRenderPass(device, framebuffer_formats[i].render_pass, nullptr);
  6350. }
  6351. framebuffer_formats.clear();
  6352. //all these should be clear at this point
  6353. ERR_FAIL_COND(descriptor_pools.size());
  6354. ERR_FAIL_COND(dependency_map.size());
  6355. ERR_FAIL_COND(reverse_dependency_map.size());
  6356. }
  6357. RenderingDevice *RenderingDeviceVulkan::create_local_device() {
  6358. RenderingDeviceVulkan *rd = memnew(RenderingDeviceVulkan);
  6359. rd->initialize(context, true);
  6360. return rd;
  6361. }
  6362. RenderingDeviceVulkan::RenderingDeviceVulkan() {
  6363. screen_prepared = false;
  6364. }
  6365. RenderingDeviceVulkan::~RenderingDeviceVulkan() {
  6366. if (local_device.is_valid()) {
  6367. finalize();
  6368. context->local_device_free(local_device);
  6369. }
  6370. }