rendering_device_vulkan.cpp 335 KB

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