rendering_device_vulkan.cpp 294 KB

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