rendering_device_vulkan.cpp 384 KB

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