renderer_webgpu.cpp 151 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000
  1. /*
  2. * Copyright 2011-2019 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "bgfx_p.h"
  6. //#define DAWN_ENABLE_BACKEND_D3D12
  7. #define DAWN_ENABLE_BACKEND_VULKAN
  8. #if BGFX_CONFIG_RENDERER_WEBGPU
  9. # include "renderer_webgpu.h"
  10. # include "renderer.h"
  11. # include "debug_renderdoc.h"
  12. # include "emscripten.h"
  13. # include "shader_spirv.h"
  14. # if BX_PLATFORM_ANDROID
  15. # define VK_USE_PLATFORM_ANDROID_KHR
  16. # elif BX_PLATFORM_LINUX
  17. # define VK_USE_PLATFORM_XLIB_KHR
  18. # define VK_USE_PLATFORM_XCB_KHR
  19. # elif BX_PLATFORM_WINDOWS
  20. # define VK_USE_PLATFORM_WIN32_KHR
  21. # elif BX_PLATFORM_OSX
  22. # define VK_USE_PLATFORM_MACOS_MVK
  23. # endif // BX_PLATFORM_*
  24. # define VK_NO_STDINT_H
  25. # define VK_NO_PROTOTYPES
  26. # include <vulkan-local/vulkan.h>
  27. # if BX_PLATFORM_EMSCRIPTEN
  28. # include "emscripten.h"
  29. # include "emscripten/html5_webgpu.h"
  30. # else
  31. # ifdef DAWN_ENABLE_BACKEND_D3D12
  32. # include <dawn_native/D3D12Backend.h>
  33. # endif // !BX_PLATFORM_EMSCRIPTEN
  34. # ifdef DAWN_ENABLE_BACKEND_VULKAN
  35. # include <dawn_native/VulkanBackend.h>
  36. # endif // DAWN_ENABLE_BACKEND_VULKAN
  37. # include <dawn_native/DawnNative.h>
  38. # include <dawn/dawn_wsi.h>
  39. # include <dawn/dawn_proc.h>
  40. # endif // !BX_PLATFORM_EMSCRIPTEN
  41. namespace bgfx { namespace webgpu
  42. {
  43. // TODO (hugoam) cleanup
  44. template <class T>
  45. T defaultDescriptor() { return T(); }
  46. template <> wgpu::BlendComponent defaultDescriptor() { return { wgpu::BlendOperation::Add, wgpu::BlendFactor::One, wgpu::BlendFactor::Zero }; }
  47. template <> wgpu::ColorTargetState defaultDescriptor() { return { NULL, wgpu::TextureFormat::RGBA8Unorm, NULL, wgpu::ColorWriteMask::All }; }
  48. template <> wgpu::StencilFaceState defaultDescriptor() { return { wgpu::CompareFunction::Always, wgpu::StencilOperation::Keep, wgpu::StencilOperation::Keep, wgpu::StencilOperation::Keep }; }
  49. template <> wgpu::VertexState defaultDescriptor() { return { NULL, {}, "main", 0, NULL }; }
  50. template <> wgpu::FragmentState defaultDescriptor() { return { NULL, {}, "main", 0, NULL }; }
  51. template <> wgpu::VertexBufferLayout defaultDescriptor() { return { 0, wgpu::InputStepMode::Vertex, 0, NULL }; }
  52. template <> wgpu::VertexAttribute defaultDescriptor() { return { wgpu::VertexFormat::Float, 0, 0 }; }
  53. template <> wgpu::PrimitiveState defaultDescriptor() { return { NULL, wgpu::PrimitiveTopology::TriangleList, wgpu::IndexFormat::Undefined, wgpu::FrontFace::CCW, wgpu::CullMode::None }; }
  54. template <> wgpu::DepthStencilState defaultDescriptor() { return { NULL, wgpu::TextureFormat::Depth24PlusStencil8, false, wgpu::CompareFunction::Always, defaultDescriptor<wgpu::StencilFaceState>(), defaultDescriptor<wgpu::StencilFaceState>(), 0xff, 0xff }; }
  55. template <> wgpu::PipelineLayoutDescriptor defaultDescriptor() { return { NULL, "", 0, NULL }; }
  56. template <> wgpu::TextureViewDescriptor defaultDescriptor() { return {}; }
  57. template <> wgpu::RenderPassColorAttachment defaultDescriptor() { return { {}, {}, wgpu::LoadOp::Clear, wgpu::StoreOp::Store, { 0.0f, 0.0f, 0.0f, 0.0f } }; }
  58. template <> wgpu::RenderPassDepthStencilAttachment defaultDescriptor() { return { {}, wgpu::LoadOp::Clear, wgpu::StoreOp::Store, 1.0f, false, wgpu::LoadOp::Clear, wgpu::StoreOp::Store, 0, false }; }
  59. RenderPassDescriptor::RenderPassDescriptor()
  60. {
  61. depthStencilAttachment = defaultDescriptor<wgpu::RenderPassDepthStencilAttachment>();
  62. for(uint32_t i = 0; i < kMaxColorAttachments; ++i)
  63. {
  64. colorAttachments[i] = defaultDescriptor<wgpu::RenderPassColorAttachment>();
  65. }
  66. desc = defaultDescriptor<wgpu::RenderPassDescriptor>();
  67. //desc.colorAttachmentCount = colorAttachmentCount;
  68. desc.colorAttachments = colorAttachments;
  69. desc.colorAttachmentCount = 1; // TODO (hugoam) set it properly everywhere
  70. }
  71. VertexStateDescriptor::VertexStateDescriptor()
  72. {
  73. for(uint32_t i = 0; i < kMaxVertexInputs; ++i)
  74. {
  75. buffers[i] = defaultDescriptor<wgpu::VertexBufferLayout>();
  76. }
  77. for (uint32_t i = 0; i < kMaxVertexAttributes; ++i)
  78. {
  79. attributes[i] = defaultDescriptor<wgpu::VertexAttribute>();
  80. }
  81. buffers[0].attributes = &attributes[0];
  82. //buffers[0].attributeCount = numAttributes;
  83. desc = defaultDescriptor<wgpu::VertexState>();
  84. desc.buffers = buffers;
  85. //desc.vertexBufferCount = numVertexBuffers;
  86. }
  87. RenderPipelineDescriptor::RenderPipelineDescriptor()
  88. {
  89. //vertex = defaultDescriptor<wgpu::VertexState>();
  90. fragment = defaultDescriptor<wgpu::FragmentState>();
  91. depthStencil = defaultDescriptor<wgpu::DepthStencilState>();
  92. for(uint32_t i = 0; i < kMaxColorAttachments; ++i)
  93. {
  94. targets[i] = defaultDescriptor<wgpu::ColorTargetState>();
  95. }
  96. desc = defaultDescriptor<wgpu::RenderPipelineDescriptor2>();
  97. desc.primitive.topology = wgpu::PrimitiveTopology::TriangleList;
  98. desc.multisample.count = 1;
  99. fragment.targetCount = 1;
  100. fragment.targets = targets;
  101. //wgpu::VertexStateDescriptor inputState = inputState.descriptor();
  102. desc.vertex = defaultDescriptor<wgpu::VertexState>();
  103. desc.fragment = NULL;
  104. //desc.vertexState = &inputState;
  105. desc.primitive = defaultDescriptor<wgpu::PrimitiveState>();
  106. desc.depthStencil = NULL;
  107. }
  108. // TODO (hugoam) cleanup (end)
  109. static char s_viewName[BGFX_CONFIG_MAX_VIEWS][BGFX_CONFIG_MAX_VIEW_NAME];
  110. inline void setViewType(ViewId _view, const bx::StringView _str)
  111. {
  112. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION || BGFX_CONFIG_PROFILER) )
  113. {
  114. bx::memCopy(&s_viewName[_view][3], _str.getPtr(), _str.getLength() );
  115. }
  116. }
  117. struct PrimInfo
  118. {
  119. wgpu::PrimitiveTopology m_type;
  120. uint32_t m_min;
  121. uint32_t m_div;
  122. uint32_t m_sub;
  123. };
  124. static const PrimInfo s_primInfo[] =
  125. {
  126. { wgpu::PrimitiveTopology::TriangleList, 3, 3, 0 },
  127. { wgpu::PrimitiveTopology::TriangleStrip, 3, 1, 2 },
  128. { wgpu::PrimitiveTopology::LineList, 2, 2, 0 },
  129. { wgpu::PrimitiveTopology::LineStrip, 2, 1, 1 },
  130. { wgpu::PrimitiveTopology::PointList, 1, 1, 0 },
  131. };
  132. BX_STATIC_ASSERT(Topology::Count == BX_COUNTOF(s_primInfo) );
  133. static const wgpu::VertexFormat s_attribType[][4][2] =
  134. {
  135. { // Uint8
  136. { wgpu::VertexFormat::Uint8x2, wgpu::VertexFormat::Unorm8x2 },
  137. { wgpu::VertexFormat::Uint8x2, wgpu::VertexFormat::Unorm8x2 },
  138. { wgpu::VertexFormat::Uint8x4, wgpu::VertexFormat::Unorm8x4 },
  139. { wgpu::VertexFormat::Uint8x4, wgpu::VertexFormat::Unorm8x4 },
  140. },
  141. { // Uint10
  142. { wgpu::VertexFormat::Uint16x2, wgpu::VertexFormat::Unorm16x2 },
  143. { wgpu::VertexFormat::Uint16x2, wgpu::VertexFormat::Unorm16x2 },
  144. { wgpu::VertexFormat::Uint16x4, wgpu::VertexFormat::Unorm16x4 },
  145. { wgpu::VertexFormat::Uint16x4, wgpu::VertexFormat::Unorm16x4 },
  146. },
  147. { // Int16
  148. { wgpu::VertexFormat::Sint16x2, wgpu::VertexFormat::Snorm16x2 },
  149. { wgpu::VertexFormat::Sint16x2, wgpu::VertexFormat::Snorm16x2 },
  150. { wgpu::VertexFormat::Sint16x4, wgpu::VertexFormat::Snorm16x4 },
  151. { wgpu::VertexFormat::Sint16x4, wgpu::VertexFormat::Snorm16x4 },
  152. },
  153. { // Half
  154. { wgpu::VertexFormat::Float16x2, wgpu::VertexFormat::Float16x2 },
  155. { wgpu::VertexFormat::Float16x2, wgpu::VertexFormat::Float16x2 },
  156. { wgpu::VertexFormat::Float16x4, wgpu::VertexFormat::Float16x4 },
  157. { wgpu::VertexFormat::Float16x4, wgpu::VertexFormat::Float16x4 },
  158. },
  159. { // Float
  160. { wgpu::VertexFormat::Float32, wgpu::VertexFormat::Float32 },
  161. { wgpu::VertexFormat::Float32x2, wgpu::VertexFormat::Float32x2 },
  162. { wgpu::VertexFormat::Float32x3, wgpu::VertexFormat::Float32x3 },
  163. { wgpu::VertexFormat::Float32x4, wgpu::VertexFormat::Float32x4 },
  164. },
  165. };
  166. BX_STATIC_ASSERT(AttribType::Count == BX_COUNTOF(s_attribType) );
  167. static const wgpu::CullMode s_cullMode[] =
  168. {
  169. wgpu::CullMode::None,
  170. wgpu::CullMode::Front,
  171. wgpu::CullMode::Back,
  172. wgpu::CullMode::None,
  173. };
  174. static const wgpu::BlendFactor s_blendFactor[][2] =
  175. {
  176. { wgpu::BlendFactor(0), wgpu::BlendFactor(0) }, // ignored
  177. { wgpu::BlendFactor::Zero, wgpu::BlendFactor::Zero }, // ZERO
  178. { wgpu::BlendFactor::One, wgpu::BlendFactor::One }, // ONE
  179. { wgpu::BlendFactor::SrcColor, wgpu::BlendFactor::SrcAlpha }, // SRC_COLOR
  180. { wgpu::BlendFactor::OneMinusSrcColor, wgpu::BlendFactor::OneMinusSrcAlpha }, // INV_SRC_COLOR
  181. { wgpu::BlendFactor::SrcAlpha, wgpu::BlendFactor::SrcAlpha }, // SRC_ALPHA
  182. { wgpu::BlendFactor::OneMinusSrcAlpha, wgpu::BlendFactor::OneMinusSrcAlpha }, // INV_SRC_ALPHA
  183. { wgpu::BlendFactor::DstAlpha, wgpu::BlendFactor::DstAlpha }, // DST_ALPHA
  184. { wgpu::BlendFactor::OneMinusDstAlpha, wgpu::BlendFactor::OneMinusDstAlpha }, // INV_DST_ALPHA
  185. { wgpu::BlendFactor::DstColor, wgpu::BlendFactor::DstAlpha }, // DST_COLOR
  186. { wgpu::BlendFactor::OneMinusDstColor, wgpu::BlendFactor::OneMinusDstAlpha }, // INV_DST_COLOR
  187. { wgpu::BlendFactor::SrcAlphaSaturated, wgpu::BlendFactor::One }, // SRC_ALPHA_SAT
  188. { wgpu::BlendFactor::BlendColor, wgpu::BlendFactor::BlendColor }, // FACTOR
  189. { wgpu::BlendFactor::OneMinusBlendColor, wgpu::BlendFactor::OneMinusBlendColor }, // INV_FACTOR
  190. };
  191. static const wgpu::BlendOperation s_blendEquation[] =
  192. {
  193. wgpu::BlendOperation::Add,
  194. wgpu::BlendOperation::Subtract,
  195. wgpu::BlendOperation::ReverseSubtract,
  196. wgpu::BlendOperation::Min,
  197. wgpu::BlendOperation::Max,
  198. };
  199. static const wgpu::CompareFunction s_cmpFunc[] =
  200. {
  201. wgpu::CompareFunction::Always, // ignored
  202. wgpu::CompareFunction::Less,
  203. wgpu::CompareFunction::LessEqual,
  204. wgpu::CompareFunction::Equal,
  205. wgpu::CompareFunction::GreaterEqual,
  206. wgpu::CompareFunction::Greater,
  207. wgpu::CompareFunction::NotEqual,
  208. wgpu::CompareFunction::Never,
  209. wgpu::CompareFunction::Always,
  210. };
  211. static const wgpu::StencilOperation s_stencilOp[] =
  212. {
  213. wgpu::StencilOperation::Zero,
  214. wgpu::StencilOperation::Keep,
  215. wgpu::StencilOperation::Replace,
  216. wgpu::StencilOperation::IncrementWrap,
  217. wgpu::StencilOperation::IncrementClamp,
  218. wgpu::StencilOperation::DecrementWrap,
  219. wgpu::StencilOperation::DecrementClamp,
  220. wgpu::StencilOperation::Invert,
  221. };
  222. static const wgpu::AddressMode s_textureAddress[] =
  223. {
  224. wgpu::AddressMode::Repeat,
  225. wgpu::AddressMode::MirrorRepeat,
  226. wgpu::AddressMode::ClampToEdge,
  227. wgpu::AddressMode(0), // Border ? ClampToZero ?
  228. };
  229. static const wgpu::FilterMode s_textureFilterMinMag[] =
  230. {
  231. wgpu::FilterMode::Linear,
  232. wgpu::FilterMode::Nearest,
  233. wgpu::FilterMode::Linear,
  234. };
  235. static const wgpu::FilterMode s_textureFilterMip[] =
  236. {
  237. wgpu::FilterMode::Linear,
  238. wgpu::FilterMode::Nearest,
  239. };
  240. struct TextureFormatInfo
  241. {
  242. wgpu::TextureFormat m_fmt;
  243. wgpu::TextureFormat m_fmtSrgb;
  244. };
  245. static TextureFormatInfo s_textureFormat[] =
  246. {
  247. { wgpu::TextureFormat::BC1RGBAUnorm, wgpu::TextureFormat::BC1RGBAUnormSrgb }, // BC1
  248. { wgpu::TextureFormat::BC2RGBAUnorm, wgpu::TextureFormat::BC2RGBAUnormSrgb }, // BC2
  249. { wgpu::TextureFormat::BC3RGBAUnorm, wgpu::TextureFormat::BC3RGBAUnormSrgb }, // BC3
  250. { wgpu::TextureFormat::BC4RUnorm, wgpu::TextureFormat::Undefined }, // BC4 // BC4RSnorm ??
  251. { wgpu::TextureFormat::BC5RGUnorm, wgpu::TextureFormat::Undefined }, // BC5 // BC5RGSnorm ??
  252. { wgpu::TextureFormat::BC6HRGBUfloat, wgpu::TextureFormat::Undefined }, // BC6H // BC6HRGBSfloat ??
  253. { wgpu::TextureFormat::BC7RGBAUnorm, wgpu::TextureFormat::BC7RGBAUnormSrgb }, // BC7
  254. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ETC1
  255. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ETC2
  256. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ETC2A
  257. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ETC2A1
  258. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // PTC12
  259. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // PTC14
  260. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // PTC12A
  261. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // PTC14A
  262. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // PTC22
  263. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // PTC24
  264. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ATC
  265. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ATCE
  266. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ATCI
  267. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ASTC4x4
  268. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ASTC5x5
  269. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ASTC6x6
  270. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ASTC8x5
  271. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ASTC8x6
  272. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ASTC10x5
  273. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // Unknown
  274. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // R1
  275. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // A8
  276. { wgpu::TextureFormat::R8Unorm, wgpu::TextureFormat::Undefined }, // R8
  277. { wgpu::TextureFormat::R8Sint, wgpu::TextureFormat::Undefined }, // R8I
  278. { wgpu::TextureFormat::R8Uint, wgpu::TextureFormat::Undefined }, // R8U
  279. { wgpu::TextureFormat::R8Snorm, wgpu::TextureFormat::Undefined }, // R8S
  280. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // R16
  281. { wgpu::TextureFormat::R16Sint, wgpu::TextureFormat::Undefined }, // R16I
  282. { wgpu::TextureFormat::R16Uint, wgpu::TextureFormat::Undefined }, // R16U
  283. { wgpu::TextureFormat::R16Float, wgpu::TextureFormat::Undefined }, // R16F
  284. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // R16S
  285. { wgpu::TextureFormat::R32Sint, wgpu::TextureFormat::Undefined }, // R32I
  286. { wgpu::TextureFormat::R32Uint, wgpu::TextureFormat::Undefined }, // R32U
  287. { wgpu::TextureFormat::R32Float, wgpu::TextureFormat::Undefined }, // R32F
  288. { wgpu::TextureFormat::RG8Unorm, wgpu::TextureFormat::Undefined }, // RG8
  289. { wgpu::TextureFormat::RG8Sint, wgpu::TextureFormat::Undefined }, // RG8I
  290. { wgpu::TextureFormat::RG8Uint, wgpu::TextureFormat::Undefined }, // RG8U
  291. { wgpu::TextureFormat::RG8Snorm, wgpu::TextureFormat::Undefined }, // RG8S
  292. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RG16
  293. { wgpu::TextureFormat::RG16Sint, wgpu::TextureFormat::Undefined }, // RG16I
  294. { wgpu::TextureFormat::RG16Uint, wgpu::TextureFormat::Undefined }, // RG16U
  295. { wgpu::TextureFormat::RG16Float, wgpu::TextureFormat::Undefined }, // RG16F
  296. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RG16S
  297. { wgpu::TextureFormat::RG32Sint, wgpu::TextureFormat::Undefined }, // RG32I
  298. { wgpu::TextureFormat::RG32Uint, wgpu::TextureFormat::Undefined }, // RG32U
  299. { wgpu::TextureFormat::RG32Float, wgpu::TextureFormat::Undefined }, // RG32F
  300. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGB8
  301. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGB8I
  302. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGB8U
  303. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGB8S
  304. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGB9E5F
  305. { wgpu::TextureFormat::BGRA8Unorm, wgpu::TextureFormat::BGRA8UnormSrgb }, // BGRA8
  306. { wgpu::TextureFormat::RGBA8Unorm, wgpu::TextureFormat::RGBA8UnormSrgb }, // RGBA8
  307. { wgpu::TextureFormat::RGBA8Sint, wgpu::TextureFormat::Undefined }, // RGBA8I
  308. { wgpu::TextureFormat::RGBA8Uint, wgpu::TextureFormat::Undefined }, // RGBA8U
  309. { wgpu::TextureFormat::RGBA8Snorm, wgpu::TextureFormat::Undefined }, // RGBA8S
  310. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGBA16
  311. { wgpu::TextureFormat::RGBA16Sint, wgpu::TextureFormat::Undefined }, // RGBA16I
  312. { wgpu::TextureFormat::RGBA16Uint, wgpu::TextureFormat::Undefined }, // RGBA16U
  313. { wgpu::TextureFormat::RGBA16Float, wgpu::TextureFormat::Undefined }, // RGBA16F
  314. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGBA16S
  315. { wgpu::TextureFormat::RGBA32Sint, wgpu::TextureFormat::Undefined }, // RGBA32I
  316. { wgpu::TextureFormat::RGBA32Uint, wgpu::TextureFormat::Undefined }, // RGBA32U
  317. { wgpu::TextureFormat::RGBA32Float, wgpu::TextureFormat::Undefined }, // RGBA32F
  318. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // R5G6B5
  319. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGBA4
  320. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGB5A1
  321. { wgpu::TextureFormat::RGB10A2Unorm, wgpu::TextureFormat::Undefined }, // RGB10A2
  322. { wgpu::TextureFormat::RG11B10Ufloat, wgpu::TextureFormat::Undefined }, // RG11B10F
  323. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // UnknownDepth
  324. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // D16
  325. { wgpu::TextureFormat::Depth24Plus, wgpu::TextureFormat::Undefined }, // D24
  326. { wgpu::TextureFormat::Depth24PlusStencil8, wgpu::TextureFormat::Undefined }, // D24S8
  327. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // D32
  328. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // D16F
  329. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // D24F
  330. { wgpu::TextureFormat::Depth32Float, wgpu::TextureFormat::Undefined }, // D32F
  331. { wgpu::TextureFormat::Stencil8, wgpu::TextureFormat::Undefined }, // D0S8
  332. };
  333. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_textureFormat));
  334. int32_t s_msaa[] =
  335. {
  336. 1,
  337. 2,
  338. 4,
  339. 8,
  340. 16,
  341. };
  342. struct RendererContextWgpu;
  343. static RendererContextWgpu* s_renderWgpu;
  344. static bool s_ignoreError = false;
  345. #if !BX_PLATFORM_EMSCRIPTEN
  346. DawnSwapChainImplementation(*createSwapChain)(wgpu::Device device, void* nwh);
  347. # if defined(DAWN_ENABLE_BACKEND_D3D12)
  348. DawnSwapChainImplementation CreateSwapChainD3D12(wgpu::Device device, void* nwh)
  349. {
  350. HWND win32Window = (HWND)nwh;
  351. return dawn_native::d3d12::CreateNativeSwapChainImpl(device.Get(), win32Window);
  352. }
  353. # endif // defined(DAWN_ENABLE_BACKEND_D3D12)
  354. # if defined(DAWN_ENABLE_BACKEND_VULKAN)
  355. DawnSwapChainImplementation CreateSwapChainVulkan(wgpu::Device device, void* nwh)
  356. {
  357. VkInstance instance = dawn_native::vulkan::GetInstance(device.Get());
  358. PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR = (PFN_vkCreateWin32SurfaceKHR)dawn_native::vulkan::GetInstanceProcAddr(device.Get(), "vkCreateWin32SurfaceKHR");
  359. VkSurfaceKHR surface;
  360. # if BX_PLATFORM_WINDOWS
  361. // Copied from renderer_vk.cpp -> needs refactor
  362. {
  363. VkWin32SurfaceCreateInfoKHR sci;
  364. sci.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
  365. sci.pNext = NULL;
  366. sci.flags = 0;
  367. sci.hinstance = (HINSTANCE)GetModuleHandle(NULL);
  368. sci.hwnd = (HWND)nwh;
  369. VkResult result = vkCreateWin32SurfaceKHR(instance, &sci, NULL, &surface);
  370. }
  371. # endif // BX_PLATFORM_WINDOWS
  372. return dawn_native::vulkan::CreateNativeSwapChainImpl(device.Get(), surface);
  373. }
  374. # endif // defined(DAWN_ENABLE_BACKEND_VULKAN)
  375. #endif // !BX_PLATFORM_EMSCRIPTEN
  376. struct RendererContextWgpu : public RendererContextI
  377. {
  378. RendererContextWgpu()
  379. : m_frameIndex(0)
  380. , m_numWindows(0)
  381. , m_rtMsaa(false)
  382. , m_capture(NULL)
  383. , m_captureSize(0)
  384. {
  385. bx::memSet(&m_windows, 0xff, sizeof(m_windows) );
  386. }
  387. ~RendererContextWgpu()
  388. {
  389. }
  390. bool init(const Init& _init)
  391. {
  392. BX_UNUSED(_init);
  393. BX_TRACE("Init.");
  394. if (_init.debug
  395. || _init.profile)
  396. {
  397. m_renderDocDll = loadRenderDoc();
  398. }
  399. setGraphicsDebuggerPresent(NULL != m_renderDocDll);
  400. m_fbh.idx = kInvalidHandle;
  401. bx::memSet(m_uniforms, 0, sizeof(m_uniforms) );
  402. bx::memSet(&m_resolution, 0, sizeof(m_resolution) );
  403. #if !BX_PLATFORM_EMSCRIPTEN
  404. // Default to D3D12, Metal, Vulkan, OpenGL in that order as D3D12 and Metal are the preferred on
  405. // their respective platforms, and Vulkan is preferred to OpenGL
  406. # if defined(DAWN_ENABLE_BACKEND_D3D12)
  407. static wgpu::BackendType backendType = wgpu::BackendType::D3D12;
  408. # elif defined(DAWN_ENABLE_BACKEND_METAL)
  409. static wgpu::BackendType backendType = wgpu::BackendType::Metal;
  410. # elif defined(DAWN_ENABLE_BACKEND_OPENGL)
  411. static wgpu::BackendType backendType = wgpu::BackendType::OpenGL;
  412. # elif defined(DAWN_ENABLE_BACKEND_VULKAN)
  413. static wgpu::BackendType backendType = wgpu::BackendType::Vulkan;
  414. # else
  415. # error "Unknown platform."
  416. # endif // defined(DAWN_ENABLE_BACKEND_*)
  417. if (BX_ENABLED(BGFX_CONFIG_DEBUG))
  418. {
  419. m_instance.EnableBackendValidation(true);
  420. }
  421. m_instance.DiscoverDefaultAdapters();
  422. dawn_native::Adapter backendAdapter;
  423. std::vector<dawn_native::Adapter> adapters = m_instance.GetAdapters();
  424. for (dawn_native::Adapter& adapter : adapters)
  425. {
  426. wgpu::AdapterProperties properties;
  427. adapter.GetProperties(&properties);
  428. if (properties.backendType == backendType)
  429. {
  430. backendAdapter = adapter;
  431. break;
  432. }
  433. }
  434. //BX_ASSERT(adapterIt != adapters.end());
  435. dawn_native::DeviceDescriptor desc;
  436. # if defined(DAWN_ENABLE_BACKEND_D3D12)
  437. desc.forceEnabledToggles.push_back("use_dxc");
  438. # endif
  439. desc.forceDisabledToggles.push_back("disallow_unsafe_apis");
  440. WGPUDevice backendDevice = backendAdapter.CreateDevice(&desc);
  441. DawnProcTable backendProcs = dawn_native::GetProcs();
  442. using CreateSwapChain = DawnSwapChainImplementation (*)(wgpu::Device device, void* nwh);
  443. # if defined(DAWN_ENABLE_BACKEND_D3D12)
  444. createSwapChain = CreateSwapChainD3D12;
  445. # elif defined(DAWN_ENABLE_BACKEND_METAL)
  446. createSwapChain = CreateSwapChainMetal;
  447. # elif defined(DAWN_ENABLE_BACKEND_NULL)
  448. createSwapChain = CreateSwapChainNull;
  449. # elif defined(DAWN_ENABLE_BACKEND_OPENGL)
  450. createSwapChain = CreateSwapChainOpenGL;
  451. # elif defined(DAWN_ENABLE_BACKEND_VULKAN)
  452. createSwapChain = CreateSwapChainVulkan;
  453. # endif // defined(DAWN_ENABLE_BACKEND_*)
  454. // Choose whether to use the backend procs and devices directly, or set up the wire.
  455. WGPUDevice cDevice = backendDevice;
  456. DawnProcTable procs = backendProcs;
  457. dawnProcSetProcs(&procs);
  458. m_device = wgpu::Device::Acquire(cDevice);
  459. #else
  460. m_device = wgpu::Device(emscripten_webgpu_get_device());
  461. #endif // !BX_PLATFORM_EMSCRIPTEN
  462. auto PrintDeviceError = [](WGPUErrorType errorType, const char* message, void*) {
  463. BX_UNUSED(errorType);
  464. if (s_ignoreError)
  465. {
  466. BX_TRACE("Device error: %s", message);
  467. }
  468. else
  469. {
  470. BX_ASSERT(false, "Device error: %s", message);
  471. }
  472. s_ignoreError = false;
  473. };
  474. if (!m_device)
  475. {
  476. BX_WARN(!m_device, "Unable to create WebGPU device.");
  477. return false;
  478. }
  479. m_device.SetUncapturedErrorCallback(PrintDeviceError, NULL);
  480. bool success = m_mainFrameBuffer.create(
  481. 0
  482. , g_platformData.nwh
  483. , _init.resolution.width
  484. , _init.resolution.height
  485. , TextureFormat::Unknown
  486. , TextureFormat::UnknownDepth
  487. );
  488. m_numWindows = 1;
  489. if (!success)
  490. {
  491. return false;
  492. }
  493. m_queue = m_device.GetQueue();
  494. m_cmd.init(m_queue);
  495. //BGFX_FATAL(NULL != m_cmd.m_commandQueue, Fatal::UnableToInitialize, "Unable to create Metal device.");
  496. for (uint8_t ii = 0; ii < BGFX_CONFIG_MAX_FRAME_LATENCY; ++ii)
  497. {
  498. BX_TRACE("Create scratch buffer %d", ii);
  499. m_scratchBuffers[ii].create(BGFX_CONFIG_MAX_DRAW_CALLS * 128);
  500. m_bindStateCache[ii].create(); // (1024);
  501. }
  502. for (uint8_t ii = 0; ii < WEBGPU_NUM_UNIFORM_BUFFERS; ++ii)
  503. {
  504. bool mapped = true; // ii == WEBGPU_NUM_UNIFORM_BUFFERS - 1;
  505. m_uniformBuffers[ii].create(BGFX_CONFIG_MAX_DRAW_CALLS * 128, mapped);
  506. }
  507. g_caps.supported |= (0
  508. | BGFX_CAPS_ALPHA_TO_COVERAGE
  509. | BGFX_CAPS_BLEND_INDEPENDENT
  510. | BGFX_CAPS_FRAGMENT_DEPTH
  511. | BGFX_CAPS_INDEX32
  512. | BGFX_CAPS_INSTANCING
  513. // | BGFX_CAPS_OCCLUSION_QUERY
  514. | BGFX_CAPS_SWAP_CHAIN
  515. | BGFX_CAPS_TEXTURE_2D_ARRAY
  516. | BGFX_CAPS_TEXTURE_3D
  517. | BGFX_CAPS_TEXTURE_BLIT
  518. | BGFX_CAPS_TEXTURE_COMPARE_ALL
  519. | BGFX_CAPS_TEXTURE_COMPARE_LEQUAL
  520. | BGFX_CAPS_TEXTURE_READ_BACK
  521. | BGFX_CAPS_VERTEX_ATTRIB_HALF
  522. | BGFX_CAPS_VERTEX_ATTRIB_UINT10
  523. | BGFX_CAPS_COMPUTE
  524. );
  525. g_caps.limits.maxTextureSize = 8192;
  526. g_caps.limits.maxFBAttachments = 4;
  527. g_caps.supported |= BGFX_CAPS_TEXTURE_CUBE_ARRAY;
  528. g_caps.supported |= BGFX_CAPS_DRAW_INDIRECT;
  529. g_caps.limits.maxTextureLayers = 2048;
  530. g_caps.limits.maxVertexStreams = BGFX_CONFIG_MAX_VERTEX_STREAMS;
  531. // Maximum number of entries in the buffer argument table, per graphics or compute function are 31.
  532. // It is decremented by 1 because 1 entry is used for uniforms.
  533. g_caps.limits.maxComputeBindings = bx::uint32_min(30, BGFX_MAX_COMPUTE_BINDINGS);
  534. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  535. {
  536. uint16_t support = 0;
  537. support |= wgpu::TextureFormat::Undefined != s_textureFormat[ii].m_fmt
  538. ? BGFX_CAPS_FORMAT_TEXTURE_2D
  539. | BGFX_CAPS_FORMAT_TEXTURE_3D
  540. | BGFX_CAPS_FORMAT_TEXTURE_CUBE
  541. | BGFX_CAPS_FORMAT_TEXTURE_VERTEX
  542. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  543. ;
  544. support |= wgpu::TextureFormat::Undefined != s_textureFormat[ii].m_fmtSrgb
  545. ? BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB
  546. | BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB
  547. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB
  548. | BGFX_CAPS_FORMAT_TEXTURE_VERTEX
  549. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  550. ;
  551. if (!bimg::isCompressed(bimg::TextureFormat::Enum(ii) ) )
  552. {
  553. support |= 0
  554. | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER
  555. // | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA
  556. ;
  557. }
  558. g_caps.formats[ii] = support;
  559. }
  560. g_caps.formats[TextureFormat::A8 ] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  561. g_caps.formats[TextureFormat::RG32I ] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  562. g_caps.formats[TextureFormat::RG32U ] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  563. g_caps.formats[TextureFormat::RGBA32I] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  564. g_caps.formats[TextureFormat::RGBA32U] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  565. g_caps.formats[TextureFormat::ETC2 ] =
  566. g_caps.formats[TextureFormat::ETC2A ] =
  567. g_caps.formats[TextureFormat::ETC2A1] =
  568. g_caps.formats[TextureFormat::PTC12 ] =
  569. g_caps.formats[TextureFormat::PTC14 ] =
  570. g_caps.formats[TextureFormat::PTC12A] =
  571. g_caps.formats[TextureFormat::PTC14A] =
  572. g_caps.formats[TextureFormat::R5G6B5] =
  573. g_caps.formats[TextureFormat::RGBA4 ] =
  574. g_caps.formats[TextureFormat::RGB5A1] = BGFX_CAPS_FORMAT_TEXTURE_NONE;
  575. g_caps.formats[TextureFormat::RGB9E5F] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  576. g_caps.formats[TextureFormat::RG11B10F] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  577. // disable compressed formats
  578. for (uint32_t ii = 0; ii < TextureFormat::Unknown; ++ii)
  579. {
  580. s_textureFormat[ii].m_fmt = wgpu::TextureFormat::Undefined;
  581. }
  582. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  583. {
  584. if (BGFX_CAPS_FORMAT_TEXTURE_NONE == g_caps.formats[ii])
  585. {
  586. s_textureFormat[ii].m_fmt = wgpu::TextureFormat::Undefined;
  587. s_textureFormat[ii].m_fmtSrgb = wgpu::TextureFormat::Undefined;
  588. }
  589. }
  590. for (uint32_t ii = 1, last = 0; ii < BX_COUNTOF(s_msaa); ++ii)
  591. {
  592. // TODO (hugoam)
  593. //const int32_t sampleCount = 1; //1<<ii;
  594. //if (m_device.supportsTextureSampleCount(sampleCount) )
  595. //{
  596. // s_msaa[ii] = sampleCount;
  597. // last = ii;
  598. //}
  599. //else
  600. {
  601. s_msaa[ii] = s_msaa[last];
  602. }
  603. }
  604. // Init reserved part of view name.
  605. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  606. {
  607. bx::snprintf(s_viewName[ii], BGFX_CONFIG_MAX_VIEW_NAME_RESERVED+1, "%3d ", ii);
  608. }
  609. m_gpuTimer.init();
  610. g_internalData.context = &m_device;
  611. return true;
  612. }
  613. void shutdown()
  614. {
  615. m_gpuTimer.shutdown();
  616. m_pipelineStateCache.invalidate();
  617. for (uint32_t ii = 0; ii < BX_COUNTOF(m_shaders); ++ii)
  618. {
  619. m_shaders[ii].destroy();
  620. }
  621. for (uint32_t ii = 0; ii < BX_COUNTOF(m_textures); ++ii)
  622. {
  623. m_textures[ii].destroy();
  624. }
  625. captureFinish();
  626. m_mainFrameBuffer.destroy();
  627. for (uint32_t ii = 0; ii < BX_COUNTOF(m_scratchBuffers); ++ii)
  628. {
  629. m_scratchBuffers[ii].destroy();
  630. }
  631. m_cmd.shutdown();
  632. }
  633. RendererType::Enum getRendererType() const override
  634. {
  635. return RendererType::WebGPU;
  636. }
  637. const char* getRendererName() const override
  638. {
  639. return BGFX_RENDERER_WEBGPU_NAME;
  640. }
  641. void createIndexBuffer(IndexBufferHandle _handle, const Memory* _mem, uint16_t _flags) override
  642. {
  643. m_indexBuffers[_handle.idx].create(_mem->size, _mem->data, _flags);
  644. }
  645. void destroyIndexBuffer(IndexBufferHandle _handle) override
  646. {
  647. m_indexBuffers[_handle.idx].destroy();
  648. }
  649. void createVertexLayout(VertexLayoutHandle _handle, const VertexLayout& _decl) override
  650. {
  651. VertexLayout& decl = m_vertexDecls[_handle.idx];
  652. bx::memCopy(&decl, &_decl, sizeof(VertexLayout) );
  653. dump(decl);
  654. }
  655. void destroyVertexLayout(VertexLayoutHandle /*_handle*/) override
  656. {
  657. }
  658. void createVertexBuffer(VertexBufferHandle _handle, const Memory* _mem, VertexLayoutHandle _declHandle, uint16_t _flags) override
  659. {
  660. m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle, _flags);
  661. }
  662. void destroyVertexBuffer(VertexBufferHandle _handle) override
  663. {
  664. m_vertexBuffers[_handle.idx].destroy();
  665. }
  666. void createDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size, uint16_t _flags) override
  667. {
  668. m_indexBuffers[_handle.idx].create(_size, NULL, _flags);
  669. }
  670. void updateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, const Memory* _mem) override
  671. {
  672. m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  673. }
  674. void destroyDynamicIndexBuffer(IndexBufferHandle _handle) override
  675. {
  676. m_indexBuffers[_handle.idx].destroy();
  677. }
  678. void createDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size, uint16_t _flags) override
  679. {
  680. VertexLayoutHandle decl = BGFX_INVALID_HANDLE;
  681. m_vertexBuffers[_handle.idx].create(_size, NULL, decl, _flags);
  682. }
  683. void updateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, const Memory* _mem) override
  684. {
  685. m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  686. }
  687. void destroyDynamicVertexBuffer(VertexBufferHandle _handle) override
  688. {
  689. m_vertexBuffers[_handle.idx].destroy();
  690. }
  691. void createShader(ShaderHandle _handle, const Memory* _mem) override
  692. {
  693. m_shaders[_handle.idx].create(_handle, _mem);
  694. }
  695. void destroyShader(ShaderHandle _handle) override
  696. {
  697. m_shaders[_handle.idx].destroy();
  698. }
  699. void createProgram(ProgramHandle _handle, ShaderHandle _vsh, ShaderHandle _fsh) override
  700. {
  701. m_program[_handle.idx].create(&m_shaders[_vsh.idx], isValid(_fsh) ? &m_shaders[_fsh.idx] : NULL);
  702. }
  703. void destroyProgram(ProgramHandle _handle) override
  704. {
  705. m_program[_handle.idx].destroy();
  706. }
  707. void* createTexture(TextureHandle _handle, const Memory* _mem, uint64_t _flags, uint8_t _skip) override
  708. {
  709. m_textures[_handle.idx].create(_handle, _mem, _flags, _skip);
  710. return NULL;
  711. }
  712. void updateTextureBegin(TextureHandle /*_handle*/, uint8_t /*_side*/, uint8_t /*_mip*/) override
  713. {
  714. }
  715. void updateTexture(TextureHandle _handle, uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem) override
  716. {
  717. m_textures[_handle.idx].update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  718. }
  719. void updateTextureEnd() override
  720. {
  721. }
  722. void readback(ReadbackWgpu& readback, const TextureWgpu& texture, void* _data)
  723. {
  724. m_cmd.kick(false, true);
  725. m_cmd.beginRender();
  726. if (readback.m_mapped)
  727. return;
  728. BX_ASSERT(readback.m_mip<texture.m_numMips,"Invalid mip: %d num mips:", readback.m_mip,texture.m_numMips);
  729. uint32_t srcWidth = bx::uint32_max(1, texture.m_width >> readback.m_mip);
  730. uint32_t srcHeight = bx::uint32_max(1, texture.m_height >> readback.m_mip);
  731. const uint32_t bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(texture.m_textureFormat));
  732. const uint32_t pitch = srcWidth * bpp / 8;
  733. const uint32_t dstpitch = bx::strideAlign(pitch, kMinBufferOffsetAlignment);
  734. const uint32_t size = dstpitch * srcHeight;
  735. // TODO move inside ReadbackWgpu::create
  736. if (!readback.m_buffer)
  737. {
  738. wgpu::BufferDescriptor desc;
  739. desc.size = size;
  740. desc.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::MapRead;
  741. readback.m_buffer = m_device.CreateBuffer(&desc);
  742. }
  743. wgpu::ImageCopyTexture imageCopyTexture;
  744. imageCopyTexture.texture = texture.m_ptr;
  745. imageCopyTexture.origin = { 0, 0, 0 };
  746. wgpu::ImageCopyBuffer imageCopyBuffer;
  747. imageCopyBuffer.buffer = readback.m_buffer;
  748. imageCopyBuffer.layout.bytesPerRow = dstpitch;
  749. imageCopyBuffer.layout.rowsPerImage = srcHeight;
  750. wgpu::Extent3D extent3D = { srcWidth, srcHeight, 1 };
  751. getBlitCommandEncoder().CopyTextureToBuffer(&imageCopyTexture, &imageCopyBuffer, &extent3D);
  752. auto finish = [](WGPUBufferMapAsyncStatus status, void* userdata)
  753. {
  754. ReadbackWgpu* readback = static_cast<ReadbackWgpu*>(userdata);
  755. void const* data = readback->m_buffer.GetConstMappedRange();
  756. if(status == WGPUBufferMapAsyncStatus_Success)
  757. readback->readback(data);
  758. };
  759. m_cmd.finish();
  760. m_cmd.kick(true);
  761. readback.m_mapped = true;
  762. readback.m_data = _data;
  763. readback.m_size = pitch * srcHeight;
  764. readback.m_buffer.MapAsync(wgpu::MapMode::Read, 0, size, finish, &readback);
  765. }
  766. void readTexture(TextureHandle _handle, void* _data, uint8_t _mip) override
  767. {
  768. TextureWgpu& texture = m_textures[_handle.idx];
  769. readback(texture.m_readback, texture, _data);
  770. }
  771. void resizeTexture(TextureHandle _handle, uint16_t _width, uint16_t _height, uint8_t _numMips, uint16_t _numLayers) override
  772. {
  773. TextureWgpu& texture = m_textures[_handle.idx];
  774. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  775. const Memory* mem = alloc(size);
  776. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  777. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  778. bx::write(&writer, magic);
  779. TextureCreate tc;
  780. tc.m_width = _width;
  781. tc.m_height = _height;
  782. tc.m_depth = 0;
  783. tc.m_numLayers = _numLayers;
  784. tc.m_numMips = _numMips;
  785. tc.m_format = TextureFormat::Enum(texture.m_requestedFormat);
  786. tc.m_cubeMap = false;
  787. tc.m_mem = NULL;
  788. bx::write(&writer, tc);
  789. texture.destroy();
  790. texture.create(_handle, mem, texture.m_flags, 0);
  791. release(mem);
  792. }
  793. void overrideInternal(TextureHandle _handle, uintptr_t _ptr) override
  794. {
  795. BX_UNUSED(_handle, _ptr);
  796. }
  797. uintptr_t getInternal(TextureHandle _handle) override
  798. {
  799. BX_UNUSED(_handle);
  800. return 0;
  801. }
  802. void destroyTexture(TextureHandle _handle) override
  803. {
  804. m_textures[_handle.idx].destroy();
  805. }
  806. void createFrameBuffer(FrameBufferHandle _handle, uint8_t _num, const Attachment* _attachment) override
  807. {
  808. m_frameBuffers[_handle.idx].create(_num, _attachment);
  809. }
  810. void createFrameBuffer(FrameBufferHandle _handle, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _format, TextureFormat::Enum _depthFormat) override
  811. {
  812. for (uint32_t ii = 0, num = m_numWindows; ii < num; ++ii)
  813. {
  814. FrameBufferHandle handle = m_windows[ii];
  815. if (isValid(handle)
  816. && m_frameBuffers[handle.idx].m_nwh == _nwh)
  817. {
  818. destroyFrameBuffer(handle);
  819. }
  820. }
  821. uint16_t denseIdx = m_numWindows++;
  822. m_windows[denseIdx] = _handle;
  823. FrameBufferWgpu& fb = m_frameBuffers[_handle.idx];
  824. fb.create(denseIdx, _nwh, _width, _height, _format, _depthFormat);
  825. fb.m_swapChain->resize(m_frameBuffers[_handle.idx], _width, _height, 0);
  826. }
  827. void destroyFrameBuffer(FrameBufferHandle _handle) override
  828. {
  829. uint16_t denseIdx = m_frameBuffers[_handle.idx].destroy();
  830. if (UINT16_MAX != denseIdx)
  831. {
  832. --m_numWindows;
  833. if (m_numWindows > 1)
  834. {
  835. FrameBufferHandle handle = m_windows[m_numWindows];
  836. m_windows[m_numWindows] = {kInvalidHandle};
  837. if (m_numWindows != denseIdx)
  838. {
  839. m_windows[denseIdx] = handle;
  840. m_frameBuffers[handle.idx].m_denseIdx = denseIdx;
  841. }
  842. }
  843. }
  844. }
  845. void createUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name) override
  846. {
  847. if (NULL != m_uniforms[_handle.idx])
  848. {
  849. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  850. }
  851. uint32_t size = bx::alignUp(g_uniformTypeSize[_type]*_num, 16);
  852. void* data = BX_ALLOC(g_allocator, size);
  853. bx::memSet(data, 0, size);
  854. m_uniforms[_handle.idx] = data;
  855. m_uniformReg.add(_handle, _name);
  856. }
  857. void destroyUniform(UniformHandle _handle) override
  858. {
  859. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  860. m_uniforms[_handle.idx] = NULL;
  861. m_uniformReg.remove(_handle);
  862. }
  863. void requestScreenShot(FrameBufferHandle _handle, const char* _filePath) override
  864. {
  865. BX_UNUSED(_handle); BX_UNUSED(_filePath);
  866. }
  867. void updateViewName(ViewId _id, const char* _name) override
  868. {
  869. bx::strCopy(
  870. &s_viewName[_id][BGFX_CONFIG_MAX_VIEW_NAME_RESERVED]
  871. , BX_COUNTOF(s_viewName[0])-BGFX_CONFIG_MAX_VIEW_NAME_RESERVED
  872. , _name
  873. );
  874. }
  875. void updateUniform(uint16_t _loc, const void* _data, uint32_t _size) override
  876. {
  877. bx::memCopy(m_uniforms[_loc], _data, _size);
  878. }
  879. void invalidateOcclusionQuery(OcclusionQueryHandle _handle) override
  880. {
  881. BX_UNUSED(_handle);
  882. }
  883. void setMarker(const char* _marker, uint16_t _len) override
  884. {
  885. BX_UNUSED(_len);
  886. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION) )
  887. {
  888. m_renderEncoder.InsertDebugMarker(_marker);
  889. }
  890. }
  891. virtual void setName(Handle _handle, const char* _name, uint16_t _len) override
  892. {
  893. BX_UNUSED(_handle); BX_UNUSED(_name); BX_UNUSED(_len);
  894. BX_UNUSED(_len);
  895. switch (_handle.type)
  896. {
  897. case Handle::IndexBuffer:
  898. m_indexBuffers[_handle.idx].m_label.clear();
  899. m_indexBuffers[_handle.idx].m_label.append(_name);
  900. break;
  901. case Handle::Shader:
  902. m_shaders[_handle.idx].m_label.clear();
  903. m_shaders[_handle.idx].m_label.append(_name);
  904. break;
  905. case Handle::Texture:
  906. m_textures[_handle.idx].m_label.clear();
  907. m_textures[_handle.idx].m_label.append(_name);
  908. break;
  909. case Handle::VertexBuffer:
  910. m_vertexBuffers[_handle.idx].m_label.clear();
  911. m_vertexBuffers[_handle.idx].m_label.append(_name);
  912. break;
  913. default:
  914. BX_ASSERT(false, "Invalid handle type?! %d", _handle.type);
  915. break;
  916. }
  917. }
  918. void submitBlit(BlitState& _bs, uint16_t _view);
  919. void submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) override;
  920. void blitSetup(TextVideoMemBlitter& _blitter) override
  921. {
  922. BX_UNUSED(_blitter);
  923. }
  924. void blitRender(TextVideoMemBlitter& _blitter, uint32_t _numIndices) override
  925. {
  926. const uint32_t numVertices = _numIndices*4/6;
  927. if (0 < numVertices)
  928. {
  929. m_indexBuffers [_blitter.m_ib->handle.idx].update(
  930. 0
  931. , bx::strideAlign(_numIndices*2, 4)
  932. , _blitter.m_ib->data
  933. , true
  934. );
  935. m_vertexBuffers[_blitter.m_vb->handle.idx].update(
  936. 0
  937. , numVertices*_blitter.m_layout.m_stride
  938. , _blitter.m_vb->data
  939. , true
  940. );
  941. endEncoding();
  942. uint32_t width = m_resolution.width;
  943. uint32_t height = m_resolution.height;
  944. FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
  945. uint64_t state = 0
  946. | BGFX_STATE_WRITE_RGB
  947. | BGFX_STATE_WRITE_A
  948. | BGFX_STATE_DEPTH_TEST_ALWAYS
  949. ;
  950. PipelineStateWgpu* pso = getPipelineState(
  951. state
  952. , 0
  953. , 0
  954. , fbh
  955. , _blitter.m_vb->layoutHandle
  956. , false
  957. , _blitter.m_program
  958. , 0
  959. );
  960. RenderPassDescriptor renderPassDescriptor;
  961. wgpu::RenderPassColorAttachment& color = renderPassDescriptor.colorAttachments[0];
  962. setFrameBuffer(renderPassDescriptor, fbh);
  963. color.loadOp = wgpu::LoadOp::Load;
  964. color.storeOp = wgpu::StoreOp::Store;
  965. // NULL != renderPassDescriptor.colorAttachments[0].resolveTexture
  966. // ? wgpu::StoreOp::MultisampleResolve
  967. // : wgpu::StoreOp::Store
  968. //;
  969. wgpu::RenderPassEncoder rce = m_cmd.m_renderEncoder.BeginRenderPass(&renderPassDescriptor.desc);
  970. m_renderEncoder = rce;
  971. rce.SetViewport(0.0f, 0.0f, (float)width, (float)height, 0.0f, 1.0f);
  972. rce.SetScissorRect(0.0f, 0.0f, (float)width, (float)height);
  973. rce.SetPipeline(pso->m_rps);
  974. ProgramWgpu& program = m_program[_blitter.m_program.idx];
  975. ScratchBufferWgpu& scratchBuffer = m_scratchBuffers[0];
  976. BindStateCacheWgpu& bindStates = m_bindStateCache[0];
  977. float proj[16];
  978. bx::mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f, 0.0f, false);
  979. PredefinedUniform& predefined = program.m_predefined[0];
  980. uint8_t flags = predefined.m_type;
  981. setShaderUniform(flags, predefined.m_loc, proj, 4);
  982. BX_ASSERT(program.m_vsh->m_size > 0, "Not supposed to happen");
  983. const uint32_t voffset = scratchBuffer.write(m_vsScratch, program.m_vsh->m_gpuSize);
  984. const uint32_t fsize = (NULL != program.m_fsh ? program.m_fsh->m_gpuSize : 0);
  985. BX_ASSERT(fsize == 0, "Not supposed to happen");
  986. TextureWgpu& texture = m_textures[_blitter.m_texture.idx];
  987. BindingsWgpu b;
  988. BindStateWgpu& bindState = allocBindState(program, bindStates, b, scratchBuffer);
  989. wgpu::BindGroupEntry& textureEntry = b.m_entries[b.numEntries++];
  990. textureEntry.binding = program.m_textures[0].binding;
  991. textureEntry.textureView = texture.m_ptr.CreateView();
  992. wgpu::BindGroupEntry& samplerEntry = b.m_entries[b.numEntries++];
  993. samplerEntry.binding = program.m_samplers[0].binding;
  994. samplerEntry.sampler = 0 == (BGFX_SAMPLER_INTERNAL_DEFAULT & state)
  995. ? getSamplerState(state)
  996. : texture.m_sampler;
  997. bindGroups(program, bindState, b);
  998. uint32_t numOffset = 1;
  999. uint32_t offsets[1] = { voffset };
  1000. bindProgram(rce, program, bindState, numOffset, offsets);
  1001. VertexBufferWgpu& vb = m_vertexBuffers[_blitter.m_vb->handle.idx];
  1002. rce.SetVertexBuffer(0, vb.m_ptr);
  1003. IndexBufferWgpu& ib = m_indexBuffers[_blitter.m_ib->handle.idx];
  1004. rce.SetIndexBuffer(ib.m_ptr, ib.m_format);
  1005. rce.DrawIndexed(_numIndices, 1, 0, 0, 0);
  1006. }
  1007. }
  1008. bool isDeviceRemoved() override
  1009. {
  1010. return false;
  1011. }
  1012. void flip() override
  1013. {
  1014. for (uint32_t ii = 0, num = m_numWindows; ii < num; ++ii)
  1015. {
  1016. FrameBufferWgpu& frameBuffer = ii == 0 ? m_mainFrameBuffer : m_frameBuffers[m_windows[ii].idx];
  1017. if (NULL != frameBuffer.m_swapChain)
  1018. //&& frameBuffer.m_swapChain->m_drawable)
  1019. {
  1020. SwapChainWgpu& swapChain = *frameBuffer.m_swapChain;
  1021. swapChain.flip();
  1022. }
  1023. }
  1024. m_cmd.m_stagingEncoder = NULL;
  1025. m_cmd.m_renderEncoder = NULL;
  1026. }
  1027. void updateResolution(const Resolution& _resolution)
  1028. {
  1029. m_resolution = _resolution;
  1030. return; // TODO (hugoam)
  1031. m_mainFrameBuffer.m_swapChain->m_maxAnisotropy = !!(_resolution.reset & BGFX_RESET_MAXANISOTROPY)
  1032. ? 16
  1033. : 1
  1034. ;
  1035. const uint32_t maskFlags = ~(0
  1036. | BGFX_RESET_MAXANISOTROPY
  1037. | BGFX_RESET_DEPTH_CLAMP
  1038. | BGFX_RESET_SUSPEND
  1039. );
  1040. if (m_resolution.width != _resolution.width
  1041. || m_resolution.height != _resolution.height
  1042. || (m_resolution.reset&maskFlags) != (_resolution.reset&maskFlags) )
  1043. {
  1044. wgpu::TextureFormat prevMetalLayerPixelFormat; // = m_mainFrameBuffer.m_swapChain->m_metalLayer.pixelFormat;
  1045. BX_UNUSED(prevMetalLayerPixelFormat);
  1046. m_resolution = _resolution;
  1047. m_resolution.reset &= ~BGFX_RESET_INTERNAL_FORCE;
  1048. m_mainFrameBuffer.m_swapChain->resize(m_mainFrameBuffer, _resolution.width, _resolution.height, _resolution.reset);
  1049. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  1050. {
  1051. m_frameBuffers[ii].postReset();
  1052. }
  1053. updateCapture();
  1054. m_textVideoMem.resize(false, _resolution.width, _resolution.height);
  1055. m_textVideoMem.clear();
  1056. //if (prevMetalLayerPixelFormat != m_mainFrameBuffer.m_swapChain->m_metalLayer.pixelFormat)
  1057. {
  1058. //MTL_RELEASE(m_screenshotBlitRenderPipelineState)
  1059. //reset(m_renderPipelineDescriptor);
  1060. //m_renderPipelineDescriptor.colorAttachments[0].pixelFormat = m_mainFrameBuffer.m_swapChain->m_metalLayer.pixelFormat;
  1061. //m_renderPipelineDescriptor.vertexFunction = m_screenshotBlitProgram.m_vsh->m_function;
  1062. //m_renderPipelineDescriptor.fragmentFunction = m_screenshotBlitProgram.m_fsh->m_function;
  1063. //m_screenshotBlitRenderPipelineState = m_device.newRenderPipelineStateWithDescriptor(m_renderPipelineDescriptor);
  1064. }
  1065. }
  1066. }
  1067. void invalidateCompute()
  1068. {
  1069. if (m_computeEncoder)
  1070. {
  1071. m_computeEncoder.EndPass();
  1072. m_computeEncoder = NULL;
  1073. }
  1074. }
  1075. void updateCapture()
  1076. {
  1077. }
  1078. void capture()
  1079. {
  1080. }
  1081. void captureFinish()
  1082. {
  1083. }
  1084. BindStateWgpu& allocBindState(const ProgramWgpu& program, BindStateCacheWgpu& bindStates, BindingsWgpu& bindings, ScratchBufferWgpu& scratchBuffer)
  1085. {
  1086. BindStateWgpu& bindState = bindStates.m_bindStates[bindStates.m_currentBindState];
  1087. bindStates.m_currentBindState++;
  1088. bindState.numOffset = program.m_numUniforms;
  1089. // first two bindings are always uniform buffer (vertex/fragment)
  1090. if (0 < program.m_vsh->m_gpuSize)
  1091. {
  1092. bindings.m_entries[0].binding = kSpirvVertexBinding;
  1093. bindings.m_entries[0].offset = 0;
  1094. bindings.m_entries[0].size = program.m_vsh->m_gpuSize;
  1095. bindings.m_entries[0].buffer = scratchBuffer.m_buffer;
  1096. bindings.numEntries++;
  1097. }
  1098. if (NULL != program.m_fsh
  1099. && 0 < program.m_fsh->m_gpuSize)
  1100. {
  1101. bindings.m_entries[1].binding = kSpirvFragmentBinding;
  1102. bindings.m_entries[1].offset = 0;
  1103. bindings.m_entries[1].size = program.m_fsh->m_gpuSize;
  1104. bindings.m_entries[1].buffer = scratchBuffer.m_buffer;
  1105. bindings.numEntries++;
  1106. }
  1107. return bindState;
  1108. }
  1109. void bindGroups(const ProgramWgpu& program, BindStateWgpu& bindState, BindingsWgpu& bindings)
  1110. {
  1111. wgpu::BindGroupDescriptor bindGroupDesc;
  1112. bindGroupDesc.layout = program.m_bindGroupLayout;
  1113. bindGroupDesc.entryCount = bindings.numEntries;
  1114. bindGroupDesc.entries = bindings.m_entries;
  1115. bindState.m_bindGroup = m_device.CreateBindGroup(&bindGroupDesc);
  1116. }
  1117. template <class Encoder>
  1118. void bindProgram(Encoder& encoder, const ProgramWgpu& program, BindStateWgpu& bindState, uint32_t numOffset, uint32_t* offsets)
  1119. {
  1120. BX_ASSERT(bindState.numOffset == numOffset, "We're obviously doing something wrong");
  1121. encoder.SetBindGroup(0, bindState.m_bindGroup, numOffset, offsets);
  1122. }
  1123. BindStateWgpu& allocAndFillBindState(const ProgramWgpu& program, BindStateCacheWgpu& bindStates, ScratchBufferWgpu& scratchBuffer, const RenderBind& renderBind)
  1124. {
  1125. BindingsWgpu b;
  1126. BindStateWgpu& bindState = allocBindState(program, bindStates, b, scratchBuffer);
  1127. for (uint8_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  1128. {
  1129. const Binding& bind = renderBind.m_bind[stage];
  1130. const BindInfo& bindInfo = program.m_bindInfo[stage];
  1131. bool isUsed = isValid(program.m_bindInfo[stage].m_uniform);
  1132. BX_ASSERT(!isUsed || kInvalidHandle != bind.m_idx, "All expected bindings must be bound with WebGPU");
  1133. if (kInvalidHandle != bind.m_idx)
  1134. {
  1135. switch (bind.m_type)
  1136. {
  1137. case Binding::Image:
  1138. {
  1139. TextureWgpu& texture = m_textures[bind.m_idx];
  1140. wgpu::BindGroupEntry& entry = b.m_entries[b.numEntries++];
  1141. entry.binding = bindInfo.m_binding;
  1142. entry.textureView = texture.getTextureMipLevel(bind.m_mip);
  1143. if (Access::Read == bind.m_access)
  1144. {
  1145. wgpu::BindGroupEntry& samplerEntry = b.m_entries[b.numEntries++];
  1146. samplerEntry.binding = bindInfo.m_binding + 16;
  1147. samplerEntry.sampler = texture.m_sampler;
  1148. }
  1149. }
  1150. break;
  1151. case Binding::Texture:
  1152. {
  1153. // apparently bgfx allows to set a texture to a stage that a program does not even use
  1154. if (isUsed)
  1155. {
  1156. TextureWgpu& texture = m_textures[bind.m_idx];
  1157. uint32_t flags = bind.m_samplerFlags;
  1158. wgpu::TextureViewDescriptor viewDesc = defaultDescriptor<wgpu::TextureViewDescriptor>();
  1159. viewDesc.dimension = program.m_textures[bindInfo.m_index].texture.viewDimension;
  1160. wgpu::BindGroupEntry& textureEntry = b.m_entries[b.numEntries++];
  1161. textureEntry.binding = bindInfo.m_binding;
  1162. //textureEntry.textureView = texture.m_ptr.CreateView();
  1163. textureEntry.textureView = texture.m_ptr.CreateView(&viewDesc);
  1164. wgpu::BindGroupEntry& samplerEntry = b.m_entries[b.numEntries++];
  1165. samplerEntry.binding = bindInfo.m_binding + kSpirvSamplerShift;
  1166. samplerEntry.sampler = 0 == (BGFX_SAMPLER_INTERNAL_DEFAULT & flags)
  1167. ? getSamplerState(flags)
  1168. : texture.m_sampler;
  1169. }
  1170. }
  1171. break;
  1172. case Binding::IndexBuffer:
  1173. case Binding::VertexBuffer:
  1174. {
  1175. const BufferWgpu& buffer = Binding::IndexBuffer == bind.m_type
  1176. ? (const BufferWgpu&) m_indexBuffers[bind.m_idx]
  1177. : (const BufferWgpu&) m_vertexBuffers[bind.m_idx]
  1178. ;
  1179. wgpu::BindGroupEntry& entry = b.m_entries[b.numEntries++];
  1180. entry.binding = bindInfo.m_binding;
  1181. entry.offset = 0;
  1182. entry.size = buffer.m_size;
  1183. entry.buffer = buffer.m_ptr;
  1184. }
  1185. break;
  1186. }
  1187. }
  1188. }
  1189. bindGroups(program, bindState, b);
  1190. return bindState;
  1191. };
  1192. void setShaderUniform(uint8_t _flags, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  1193. {
  1194. if(_flags&kUniformFragmentBit)
  1195. {
  1196. bx::memCopy(&m_fsScratch[_regIndex], _val, _numRegs * 16);
  1197. }
  1198. else
  1199. {
  1200. bx::memCopy(&m_vsScratch[_regIndex], _val, _numRegs * 16);
  1201. }
  1202. }
  1203. void setShaderUniform4f(uint8_t _flags, uint32_t _loc, const void* _val, uint32_t _numRegs)
  1204. {
  1205. setShaderUniform(_flags, _loc, _val, _numRegs);
  1206. }
  1207. void setShaderUniform4x4f(uint8_t _flags, uint32_t _loc, const void* _val, uint32_t _numRegs)
  1208. {
  1209. setShaderUniform(_flags, _loc, _val, _numRegs);
  1210. }
  1211. void commit(UniformBuffer& _uniformBuffer)
  1212. {
  1213. _uniformBuffer.reset();
  1214. for (;;)
  1215. {
  1216. uint32_t opcode = _uniformBuffer.read();
  1217. if (UniformType::End == opcode)
  1218. {
  1219. break;
  1220. }
  1221. UniformType::Enum type;
  1222. uint16_t loc;
  1223. uint16_t num;
  1224. uint16_t copy;
  1225. UniformBuffer::decodeOpcode(opcode, type, loc, num, copy);
  1226. const char* data;
  1227. if (copy)
  1228. {
  1229. data = _uniformBuffer.read(g_uniformTypeSize[type]*num);
  1230. }
  1231. else
  1232. {
  1233. UniformHandle handle;
  1234. bx::memCopy(&handle, _uniformBuffer.read(sizeof(UniformHandle) ), sizeof(UniformHandle) );
  1235. data = (const char*)m_uniforms[handle.idx];
  1236. }
  1237. switch ( (uint32_t)type)
  1238. {
  1239. case UniformType::Mat3:
  1240. case UniformType::Mat3|kUniformFragmentBit:
  1241. {
  1242. float* value = (float*)data;
  1243. for (uint32_t ii = 0, count = num/3; ii < count; ++ii, loc += 3*16, value += 9)
  1244. {
  1245. Matrix4 mtx;
  1246. mtx.un.val[ 0] = value[0];
  1247. mtx.un.val[ 1] = value[1];
  1248. mtx.un.val[ 2] = value[2];
  1249. mtx.un.val[ 3] = 0.0f;
  1250. mtx.un.val[ 4] = value[3];
  1251. mtx.un.val[ 5] = value[4];
  1252. mtx.un.val[ 6] = value[5];
  1253. mtx.un.val[ 7] = 0.0f;
  1254. mtx.un.val[ 8] = value[6];
  1255. mtx.un.val[ 9] = value[7];
  1256. mtx.un.val[10] = value[8];
  1257. mtx.un.val[11] = 0.0f;
  1258. setShaderUniform(uint8_t(type), loc, &mtx.un.val[0], 3);
  1259. }
  1260. }
  1261. break;
  1262. case UniformType::Sampler:
  1263. case UniformType::Sampler | kUniformFragmentBit:
  1264. case UniformType::Vec4:
  1265. case UniformType::Vec4 | kUniformFragmentBit:
  1266. case UniformType::Mat4:
  1267. case UniformType::Mat4 | kUniformFragmentBit:
  1268. {
  1269. setShaderUniform(uint8_t(type), loc, data, num);
  1270. }
  1271. break;
  1272. case UniformType::End:
  1273. break;
  1274. default:
  1275. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", _uniformBuffer.getPos(), opcode, type, loc, num, copy);
  1276. break;
  1277. }
  1278. }
  1279. }
  1280. void clearQuad(ClearQuad& _clearQuad, const Rect& _rect, const Clear& _clear, const float _palette[][4])
  1281. {
  1282. uint32_t width;
  1283. uint32_t height;
  1284. if (isValid(m_fbh) )
  1285. {
  1286. const FrameBufferWgpu& fb = m_frameBuffers[m_fbh.idx];
  1287. width = fb.m_width;
  1288. height = fb.m_height;
  1289. }
  1290. else
  1291. {
  1292. width = m_resolution.width;
  1293. height = m_resolution.height;
  1294. }
  1295. uint64_t state = 0;
  1296. state |= _clear.m_flags & BGFX_CLEAR_COLOR ? BGFX_STATE_WRITE_RGB|BGFX_STATE_WRITE_A : 0;
  1297. state |= _clear.m_flags & BGFX_CLEAR_DEPTH ? BGFX_STATE_DEPTH_TEST_ALWAYS|BGFX_STATE_WRITE_Z : 0;
  1298. state |= BGFX_STATE_PT_TRISTRIP;
  1299. uint64_t stencil = 0;
  1300. stencil |= _clear.m_flags & BGFX_CLEAR_STENCIL ? 0
  1301. | BGFX_STENCIL_TEST_ALWAYS
  1302. | BGFX_STENCIL_FUNC_REF(_clear.m_stencil)
  1303. | BGFX_STENCIL_FUNC_RMASK(0xff)
  1304. | BGFX_STENCIL_OP_FAIL_S_REPLACE
  1305. | BGFX_STENCIL_OP_FAIL_Z_REPLACE
  1306. | BGFX_STENCIL_OP_PASS_Z_REPLACE
  1307. : 0
  1308. ;
  1309. uint32_t numMrt = 1;
  1310. FrameBufferHandle fbh = m_fbh;
  1311. if (isValid(fbh) && m_frameBuffers[fbh.idx].m_swapChain == NULL)
  1312. {
  1313. const FrameBufferWgpu& fb = m_frameBuffers[fbh.idx];
  1314. numMrt = bx::uint32_max(1, fb.m_num);
  1315. }
  1316. wgpu::RenderPassEncoder rce = m_renderEncoder;
  1317. ProgramHandle programHandle = _clearQuad.m_program[numMrt-1];
  1318. const VertexLayout* decl = &_clearQuad.m_layout;
  1319. const PipelineStateWgpu* pso = getPipelineState(
  1320. state
  1321. , stencil
  1322. , 0
  1323. , fbh
  1324. , 1
  1325. , &decl
  1326. , false
  1327. , programHandle
  1328. , 0
  1329. );
  1330. rce.SetPipeline(pso->m_rps);
  1331. float mrtClearColor[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS][4];
  1332. float mrtClearDepth[4] = { _clear.m_depth };
  1333. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  1334. {
  1335. for (uint32_t ii = 0; ii < numMrt; ++ii)
  1336. {
  1337. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[ii]);
  1338. bx::memCopy(mrtClearColor[ii], _palette[index], 16);
  1339. }
  1340. }
  1341. else
  1342. {
  1343. float rgba[4] =
  1344. {
  1345. _clear.m_index[0]*1.0f/255.0f,
  1346. _clear.m_index[1]*1.0f/255.0f,
  1347. _clear.m_index[2]*1.0f/255.0f,
  1348. _clear.m_index[3]*1.0f/255.0f,
  1349. };
  1350. for (uint32_t ii = 0; ii < numMrt; ++ii)
  1351. {
  1352. bx::memCopy( mrtClearColor[ii]
  1353. , rgba
  1354. , 16
  1355. );
  1356. }
  1357. }
  1358. ProgramWgpu& program = m_program[programHandle.idx];
  1359. ScratchBufferWgpu& scratchBuffer = m_scratchBuffers[0];
  1360. BindStateCacheWgpu& bindStates = m_bindStateCache[0];
  1361. BindingsWgpu b;
  1362. BindStateWgpu& bindState = allocBindState(program, bindStates, b, scratchBuffer);
  1363. const uint32_t voffset = scratchBuffer.write(mrtClearDepth, sizeof(mrtClearDepth), program.m_vsh->m_gpuSize);
  1364. const uint32_t foffset = scratchBuffer.write(mrtClearColor, sizeof(mrtClearColor), program.m_fsh->m_gpuSize);
  1365. uint32_t numOffset = 2;
  1366. uint32_t offsets[2] = { voffset, foffset };
  1367. bindGroups(program, bindState, b);
  1368. const VertexBufferWgpu& vb = m_vertexBuffers[_clearQuad.m_vb.idx];
  1369. bindProgram(rce, program, bindState, numOffset, offsets);
  1370. rce.SetViewport(_rect.m_x, _rect.m_y, _rect.m_width, _rect.m_height, 0.0f, 1.0f);
  1371. rce.SetScissorRect(_rect.m_x, _rect.m_y, _rect.m_width, _rect.m_height);
  1372. rce.SetVertexBuffer(0, vb.m_ptr);
  1373. rce.Draw(4, 1, 0, 0);
  1374. }
  1375. wgpu::TextureViewDescriptor attachmentView(const Attachment& _at, const TextureWgpu& _texture)
  1376. {
  1377. bool _resolve = bool(_texture.m_ptrMsaa);
  1378. BX_UNUSED(_resolve);
  1379. wgpu::TextureViewDescriptor desc;
  1380. if (1 < _texture.m_numSides)
  1381. {
  1382. desc.baseArrayLayer = _at.layer;
  1383. }
  1384. desc.baseMipLevel = _at.mip;
  1385. desc.arrayLayerCount = 1;
  1386. desc.mipLevelCount = 1;
  1387. if (_texture.m_type == TextureWgpu::Texture3D)
  1388. {
  1389. desc.dimension = wgpu::TextureViewDimension::e3D;
  1390. }
  1391. return desc;
  1392. }
  1393. void setFrameBuffer(RenderPassDescriptor& _renderPassDescriptor, FrameBufferHandle _fbh, bool _msaa = true)
  1394. {
  1395. if (!isValid(_fbh)
  1396. || m_frameBuffers[_fbh.idx].m_swapChain)
  1397. {
  1398. SwapChainWgpu* swapChain = !isValid(_fbh)
  1399. ? m_mainFrameBuffer.m_swapChain
  1400. : m_frameBuffers[_fbh.idx].m_swapChain
  1401. ;
  1402. _renderPassDescriptor.colorAttachments[0] = defaultDescriptor<wgpu::RenderPassColorAttachment>();
  1403. _renderPassDescriptor.desc.colorAttachmentCount = 1;
  1404. // Force 1 array layers for attachments
  1405. wgpu::TextureViewDescriptor desc;
  1406. desc.arrayLayerCount = 1;
  1407. if (swapChain->m_backBufferColorMsaa)
  1408. {
  1409. _renderPassDescriptor.colorAttachments[0].view = swapChain->m_backBufferColorMsaa.CreateView(&desc);
  1410. _renderPassDescriptor.colorAttachments[0].resolveTarget = swapChain->current();
  1411. }
  1412. else
  1413. {
  1414. _renderPassDescriptor.colorAttachments[0].view = swapChain->current();
  1415. }
  1416. _renderPassDescriptor.depthStencilAttachment = defaultDescriptor<wgpu::RenderPassDepthStencilAttachment>();
  1417. _renderPassDescriptor.depthStencilAttachment.view = swapChain->m_backBufferDepth.CreateView();
  1418. _renderPassDescriptor.desc.depthStencilAttachment = &_renderPassDescriptor.depthStencilAttachment;
  1419. }
  1420. else
  1421. {
  1422. FrameBufferWgpu& frameBuffer = m_frameBuffers[_fbh.idx];
  1423. _renderPassDescriptor.desc.colorAttachmentCount = frameBuffer.m_num;
  1424. for (uint32_t ii = 0; ii < frameBuffer.m_num; ++ii)
  1425. {
  1426. const TextureWgpu& texture = m_textures[frameBuffer.m_colorHandle[ii].idx];
  1427. const wgpu::TextureViewDescriptor desc = attachmentView(frameBuffer.m_colorAttachment[ii], texture);
  1428. _renderPassDescriptor.colorAttachments[ii] = defaultDescriptor<wgpu::RenderPassColorAttachment>();
  1429. _renderPassDescriptor.colorAttachments[ii].view = texture.m_ptrMsaa
  1430. ? texture.m_ptrMsaa.CreateView(&desc)
  1431. : texture.m_ptr.CreateView(&desc)
  1432. ;
  1433. _renderPassDescriptor.colorAttachments[ii].resolveTarget = texture.m_ptrMsaa
  1434. ? texture.m_ptr.CreateView(&desc)
  1435. : wgpu::TextureView()
  1436. ;
  1437. }
  1438. if (isValid(frameBuffer.m_depthHandle) )
  1439. {
  1440. const TextureWgpu& texture = m_textures[frameBuffer.m_depthHandle.idx];
  1441. const wgpu::TextureViewDescriptor desc = attachmentView(frameBuffer.m_depthAttachment, texture);
  1442. _renderPassDescriptor.depthStencilAttachment = defaultDescriptor<wgpu::RenderPassDepthStencilAttachment>();
  1443. _renderPassDescriptor.depthStencilAttachment.view = texture.m_ptrMsaa
  1444. ? texture.m_ptrMsaa.CreateView(&desc)
  1445. : texture.m_ptr.CreateView(&desc)
  1446. ;
  1447. _renderPassDescriptor.desc.depthStencilAttachment = &_renderPassDescriptor.depthStencilAttachment;
  1448. }
  1449. }
  1450. m_fbh = _fbh;
  1451. m_rtMsaa = _msaa;
  1452. }
  1453. void setDepthStencilState(wgpu::DepthStencilState& desc, uint64_t _state, uint64_t _stencil = 0)
  1454. {
  1455. const uint32_t fstencil = unpackStencil(0, _stencil);
  1456. const uint32_t func = (_state&BGFX_STATE_DEPTH_TEST_MASK) >> BGFX_STATE_DEPTH_TEST_SHIFT;
  1457. desc.depthWriteEnabled = !!(BGFX_STATE_WRITE_Z & _state);
  1458. desc.depthCompare = s_cmpFunc[func];
  1459. uint32_t bstencil = unpackStencil(1, _stencil);
  1460. const uint32_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != fstencil;
  1461. bstencil = frontAndBack ? bstencil : fstencil;
  1462. desc.stencilFront = defaultDescriptor<wgpu::StencilFaceState>();
  1463. desc.stencilBack = defaultDescriptor<wgpu::StencilFaceState>();
  1464. if (0 != _stencil)
  1465. {
  1466. // TODO (hugoam)
  1467. const uint32_t readMask = (fstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  1468. const uint32_t writeMask = 0xff;
  1469. desc.stencilReadMask = readMask;
  1470. desc.stencilWriteMask = writeMask;
  1471. desc.stencilFront.failOp = s_stencilOp[(fstencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT];
  1472. desc.stencilFront.depthFailOp = s_stencilOp[(fstencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT];
  1473. desc.stencilFront.passOp = s_stencilOp[(fstencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT];
  1474. desc.stencilFront.compare = s_cmpFunc[(fstencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT];
  1475. desc.stencilBack.failOp = s_stencilOp[(bstencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT];
  1476. desc.stencilBack.depthFailOp = s_stencilOp[(bstencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT];
  1477. desc.stencilBack.passOp = s_stencilOp[(bstencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT];
  1478. desc.stencilBack.compare = s_cmpFunc[(bstencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT];
  1479. }
  1480. }
  1481. RenderPassStateWgpu* getRenderPassState(bgfx::FrameBufferHandle fbh, bool clear, Clear clr)
  1482. {
  1483. bx::HashMurmur2A murmur;
  1484. murmur.begin();
  1485. murmur.add(fbh.idx);
  1486. murmur.add(clear);
  1487. murmur.add(&clr, sizeof(clr));
  1488. uint32_t hash = murmur.end();
  1489. RenderPassStateWgpu* rps = m_renderPassStateCache.find(hash);
  1490. if (NULL == rps)
  1491. {
  1492. rps = BX_NEW(g_allocator, RenderPassStateWgpu);
  1493. m_renderPassStateCache.add(hash, rps);
  1494. }
  1495. return rps;
  1496. }
  1497. PipelineStateWgpu* getPipelineState(
  1498. uint64_t _state
  1499. , uint64_t _stencil
  1500. , uint32_t _rgba
  1501. , FrameBufferHandle _fbh
  1502. , uint8_t _numStreams
  1503. , const VertexLayout** _vertexDecls
  1504. , bool _isIndex16
  1505. , ProgramHandle _program
  1506. , uint8_t _numInstanceData
  1507. )
  1508. {
  1509. _state &= 0
  1510. | BGFX_STATE_WRITE_RGB
  1511. | BGFX_STATE_WRITE_A
  1512. | BGFX_STATE_WRITE_Z
  1513. | BGFX_STATE_DEPTH_TEST_MASK
  1514. | BGFX_STATE_BLEND_MASK
  1515. | BGFX_STATE_BLEND_EQUATION_MASK
  1516. | BGFX_STATE_BLEND_INDEPENDENT
  1517. | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  1518. | BGFX_STATE_CULL_MASK
  1519. | BGFX_STATE_MSAA
  1520. | BGFX_STATE_LINEAA
  1521. | BGFX_STATE_CONSERVATIVE_RASTER
  1522. | BGFX_STATE_PT_MASK
  1523. ;
  1524. const bool independentBlendEnable = !!(BGFX_STATE_BLEND_INDEPENDENT & _state);
  1525. const ProgramWgpu& program = m_program[_program.idx];
  1526. bx::HashMurmur2A murmur;
  1527. murmur.begin();
  1528. murmur.add(_state);
  1529. murmur.add(_stencil);
  1530. murmur.add(independentBlendEnable ? _rgba : 0);
  1531. murmur.add(_numInstanceData);
  1532. FrameBufferWgpu& frameBuffer = !isValid(_fbh) ? m_mainFrameBuffer : m_frameBuffers[_fbh.idx];
  1533. murmur.add(frameBuffer.m_pixelFormatHash);
  1534. murmur.add(program.m_vsh->m_hash);
  1535. if (NULL != program.m_fsh)
  1536. {
  1537. murmur.add(program.m_fsh->m_hash);
  1538. }
  1539. for (uint8_t ii = 0; ii < _numStreams; ++ii)
  1540. {
  1541. murmur.add(_vertexDecls[ii]->m_hash);
  1542. }
  1543. uint32_t hash = murmur.end();
  1544. PipelineStateWgpu* pso = m_pipelineStateCache.find(hash);
  1545. if (NULL == pso)
  1546. {
  1547. pso = BX_NEW(g_allocator, PipelineStateWgpu);
  1548. //pd.alphaToCoverageEnabled = !!(BGFX_STATE_BLEND_ALPHA_TO_COVERAGE & _state);
  1549. RenderPipelineDescriptor& pd = pso->m_rpd;
  1550. uint32_t frameBufferAttachment = 1;
  1551. uint32_t sampleCount = 1;
  1552. if (!isValid(_fbh)
  1553. || s_renderWgpu->m_frameBuffers[_fbh.idx].m_swapChain)
  1554. {
  1555. SwapChainWgpu& swapChain = !isValid(_fbh)
  1556. ? *s_renderWgpu->m_mainFrameBuffer.m_swapChain
  1557. : *s_renderWgpu->m_frameBuffers[_fbh.idx].m_swapChain
  1558. ;
  1559. sampleCount = swapChain.m_backBufferColorMsaa
  1560. ? swapChain.m_sampleCount
  1561. : 1
  1562. ;
  1563. pd.targets[0].format = swapChain.m_colorFormat;
  1564. pd.depthStencil.format = swapChain.m_depthFormat;
  1565. pd.desc.depthStencil = &pd.depthStencil;
  1566. }
  1567. else
  1568. {
  1569. frameBufferAttachment = frameBuffer.m_num;
  1570. for (uint32_t ii = 0; ii < frameBuffer.m_num; ++ii)
  1571. {
  1572. const TextureWgpu& texture = m_textures[frameBuffer.m_colorHandle[ii].idx];
  1573. sampleCount = texture.m_ptrMsaa
  1574. ? texture.m_sampleCount
  1575. : 1
  1576. ;
  1577. pd.targets[ii].format = s_textureFormat[texture.m_textureFormat].m_fmt;
  1578. }
  1579. pd.fragment.targetCount = frameBuffer.m_num;
  1580. if (isValid(frameBuffer.m_depthHandle) )
  1581. {
  1582. const TextureWgpu& texture = m_textures[frameBuffer.m_depthHandle.idx];
  1583. pd.depthStencil.format = s_textureFormat[texture.m_textureFormat].m_fmt;
  1584. pd.desc.depthStencil = &pd.depthStencil;
  1585. }
  1586. }
  1587. const uint32_t blend = uint32_t( (_state&BGFX_STATE_BLEND_MASK )>>BGFX_STATE_BLEND_SHIFT);
  1588. const uint32_t equation = uint32_t( (_state&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT);
  1589. const uint32_t srcRGB = (blend )&0xf;
  1590. const uint32_t dstRGB = (blend>> 4)&0xf;
  1591. const uint32_t srcA = (blend>> 8)&0xf;
  1592. const uint32_t dstA = (blend>>12)&0xf;
  1593. const uint32_t equRGB = (equation )&0x7;
  1594. const uint32_t equA = (equation>>3)&0x7;
  1595. wgpu::ColorWriteMask writeMask = wgpu::ColorWriteMask::None;
  1596. writeMask |= (_state&BGFX_STATE_WRITE_R) ? wgpu::ColorWriteMask::Red : wgpu::ColorWriteMask::None;
  1597. writeMask |= (_state&BGFX_STATE_WRITE_G) ? wgpu::ColorWriteMask::Green : wgpu::ColorWriteMask::None;
  1598. writeMask |= (_state&BGFX_STATE_WRITE_B) ? wgpu::ColorWriteMask::Blue : wgpu::ColorWriteMask::None;
  1599. writeMask |= (_state&BGFX_STATE_WRITE_A) ? wgpu::ColorWriteMask::Alpha : wgpu::ColorWriteMask::None;
  1600. for (uint32_t ii = 0; ii < (independentBlendEnable ? 1 : frameBufferAttachment); ++ii)
  1601. {
  1602. wgpu::ColorTargetState& drt = pd.targets[ii];
  1603. wgpu::BlendState& blend = pd.blends[ii];
  1604. if(!(BGFX_STATE_BLEND_MASK & _state))
  1605. {
  1606. // useless
  1607. blend.color = defaultDescriptor<wgpu::BlendComponent>();
  1608. blend.alpha = defaultDescriptor<wgpu::BlendComponent>();
  1609. drt.blend = NULL;
  1610. }
  1611. else
  1612. {
  1613. blend.color.srcFactor = s_blendFactor[srcRGB][0];
  1614. blend.color.dstFactor = s_blendFactor[dstRGB][0];
  1615. blend.color.operation = s_blendEquation[equRGB];
  1616. blend.alpha.srcFactor = s_blendFactor[srcA][1];
  1617. blend.alpha.dstFactor = s_blendFactor[dstA][1];
  1618. blend.alpha.operation = s_blendEquation[equA];
  1619. drt.blend = &blend;
  1620. }
  1621. drt.writeMask = writeMask;
  1622. }
  1623. if (independentBlendEnable)
  1624. {
  1625. for (uint32_t ii = 1, rgba = _rgba; ii < frameBufferAttachment; ++ii, rgba >>= 11)
  1626. {
  1627. wgpu::ColorTargetState& drt = pd.targets[ii];
  1628. wgpu::BlendState& blend = pd.blends[ii];
  1629. //drt.blendingEnabled = 0 != (rgba&0x7ff);
  1630. const uint32_t src = (rgba )&0xf;
  1631. const uint32_t dst = (rgba>>4)&0xf;
  1632. const uint32_t equationIndex = (rgba>>8)&0x7;
  1633. blend.color.srcFactor = s_blendFactor[src][0];
  1634. blend.color.dstFactor = s_blendFactor[dst][0];
  1635. blend.color.operation = s_blendEquation[equationIndex];
  1636. blend.alpha.srcFactor = s_blendFactor[src][1];
  1637. blend.alpha.dstFactor = s_blendFactor[dst][1];
  1638. blend.alpha.operation = s_blendEquation[equationIndex];
  1639. drt.writeMask = writeMask;
  1640. }
  1641. }
  1642. pd.desc.vertex.module = program.m_vsh->m_module;
  1643. if (NULL != program.m_fsh)
  1644. {
  1645. pd.fragment.module = program.m_fsh->m_module;
  1646. pd.desc.fragment = &pd.fragment;
  1647. }
  1648. setDepthStencilState(pd.depthStencil, _state, _stencil);
  1649. const uint64_t cull = _state & BGFX_STATE_CULL_MASK;
  1650. const uint8_t cullIndex = uint8_t(cull >> BGFX_STATE_CULL_SHIFT);
  1651. pd.desc.primitive.cullMode = s_cullMode[cullIndex];
  1652. pd.desc.primitive.frontFace = (_state & BGFX_STATE_FRONT_CCW) ? wgpu::FrontFace::CCW : wgpu::FrontFace::CW;
  1653. // pd.desc = m_renderPipelineDescriptor;
  1654. pd.desc.multisample.count = sampleCount;
  1655. wgpu::PipelineLayoutDescriptor layout = defaultDescriptor<wgpu::PipelineLayoutDescriptor>();
  1656. layout.bindGroupLayouts = &program.m_bindGroupLayout;
  1657. layout.bindGroupLayoutCount = 1;
  1658. BX_TRACE("Creating WebGPU render pipeline layout for program %s", program.m_vsh->name());
  1659. pd.desc.layout = m_device.CreatePipelineLayout(&layout);
  1660. // TODO (hugoam) this should be cached too ?
  1661. //uint32_t ref = (_state&BGFX_STATE_ALPHA_REF_MASK) >> BGFX_STATE_ALPHA_REF_SHIFT;
  1662. //viewState.m_alphaRef = ref / 255.0f;
  1663. const uint64_t primType = _state & BGFX_STATE_PT_MASK;
  1664. uint8_t primIndex = uint8_t(primType >> BGFX_STATE_PT_SHIFT);
  1665. PrimInfo prim = s_primInfo[primIndex];
  1666. pd.desc.primitive.topology = prim.m_type;
  1667. VertexStateDescriptor vertex;
  1668. vertex.desc.module = program.m_vsh->m_module;
  1669. vertex.desc.bufferCount = 0;
  1670. wgpu::VertexBufferLayout* inputBinding = vertex.buffers;
  1671. wgpu::VertexAttribute* inputAttrib = vertex.attributes;
  1672. auto fillVertexDecl = [&](const ShaderWgpu* _vsh, const VertexLayout& _decl)
  1673. {
  1674. vertex.desc.bufferCount += 1;
  1675. inputBinding->arrayStride = _decl.m_stride;
  1676. inputBinding->stepMode = wgpu::InputStepMode::Vertex;
  1677. inputBinding->attributes = inputAttrib;
  1678. uint32_t numAttribs = 0;
  1679. for(uint32_t attr = 0; attr < Attrib::Count; ++attr)
  1680. {
  1681. if(UINT16_MAX != _decl.m_attributes[attr])
  1682. {
  1683. if(UINT8_MAX == _vsh->m_attrRemap[attr])
  1684. continue;
  1685. inputAttrib->shaderLocation = _vsh->m_attrRemap[attr];
  1686. if(0 == _decl.m_attributes[attr])
  1687. {
  1688. inputAttrib->format = wgpu::VertexFormat::Float3;
  1689. inputAttrib->offset = 0;
  1690. }
  1691. else
  1692. {
  1693. uint8_t num;
  1694. AttribType::Enum type;
  1695. bool normalized;
  1696. bool asInt;
  1697. _decl.decode(Attrib::Enum(attr), num, type, normalized, asInt);
  1698. inputAttrib->format = s_attribType[type][num-1][normalized];
  1699. inputAttrib->offset = _decl.m_offset[attr];
  1700. }
  1701. ++inputAttrib;
  1702. ++numAttribs;
  1703. }
  1704. }
  1705. inputBinding->attributeCount = numAttribs;
  1706. inputBinding++;
  1707. return numAttribs;
  1708. };
  1709. //bool attrSet[Attrib::Count] = {};
  1710. uint16_t unsettedAttr[Attrib::Count];
  1711. bx::memCopy(unsettedAttr, program.m_vsh->m_attrMask, sizeof(uint16_t) * Attrib::Count);
  1712. uint8_t stream = 0;
  1713. for (; stream < _numStreams; ++stream)
  1714. {
  1715. VertexLayout layout;
  1716. bx::memCopy(&layout, _vertexDecls[stream], sizeof(VertexLayout));
  1717. const uint16_t* attrMask = program.m_vsh->m_attrMask;
  1718. for (uint32_t ii = 0; ii < Attrib::Count; ++ii)
  1719. {
  1720. Attrib::Enum iiattr = Attrib::Enum(ii);
  1721. uint16_t mask = attrMask[ii];
  1722. uint16_t attr = (layout.m_attributes[ii] & mask);
  1723. if (attr == 0)
  1724. {
  1725. layout.m_attributes[ii] = UINT16_MAX;
  1726. }
  1727. if (unsettedAttr[ii] && attr != UINT16_MAX)
  1728. {
  1729. unsettedAttr[ii] = 0;
  1730. }
  1731. }
  1732. fillVertexDecl(program.m_vsh, layout);
  1733. }
  1734. for (uint32_t ii = 0; ii < Attrib::Count; ++ii)
  1735. {
  1736. Attrib::Enum iiattr = Attrib::Enum(ii);
  1737. if (0 < unsettedAttr[ii])
  1738. {
  1739. //uint32_t numAttribs = vertexs.buffers[stream].attributeCount;
  1740. //uint32_t numAttribs = inputBinding->attributeCount;
  1741. //wgpu::VertexBufferLayout* inputAttrib = const_cast<VkVertexInputAttributeDescription*>(_vertexInputState.pVertexAttributeDescriptions + numAttribs);
  1742. inputAttrib->shaderLocation = program.m_vsh->m_attrRemap[ii];
  1743. //inputAttrib->binding = 0;
  1744. inputAttrib->format = wgpu::VertexFormat::Float3; // VK_FORMAT_R32G32B32_SFLOAT;
  1745. inputAttrib->offset = 0;
  1746. vertex.buffers[stream-1].attributeCount++;
  1747. ++inputAttrib;
  1748. }
  1749. }
  1750. // TODO (hugoam) WebGPU will crash whenever we are not supplying the correct number of attributes (which depends on the stride passed to bgfx::allocInstanceDataBuffer)
  1751. // so we need to know the number of live instance attributes in the shader and if they aren't all supplied:
  1752. // - fail the pipeline state creation
  1753. // - bind dummy attributes
  1754. if (0 < _numInstanceData)
  1755. {
  1756. uint32_t numBindings = vertex.desc.bufferCount; // == stream+1 // .vertexBindingDescriptionCount;
  1757. uint32_t firstAttrib = vertex.buffers[stream-1].attributeCount;
  1758. uint32_t numAttribs = firstAttrib;
  1759. inputBinding->arrayStride = _numInstanceData * 16;
  1760. inputBinding->stepMode = wgpu::InputStepMode::Instance;
  1761. for (uint32_t inst = 0; inst < _numInstanceData; ++inst)
  1762. {
  1763. inputAttrib->shaderLocation = numAttribs;
  1764. inputAttrib->format = wgpu::VertexFormat::Float32x4;
  1765. inputAttrib->offset = inst * 16;
  1766. ++numAttribs;
  1767. ++inputAttrib;
  1768. }
  1769. vertex.desc.bufferCount = numBindings + 1;
  1770. vertex.buffers[stream].attributeCount = numAttribs - firstAttrib;
  1771. vertex.buffers[stream].attributes = &vertex.attributes[firstAttrib];
  1772. }
  1773. bool isStrip = prim.m_type == wgpu::PrimitiveTopology::LineStrip
  1774. || prim.m_type == wgpu::PrimitiveTopology::TriangleStrip;
  1775. if (isStrip)
  1776. pd.desc.primitive.stripIndexFormat = _isIndex16 ? wgpu::IndexFormat::Uint16 : wgpu::IndexFormat::Uint32;
  1777. else
  1778. pd.desc.primitive.stripIndexFormat = wgpu::IndexFormat::Undefined;
  1779. pd.desc.vertex = vertex.desc;
  1780. BX_TRACE("Creating WebGPU render pipeline state for program %s", program.m_vsh->name());
  1781. pso->m_rps = m_device.CreateRenderPipeline2(&pd.desc);
  1782. m_pipelineStateCache.add(hash, pso);
  1783. }
  1784. return pso;
  1785. }
  1786. PipelineStateWgpu* getPipelineState(
  1787. uint64_t _state
  1788. , uint64_t _stencil
  1789. , uint32_t _rgba
  1790. , FrameBufferHandle _fbh
  1791. , VertexLayoutHandle _declHandle
  1792. , bool _isIndex16
  1793. , ProgramHandle _program
  1794. , uint8_t _numInstanceData
  1795. )
  1796. {
  1797. const VertexLayout* decl = &m_vertexDecls[_declHandle.idx];
  1798. return getPipelineState(
  1799. _state
  1800. , _stencil
  1801. , _rgba
  1802. , _fbh
  1803. , 1
  1804. , &decl
  1805. , _isIndex16
  1806. , _program
  1807. , _numInstanceData
  1808. );
  1809. }
  1810. PipelineStateWgpu* getComputePipelineState(ProgramHandle _program)
  1811. {
  1812. ProgramWgpu& program = m_program[_program.idx];
  1813. if (NULL == program.m_computePS)
  1814. {
  1815. PipelineStateWgpu* pso = BX_NEW(g_allocator, PipelineStateWgpu);
  1816. program.m_computePS = pso;
  1817. wgpu::PipelineLayoutDescriptor layout = defaultDescriptor<wgpu::PipelineLayoutDescriptor>();
  1818. layout.bindGroupLayouts = &program.m_bindGroupLayout;
  1819. layout.bindGroupLayoutCount = 1;
  1820. BX_TRACE("Creating WebGPU render pipeline layout for program %s", program.m_vsh->name());
  1821. pso->m_layout = m_device.CreatePipelineLayout(&layout);
  1822. wgpu::ComputePipelineDescriptor desc;
  1823. desc.layout = pso->m_layout;
  1824. desc.computeStage = { NULL, program.m_vsh->m_module, "main" };
  1825. BX_TRACE("Creating WebGPU render pipeline state for program %s", program.m_vsh->name());
  1826. pso->m_cps = m_device.CreateComputePipeline(&desc);
  1827. }
  1828. return program.m_computePS;
  1829. }
  1830. wgpu::Sampler getSamplerState(uint32_t _flags)
  1831. {
  1832. _flags &= BGFX_SAMPLER_BITS_MASK;
  1833. SamplerStateWgpu* sampler = m_samplerStateCache.find(_flags);
  1834. if (NULL == sampler)
  1835. {
  1836. sampler = BX_NEW(g_allocator, SamplerStateWgpu);
  1837. wgpu::SamplerDescriptor desc;
  1838. desc.addressModeU = s_textureAddress[(_flags&BGFX_SAMPLER_U_MASK)>>BGFX_SAMPLER_U_SHIFT];
  1839. desc.addressModeV = s_textureAddress[(_flags&BGFX_SAMPLER_V_MASK)>>BGFX_SAMPLER_V_SHIFT];
  1840. desc.addressModeW = s_textureAddress[(_flags&BGFX_SAMPLER_W_MASK)>>BGFX_SAMPLER_W_SHIFT];
  1841. desc.minFilter = s_textureFilterMinMag[(_flags&BGFX_SAMPLER_MIN_MASK)>>BGFX_SAMPLER_MIN_SHIFT];
  1842. desc.magFilter = s_textureFilterMinMag[(_flags&BGFX_SAMPLER_MAG_MASK)>>BGFX_SAMPLER_MAG_SHIFT];
  1843. desc.mipmapFilter = s_textureFilterMip[(_flags&BGFX_SAMPLER_MIP_MASK)>>BGFX_SAMPLER_MIP_SHIFT];
  1844. desc.lodMinClamp = 0;
  1845. desc.lodMaxClamp = bx::kFloatMax;
  1846. const uint32_t cmpFunc = (_flags&BGFX_SAMPLER_COMPARE_MASK)>>BGFX_SAMPLER_COMPARE_SHIFT;
  1847. desc.compare = 0 == cmpFunc
  1848. ? wgpu::CompareFunction::Undefined
  1849. : s_cmpFunc[cmpFunc]
  1850. ;
  1851. sampler->m_sampler = s_renderWgpu->m_device.CreateSampler(&desc);
  1852. m_samplerStateCache.add(_flags, sampler);
  1853. }
  1854. return sampler->m_sampler;
  1855. }
  1856. wgpu::CommandEncoder& getRenderEncoder()
  1857. {
  1858. if (!m_cmd.m_renderEncoder)
  1859. m_cmd.beginRender();
  1860. return m_cmd.m_renderEncoder;
  1861. }
  1862. wgpu::CommandEncoder& getStagingEncoder()
  1863. {
  1864. if (!m_cmd.m_stagingEncoder)
  1865. m_cmd.beginStaging();
  1866. return m_cmd.m_stagingEncoder;
  1867. }
  1868. wgpu::CommandEncoder& getBlitCommandEncoder()
  1869. {
  1870. if (m_renderEncoder || m_computeEncoder)
  1871. endEncoding();
  1872. return getRenderEncoder();
  1873. }
  1874. wgpu::RenderPassEncoder renderPass(bgfx::Frame* _render, bgfx::FrameBufferHandle fbh, bool clear, Clear clr, const char* name = NULL)
  1875. {
  1876. RenderPassStateWgpu* rps = s_renderWgpu->getRenderPassState(fbh, clear, clr);
  1877. RenderPassDescriptor& renderPassDescriptor = rps->m_rpd;
  1878. renderPassDescriptor.desc.label = name;
  1879. setFrameBuffer(renderPassDescriptor, fbh);
  1880. if(clear)
  1881. {
  1882. for(uint32_t ii = 0; ii < g_caps.limits.maxFBAttachments; ++ii)
  1883. {
  1884. wgpu::RenderPassColorAttachment& color = renderPassDescriptor.colorAttachments[ii];
  1885. if(0 != (BGFX_CLEAR_COLOR & clr.m_flags))
  1886. {
  1887. if(0 != (BGFX_CLEAR_COLOR_USE_PALETTE & clr.m_flags))
  1888. {
  1889. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE - 1, clr.m_index[ii]);
  1890. const float* rgba = _render->m_colorPalette[index];
  1891. const float rr = rgba[0];
  1892. const float gg = rgba[1];
  1893. const float bb = rgba[2];
  1894. const float aa = rgba[3];
  1895. color.clearColor = { rr, gg, bb, aa };
  1896. }
  1897. else
  1898. {
  1899. float rr = clr.m_index[0] * 1.0f / 255.0f;
  1900. float gg = clr.m_index[1] * 1.0f / 255.0f;
  1901. float bb = clr.m_index[2] * 1.0f / 255.0f;
  1902. float aa = clr.m_index[3] * 1.0f / 255.0f;
  1903. color.clearColor = { rr, gg, bb, aa };
  1904. }
  1905. color.loadOp = wgpu::LoadOp::Clear;
  1906. }
  1907. else
  1908. {
  1909. color.loadOp = wgpu::LoadOp::Load;
  1910. }
  1911. //desc.storeOp = desc.view.sampleCount > 1 ? wgpu::StoreOp::MultisampleResolve : wgpu::StoreOp::Store;
  1912. color.storeOp = wgpu::StoreOp::Store;
  1913. }
  1914. wgpu::RenderPassDepthStencilAttachment& depthStencil = renderPassDescriptor.depthStencilAttachment;
  1915. if(depthStencil.view)
  1916. {
  1917. depthStencil.clearDepth = clr.m_depth;
  1918. depthStencil.depthLoadOp = 0 != (BGFX_CLEAR_DEPTH & clr.m_flags)
  1919. ? wgpu::LoadOp::Clear
  1920. : wgpu::LoadOp::Load
  1921. ;
  1922. depthStencil.depthStoreOp = m_mainFrameBuffer.m_swapChain->m_backBufferColorMsaa
  1923. ? wgpu::StoreOp(0) //wgpu::StoreOp::DontCare
  1924. : wgpu::StoreOp::Store
  1925. ;
  1926. depthStencil.clearStencil = clr.m_stencil;
  1927. depthStencil.stencilLoadOp = 0 != (BGFX_CLEAR_STENCIL & clr.m_flags)
  1928. ? wgpu::LoadOp::Clear
  1929. : wgpu::LoadOp::Load
  1930. ;
  1931. depthStencil.stencilStoreOp = m_mainFrameBuffer.m_swapChain->m_backBufferColorMsaa
  1932. ? wgpu::StoreOp(0) //wgpu::StoreOp::DontCare
  1933. : wgpu::StoreOp::Store
  1934. ;
  1935. }
  1936. }
  1937. else
  1938. {
  1939. for(uint32_t ii = 0; ii < g_caps.limits.maxFBAttachments; ++ii)
  1940. {
  1941. wgpu::RenderPassColorAttachment& color = renderPassDescriptor.colorAttachments[ii];
  1942. if(color.view)
  1943. {
  1944. color.loadOp = wgpu::LoadOp::Load;
  1945. }
  1946. }
  1947. wgpu::RenderPassDepthStencilAttachment& depthStencil = renderPassDescriptor.depthStencilAttachment;
  1948. if(depthStencil.view)
  1949. {
  1950. depthStencil.depthLoadOp = wgpu::LoadOp::Load;
  1951. depthStencil.depthStoreOp = wgpu::StoreOp::Store;
  1952. depthStencil.stencilLoadOp = wgpu::LoadOp::Load;
  1953. depthStencil.stencilStoreOp = wgpu::StoreOp::Store;
  1954. }
  1955. }
  1956. wgpu::RenderPassEncoder rce = m_cmd.m_renderEncoder.BeginRenderPass(&renderPassDescriptor.desc);
  1957. m_renderEncoder = rce;
  1958. return rce;
  1959. }
  1960. void endEncoding()
  1961. {
  1962. if (m_renderEncoder)
  1963. {
  1964. m_renderEncoder.EndPass();
  1965. m_renderEncoder = NULL;
  1966. }
  1967. if (m_computeEncoder)
  1968. {
  1969. m_computeEncoder.EndPass();
  1970. m_computeEncoder = NULL;
  1971. }
  1972. }
  1973. void* m_renderDocDll;
  1974. #if !BX_PLATFORM_EMSCRIPTEN
  1975. dawn_native::Instance m_instance;
  1976. #endif
  1977. wgpu::Device m_device;
  1978. wgpu::Queue m_queue;
  1979. TimerQueryWgpu m_gpuTimer;
  1980. CommandQueueWgpu m_cmd;
  1981. StagingBufferWgpu m_uniformBuffers[WEBGPU_NUM_UNIFORM_BUFFERS];
  1982. ScratchBufferWgpu m_scratchBuffers[BGFX_CONFIG_MAX_FRAME_LATENCY];
  1983. BindStateCacheWgpu m_bindStateCache[BGFX_CONFIG_MAX_FRAME_LATENCY];
  1984. uint8_t m_frameIndex;
  1985. uint16_t m_numWindows;
  1986. FrameBufferHandle m_windows[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  1987. IndexBufferWgpu m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  1988. VertexBufferWgpu m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  1989. ShaderWgpu m_shaders[BGFX_CONFIG_MAX_SHADERS];
  1990. ProgramWgpu m_program[BGFX_CONFIG_MAX_PROGRAMS];
  1991. TextureWgpu m_textures[BGFX_CONFIG_MAX_TEXTURES];
  1992. ReadbackWgpu m_readbacks[BGFX_CONFIG_MAX_TEXTURES];
  1993. FrameBufferWgpu m_mainFrameBuffer;
  1994. FrameBufferWgpu m_frameBuffers[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  1995. VertexLayout m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_LAYOUTS];
  1996. UniformRegistry m_uniformReg;
  1997. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  1998. //StateCacheT<BindStateWgpu*> m_bindStateCache;
  1999. StateCacheT<RenderPassStateWgpu*> m_renderPassStateCache;
  2000. StateCacheT<PipelineStateWgpu*> m_pipelineStateCache;
  2001. StateCacheT<SamplerStateWgpu*> m_samplerStateCache;
  2002. TextVideoMem m_textVideoMem;
  2003. uint8_t m_fsScratch[64 << 10];
  2004. uint8_t m_vsScratch[64 << 10];
  2005. FrameBufferHandle m_fbh;
  2006. bool m_rtMsaa;
  2007. Resolution m_resolution;
  2008. void* m_capture;
  2009. uint32_t m_captureSize;
  2010. wgpu::RenderPassEncoder m_renderEncoder;
  2011. wgpu::ComputePassEncoder m_computeEncoder;
  2012. };
  2013. RendererContextI* rendererCreate(const Init& _init)
  2014. {
  2015. s_renderWgpu = BX_NEW(g_allocator, RendererContextWgpu);
  2016. if (!s_renderWgpu->init(_init) )
  2017. {
  2018. BX_DELETE(g_allocator, s_renderWgpu);
  2019. s_renderWgpu = NULL;
  2020. }
  2021. return s_renderWgpu;
  2022. }
  2023. void rendererDestroy()
  2024. {
  2025. s_renderWgpu->shutdown();
  2026. BX_DELETE(g_allocator, s_renderWgpu);
  2027. s_renderWgpu = NULL;
  2028. }
  2029. void writeString(bx::WriterI* _writer, const char* _str)
  2030. {
  2031. bx::write(_writer, _str, (int32_t)bx::strLen(_str) );
  2032. }
  2033. void ShaderWgpu::create(ShaderHandle _handle, const Memory* _mem)
  2034. {
  2035. m_handle = _handle;
  2036. BX_TRACE("Creating shader %s", getName(_handle));
  2037. bx::MemoryReader reader(_mem->data, _mem->size);
  2038. uint32_t magic;
  2039. bx::read(&reader, magic);
  2040. wgpu::ShaderStage shaderStage;
  2041. if (isShaderType(magic, 'C'))
  2042. {
  2043. shaderStage = wgpu::ShaderStage::Compute;
  2044. }
  2045. else if (isShaderType(magic, 'F'))
  2046. {
  2047. shaderStage = wgpu::ShaderStage::Fragment;
  2048. }
  2049. else if (isShaderType(magic, 'G'))
  2050. {
  2051. //shaderStage = wgpu::ShaderStage::Geometry;
  2052. }
  2053. else if (isShaderType(magic, 'V'))
  2054. {
  2055. shaderStage = wgpu::ShaderStage::Vertex;
  2056. }
  2057. m_stage = shaderStage;
  2058. uint32_t hashIn;
  2059. bx::read(&reader, hashIn);
  2060. uint32_t hashOut;
  2061. if (isShaderVerLess(magic, 6) )
  2062. {
  2063. hashOut = hashIn;
  2064. }
  2065. else
  2066. {
  2067. bx::read(&reader, hashOut);
  2068. }
  2069. uint16_t count;
  2070. bx::read(&reader, count);
  2071. m_numPredefined = 0;
  2072. m_numUniforms = count;
  2073. BX_TRACE("%s Shader consts %d"
  2074. , getShaderTypeName(magic)
  2075. , count
  2076. );
  2077. const bool fragment = isShaderType(magic, 'F');
  2078. uint8_t fragmentBit = fragment ? kUniformFragmentBit : 0;
  2079. BX_ASSERT(!isShaderVerLess(magic, 11), "WebGPU backend supports only shader binary version >= 11");
  2080. if (0 < count)
  2081. {
  2082. for (uint32_t ii = 0; ii < count; ++ii)
  2083. {
  2084. uint8_t nameSize = 0;
  2085. bx::read(&reader, nameSize);
  2086. char name[256];
  2087. bx::read(&reader, &name, nameSize);
  2088. name[nameSize] = '\0';
  2089. uint8_t type = 0;
  2090. bx::read(&reader, type);
  2091. uint8_t num;
  2092. bx::read(&reader, num);
  2093. uint16_t regIndex;
  2094. bx::read(&reader, regIndex);
  2095. uint16_t regCount;
  2096. bx::read(&reader, regCount);
  2097. uint8_t texComponent;
  2098. bx::read(&reader, texComponent);
  2099. uint8_t texDimension;
  2100. bx::read(&reader, texDimension);
  2101. uint16_t texFormat = 0;
  2102. bx::read(&reader, texFormat);
  2103. const char* kind = "invalid";
  2104. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  2105. if (PredefinedUniform::Count != predefined)
  2106. {
  2107. kind = "predefined";
  2108. m_predefined[m_numPredefined].m_loc = regIndex;
  2109. m_predefined[m_numPredefined].m_count = regCount;
  2110. m_predefined[m_numPredefined].m_type = uint8_t(predefined|fragmentBit);
  2111. m_numPredefined++;
  2112. }
  2113. else if (UniformType::End == (~kUniformMask & type))
  2114. {
  2115. // regCount is used for descriptor type
  2116. const bool buffer = idToDescriptorType(regCount) == DescriptorType::StorageBuffer;
  2117. const bool readonly = (type & kUniformReadOnlyBit) != 0;
  2118. const uint8_t reverseShift = kSpirvBindShift;
  2119. const uint8_t stage = regIndex - reverseShift;
  2120. m_bindInfo[stage].m_index = m_numBuffers;
  2121. m_bindInfo[stage].m_binding = regIndex;
  2122. m_bindInfo[stage].m_uniform = { 0 };
  2123. m_buffers[m_numBuffers] = wgpu::BindGroupLayoutEntry();
  2124. m_buffers[m_numBuffers].binding = regIndex;
  2125. m_buffers[m_numBuffers].visibility = shaderStage;
  2126. if (buffer)
  2127. {
  2128. m_buffers[m_numBuffers].buffer.type = readonly
  2129. ? wgpu::BufferBindingType::ReadOnlyStorage
  2130. : wgpu::BufferBindingType::Storage;
  2131. }
  2132. else
  2133. {
  2134. m_buffers[m_numBuffers].storageTexture.access = readonly
  2135. ? wgpu::StorageTextureAccess::ReadOnly
  2136. : wgpu::StorageTextureAccess::WriteOnly;
  2137. m_buffers[m_numBuffers].storageTexture.format = s_textureFormat[texFormat].m_fmt;
  2138. }
  2139. m_numBuffers++;
  2140. kind = "storage";
  2141. }
  2142. else if (UniformType::Sampler == (~kUniformMask & type))
  2143. {
  2144. const UniformRegInfo* info = s_renderWgpu->m_uniformReg.find(name);
  2145. BX_ASSERT(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  2146. const uint8_t reverseShift = kSpirvBindShift;
  2147. const uint8_t stage = regIndex - reverseShift;
  2148. m_bindInfo[stage].m_index = m_numSamplers;
  2149. m_bindInfo[stage].m_binding = regIndex;
  2150. m_bindInfo[stage].m_uniform = info->m_handle;
  2151. auto textureDimensionToWgpu = [](TextureDimension::Enum dimension)
  2152. {
  2153. switch (dimension)
  2154. {
  2155. case TextureDimension::Dimension1D: return wgpu::TextureViewDimension::e1D;
  2156. case TextureDimension::Dimension2D: return wgpu::TextureViewDimension::e2D;
  2157. case TextureDimension::Dimension2DArray: return wgpu::TextureViewDimension::e2DArray;
  2158. case TextureDimension::DimensionCube: return wgpu::TextureViewDimension::Cube;
  2159. case TextureDimension::DimensionCubeArray: return wgpu::TextureViewDimension::CubeArray;
  2160. case TextureDimension::Dimension3D: return wgpu::TextureViewDimension::e3D;
  2161. default: return wgpu::TextureViewDimension::Undefined;
  2162. }
  2163. };
  2164. auto textureComponentToWgpuSampleType = [](TextureComponentType::Enum componentType)
  2165. {
  2166. switch (componentType)
  2167. {
  2168. case TextureComponentType::Float: return wgpu::TextureSampleType::Float;
  2169. case TextureComponentType::Int: return wgpu::TextureSampleType::Sint;
  2170. case TextureComponentType::Uint: return wgpu::TextureSampleType::Uint;
  2171. default: return wgpu::TextureSampleType::Float;
  2172. }
  2173. };
  2174. m_textures[m_numSamplers] = wgpu::BindGroupLayoutEntry();
  2175. m_textures[m_numSamplers].binding = regIndex;
  2176. m_textures[m_numSamplers].visibility = shaderStage;
  2177. m_textures[m_numSamplers].texture.viewDimension = textureDimensionToWgpu(idToTextureDimension(texDimension));
  2178. m_textures[m_numSamplers].texture.sampleType = textureComponentToWgpuSampleType(idToTextureComponentType(texComponent));
  2179. const bool comparisonSampler = (type & kUniformCompareBit) != 0;
  2180. m_samplers[m_numSamplers] = wgpu::BindGroupLayoutEntry();
  2181. m_samplers[m_numSamplers].binding = regIndex + kSpirvSamplerShift;
  2182. m_samplers[m_numSamplers].visibility = shaderStage;
  2183. m_samplers[m_numSamplers].sampler.type = comparisonSampler
  2184. ? wgpu::SamplerBindingType::Comparison
  2185. : wgpu::SamplerBindingType::Filtering;
  2186. m_numSamplers++;
  2187. kind = "sampler";
  2188. }
  2189. else
  2190. {
  2191. const UniformRegInfo* info = s_renderWgpu->m_uniformReg.find(name);
  2192. BX_ASSERT(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  2193. if(NULL == m_constantBuffer)
  2194. {
  2195. m_constantBuffer = UniformBuffer::create(1024);
  2196. }
  2197. kind = "user";
  2198. m_constantBuffer->writeUniformHandle((UniformType::Enum)(type | fragmentBit), regIndex, info->m_handle, regCount);
  2199. }
  2200. BX_TRACE("\t%s: %s (%s), r.index %3d, r.count %2d, r.texComponent %1d, r.texDimension %1d"
  2201. , kind
  2202. , name
  2203. , getUniformTypeName(UniformType::Enum(type&~kUniformMask) )
  2204. , regIndex
  2205. , regCount
  2206. , texComponent
  2207. , texDimension
  2208. );
  2209. BX_UNUSED(kind);
  2210. }
  2211. if (NULL != m_constantBuffer)
  2212. {
  2213. m_constantBuffer->finish();
  2214. }
  2215. }
  2216. uint32_t shaderSize;
  2217. bx::read(&reader, shaderSize);
  2218. BX_TRACE("Shader body is at %lld size %u remaining %lld", reader.getPos(), shaderSize, reader.remaining());
  2219. const uint32_t* code = (const uint32_t*)reader.getDataPtr();
  2220. bx::skip(&reader, shaderSize+1);
  2221. m_code = (uint32_t*)BX_ALLOC(g_allocator, shaderSize);
  2222. m_codeSize = shaderSize;
  2223. bx::memCopy(m_code, code, shaderSize);
  2224. // TODO (hugoam) delete this
  2225. BX_TRACE("First word %08" PRIx32, code[0]);
  2226. uint8_t numAttrs = 0;
  2227. bx::read(&reader, numAttrs);
  2228. m_numAttrs = numAttrs;
  2229. bx::memSet(m_attrMask, 0, sizeof(m_attrMask));
  2230. bx::memSet(m_attrRemap, UINT8_MAX, sizeof(m_attrRemap));
  2231. for(uint8_t ii = 0; ii < numAttrs; ++ii)
  2232. {
  2233. uint16_t id;
  2234. bx::read(&reader, id);
  2235. auto toString = [](Attrib::Enum attr)
  2236. {
  2237. if (attr == Attrib::Position) return "Position";
  2238. else if (attr == Attrib::Normal) return "Normal";
  2239. else if (attr == Attrib::Tangent) return "Tangent";
  2240. else if (attr == Attrib::Bitangent) return "Bitangent";
  2241. else if (attr == Attrib::Color0) return "Color0";
  2242. else if (attr == Attrib::Color1) return "Color1";
  2243. else if (attr == Attrib::Color2) return "Color2";
  2244. else if (attr == Attrib::Color3) return "Color3";
  2245. else if (attr == Attrib::Indices) return "Indices";
  2246. else if (attr == Attrib::Weight) return "Weight";
  2247. else if (attr == Attrib::TexCoord0) return "TexCoord0";
  2248. else if (attr == Attrib::TexCoord1) return "TexCoord1";
  2249. else if (attr == Attrib::TexCoord2) return "TexCoord2";
  2250. else if (attr == Attrib::TexCoord3) return "TexCoord3";
  2251. else if (attr == Attrib::TexCoord4) return "TexCoord4";
  2252. else if (attr == Attrib::TexCoord5) return "TexCoord5";
  2253. else if (attr == Attrib::TexCoord6) return "TexCoord6";
  2254. else if (attr == Attrib::TexCoord7) return "TexCoord7";
  2255. return "Invalid";
  2256. };
  2257. Attrib::Enum attr = idToAttrib(id);
  2258. if(Attrib::Count != attr)
  2259. {
  2260. m_attrMask[attr] = UINT16_MAX;
  2261. m_attrRemap[attr] = ii;
  2262. BX_TRACE("\tattrib: %s (%i) at index %i", toString(attr), attr, ii);
  2263. }
  2264. }
  2265. wgpu::ShaderModuleSPIRVDescriptor spirv;
  2266. spirv.code = m_code;
  2267. spirv.codeSize = shaderSize / 4;
  2268. wgpu::ShaderModuleDescriptor desc;
  2269. desc.label = getName(_handle);
  2270. desc.nextInChain = &spirv;
  2271. m_module = s_renderWgpu->m_device.CreateShaderModule(&desc);
  2272. BGFX_FATAL(m_module
  2273. , bgfx::Fatal::InvalidShader
  2274. , "Failed to create %s shader."
  2275. , getShaderTypeName(magic)
  2276. );
  2277. bx::HashMurmur2A murmur;
  2278. murmur.begin();
  2279. murmur.add(hashIn);
  2280. murmur.add(hashOut);
  2281. murmur.add(code, shaderSize);
  2282. murmur.add(numAttrs);
  2283. murmur.add(m_attrMask, numAttrs);
  2284. m_hash = murmur.end();
  2285. auto roundUp = [](auto value, auto multiple)
  2286. {
  2287. return ((value + multiple - 1) / multiple) * multiple;
  2288. };
  2289. bx::read(&reader, m_size);
  2290. const uint32_t align = kMinBufferOffsetAlignment;
  2291. m_gpuSize = (uint16_t) bx::strideAlign(m_size, align);
  2292. BX_TRACE("shader size %d (used=%d) (prev=%d)", (int)m_size, (int)m_gpuSize, (int)bx::strideAlign(roundUp(m_size, 4), align));
  2293. }
  2294. void ProgramWgpu::create(const ShaderWgpu* _vsh, const ShaderWgpu* _fsh)
  2295. {
  2296. BX_ASSERT(_vsh->m_module, "Vertex shader doesn't exist.");
  2297. m_vsh = _vsh;
  2298. m_fsh = _fsh;
  2299. m_gpuSize = _vsh->m_gpuSize + (_fsh ? _fsh->m_gpuSize : 0);
  2300. //BX_ASSERT(NULL != _vsh->m_code, "Vertex shader doesn't exist.");
  2301. m_vsh = _vsh;
  2302. bx::memCopy(&m_predefined[0], _vsh->m_predefined, _vsh->m_numPredefined * sizeof(PredefinedUniform));
  2303. m_numPredefined = _vsh->m_numPredefined;
  2304. if(NULL != _fsh)
  2305. {
  2306. //BX_ASSERT(NULL != _fsh->m_code, "Fragment shader doesn't exist.");
  2307. m_fsh = _fsh;
  2308. bx::memCopy(&m_predefined[m_numPredefined], _fsh->m_predefined, _fsh->m_numPredefined * sizeof(PredefinedUniform));
  2309. m_numPredefined += _fsh->m_numPredefined;
  2310. }
  2311. wgpu::BindGroupLayoutEntry bindings[2 + BGFX_CONFIG_MAX_TEXTURE_SAMPLERS * 3];
  2312. m_numUniforms = 0 + (_vsh->m_size > 0 ? 1 : 0) + (NULL != _fsh && _fsh->m_size > 0 ? 1 : 0);
  2313. uint8_t numBindings = 0;
  2314. if (_vsh->m_size > 0)
  2315. {
  2316. bindings[numBindings].binding = kSpirvVertexBinding;
  2317. bindings[numBindings].visibility = _vsh->m_stage;
  2318. bindings[numBindings].buffer.type = wgpu::BufferBindingType::Uniform;
  2319. bindings[numBindings].buffer.hasDynamicOffset = true;
  2320. numBindings++;
  2321. }
  2322. if (NULL != _fsh && _fsh->m_size > 0)
  2323. {
  2324. bindings[numBindings].binding = kSpirvFragmentBinding;
  2325. bindings[numBindings].visibility = wgpu::ShaderStage::Fragment;
  2326. bindings[numBindings].buffer.type = wgpu::BufferBindingType::Uniform;
  2327. bindings[numBindings].buffer.hasDynamicOffset = true;
  2328. numBindings++;
  2329. }
  2330. uint8_t numSamplers = 0;
  2331. for (uint32_t ii = 0; ii < _vsh->m_numSamplers; ++ii)
  2332. {
  2333. m_textures[ii] = _vsh->m_textures[ii];
  2334. m_samplers[ii] = _vsh->m_samplers[ii];
  2335. bindings[numBindings++] = _vsh->m_textures[ii];
  2336. bindings[numBindings++] = _vsh->m_samplers[ii];
  2337. }
  2338. numSamplers += _vsh->m_numSamplers;
  2339. if (NULL != _fsh)
  2340. {
  2341. for (uint32_t ii = 0; ii < _fsh->m_numSamplers; ++ii)
  2342. {
  2343. m_textures[numSamplers + ii] = _fsh->m_textures[ii];
  2344. m_samplers[numSamplers + ii] = _fsh->m_samplers[ii];
  2345. bindings[numBindings++] = _fsh->m_textures[ii];
  2346. bindings[numBindings++] = _fsh->m_samplers[ii];
  2347. }
  2348. numSamplers += _fsh->m_numSamplers;
  2349. }
  2350. for (uint8_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  2351. {
  2352. if (isValid(m_vsh->m_bindInfo[stage].m_uniform))
  2353. {
  2354. m_bindInfo[stage] = m_vsh->m_bindInfo[stage];
  2355. }
  2356. else if (NULL != m_fsh && isValid(m_fsh->m_bindInfo[stage].m_uniform))
  2357. {
  2358. m_bindInfo[stage] = m_fsh->m_bindInfo[stage];
  2359. m_bindInfo[stage].m_index += _vsh->m_numSamplers;
  2360. }
  2361. }
  2362. m_numSamplers = numSamplers;
  2363. uint8_t numBuffers = 0;
  2364. for (uint32_t ii = 0; ii < _vsh->m_numBuffers; ++ii)
  2365. {
  2366. m_buffers[ii] = _vsh->m_buffers[ii];
  2367. bindings[numBindings++] = _vsh->m_buffers[ii];
  2368. }
  2369. numBuffers += _vsh->m_numBuffers;
  2370. if (NULL != _fsh)
  2371. {
  2372. for (uint32_t ii = 0; ii < _fsh->m_numBuffers; ++ii)
  2373. {
  2374. m_buffers[numBuffers + ii] = _fsh->m_buffers[ii];
  2375. bindings[numBindings++] = _fsh->m_buffers[ii];
  2376. }
  2377. numBuffers += _fsh->m_numBuffers;
  2378. }
  2379. m_numBuffers = numBuffers;
  2380. BX_ASSERT(m_numUniforms + m_numSamplers * 2 + m_numBuffers == numBindings, "");
  2381. wgpu::BindGroupLayoutDescriptor bindGroupDesc;
  2382. bindGroupDesc.entryCount = numBindings;
  2383. bindGroupDesc.entries = bindings;
  2384. m_bindGroupLayout = s_renderWgpu->m_device.CreateBindGroupLayout(&bindGroupDesc);
  2385. bx::HashMurmur2A murmur;
  2386. murmur.begin();
  2387. murmur.add(m_numUniforms);
  2388. murmur.add(m_textures, sizeof(wgpu::BindGroupLayoutEntry) * numSamplers);
  2389. murmur.add(m_samplers, sizeof(wgpu::BindGroupLayoutEntry) * numSamplers);
  2390. murmur.add(m_buffers, sizeof(wgpu::BindGroupLayoutEntry) * m_numBuffers);
  2391. m_bindGroupLayoutHash = murmur.end();
  2392. }
  2393. void ProgramWgpu::destroy()
  2394. {
  2395. m_vsh = NULL;
  2396. m_fsh = NULL;
  2397. if ( NULL != m_computePS )
  2398. {
  2399. BX_DELETE(g_allocator, m_computePS);
  2400. m_computePS = NULL;
  2401. }
  2402. }
  2403. void BufferWgpu::create(uint32_t _size, void* _data, uint16_t _flags, uint16_t _stride, bool _vertex)
  2404. {
  2405. BX_UNUSED(_stride);
  2406. m_size = _size;
  2407. m_flags = _flags;
  2408. m_vertex = _vertex;
  2409. const uint32_t paddedSize = bx::strideAlign(_size, 4);
  2410. bool storage = m_flags & BGFX_BUFFER_COMPUTE_READ_WRITE;
  2411. bool indirect = m_flags & BGFX_BUFFER_DRAW_INDIRECT;
  2412. wgpu::BufferDescriptor desc;
  2413. desc.size = paddedSize;
  2414. desc.usage = _vertex ? wgpu::BufferUsage::Vertex : wgpu::BufferUsage::Index;
  2415. desc.usage |= (storage || indirect) ? wgpu::BufferUsage::Storage : wgpu::BufferUsage::None;
  2416. desc.usage |= indirect ? wgpu::BufferUsage::Indirect : wgpu::BufferUsage::None;
  2417. desc.usage |= NULL == _data ? wgpu::BufferUsage::CopyDst : wgpu::BufferUsage::None;
  2418. desc.mappedAtCreation = NULL != _data;
  2419. m_ptr = s_renderWgpu->m_device.CreateBuffer(&desc);
  2420. if(NULL != _data)
  2421. {
  2422. bx::memCopy(m_ptr.GetMappedRange(), _data, _size);
  2423. m_ptr.Unmap();
  2424. }
  2425. }
  2426. void BufferWgpu::update(uint32_t _offset, uint32_t _size, void* _data, bool _discard)
  2427. {
  2428. wgpu::CommandEncoder& bce = s_renderWgpu->getBlitCommandEncoder();
  2429. if (!m_vertex && !_discard)
  2430. {
  2431. if ( m_dynamic == NULL )
  2432. {
  2433. m_dynamic = (uint8_t*)BX_ALLOC(g_allocator, m_size);
  2434. }
  2435. bx::memCopy(m_dynamic + _offset, _data, _size);
  2436. uint32_t start = _offset & 4;
  2437. uint32_t end = bx::strideAlign(_offset + _size, 4);
  2438. wgpu::BufferDescriptor desc;
  2439. desc.size = end - start;
  2440. desc.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::CopySrc;
  2441. desc.mappedAtCreation = true;
  2442. wgpu::Buffer staging = s_renderWgpu->m_device.CreateBuffer(&desc);
  2443. bx::memCopy(staging.GetMappedRange(), m_dynamic, end - start);
  2444. staging.Unmap();
  2445. // TODO pad to 4 bytes
  2446. bce.CopyBufferToBuffer(staging, 0, m_ptr, start, end - start);
  2447. s_renderWgpu->m_cmd.release(staging);
  2448. }
  2449. else
  2450. {
  2451. wgpu::BufferDescriptor desc;
  2452. desc.size = _size;
  2453. desc.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::CopySrc;
  2454. desc.mappedAtCreation = true;
  2455. wgpu::Buffer staging = s_renderWgpu->m_device.CreateBuffer(&desc);
  2456. bx::memCopy(staging.GetMappedRange(), _data, _size);
  2457. staging.Unmap();
  2458. bce.CopyBufferToBuffer(staging, 0, m_ptr, _offset, _size);
  2459. s_renderWgpu->m_cmd.release(staging);
  2460. }
  2461. }
  2462. void IndexBufferWgpu::create(uint32_t _size, void* _data, uint16_t _flags)
  2463. {
  2464. m_format = (_flags & BGFX_BUFFER_INDEX32) != 0
  2465. ? wgpu::IndexFormat::Uint32
  2466. : wgpu::IndexFormat::Uint16;
  2467. BufferWgpu::create(_size, _data, _flags);
  2468. }
  2469. void VertexBufferWgpu::create(uint32_t _size, void* _data, VertexLayoutHandle _layoutHandle, uint16_t _flags)
  2470. {
  2471. m_layoutHandle = _layoutHandle;
  2472. uint16_t stride = isValid(_layoutHandle)
  2473. ? s_renderWgpu->m_vertexDecls[_layoutHandle.idx].m_stride
  2474. : 0
  2475. ;
  2476. BufferWgpu::create(_size, _data, _flags, stride, true);
  2477. }
  2478. void TextureWgpu::create(TextureHandle _handle, const Memory* _mem, uint64_t _flags, uint8_t _skip)
  2479. {
  2480. m_handle = _handle;
  2481. m_sampler = s_renderWgpu->getSamplerState(uint32_t(_flags) );
  2482. bimg::ImageContainer imageContainer;
  2483. if (bimg::imageParse(imageContainer, _mem->data, _mem->size) )
  2484. {
  2485. const bimg::ImageBlockInfo& blockInfo = getBlockInfo(bimg::TextureFormat::Enum(imageContainer.m_format) );
  2486. const uint8_t startLod = bx::min<uint8_t>(_skip, imageContainer.m_numMips-1);
  2487. bimg::TextureInfo ti;
  2488. bimg::imageGetSize(
  2489. &ti
  2490. , uint16_t(imageContainer.m_width >>startLod)
  2491. , uint16_t(imageContainer.m_height>>startLod)
  2492. , uint16_t(imageContainer.m_depth >>startLod)
  2493. , imageContainer.m_cubeMap
  2494. , 1 < imageContainer.m_numMips
  2495. , imageContainer.m_numLayers
  2496. , imageContainer.m_format
  2497. );
  2498. ti.numMips = bx::min<uint8_t>(imageContainer.m_numMips-startLod, ti.numMips);
  2499. m_flags = _flags;
  2500. m_width = ti.width;
  2501. m_height = ti.height;
  2502. m_depth = ti.depth;
  2503. m_numLayers = ti.numLayers;
  2504. m_numMips = ti.numMips;
  2505. m_numSides = ti.numLayers * (imageContainer.m_cubeMap ? 6 : 1);
  2506. m_requestedFormat = TextureFormat::Enum(imageContainer.m_format);
  2507. m_textureFormat = getViableTextureFormat(imageContainer);
  2508. if (m_requestedFormat == bgfx::TextureFormat::D16)
  2509. m_textureFormat = bgfx::TextureFormat::D32F;
  2510. const bool compressed = bimg::isCompressed(bimg::TextureFormat::Enum(imageContainer.m_format));
  2511. if (compressed)
  2512. m_textureFormat = bgfx::TextureFormat::BGRA8;
  2513. const bool convert = m_textureFormat != m_requestedFormat;
  2514. const uint8_t bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(m_textureFormat) );
  2515. wgpu::TextureDescriptor desc = defaultDescriptor<wgpu::TextureDescriptor>();
  2516. //desc.label = getName(_handle);
  2517. if (1 < ti.numLayers)
  2518. {
  2519. if (imageContainer.m_cubeMap)
  2520. {
  2521. m_type = TextureCube;
  2522. desc.dimension = wgpu::TextureDimension::e2D;
  2523. }
  2524. else
  2525. {
  2526. m_type = Texture2D;
  2527. desc.dimension = wgpu::TextureDimension::e2D;
  2528. }
  2529. }
  2530. else if (imageContainer.m_cubeMap)
  2531. {
  2532. m_type = TextureCube;
  2533. desc.dimension = wgpu::TextureDimension::e2D;
  2534. }
  2535. else if (1 < imageContainer.m_depth)
  2536. {
  2537. m_type = Texture3D;
  2538. desc.dimension = wgpu::TextureDimension::e3D;
  2539. }
  2540. else
  2541. {
  2542. m_type = Texture2D;
  2543. desc.dimension = wgpu::TextureDimension::e2D;
  2544. }
  2545. const uint16_t numSides = ti.numLayers * (imageContainer.m_cubeMap ? 6 : 1);
  2546. const uint32_t numSrd = numSides * ti.numMips;
  2547. const bool writeOnly = 0 != (_flags&BGFX_TEXTURE_RT_WRITE_ONLY);
  2548. const bool computeWrite = 0 != (_flags&BGFX_TEXTURE_COMPUTE_WRITE);
  2549. const bool renderTarget = 0 != (_flags&BGFX_TEXTURE_RT_MASK);
  2550. const bool srgb = 0 != (_flags&BGFX_TEXTURE_SRGB);
  2551. BX_TRACE("Texture %3d: %s (requested: %s), layers %d, %dx%d%s RT[%c], WO[%c], CW[%c], sRGB[%c]"
  2552. , this - s_renderWgpu->m_textures
  2553. , getName( (TextureFormat::Enum)m_textureFormat)
  2554. , getName( (TextureFormat::Enum)m_requestedFormat)
  2555. , ti.numLayers
  2556. , ti.width
  2557. , ti.height
  2558. , imageContainer.m_cubeMap ? "x6" : ""
  2559. , renderTarget ? 'x' : ' '
  2560. , writeOnly ? 'x' : ' '
  2561. , computeWrite ? 'x' : ' '
  2562. , srgb ? 'x' : ' '
  2563. );
  2564. const uint32_t msaaQuality = bx::uint32_satsub( (_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT, 1);
  2565. const int32_t sampleCount = s_msaa[msaaQuality];
  2566. wgpu::TextureFormat format = wgpu::TextureFormat::Undefined;
  2567. if (srgb)
  2568. {
  2569. format = s_textureFormat[m_textureFormat].m_fmtSrgb;
  2570. BX_WARN(format != wgpu::TextureFormat::Undefined
  2571. , "sRGB not supported for texture format %d"
  2572. , m_textureFormat
  2573. );
  2574. }
  2575. if (format == wgpu::TextureFormat::Undefined)
  2576. {
  2577. // not swizzled and not sRGB, or sRGB unsupported
  2578. format = s_textureFormat[m_textureFormat].m_fmt;
  2579. }
  2580. desc.format = format;
  2581. desc.size.width = m_width;
  2582. desc.size.height = m_height;
  2583. desc.size.depthOrArrayLayers = m_numSides * bx::uint32_max(1,imageContainer.m_depth);
  2584. desc.mipLevelCount = m_numMips;
  2585. desc.sampleCount = 1;
  2586. desc.usage = wgpu::TextureUsage::Sampled;
  2587. desc.usage |= wgpu::TextureUsage::CopyDst;
  2588. desc.usage |= wgpu::TextureUsage::CopySrc;
  2589. if (computeWrite)
  2590. {
  2591. desc.usage |= wgpu::TextureUsage::Storage;
  2592. }
  2593. if (renderTarget)
  2594. {
  2595. desc.usage |= wgpu::TextureUsage::OutputAttachment;
  2596. }
  2597. m_ptr = s_renderWgpu->m_device.CreateTexture(&desc);
  2598. if (sampleCount > 1)
  2599. {
  2600. desc.sampleCount = sampleCount;
  2601. m_ptrMsaa = s_renderWgpu->m_device.CreateTexture(&desc);
  2602. }
  2603. // decode images
  2604. struct ImageInfo
  2605. {
  2606. uint8_t* data;
  2607. uint32_t width;
  2608. uint32_t height;
  2609. uint32_t depth;
  2610. uint32_t pitch;
  2611. uint32_t slice;
  2612. uint32_t size;
  2613. uint8_t mipLevel;
  2614. uint8_t layer;
  2615. };
  2616. ImageInfo* imageInfos = (ImageInfo*)BX_ALLOC(g_allocator, sizeof(ImageInfo) * numSrd);
  2617. bx::memSet(imageInfos, 0, sizeof(ImageInfo) * numSrd);
  2618. uint32_t alignment = 1; // tightly aligned buffer
  2619. uint32_t kk = 0;
  2620. for (uint8_t side = 0; side < numSides; ++side)
  2621. {
  2622. for (uint8_t lod = 0; lod < ti.numMips; ++lod)
  2623. {
  2624. bimg::ImageMip mip;
  2625. if (bimg::imageGetRawData(imageContainer, side, lod + startLod, _mem->data, _mem->size, mip))
  2626. {
  2627. if (convert)
  2628. {
  2629. const uint32_t pitch = bx::strideAlign(bx::max<uint32_t>(mip.m_width, 4) * bpp / 8, alignment);
  2630. const uint32_t slice = bx::strideAlign(bx::max<uint32_t>(mip.m_height, 4) * pitch, alignment);
  2631. const uint32_t size = slice * mip.m_depth;
  2632. uint8_t* temp = (uint8_t*)BX_ALLOC(g_allocator, size);
  2633. bimg::imageDecodeToBgra8(
  2634. g_allocator
  2635. , temp
  2636. , mip.m_data
  2637. , mip.m_width
  2638. , mip.m_height
  2639. , pitch
  2640. , mip.m_format
  2641. );
  2642. imageInfos[kk].data = temp;
  2643. imageInfos[kk].width = mip.m_width;
  2644. imageInfos[kk].height = mip.m_height;
  2645. imageInfos[kk].depth = mip.m_depth;
  2646. imageInfos[kk].pitch = pitch;
  2647. imageInfos[kk].slice = slice;
  2648. imageInfos[kk].size = size;
  2649. imageInfos[kk].mipLevel = lod;
  2650. imageInfos[kk].layer = side;
  2651. }
  2652. else if (compressed)
  2653. {
  2654. const uint32_t pitch = bx::strideAlign((mip.m_width / blockInfo.blockWidth) * mip.m_blockSize, alignment);
  2655. const uint32_t slice = bx::strideAlign((mip.m_height / blockInfo.blockHeight) * pitch, alignment);
  2656. const uint32_t size = slice * mip.m_depth;
  2657. uint8_t* temp = (uint8_t*)BX_ALLOC(g_allocator, size);
  2658. bimg::imageCopy(
  2659. temp
  2660. , mip.m_height / blockInfo.blockHeight
  2661. , (mip.m_width / blockInfo.blockWidth) * mip.m_blockSize
  2662. , mip.m_depth
  2663. , mip.m_data
  2664. , pitch
  2665. );
  2666. imageInfos[kk].data = temp;
  2667. imageInfos[kk].width = mip.m_width;
  2668. imageInfos[kk].height = mip.m_height;
  2669. imageInfos[kk].depth = mip.m_depth;
  2670. imageInfos[kk].pitch = pitch;
  2671. imageInfos[kk].slice = slice;
  2672. imageInfos[kk].size = size;
  2673. imageInfos[kk].mipLevel = lod;
  2674. imageInfos[kk].layer = side;
  2675. }
  2676. else
  2677. {
  2678. const uint32_t pitch = bx::strideAlign(mip.m_width * mip.m_bpp / 8, alignment);
  2679. const uint32_t slice = bx::strideAlign(mip.m_height * pitch, alignment);
  2680. const uint32_t size = slice * mip.m_depth;
  2681. uint8_t* temp = (uint8_t*)BX_ALLOC(g_allocator, size);
  2682. bimg::imageCopy(temp
  2683. , mip.m_height
  2684. , mip.m_width * mip.m_bpp / 8
  2685. , mip.m_depth
  2686. , mip.m_data
  2687. , pitch
  2688. );
  2689. imageInfos[kk].data = temp;
  2690. imageInfos[kk].width = mip.m_width;
  2691. imageInfos[kk].height = mip.m_height;
  2692. imageInfos[kk].depth = mip.m_depth;
  2693. imageInfos[kk].pitch = pitch;
  2694. imageInfos[kk].slice = slice;
  2695. imageInfos[kk].size = size;
  2696. imageInfos[kk].mipLevel = lod;
  2697. imageInfos[kk].layer = side;
  2698. }
  2699. }
  2700. ++kk;
  2701. }
  2702. }
  2703. uint32_t totalMemSize = 0;
  2704. for (uint32_t ii = 0; ii < numSrd; ++ii)
  2705. {
  2706. const uint32_t dstpitch = bx::strideAlign(imageInfos[ii].pitch, kMinBufferOffsetAlignment);
  2707. totalMemSize += dstpitch * imageInfos[ii].height;
  2708. //totalMemSize += imageInfos[ii].size;
  2709. }
  2710. wgpu::Buffer stagingBuffer;
  2711. if (totalMemSize > 0)
  2712. {
  2713. wgpu::BufferDescriptor staginBufferDesc;
  2714. staginBufferDesc.size = totalMemSize;
  2715. staginBufferDesc.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::CopySrc;
  2716. staginBufferDesc.mappedAtCreation = true;
  2717. stagingBuffer = s_renderWgpu->m_device.CreateBuffer(&staginBufferDesc);
  2718. void* stagingData = stagingBuffer.GetMappedRange();
  2719. uint64_t offset = 0;
  2720. for (uint32_t ii = 0; ii < numSrd; ++ii)
  2721. {
  2722. const uint32_t dstpitch = bx::strideAlign(imageInfos[ii].pitch, kMinBufferOffsetAlignment);
  2723. const uint8_t* src = (uint8_t*)imageInfos[ii].data;
  2724. uint8_t* dst = (uint8_t*)stagingData;
  2725. for (uint32_t yy = 0; yy < imageInfos[ii].height; ++yy, src += imageInfos[ii].pitch, offset += dstpitch)
  2726. {
  2727. bx::memCopy(dst + offset, src, imageInfos[ii].pitch);
  2728. }
  2729. //bx::memCopy(dst + offset, imageInfos[ii].data, imageInfos[ii].size);
  2730. //offset += imageInfos[ii].size;
  2731. }
  2732. stagingBuffer.Unmap();
  2733. }
  2734. wgpu::ImageCopyBuffer* imageCopyBuffer = (wgpu::ImageCopyBuffer*)BX_ALLOC(g_allocator, sizeof(wgpu::ImageCopyBuffer) * numSrd);
  2735. wgpu::ImageCopyTexture* imageCopyTexture = (wgpu::ImageCopyTexture*)BX_ALLOC(g_allocator, sizeof(wgpu::ImageCopyTexture) * numSrd);
  2736. wgpu::Extent3D* textureCopySize = (wgpu::Extent3D*)BX_ALLOC(g_allocator, sizeof(wgpu::Extent3D) * numSrd);
  2737. uint64_t offset = 0;
  2738. for (uint32_t ii = 0; ii < numSrd; ++ii)
  2739. {
  2740. const uint32_t dstpitch = bx::strideAlign(imageInfos[ii].pitch, kMinBufferOffsetAlignment);
  2741. uint32_t idealWidth = bx::max<uint32_t>(1, m_width >> imageInfos[ii].mipLevel);
  2742. uint32_t idealHeight = bx::max<uint32_t>(1, m_height >> imageInfos[ii].mipLevel);
  2743. BX_PLACEMENT_NEW(&imageCopyBuffer[ii], wgpu::ImageCopyBuffer)();
  2744. BX_PLACEMENT_NEW(&imageCopyTexture[ii], wgpu::ImageCopyTexture)();
  2745. BX_PLACEMENT_NEW(&textureCopySize[ii], wgpu::Extent3D)();
  2746. imageCopyBuffer[ii].buffer = stagingBuffer;
  2747. imageCopyBuffer[ii].layout.offset = offset;
  2748. imageCopyBuffer[ii].layout.bytesPerRow = dstpitch; // assume that image data are tightly aligned
  2749. imageCopyBuffer[ii].layout.rowsPerImage = 0; // assume that image data are tightly aligned
  2750. imageCopyTexture[ii].texture = m_ptr;
  2751. imageCopyTexture[ii].mipLevel = imageInfos[ii].mipLevel;
  2752. imageCopyTexture[ii].origin = { 0, 0, imageInfos[ii].layer };
  2753. textureCopySize[ii] = { idealWidth, idealHeight, imageInfos[ii].depth };
  2754. offset += dstpitch * imageInfos[ii].height;
  2755. //offset += imageInfos[ii].size;
  2756. }
  2757. if (stagingBuffer)
  2758. {
  2759. wgpu::CommandEncoder encoder = s_renderWgpu->getBlitCommandEncoder();
  2760. //wgpu::CommandEncoder encoder = s_renderWgpu->m_cmd.m_encoder;
  2761. for (uint32_t ii = 0; ii < numSrd; ++ii)
  2762. {
  2763. encoder.CopyBufferToTexture(&imageCopyBuffer[ii], &imageCopyTexture[ii], &textureCopySize[ii]);
  2764. }
  2765. }
  2766. else
  2767. {
  2768. //VkCommandBuffer commandBuffer = s_renderVK->beginNewCommand();
  2769. //setImageMemoryBarrier(
  2770. // commandBuffer
  2771. // , (m_flags & BGFX_TEXTURE_COMPUTE_WRITE
  2772. // ? VK_IMAGE_LAYOUT_GENERAL
  2773. // : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
  2774. // )
  2775. //);
  2776. //s_renderVK->submitCommandAndWait(commandBuffer);
  2777. }
  2778. //vkFreeMemory(device, stagingDeviceMem, allocatorCb);
  2779. //vkDestroy(stagingBuffer);
  2780. BX_FREE(g_allocator, imageCopyBuffer);
  2781. BX_FREE(g_allocator, imageCopyTexture);
  2782. BX_FREE(g_allocator, textureCopySize);
  2783. for (uint32_t ii = 0; ii < numSrd; ++ii)
  2784. {
  2785. BX_FREE(g_allocator, imageInfos[ii].data);
  2786. }
  2787. BX_FREE(g_allocator, imageInfos);
  2788. }
  2789. }
  2790. void TextureWgpu::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  2791. {
  2792. const uint32_t bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(m_textureFormat) );
  2793. const uint32_t rectpitch = _rect.m_width*bpp/8;
  2794. const uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  2795. const uint16_t zz = (m_type == Texture3D) ? _z : _side;
  2796. // TODO (hugoam) This won't work for 3D texture arrays, but do we even support that
  2797. const bool convert = m_textureFormat != m_requestedFormat;
  2798. uint8_t* data = _mem->data;
  2799. uint8_t* temp = NULL;
  2800. if (convert)
  2801. {
  2802. temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*_rect.m_height);
  2803. bimg::imageDecodeToBgra8(
  2804. g_allocator
  2805. , temp
  2806. , data
  2807. , _rect.m_width
  2808. , _rect.m_height
  2809. , srcpitch
  2810. , bimg::TextureFormat::Enum(m_requestedFormat)
  2811. );
  2812. data = temp;
  2813. }
  2814. const uint32_t dstpitch = bx::strideAlign(rectpitch, kMinBufferOffsetAlignment);
  2815. wgpu::BufferDescriptor desc;
  2816. desc.size = dstpitch * _rect.m_height;
  2817. desc.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::CopySrc;
  2818. desc.mappedAtCreation = true;
  2819. wgpu::Buffer staging = s_renderWgpu->m_device.CreateBuffer(&desc);
  2820. const uint8_t* src = (uint8_t*)data;
  2821. uint8_t* dst = (uint8_t*)staging.GetMappedRange();
  2822. uint64_t offset = 0;
  2823. for (uint32_t yy = 0; yy < _rect.m_height; ++yy, src += srcpitch, offset += dstpitch)
  2824. {
  2825. const uint32_t size = bx::strideAlign(rectpitch, 4);
  2826. bx::memCopy(dst + offset, src, size);
  2827. }
  2828. staging.Unmap();
  2829. wgpu::ImageCopyBuffer srcView;
  2830. srcView.buffer = staging;
  2831. srcView.layout.bytesPerRow = dstpitch;
  2832. srcView.layout.rowsPerImage = 0;
  2833. wgpu::ImageCopyTexture destView;
  2834. destView.texture = m_ptr;
  2835. destView.mipLevel = _mip;
  2836. destView.origin = { _rect.m_x, _rect.m_y, zz };
  2837. wgpu::Extent3D destExtent = { _rect.m_width, _rect.m_height, _depth };
  2838. //region.imageSubresource.aspectMask = m_vkTextureAspect;
  2839. wgpu::CommandEncoder encoder = s_renderWgpu->getBlitCommandEncoder();
  2840. //wgpu::CommandEncoder encoder = s_renderWgpu->m_cmd.m_encoder;
  2841. encoder.CopyBufferToTexture(&srcView, &destView, &destExtent);
  2842. //wgpu::CommandBuffer copy = encoder.Finish();
  2843. //wgpu::Queue queue = s_renderWgpu->m_queue;
  2844. //queue.Submit(1, &copy);
  2845. //staging.Destroy();
  2846. if (NULL != temp)
  2847. {
  2848. BX_FREE(g_allocator, temp);
  2849. }
  2850. }
  2851. void BindStateWgpu::clear()
  2852. {
  2853. m_bindGroup = NULL;
  2854. }
  2855. void StagingBufferWgpu::create(uint32_t _size, bool mapped)
  2856. {
  2857. m_size = _size;
  2858. wgpu::BufferDescriptor desc;
  2859. desc.size = _size;
  2860. desc.usage = wgpu::BufferUsage::MapWrite | wgpu::BufferUsage::CopySrc;
  2861. desc.mappedAtCreation = mapped;
  2862. m_buffer = s_renderWgpu->m_device.CreateBuffer(&desc);
  2863. if (mapped)
  2864. {
  2865. m_data = m_buffer.GetMappedRange();
  2866. }
  2867. else
  2868. {
  2869. map();
  2870. }
  2871. }
  2872. void StagingBufferWgpu::map()
  2873. {
  2874. auto ready = [](WGPUBufferMapAsyncStatus status, void* userdata)
  2875. {
  2876. StagingBufferWgpu* staging = static_cast<StagingBufferWgpu*>(userdata);
  2877. BX_WARN(status == WGPUBufferMapAsyncStatus_Success, "Failed mapping staging buffer (size %d) for writing with error %d", staging->m_size, status);
  2878. if (status == WGPUBufferMapAsyncStatus_Success)
  2879. {
  2880. void* data = staging->m_buffer.GetMappedRange();
  2881. staging->mapped(data);
  2882. }
  2883. };
  2884. m_buffer.MapAsync(wgpu::MapMode::Write, 0, m_size, ready, this);
  2885. }
  2886. void StagingBufferWgpu::unmap()
  2887. {
  2888. m_data = NULL;
  2889. m_buffer.Unmap();
  2890. }
  2891. void StagingBufferWgpu::destroy()
  2892. {
  2893. m_buffer = NULL;
  2894. }
  2895. void StagingBufferWgpu::mapped(void* _data)
  2896. {
  2897. m_data = _data;
  2898. }
  2899. void ScratchBufferWgpu::create(uint32_t _size)
  2900. {
  2901. m_offset = 0;
  2902. m_size = _size;
  2903. wgpu::BufferDescriptor desc;
  2904. desc.size = BGFX_CONFIG_MAX_DRAW_CALLS * 128;
  2905. desc.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::Uniform;
  2906. m_buffer = s_renderWgpu->m_device.CreateBuffer(&desc);
  2907. }
  2908. void ScratchBufferWgpu::destroy()
  2909. {
  2910. }
  2911. void ScratchBufferWgpu::begin()
  2912. {
  2913. for (uint8_t ii = 0; ii < WEBGPU_NUM_UNIFORM_BUFFERS; ++ii)
  2914. {
  2915. if (NULL != s_renderWgpu->m_uniformBuffers[ii].m_data)
  2916. {
  2917. m_staging = &s_renderWgpu->m_uniformBuffers[ii];
  2918. break;
  2919. }
  2920. }
  2921. BX_ASSERT(NULL != m_staging, "No available mapped uniform buffer");
  2922. }
  2923. uint32_t ScratchBufferWgpu::write(void* data, uint64_t _size, uint64_t _offset)
  2924. {
  2925. BX_ASSERT(nullptr != m_staging, "Cannot write uniforms outside of begin()/submit() calls");
  2926. BX_ASSERT(m_size > m_offset + _offset, "Out-of-bounds scratch buffer write");
  2927. uint32_t offset = m_offset;
  2928. bx::memCopy((void*)((uint8_t*)m_staging->m_data + offset), data, _size);
  2929. m_offset += _offset;
  2930. return offset;
  2931. }
  2932. uint32_t ScratchBufferWgpu::write(void* data, uint64_t _size)
  2933. {
  2934. BX_ASSERT(nullptr != m_staging, "Cannot write uniforms outside of begin()/submit() calls");
  2935. BX_ASSERT(m_size > m_offset + _size, "Out-of-bounds scratch buffer write");
  2936. uint32_t offset = m_offset;
  2937. bx::memCopy((void*)((uint8_t*)m_staging->m_data + offset), data, _size);
  2938. m_offset += _size;
  2939. return offset;
  2940. }
  2941. void ScratchBufferWgpu::submit()
  2942. {
  2943. m_staging->unmap();
  2944. if (m_offset != 0)
  2945. {
  2946. wgpu::CommandEncoder& bce = s_renderWgpu->getStagingEncoder();
  2947. bce.CopyBufferToBuffer(m_staging->m_buffer, 0, m_buffer, 0, m_offset);
  2948. }
  2949. }
  2950. void ScratchBufferWgpu::release()
  2951. {
  2952. m_staging->map();
  2953. m_staging = NULL;
  2954. m_offset = 0;
  2955. }
  2956. void BindStateCacheWgpu::create() //(uint32_t _maxBindGroups)
  2957. {
  2958. //m_maxBindStates = 1024; // _maxBindStates;
  2959. m_currentBindState = 0;
  2960. }
  2961. void BindStateCacheWgpu::destroy()
  2962. {
  2963. reset();
  2964. }
  2965. void BindStateCacheWgpu::reset()
  2966. {
  2967. for (size_t i = 0; i < m_currentBindState; ++i)
  2968. {
  2969. m_bindStates[i] = {};
  2970. }
  2971. m_currentBindState = 0;
  2972. }
  2973. wgpu::TextureView TextureWgpu::getTextureMipLevel(int _mip)
  2974. {
  2975. if (_mip >= 0
  2976. && _mip < m_numMips
  2977. && m_ptr)
  2978. {
  2979. if (!m_ptrMips[_mip])
  2980. {
  2981. wgpu::TextureViewDescriptor desc;
  2982. desc.baseMipLevel = _mip;
  2983. desc.mipLevelCount = 1;
  2984. desc.format = s_textureFormat[m_textureFormat].m_fmt;
  2985. if (TextureCube == m_type)
  2986. {
  2987. //desc.dimension = MTLTextureType2DArray;
  2988. desc.baseArrayLayer = 0;
  2989. desc.arrayLayerCount = m_numLayers * 6;
  2990. }
  2991. else
  2992. {
  2993. desc.baseArrayLayer = 0;
  2994. desc.arrayLayerCount = m_numLayers;
  2995. }
  2996. m_ptrMips[_mip] = m_ptr.CreateView(&desc);
  2997. }
  2998. return m_ptrMips[_mip];
  2999. }
  3000. return wgpu::TextureView();
  3001. }
  3002. void SwapChainWgpu::init(wgpu::Device _device, void* _nwh, uint32_t _width, uint32_t _height)
  3003. {
  3004. BX_UNUSED(_nwh);
  3005. wgpu::SwapChainDescriptor desc;
  3006. desc.usage = wgpu::TextureUsage::OutputAttachment;
  3007. desc.width = _width;
  3008. desc.height = _height;
  3009. #if !BX_PLATFORM_EMSCRIPTEN
  3010. m_impl = createSwapChain(_device, _nwh);
  3011. desc.presentMode = wgpu::PresentMode::Immediate;
  3012. desc.format = wgpu::TextureFormat::RGBA8Unorm;
  3013. desc.implementation = reinterpret_cast<uint64_t>(&m_impl);
  3014. m_swapChain = _device.CreateSwapChain(nullptr, &desc);
  3015. #else
  3016. wgpu::SurfaceDescriptorFromCanvasHTMLSelector canvasDesc{};
  3017. canvasDesc.selector = "#canvas";
  3018. wgpu::SurfaceDescriptor surfDesc{};
  3019. surfDesc.nextInChain = &canvasDesc;
  3020. wgpu::Surface surface = wgpu::Instance().CreateSurface(&surfDesc);
  3021. desc.presentMode = wgpu::PresentMode::Fifo;
  3022. desc.format = wgpu::TextureFormat::BGRA8Unorm;
  3023. m_swapChain = _device.CreateSwapChain(surface, &desc);
  3024. #endif
  3025. m_colorFormat = desc.format;
  3026. m_depthFormat = wgpu::TextureFormat::Depth24PlusStencil8;
  3027. }
  3028. void SwapChainWgpu::resize(FrameBufferWgpu& _frameBuffer, uint32_t _width, uint32_t _height, uint32_t _flags)
  3029. {
  3030. BX_TRACE("SwapChainWgpu::resize");
  3031. const int32_t sampleCount = s_msaa[(_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT];
  3032. wgpu::TextureFormat format = (_flags & BGFX_RESET_SRGB_BACKBUFFER)
  3033. #ifdef DAWN_ENABLE_BACKEND_VULKAN
  3034. ? wgpu::TextureFormat::BGRA8UnormSrgb
  3035. : wgpu::TextureFormat::BGRA8Unorm
  3036. #else
  3037. ? wgpu::TextureFormat::RGBA8UnormSrgb
  3038. : wgpu::TextureFormat::RGBA8Unorm
  3039. #endif
  3040. ;
  3041. #if !BX_PLATFORM_EMSCRIPTEN
  3042. m_swapChain.Configure(format, wgpu::TextureUsage::OutputAttachment, _width, _height);
  3043. #endif
  3044. m_colorFormat = format;
  3045. m_depthFormat = wgpu::TextureFormat::Depth24PlusStencil8;
  3046. bx::HashMurmur2A murmur;
  3047. murmur.begin();
  3048. murmur.add(1);
  3049. murmur.add((uint32_t)m_colorFormat);
  3050. murmur.add((uint32_t)m_depthFormat);
  3051. murmur.add((uint32_t)sampleCount);
  3052. _frameBuffer.m_pixelFormatHash = murmur.end();
  3053. wgpu::TextureDescriptor desc;
  3054. desc.dimension = wgpu::TextureDimension::e2D;
  3055. desc.size.width = _width;
  3056. desc.size.height = _height;
  3057. desc.size.depthOrArrayLayers = 1;
  3058. desc.mipLevelCount = 1;
  3059. desc.sampleCount = sampleCount;
  3060. desc.usage = wgpu::TextureUsage::OutputAttachment;
  3061. if (m_backBufferDepth)
  3062. {
  3063. m_backBufferDepth.Destroy();
  3064. }
  3065. desc.format = wgpu::TextureFormat::Depth24PlusStencil8;
  3066. m_backBufferDepth = s_renderWgpu->m_device.CreateTexture(&desc);
  3067. if (sampleCount > 1)
  3068. {
  3069. if (m_backBufferColorMsaa)
  3070. {
  3071. m_backBufferColorMsaa.Destroy();
  3072. }
  3073. desc.format = m_colorFormat;
  3074. desc.sampleCount = sampleCount;
  3075. m_backBufferColorMsaa = s_renderWgpu->m_device.CreateTexture(&desc);
  3076. }
  3077. }
  3078. void SwapChainWgpu::flip()
  3079. {
  3080. m_drawable = m_swapChain.GetCurrentTextureView();
  3081. }
  3082. wgpu::TextureView SwapChainWgpu::current()
  3083. {
  3084. if (!m_drawable)
  3085. m_drawable = m_swapChain.GetCurrentTextureView();
  3086. return m_drawable;
  3087. }
  3088. void FrameBufferWgpu::create(uint8_t _num, const Attachment* _attachment)
  3089. {
  3090. m_swapChain = NULL;
  3091. m_denseIdx = UINT16_MAX;
  3092. m_num = 0;
  3093. m_width = 0;
  3094. m_height = 0;
  3095. for (uint32_t ii = 0; ii < _num; ++ii)
  3096. {
  3097. const Attachment& at = _attachment[ii];
  3098. TextureHandle handle = at.handle;
  3099. if (isValid(handle) )
  3100. {
  3101. const TextureWgpu& texture = s_renderWgpu->m_textures[handle.idx];
  3102. if (0 == m_width)
  3103. {
  3104. m_width = texture.m_width;
  3105. m_height = texture.m_height;
  3106. }
  3107. if (bimg::isDepth(bimg::TextureFormat::Enum(texture.m_textureFormat) ) )
  3108. {
  3109. m_depthHandle = handle;
  3110. m_depthAttachment = at;
  3111. }
  3112. else
  3113. {
  3114. m_colorHandle[m_num] = handle;
  3115. m_colorAttachment[m_num] = at;
  3116. m_num++;
  3117. }
  3118. }
  3119. }
  3120. bx::HashMurmur2A murmur;
  3121. murmur.begin();
  3122. murmur.add(m_num);
  3123. for (uint32_t ii = 0; ii < m_num; ++ii)
  3124. {
  3125. const TextureWgpu& texture = s_renderWgpu->m_textures[m_colorHandle[ii].idx];
  3126. murmur.add(uint32_t(s_textureFormat[texture.m_textureFormat].m_fmt) );
  3127. }
  3128. if (!isValid(m_depthHandle) )
  3129. {
  3130. murmur.add(uint32_t(wgpu::TextureFormat::Undefined) );
  3131. }
  3132. else
  3133. {
  3134. const TextureWgpu& depthTexture = s_renderWgpu->m_textures[m_depthHandle.idx];
  3135. murmur.add(uint32_t(s_textureFormat[depthTexture.m_textureFormat].m_fmt) );
  3136. }
  3137. murmur.add(1); // SampleCount
  3138. m_pixelFormatHash = murmur.end();
  3139. }
  3140. bool FrameBufferWgpu::create(uint16_t _denseIdx, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _format, TextureFormat::Enum _depthFormat)
  3141. {
  3142. BX_UNUSED(_format, _depthFormat);
  3143. m_swapChain = BX_NEW(g_allocator, SwapChainWgpu);
  3144. m_num = 0;
  3145. m_width = _width;
  3146. m_height = _height;
  3147. m_nwh = _nwh;
  3148. m_denseIdx = _denseIdx;
  3149. m_swapChain->init(s_renderWgpu->m_device, _nwh, _width, _height);
  3150. m_swapChain->resize(*this, _width, _height, 0);
  3151. return m_swapChain->m_swapChain != NULL;
  3152. }
  3153. void FrameBufferWgpu::postReset()
  3154. {
  3155. }
  3156. uint16_t FrameBufferWgpu::destroy()
  3157. {
  3158. if (NULL != m_swapChain)
  3159. {
  3160. BX_DELETE(g_allocator, m_swapChain);
  3161. m_swapChain = NULL;
  3162. }
  3163. m_num = 0;
  3164. m_nwh = NULL;
  3165. m_depthHandle.idx = kInvalidHandle;
  3166. uint16_t denseIdx = m_denseIdx;
  3167. m_denseIdx = UINT16_MAX;
  3168. return denseIdx;
  3169. }
  3170. void CommandQueueWgpu::init(wgpu::Queue _queue)
  3171. {
  3172. m_queue = _queue;
  3173. #if BGFX_CONFIG_MULTITHREADED
  3174. //m_framesSemaphore.post(BGFX_CONFIG_MAX_FRAME_LATENCY);
  3175. #endif
  3176. }
  3177. void CommandQueueWgpu::shutdown()
  3178. {
  3179. finish(true);
  3180. }
  3181. void CommandQueueWgpu::beginRender()
  3182. {
  3183. m_renderEncoder = s_renderWgpu->m_device.CreateCommandEncoder();
  3184. }
  3185. void CommandQueueWgpu::beginStaging()
  3186. {
  3187. m_stagingEncoder = s_renderWgpu->m_device.CreateCommandEncoder();
  3188. }
  3189. inline void commandBufferFinishedCallback(void* _data)
  3190. {
  3191. #if BGFX_CONFIG_MULTITHREADED
  3192. CommandQueueWgpu* queue = (CommandQueueWgpu*)_data;
  3193. if (queue)
  3194. {
  3195. //queue->m_framesSemaphore.post();
  3196. }
  3197. #else
  3198. BX_UNUSED(_data);
  3199. #endif
  3200. }
  3201. void CommandQueueWgpu::kick(bool _endFrame, bool _waitForFinish)
  3202. {
  3203. if (m_renderEncoder)
  3204. {
  3205. if (_endFrame)
  3206. {
  3207. m_releaseWriteIndex = (m_releaseWriteIndex + 1) % BGFX_CONFIG_MAX_FRAME_LATENCY;
  3208. //m_encoder.addCompletedHandler(commandBufferFinishedCallback, this);
  3209. }
  3210. if (m_stagingEncoder)
  3211. {
  3212. wgpu::CommandBuffer commands = m_stagingEncoder.Finish();
  3213. m_queue.Submit(1, &commands);
  3214. }
  3215. wgpu::CommandBuffer commands = m_renderEncoder.Finish();
  3216. m_queue.Submit(1, &commands);
  3217. if (_waitForFinish)
  3218. {
  3219. #if BGFX_CONFIG_MULTITHREADED
  3220. //m_framesSemaphore.post();
  3221. #endif
  3222. }
  3223. m_stagingEncoder = NULL;
  3224. m_renderEncoder = NULL;
  3225. }
  3226. }
  3227. void CommandQueueWgpu::finish(bool _finishAll)
  3228. {
  3229. if (_finishAll)
  3230. {
  3231. uint32_t count = m_renderEncoder
  3232. ? 2
  3233. : 3
  3234. ;
  3235. for (uint32_t ii = 0; ii < count; ++ii)
  3236. {
  3237. consume();
  3238. }
  3239. #if BGFX_CONFIG_MULTITHREADED
  3240. //m_framesSemaphore.post(count);
  3241. #endif
  3242. }
  3243. else
  3244. {
  3245. consume();
  3246. }
  3247. }
  3248. void CommandQueueWgpu::release(wgpu::Buffer _buffer)
  3249. {
  3250. m_release[m_releaseWriteIndex].push_back(_buffer);
  3251. }
  3252. void CommandQueueWgpu::consume()
  3253. {
  3254. #if BGFX_CONFIG_MULTITHREADED
  3255. //m_framesSemaphore.wait();
  3256. #endif
  3257. m_releaseReadIndex = (m_releaseReadIndex + 1) % BGFX_CONFIG_MAX_FRAME_LATENCY;
  3258. for (wgpu::Buffer& buffer : m_release[m_releaseReadIndex])
  3259. {
  3260. buffer.Destroy();
  3261. }
  3262. m_release[m_releaseReadIndex].clear();
  3263. }
  3264. void TimerQueryWgpu::init()
  3265. {
  3266. m_frequency = bx::getHPFrequency();
  3267. }
  3268. void TimerQueryWgpu::shutdown()
  3269. {
  3270. }
  3271. uint32_t TimerQueryWgpu::begin(uint32_t _resultIdx)
  3272. {
  3273. BX_UNUSED(_resultIdx);
  3274. return 0;
  3275. }
  3276. void TimerQueryWgpu::end(uint32_t _idx)
  3277. {
  3278. BX_UNUSED(_idx);
  3279. }
  3280. #if 0
  3281. static void setTimestamp(void* _data)
  3282. {
  3283. *( (int64_t*)_data) = bx::getHPCounter();
  3284. }
  3285. #endif
  3286. void TimerQueryWgpu::addHandlers(wgpu::CommandBuffer& _commandBuffer)
  3287. {
  3288. BX_UNUSED(_commandBuffer);
  3289. while (0 == m_control.reserve(1) )
  3290. {
  3291. m_control.consume(1);
  3292. }
  3293. //uint32_t offset = m_control.m_current;
  3294. //_commandBuffer.addScheduledHandler(setTimestamp, &m_result[offset].m_begin);
  3295. //_commandBuffer.addCompletedHandler(setTimestamp, &m_result[offset].m_end);
  3296. m_control.commit(1);
  3297. }
  3298. bool TimerQueryWgpu::get()
  3299. {
  3300. if (0 != m_control.available() )
  3301. {
  3302. uint32_t offset = m_control.m_read;
  3303. m_begin = m_result[offset].m_begin;
  3304. m_end = m_result[offset].m_end;
  3305. m_elapsed = m_end - m_begin;
  3306. m_control.consume(1);
  3307. return true;
  3308. }
  3309. return false;
  3310. }
  3311. void RendererContextWgpu::submitBlit(BlitState& _bs, uint16_t _view)
  3312. {
  3313. if (!_bs.hasItem(_view) )
  3314. {
  3315. return;
  3316. }
  3317. endEncoding();
  3318. wgpu::CommandEncoder& bce = getBlitCommandEncoder();
  3319. while (_bs.hasItem(_view) )
  3320. {
  3321. const BlitItem& blit = _bs.advance();
  3322. const TextureWgpu& src = m_textures[blit.m_src.idx];
  3323. const TextureWgpu& dst = m_textures[blit.m_dst.idx];
  3324. bool readBack = !!(dst.m_flags & BGFX_TEXTURE_READ_BACK);
  3325. wgpu::ImageCopyTexture srcView;
  3326. srcView.texture = src.m_ptr;
  3327. srcView.origin = { blit.m_srcX, blit.m_srcY, blit.m_srcZ };
  3328. srcView.mipLevel = blit.m_srcMip;
  3329. wgpu::ImageCopyTexture dstView;
  3330. dstView.texture = dst.m_ptr;
  3331. dstView.origin = { blit.m_dstX, blit.m_dstY, blit.m_dstZ };
  3332. dstView.mipLevel = blit.m_dstMip;
  3333. if (blit.m_depth == 0)
  3334. {
  3335. wgpu::Extent3D copyExtent = { blit.m_width, blit.m_height, 1 };
  3336. bce.CopyTextureToTexture(&srcView, &dstView, &copyExtent);
  3337. }
  3338. else
  3339. {
  3340. wgpu::Extent3D copyExtent = { blit.m_width, blit.m_height, blit.m_depth };
  3341. bce.CopyTextureToTexture(&srcView, &dstView, &copyExtent);
  3342. }
  3343. if (readBack)
  3344. {
  3345. //bce..synchronizeTexture(dst.m_ptr, 0, blit.m_dstMip);
  3346. }
  3347. }
  3348. //if (bce)
  3349. //{
  3350. // bce.endEncoding();
  3351. // bce = 0;
  3352. //}
  3353. }
  3354. void RendererContextWgpu::submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter)
  3355. {
  3356. if(_render->m_capture)
  3357. {
  3358. renderDocTriggerCapture();
  3359. }
  3360. m_cmd.finish(false);
  3361. if (!m_cmd.m_renderEncoder)
  3362. {
  3363. m_cmd.beginRender();
  3364. }
  3365. BGFX_WEBGPU_PROFILER_BEGIN_LITERAL("rendererSubmit", kColorFrame);
  3366. int64_t timeBegin = bx::getHPCounter();
  3367. int64_t captureElapsed = 0;
  3368. //m_gpuTimer.addHandlers(m_encoder);
  3369. updateResolution(_render->m_resolution);
  3370. m_frameIndex = 0; // (m_frameIndex + 1) % BGFX_CONFIG_MAX_FRAME_LATENCY;
  3371. ScratchBufferWgpu& scratchBuffer = m_scratchBuffers[m_frameIndex];
  3372. scratchBuffer.begin();
  3373. BindStateCacheWgpu& bindStates = m_bindStateCache[m_frameIndex];
  3374. bindStates.reset();
  3375. if (0 < _render->m_iboffset)
  3376. {
  3377. BGFX_PROFILER_SCOPE("bgfx/Update transient index buffer", kColorResource);
  3378. TransientIndexBuffer* ib = _render->m_transientIb;
  3379. m_indexBuffers[ib->handle.idx].update(0, bx::strideAlign(_render->m_iboffset,4), ib->data, true);
  3380. }
  3381. if (0 < _render->m_vboffset)
  3382. {
  3383. BGFX_PROFILER_SCOPE("bgfx/Update transient vertex buffer", kColorResource);
  3384. TransientVertexBuffer* vb = _render->m_transientVb;
  3385. m_vertexBuffers[vb->handle.idx].update(0, bx::strideAlign(_render->m_vboffset,4), vb->data, true);
  3386. }
  3387. _render->sort();
  3388. RenderDraw currentState;
  3389. currentState.clear();
  3390. currentState.m_stateFlags = BGFX_STATE_NONE;
  3391. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  3392. RenderBind currentBind;
  3393. currentBind.clear();
  3394. static ViewState viewState;
  3395. viewState.reset(_render);
  3396. uint32_t blendFactor = 0;
  3397. //bool wireframe = !!(_render->m_debug&BGFX_DEBUG_WIREFRAME);
  3398. ProgramHandle currentProgram = BGFX_INVALID_HANDLE;
  3399. uint32_t currentBindHash = 0;
  3400. uint32_t currentBindLayoutHash = 0;
  3401. BindStateWgpu* previousBindState = NULL;
  3402. SortKey key;
  3403. uint16_t view = UINT16_MAX;
  3404. FrameBufferHandle fbh = { BGFX_CONFIG_MAX_FRAME_BUFFERS };
  3405. BlitState bs(_render);
  3406. const uint64_t primType = 0;
  3407. uint8_t primIndex = uint8_t(primType >> BGFX_STATE_PT_SHIFT);
  3408. PrimInfo prim = s_primInfo[primIndex];
  3409. const uint32_t maxComputeBindings = g_caps.limits.maxComputeBindings;
  3410. // TODO store this
  3411. static wgpu::RenderPassEncoder rce;
  3412. PipelineStateWgpu* currentPso = NULL;
  3413. bool wasCompute = false;
  3414. bool viewHasScissor = false;
  3415. Rect viewScissorRect;
  3416. viewScissorRect.clear();
  3417. uint32_t statsNumPrimsSubmitted[BX_COUNTOF(s_primInfo)] = {};
  3418. uint32_t statsNumPrimsRendered[BX_COUNTOF(s_primInfo)] = {};
  3419. uint32_t statsNumInstances[BX_COUNTOF(s_primInfo)] = {};
  3420. uint32_t statsNumDrawIndirect[BX_COUNTOF(s_primInfo)] = {};
  3421. uint32_t statsNumIndices = 0;
  3422. uint32_t statsKeyType[2] = {};
  3423. Profiler<TimerQueryWgpu> profiler(
  3424. _render
  3425. , m_gpuTimer
  3426. , s_viewName
  3427. );
  3428. if (0 == (_render->m_debug & BGFX_DEBUG_IFH))
  3429. {
  3430. viewState.m_rect = _render->m_view[0].m_rect;
  3431. int32_t numItems = _render->m_numRenderItems;
  3432. for (int32_t item = 0; item < numItems;)
  3433. {
  3434. const uint64_t encodedKey = _render->m_sortKeys[item];
  3435. const bool isCompute = key.decode(encodedKey, _render->m_viewRemap);
  3436. statsKeyType[isCompute]++;
  3437. const bool viewChanged = 0
  3438. || key.m_view != view
  3439. || item == numItems
  3440. ;
  3441. const uint32_t itemIdx = _render->m_sortValues[item];
  3442. const RenderItem& renderItem = _render->m_renderItem[itemIdx];
  3443. const RenderBind& renderBind = _render->m_renderItemBind[itemIdx];
  3444. ++item;
  3445. if (viewChanged
  3446. || (!isCompute && wasCompute))
  3447. {
  3448. view = key.m_view;
  3449. currentProgram = BGFX_INVALID_HANDLE;
  3450. if (item > 1)
  3451. {
  3452. profiler.end();
  3453. }
  3454. BGFX_WEBGPU_PROFILER_END();
  3455. setViewType(view, " ");
  3456. BGFX_WEBGPU_PROFILER_BEGIN(view, kColorView);
  3457. profiler.begin(view);
  3458. viewState.m_rect = _render->m_view[view].m_rect;
  3459. submitBlit(bs, view);
  3460. if (!isCompute)
  3461. {
  3462. const Rect& scissorRect = _render->m_view[view].m_scissor;
  3463. viewHasScissor = !scissorRect.isZero();
  3464. viewScissorRect = viewHasScissor ? scissorRect : viewState.m_rect;
  3465. Clear& clr = _render->m_view[view].m_clear;
  3466. Rect viewRect = viewState.m_rect;
  3467. bool clearWithRenderPass = false;
  3468. if (!m_renderEncoder
  3469. || fbh.idx != _render->m_view[view].m_fbh.idx)
  3470. {
  3471. endEncoding();
  3472. fbh = _render->m_view[view].m_fbh;
  3473. uint32_t width = m_resolution.width;
  3474. uint32_t height = m_resolution.height;
  3475. if (isValid(fbh))
  3476. {
  3477. FrameBufferWgpu& frameBuffer = m_frameBuffers[fbh.idx];
  3478. width = frameBuffer.m_width;
  3479. height = frameBuffer.m_height;
  3480. }
  3481. clearWithRenderPass = true
  3482. && 0 == viewRect.m_x
  3483. && 0 == viewRect.m_y
  3484. && width == viewRect.m_width
  3485. && height == viewRect.m_height
  3486. ;
  3487. rce = renderPass(_render, fbh, clearWithRenderPass, clr, s_viewName[view]);
  3488. }
  3489. else if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  3490. {
  3491. rce.PopDebugGroup();
  3492. }
  3493. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  3494. {
  3495. rce.PushDebugGroup(s_viewName[view]);
  3496. }
  3497. //rce.setTriangleFillMode(wireframe ? MTLTriangleFillModeLines : MTLTriangleFillModeFill);
  3498. const Rect& rect = viewState.m_rect;
  3499. rce.SetViewport(rect.m_x, rect.m_y, rect.m_width, rect.m_height, 0.0f, 1.0f);
  3500. rce.SetScissorRect(rect.m_x, rect.m_y, rect.m_width, rect.m_height);
  3501. if (BGFX_CLEAR_NONE != (clr.m_flags & BGFX_CLEAR_MASK)
  3502. && !clearWithRenderPass)
  3503. {
  3504. clearQuad(_clearQuad, viewState.m_rect, clr, _render->m_colorPalette);
  3505. }
  3506. }
  3507. }
  3508. if (isCompute)
  3509. {
  3510. if (!wasCompute)
  3511. {
  3512. wasCompute = true;
  3513. endEncoding();
  3514. rce = NULL;
  3515. setViewType(view, "C");
  3516. BGFX_WEBGPU_PROFILER_END();
  3517. BGFX_WEBGPU_PROFILER_BEGIN(view, kColorCompute);
  3518. m_computeEncoder = m_cmd.m_renderEncoder.BeginComputePass();
  3519. }
  3520. else if (viewChanged)
  3521. {
  3522. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  3523. {
  3524. m_computeEncoder.PopDebugGroup();
  3525. }
  3526. endEncoding();
  3527. m_computeEncoder = m_cmd.m_renderEncoder.BeginComputePass();
  3528. }
  3529. if (viewChanged)
  3530. {
  3531. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  3532. {
  3533. s_viewName[view][3] = L'C';
  3534. m_computeEncoder.PushDebugGroup(s_viewName[view]);
  3535. s_viewName[view][3] = L' ';
  3536. }
  3537. }
  3538. const RenderCompute& compute = renderItem.compute;
  3539. bool programChanged = false;
  3540. bool constantsChanged = compute.m_uniformBegin < compute.m_uniformEnd;
  3541. rendererUpdateUniforms(this, _render->m_uniformBuffer[compute.m_uniformIdx], compute.m_uniformBegin, compute.m_uniformEnd);
  3542. if (key.m_program.idx != currentProgram.idx)
  3543. {
  3544. currentProgram = key.m_program;
  3545. currentPso = getComputePipelineState(currentProgram);
  3546. if (NULL == currentPso)
  3547. {
  3548. currentProgram = BGFX_INVALID_HANDLE;
  3549. continue;
  3550. }
  3551. m_computeEncoder.SetPipeline(currentPso->m_cps);
  3552. programChanged =
  3553. constantsChanged = true;
  3554. }
  3555. if (!isValid(currentProgram)
  3556. || NULL == currentPso)
  3557. BX_WARN(false, "Invalid program / No PSO");
  3558. const ProgramWgpu& program = m_program[currentProgram.idx];
  3559. if (constantsChanged)
  3560. {
  3561. UniformBuffer* vcb = program.m_vsh->m_constantBuffer;
  3562. if (NULL != vcb)
  3563. {
  3564. commit(*vcb);
  3565. }
  3566. }
  3567. viewState.setPredefined<4>(this, view, program, _render, compute);
  3568. uint32_t numOffset = 0;
  3569. uint32_t offsets[2] = { 0, 0 };
  3570. if (program.m_vsh->m_size > 0)
  3571. {
  3572. offsets[numOffset++] = scratchBuffer.write(m_vsScratch, program.m_vsh->m_gpuSize);
  3573. }
  3574. BindStateWgpu& bindState = allocAndFillBindState(program, bindStates, scratchBuffer, renderBind);
  3575. bindProgram(m_computeEncoder, program, bindState, numOffset, offsets);
  3576. if (isValid(compute.m_indirectBuffer))
  3577. {
  3578. const VertexBufferWgpu& vb = m_vertexBuffers[compute.m_indirectBuffer.idx];
  3579. uint32_t numDrawIndirect = UINT16_MAX == compute.m_numIndirect
  3580. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  3581. : compute.m_numIndirect
  3582. ;
  3583. uint32_t args = compute.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  3584. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  3585. {
  3586. m_computeEncoder.DispatchIndirect(
  3587. vb.m_ptr
  3588. , args
  3589. );
  3590. args += BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  3591. }
  3592. }
  3593. else
  3594. {
  3595. m_computeEncoder.Dispatch(compute.m_numX, compute.m_numY, compute.m_numZ);
  3596. }
  3597. continue;
  3598. }
  3599. bool resetState = viewChanged || wasCompute;
  3600. if (wasCompute)
  3601. {
  3602. wasCompute = false;
  3603. currentProgram = BGFX_INVALID_HANDLE;
  3604. setViewType(view, " ");
  3605. BGFX_WEBGPU_PROFILER_END();
  3606. BGFX_WEBGPU_PROFILER_BEGIN(view, kColorDraw);
  3607. }
  3608. const RenderDraw& draw = renderItem.draw;
  3609. // TODO (hugoam)
  3610. //const bool depthWrite = !!(BGFX_STATE_WRITE_Z & draw.m_stateFlags);
  3611. const uint64_t newFlags = draw.m_stateFlags;
  3612. uint64_t changedFlags = currentState.m_stateFlags ^ draw.m_stateFlags;
  3613. currentState.m_stateFlags = newFlags;
  3614. const uint64_t newStencil = draw.m_stencil;
  3615. uint64_t changedStencil = (currentState.m_stencil ^ draw.m_stencil) & BGFX_STENCIL_FUNC_REF_MASK;
  3616. currentState.m_stencil = newStencil;
  3617. if (resetState)
  3618. {
  3619. wasCompute = false;
  3620. currentState.clear();
  3621. currentState.m_scissor = !draw.m_scissor;
  3622. changedFlags = BGFX_STATE_MASK;
  3623. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  3624. currentState.m_stateFlags = newFlags;
  3625. currentState.m_stencil = newStencil;
  3626. currentBind.clear();
  3627. currentProgram = BGFX_INVALID_HANDLE;
  3628. const uint64_t pt = newFlags & BGFX_STATE_PT_MASK;
  3629. primIndex = uint8_t(pt >> BGFX_STATE_PT_SHIFT);
  3630. }
  3631. if (prim.m_type != s_primInfo[primIndex].m_type)
  3632. {
  3633. prim = s_primInfo[primIndex];
  3634. }
  3635. uint16_t scissor = draw.m_scissor;
  3636. if (currentState.m_scissor != scissor)
  3637. {
  3638. currentState.m_scissor = scissor;
  3639. if (UINT16_MAX == scissor)
  3640. {
  3641. if (viewHasScissor)
  3642. {
  3643. const auto& r = viewScissorRect;
  3644. rce.SetScissorRect(r.m_x, r.m_y, r.m_width, r.m_height);
  3645. }
  3646. else
  3647. { // can't disable: set to view rect
  3648. const auto& r = viewState.m_rect;
  3649. rce.SetScissorRect(r.m_x, r.m_y, r.m_width, r.m_height);
  3650. }
  3651. }
  3652. else
  3653. {
  3654. Rect scissorRect;
  3655. scissorRect.setIntersect(viewScissorRect, _render->m_frameCache.m_rectCache.m_cache[scissor]);
  3656. const auto& r = scissorRect;
  3657. if (r.m_width == 0 || r.m_height == 0)
  3658. {
  3659. continue;
  3660. }
  3661. rce.SetScissorRect(r.m_x, r.m_y, r.m_width, r.m_height);
  3662. }
  3663. }
  3664. if (0 != changedStencil)
  3665. {
  3666. const uint32_t fstencil = unpackStencil(0, draw.m_stencil);
  3667. const uint32_t ref = (fstencil & BGFX_STENCIL_FUNC_REF_MASK) >> BGFX_STENCIL_FUNC_REF_SHIFT;
  3668. rce.SetStencilReference(ref);
  3669. }
  3670. if ((0 | BGFX_STATE_PT_MASK) & changedFlags)
  3671. {
  3672. const uint64_t pt = newFlags & BGFX_STATE_PT_MASK;
  3673. primIndex = uint8_t(pt >> BGFX_STATE_PT_SHIFT);
  3674. if (prim.m_type != s_primInfo[primIndex].m_type)
  3675. {
  3676. prim = s_primInfo[primIndex];
  3677. }
  3678. }
  3679. if (blendFactor != draw.m_rgba
  3680. && !(newFlags & BGFX_STATE_BLEND_INDEPENDENT))
  3681. {
  3682. const uint32_t rgba = draw.m_rgba;
  3683. float rr = ((rgba >> 24)) / 255.0f;
  3684. float gg = ((rgba >> 16) & 0xff) / 255.0f;
  3685. float bb = ((rgba >> 8) & 0xff) / 255.0f;
  3686. float aa = ((rgba) & 0xff) / 255.0f;
  3687. wgpu::Color color = { rr, gg, bb, aa };
  3688. rce.SetBlendColor(&color);
  3689. blendFactor = draw.m_rgba;
  3690. }
  3691. bool programChanged = false;
  3692. bool constantsChanged = draw.m_uniformBegin < draw.m_uniformEnd;
  3693. rendererUpdateUniforms(this, _render->m_uniformBuffer[draw.m_uniformIdx], draw.m_uniformBegin, draw.m_uniformEnd);
  3694. bool vertexStreamChanged = hasVertexStreamChanged(currentState, draw);
  3695. if (key.m_program.idx != currentProgram.idx
  3696. || vertexStreamChanged
  3697. || (0
  3698. | BGFX_STATE_BLEND_MASK
  3699. | BGFX_STATE_BLEND_EQUATION_MASK
  3700. | BGFX_STATE_WRITE_RGB
  3701. | BGFX_STATE_WRITE_A
  3702. | BGFX_STATE_BLEND_INDEPENDENT
  3703. | BGFX_STATE_MSAA
  3704. | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  3705. ) & changedFlags
  3706. || ((blendFactor != draw.m_rgba) && !!(newFlags & BGFX_STATE_BLEND_INDEPENDENT)))
  3707. {
  3708. currentProgram = key.m_program;
  3709. currentState.m_streamMask = draw.m_streamMask;
  3710. currentState.m_instanceDataBuffer.idx = draw.m_instanceDataBuffer.idx;
  3711. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  3712. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  3713. const VertexLayout* decls[BGFX_CONFIG_MAX_VERTEX_STREAMS];
  3714. uint32_t numVertices = draw.m_numVertices;
  3715. uint8_t numStreams = 0;
  3716. for (uint32_t idx = 0, streamMask = draw.m_streamMask
  3717. ; 0 != streamMask
  3718. ; streamMask >>= 1, idx += 1, ++numStreams
  3719. )
  3720. {
  3721. const uint32_t ntz = bx::uint32_cnttz(streamMask);
  3722. streamMask >>= ntz;
  3723. idx += ntz;
  3724. currentState.m_stream[idx].m_layoutHandle = draw.m_stream[idx].m_layoutHandle;
  3725. currentState.m_stream[idx].m_handle = draw.m_stream[idx].m_handle;
  3726. currentState.m_stream[idx].m_startVertex = draw.m_stream[idx].m_startVertex;
  3727. const uint16_t handle = draw.m_stream[idx].m_handle.idx;
  3728. const VertexBufferWgpu& vb = m_vertexBuffers[handle];
  3729. const uint16_t decl = isValid(draw.m_stream[idx].m_layoutHandle)
  3730. ? draw.m_stream[idx].m_layoutHandle.idx
  3731. : vb.m_layoutHandle.idx;
  3732. const VertexLayout& vertexDecl = m_vertexDecls[decl];
  3733. const uint32_t stride = vertexDecl.m_stride;
  3734. decls[numStreams] = &vertexDecl;
  3735. numVertices = bx::uint32_min(UINT32_MAX == draw.m_numVertices
  3736. ? vb.m_size / stride
  3737. : draw.m_numVertices
  3738. , numVertices
  3739. );
  3740. const uint32_t offset = draw.m_stream[idx].m_startVertex * stride;
  3741. rce.SetVertexBuffer(idx, vb.m_ptr, offset);
  3742. }
  3743. if (!isValid(currentProgram))
  3744. {
  3745. continue;
  3746. }
  3747. else
  3748. {
  3749. currentPso = NULL;
  3750. if (0 < numStreams)
  3751. {
  3752. currentPso = getPipelineState(
  3753. newFlags
  3754. , newStencil
  3755. , draw.m_rgba
  3756. , fbh
  3757. , numStreams
  3758. , decls
  3759. , draw.isIndex16()
  3760. , currentProgram
  3761. , uint8_t(draw.m_instanceDataStride / 16)
  3762. );
  3763. }
  3764. if (NULL == currentPso)
  3765. {
  3766. currentProgram = BGFX_INVALID_HANDLE;
  3767. continue;
  3768. }
  3769. rce.SetPipeline(currentPso->m_rps);
  3770. }
  3771. if (isValid(draw.m_instanceDataBuffer))
  3772. {
  3773. const VertexBufferWgpu& inst = m_vertexBuffers[draw.m_instanceDataBuffer.idx];
  3774. rce.SetVertexBuffer(numStreams/*+1*/, inst.m_ptr, draw.m_instanceDataOffset);
  3775. }
  3776. programChanged =
  3777. constantsChanged = true;
  3778. }
  3779. if (isValid(currentProgram))
  3780. {
  3781. const ProgramWgpu& program = m_program[currentProgram.idx];
  3782. if (constantsChanged)
  3783. {
  3784. UniformBuffer* vcb = program.m_vsh->m_constantBuffer;
  3785. if (NULL != vcb)
  3786. {
  3787. commit(*vcb);
  3788. }
  3789. }
  3790. if (constantsChanged)
  3791. {
  3792. UniformBuffer* fcb = program.m_fsh->m_constantBuffer;
  3793. if (NULL != fcb)
  3794. {
  3795. commit(*fcb);
  3796. }
  3797. }
  3798. viewState.setPredefined<4>(this, view, program, _render, draw);
  3799. bool hasPredefined = 0 < program.m_numPredefined;
  3800. uint32_t numOffset = 0;
  3801. uint32_t offsets[2] = { 0, 0 };
  3802. if (constantsChanged
  3803. || hasPredefined)
  3804. {
  3805. //viewState.setPredefined<4>(this, view, program, _render, draw, programChanged || viewChanged);
  3806. const uint32_t vsize = program.m_vsh->m_gpuSize;
  3807. const uint32_t fsize = (NULL != program.m_fsh ? program.m_fsh->m_gpuSize : 0);
  3808. if (program.m_vsh->m_size > 0)
  3809. {
  3810. offsets[numOffset++] = scratchBuffer.write(m_vsScratch, vsize);
  3811. }
  3812. if (fsize > 0)
  3813. {
  3814. offsets[numOffset++] = scratchBuffer.write(m_fsScratch, fsize);
  3815. }
  3816. }
  3817. uint32_t bindHash = bx::hash<bx::HashMurmur2A>(renderBind.m_bind, sizeof(renderBind.m_bind));
  3818. if (currentBindHash != bindHash
  3819. || currentBindLayoutHash != program.m_bindGroupLayoutHash)
  3820. {
  3821. currentBindHash = bindHash;
  3822. currentBindLayoutHash = program.m_bindGroupLayoutHash;
  3823. previousBindState = &bindStates.m_bindStates[bindStates.m_currentBindState];
  3824. allocAndFillBindState(program, bindStates, scratchBuffer, renderBind);
  3825. }
  3826. BindStateWgpu& bindState = bindStates.m_bindStates[bindStates.m_currentBindState-1];
  3827. bindProgram(rce, program, bindState, numOffset, offsets);
  3828. }
  3829. if (0 != currentState.m_streamMask)
  3830. {
  3831. uint32_t numVertices = draw.m_numVertices;
  3832. if (UINT32_MAX == numVertices)
  3833. {
  3834. const VertexBufferWgpu& vb = m_vertexBuffers[currentState.m_stream[0].m_handle.idx];
  3835. uint16_t decl = !isValid(vb.m_layoutHandle) ? draw.m_stream[0].m_layoutHandle.idx : vb.m_layoutHandle.idx;
  3836. const VertexLayout& vertexDecl = m_vertexDecls[decl];
  3837. numVertices = vb.m_size/vertexDecl.m_stride;
  3838. }
  3839. uint32_t numIndices = 0;
  3840. uint32_t numPrimsSubmitted = 0;
  3841. uint32_t numInstances = 0;
  3842. uint32_t numPrimsRendered = 0;
  3843. uint32_t numDrawIndirect = 0;
  3844. if (isValid(draw.m_indirectBuffer) )
  3845. {
  3846. const VertexBufferWgpu& vb = m_vertexBuffers[draw.m_indirectBuffer.idx];
  3847. if (isValid(draw.m_indexBuffer) )
  3848. {
  3849. const IndexBufferWgpu& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  3850. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  3851. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  3852. : draw.m_numIndirect
  3853. ;
  3854. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  3855. {
  3856. rce.SetIndexBuffer(ib.m_ptr, ib.m_format, 0);
  3857. rce.DrawIndexedIndirect(vb.m_ptr, (draw.m_startIndirect + ii)* BGFX_CONFIG_DRAW_INDIRECT_STRIDE);
  3858. }
  3859. }
  3860. else
  3861. {
  3862. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  3863. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  3864. : draw.m_numIndirect
  3865. ;
  3866. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  3867. {
  3868. rce.DrawIndirect(vb.m_ptr, (draw.m_startIndirect + ii)* BGFX_CONFIG_DRAW_INDIRECT_STRIDE);
  3869. }
  3870. }
  3871. }
  3872. else
  3873. {
  3874. if (isValid(draw.m_indexBuffer) )
  3875. {
  3876. const IndexBufferWgpu& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  3877. const uint32_t indexSize = draw.isIndex16() ? 2 : 4;
  3878. if (UINT32_MAX == draw.m_numIndices)
  3879. {
  3880. numIndices = ib.m_size/indexSize;
  3881. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  3882. numInstances = draw.m_numInstances;
  3883. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3884. rce.SetIndexBuffer(ib.m_ptr, ib.m_format, 0);
  3885. rce.DrawIndexed(numIndices, draw.m_numInstances, 0, 0, 0);
  3886. }
  3887. else if (prim.m_min <= draw.m_numIndices)
  3888. {
  3889. numIndices = draw.m_numIndices;
  3890. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  3891. numInstances = draw.m_numInstances;
  3892. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3893. rce.SetIndexBuffer(ib.m_ptr, ib.m_format, 0);
  3894. rce.DrawIndexed(numIndices, numInstances, draw.m_startIndex, 0, 0);
  3895. }
  3896. }
  3897. else
  3898. {
  3899. numPrimsSubmitted = numVertices/prim.m_div - prim.m_sub;
  3900. numInstances = draw.m_numInstances;
  3901. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3902. rce.Draw(numVertices, draw.m_numInstances, 0, 0);
  3903. }
  3904. }
  3905. statsNumPrimsSubmitted[primIndex] += numPrimsSubmitted;
  3906. statsNumPrimsRendered[primIndex] += numPrimsRendered;
  3907. statsNumInstances[primIndex] += numInstances;
  3908. statsNumDrawIndirect[primIndex] += numDrawIndirect;
  3909. statsNumIndices += numIndices;
  3910. }
  3911. }
  3912. if (wasCompute)
  3913. {
  3914. invalidateCompute();
  3915. setViewType(view, "C");
  3916. BGFX_WEBGPU_PROFILER_END();
  3917. BGFX_WEBGPU_PROFILER_BEGIN(view, kColorCompute);
  3918. }
  3919. submitBlit(bs, BGFX_CONFIG_MAX_VIEWS);
  3920. if (0 < _render->m_numRenderItems)
  3921. {
  3922. captureElapsed = -bx::getHPCounter();
  3923. capture();
  3924. rce = m_renderEncoder;
  3925. captureElapsed += bx::getHPCounter();
  3926. profiler.end();
  3927. }
  3928. }
  3929. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION) )
  3930. {
  3931. if (0 < _render->m_numRenderItems)
  3932. {
  3933. rce.PopDebugGroup();
  3934. }
  3935. }
  3936. BGFX_WEBGPU_PROFILER_END();
  3937. int64_t timeEnd = bx::getHPCounter();
  3938. int64_t frameTime = timeEnd - timeBegin;
  3939. static int64_t min = frameTime;
  3940. static int64_t max = frameTime;
  3941. min = bx::min<int64_t>(min, frameTime);
  3942. max = bx::max<int64_t>(max, frameTime);
  3943. static uint32_t maxGpuLatency = 0;
  3944. static double maxGpuElapsed = 0.0f;
  3945. double elapsedGpuMs = 0.0;
  3946. do
  3947. {
  3948. double toGpuMs = 1000.0 / double(m_gpuTimer.m_frequency);
  3949. elapsedGpuMs = m_gpuTimer.m_elapsed * toGpuMs;
  3950. maxGpuElapsed = elapsedGpuMs > maxGpuElapsed ? elapsedGpuMs : maxGpuElapsed;
  3951. }
  3952. while (m_gpuTimer.get() );
  3953. maxGpuLatency = bx::uint32_imax(maxGpuLatency, m_gpuTimer.m_control.available()-1);
  3954. const int64_t timerFreq = bx::getHPFrequency();
  3955. Stats& perfStats = _render->m_perfStats;
  3956. perfStats.cpuTimeBegin = timeBegin;
  3957. perfStats.cpuTimeEnd = timeEnd;
  3958. perfStats.cpuTimerFreq = timerFreq;
  3959. perfStats.gpuTimeBegin = m_gpuTimer.m_begin;
  3960. perfStats.gpuTimeEnd = m_gpuTimer.m_end;
  3961. perfStats.gpuTimerFreq = m_gpuTimer.m_frequency;
  3962. perfStats.numDraw = statsKeyType[0];
  3963. perfStats.numCompute = statsKeyType[1];
  3964. perfStats.numBlit = _render->m_numBlitItems;
  3965. perfStats.maxGpuLatency = maxGpuLatency;
  3966. bx::memCopy(perfStats.numPrims, statsNumPrimsRendered, sizeof(perfStats.numPrims) );
  3967. perfStats.gpuMemoryMax = -INT64_MAX;
  3968. perfStats.gpuMemoryUsed = -INT64_MAX;
  3969. //rce.setTriangleFillMode(MTLTriangleFillModeFill);
  3970. if (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  3971. {
  3972. rce = renderPass(_render, BGFX_INVALID_HANDLE, false, Clear());
  3973. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  3974. {
  3975. rce.PushDebugGroup("debugstats");
  3976. }
  3977. TextVideoMem& tvm = m_textVideoMem;
  3978. static int64_t next = timeEnd;
  3979. if (timeEnd >= next)
  3980. {
  3981. next = timeEnd + timerFreq;
  3982. double freq = double(timerFreq);
  3983. double toMs = 1000.0/freq;
  3984. tvm.clear();
  3985. uint16_t pos = 0;
  3986. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x8c : 0x8f
  3987. , " %s / " BX_COMPILER_NAME
  3988. " / " BX_CPU_NAME
  3989. " / " BX_ARCH_NAME
  3990. " / " BX_PLATFORM_NAME
  3991. " / Version 1.%d.%d (commit: " BGFX_REV_SHA1 ")"
  3992. , getRendererName()
  3993. , BGFX_API_VERSION
  3994. , BGFX_REV_NUMBER
  3995. );
  3996. pos = 10;
  3997. tvm.printf(10, pos++, 0x8b, " Frame: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS "
  3998. , double(frameTime)*toMs
  3999. , double(min)*toMs
  4000. , double(max)*toMs
  4001. , freq/frameTime
  4002. );
  4003. const uint32_t msaa = (m_resolution.reset&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  4004. tvm.printf(10, pos++, 0x8b, " Reset flags: [%c] vsync, [%c] MSAAx%d, [%c] MaxAnisotropy "
  4005. , !!(m_resolution.reset&BGFX_RESET_VSYNC) ? '\xfe' : ' '
  4006. , 0 != msaa ? '\xfe' : ' '
  4007. , 1<<msaa
  4008. , !!(m_resolution.reset&BGFX_RESET_MAXANISOTROPY) ? '\xfe' : ' '
  4009. );
  4010. double elapsedCpuMs = double(frameTime)*toMs;
  4011. tvm.printf(10, pos++, 0x8b, " Submitted: %4d (draw %4d, compute %4d) / CPU %3.4f [ms] %c GPU %3.4f [ms] (latency %d)"
  4012. , _render->m_numRenderItems
  4013. , statsKeyType[0]
  4014. , statsKeyType[1]
  4015. , elapsedCpuMs
  4016. , elapsedCpuMs > maxGpuElapsed ? '>' : '<'
  4017. , maxGpuElapsed
  4018. , maxGpuLatency
  4019. );
  4020. maxGpuLatency = 0;
  4021. maxGpuElapsed = 0.0;
  4022. for (uint32_t ii = 0; ii < Topology::Count; ++ii)
  4023. {
  4024. tvm.printf(10, pos++, 0x8b, " %10s: %7d (#inst: %5d), submitted: %7d"
  4025. , getName(Topology::Enum(ii) )
  4026. , statsNumPrimsRendered[ii]
  4027. , statsNumInstances[ii]
  4028. , statsNumPrimsSubmitted[ii]
  4029. );
  4030. }
  4031. tvm.printf(10, pos++, 0x8b, " Indices: %7d ", statsNumIndices);
  4032. // tvm.printf(10, pos++, 0x8b, " Uniform size: %7d, Max: %7d ", _render->m_uniformEnd, _render->m_uniformMax);
  4033. tvm.printf(10, pos++, 0x8b, " DVB size: %7d ", _render->m_vboffset);
  4034. tvm.printf(10, pos++, 0x8b, " DIB size: %7d ", _render->m_iboffset);
  4035. pos++;
  4036. double captureMs = double(captureElapsed)*toMs;
  4037. tvm.printf(10, pos++, 0x8b, " Capture: %3.4f [ms]", captureMs);
  4038. uint8_t attr[2] = { 0x8c, 0x8a };
  4039. uint8_t attrIndex = _render->m_waitSubmit < _render->m_waitRender;
  4040. tvm.printf(10, pos++, attr[attrIndex &1], " Submit wait: %3.4f [ms]", _render->m_waitSubmit*toMs);
  4041. tvm.printf(10, pos++, attr[(attrIndex+1)&1], " Render wait: %3.4f [ms]", _render->m_waitRender*toMs);
  4042. min = frameTime;
  4043. max = frameTime;
  4044. }
  4045. blit(this, _textVideoMemBlitter, tvm);
  4046. rce = m_renderEncoder;
  4047. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  4048. {
  4049. rce.PopDebugGroup();
  4050. }
  4051. }
  4052. else if (_render->m_debug & BGFX_DEBUG_TEXT)
  4053. {
  4054. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  4055. {
  4056. rce.PushDebugGroup("debugtext");
  4057. }
  4058. blit(this, _textVideoMemBlitter, _render->m_textVideoMem);
  4059. rce = m_renderEncoder;
  4060. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  4061. {
  4062. rce.PopDebugGroup();
  4063. }
  4064. }
  4065. endEncoding();
  4066. scratchBuffer.submit();
  4067. m_cmd.kick(true);
  4068. scratchBuffer.release();
  4069. #if !BX_PLATFORM_EMSCRIPTEN
  4070. for (uint32_t ii = 0, num = m_numWindows; ii < num; ++ii)
  4071. {
  4072. FrameBufferWgpu& frameBuffer = ii == 0 ? m_mainFrameBuffer : m_frameBuffers[m_windows[ii].idx];
  4073. if (NULL != frameBuffer.m_swapChain
  4074. && frameBuffer.m_swapChain->m_drawable)
  4075. {
  4076. SwapChainWgpu& swapChain = *frameBuffer.m_swapChain;
  4077. swapChain.m_swapChain.Present();
  4078. }
  4079. }
  4080. #endif
  4081. }
  4082. } /* namespace webgpu */ } // namespace bgfx
  4083. #else
  4084. namespace bgfx { namespace webgpu
  4085. {
  4086. RendererContextI* rendererCreate(const Init& _init)
  4087. {
  4088. BX_UNUSED(_init);
  4089. return NULL;
  4090. }
  4091. void rendererDestroy()
  4092. {
  4093. }
  4094. } /* namespace webgpu */ } // namespace bgfx
  4095. #endif // BGFX_CONFIG_RENDERER_WEBGPU