rendering_device_vulkan.cpp 377 KB

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