webgpuEngine.ts 192 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376
  1. import { Logger } from "../Misc/logger";
  2. import { Nullable, DataArray, IndicesArray, FloatArray, Immutable } from "../types";
  3. import { Color4 } from "../Maths/math";
  4. import { Engine } from "../Engines/engine";
  5. import { InstancingAttributeInfo } from "../Engines/instancingAttributeInfo";
  6. import { RenderTargetCreationOptions } from "../Materials/Textures/renderTargetCreationOptions";
  7. import { InternalTexture, InternalTextureSource } from "../Materials/Textures/internalTexture";
  8. import { IEffectCreationOptions, Effect } from "../Materials/effect";
  9. import { EffectFallbacks } from "../Materials/effectFallbacks";
  10. import { _TimeToken } from "../Instrumentation/timeToken";
  11. import { Constants } from "./constants";
  12. import * as WebGPUConstants from './WebGPU/webgpuConstants';
  13. import { VertexBuffer } from "../Meshes/buffer";
  14. import { WebGPUPipelineContext, IWebGPUPipelineContextVertexInputsCache, IWebGPURenderPipelineStageDescriptor } from './WebGPU/webgpuPipelineContext';
  15. import { IPipelineContext } from './IPipelineContext';
  16. import { DataBuffer } from '../Meshes/dataBuffer';
  17. import { WebGPUDataBuffer } from '../Meshes/WebGPU/webgpuDataBuffer';
  18. import { BaseTexture } from "../Materials/Textures/baseTexture";
  19. import { IShaderProcessor } from "./Processors/iShaderProcessor";
  20. import { WebGPUShaderProcessor } from "./WebGPU/webgpuShaderProcessors";
  21. import { ShaderProcessingContext } from "./Processors/shaderProcessingOptions";
  22. import { WebGPUShaderProcessingContext } from "./WebGPU/webgpuShaderProcessingContext";
  23. import { Tools } from "../Misc/tools";
  24. import { WebGPUTextureHelper } from './WebGPU/webgpuTextureHelper';
  25. import { ISceneLike } from './thinEngine';
  26. import { Scene } from '../scene';
  27. import { WebGPUBufferManager } from './WebGPU/webgpuBufferManager';
  28. import { DepthTextureCreationOptions } from './depthTextureCreationOptions';
  29. import { HardwareTextureWrapper } from '../Materials/Textures/hardwareTextureWrapper';
  30. import { WebGPUHardwareTexture } from './WebGPU/webgpuHardwareTexture';
  31. import { IColor4Like } from '../Maths/math.like';
  32. import { IWebRequest } from '../Misc/interfaces/iWebRequest';
  33. import { UniformBuffer } from '../Materials/uniformBuffer';
  34. import { WebGPURenderPassWrapper } from './WebGPU/webgpuRenderPassWrapper';
  35. import { IMultiRenderTargetOptions } from '../Materials/Textures/multiRenderTarget';
  36. import { WebGPUCacheSampler } from "./WebGPU/webgpuCacheSampler";
  37. import { WebGPUShaderManager } from "./WebGPU/webgpuShaderManager";
  38. import "../Shaders/clearQuad.vertex";
  39. import "../Shaders/clearQuad.fragment";
  40. declare type VideoTexture = import("../Materials/Textures/videoTexture").VideoTexture;
  41. declare type RenderTargetTexture = import("../Materials/Textures/renderTargetTexture").RenderTargetTexture;
  42. // TODO WEBGPU remove when not needed anymore
  43. function assert(condition: any, msg?: string): asserts condition {
  44. if (!condition) {
  45. throw new Error(msg);
  46. }
  47. }
  48. /**
  49. * Options to load the associated Glslang library
  50. */
  51. export interface GlslangOptions {
  52. /**
  53. * Defines an existing instance of Glslang (usefull in modules who do not access the global instance).
  54. */
  55. glslang?: any;
  56. /**
  57. * Defines the URL of the glslang JS File.
  58. */
  59. jsPath?: string;
  60. /**
  61. * Defines the URL of the glslang WASM File.
  62. */
  63. wasmPath?: string;
  64. }
  65. /**
  66. * Options to create the WebGPU engine
  67. */
  68. export interface WebGPUEngineOptions extends GPURequestAdapterOptions {
  69. /**
  70. * If delta time between frames should be constant
  71. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  72. */
  73. deterministicLockstep?: boolean;
  74. /**
  75. * Maximum about of steps between frames (Default: 4)
  76. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  77. */
  78. lockstepMaxSteps?: number;
  79. /**
  80. * Defines the seconds between each deterministic lock step
  81. */
  82. timeStep?: number;
  83. /**
  84. * Defines that engine should ignore modifying touch action attribute and style
  85. * If not handle, you might need to set it up on your side for expected touch devices behavior.
  86. */
  87. doNotHandleTouchAction?: boolean;
  88. /**
  89. * Defines if webaudio should be initialized as well
  90. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  91. */
  92. audioEngine?: boolean;
  93. /**
  94. * Defines the category of adapter to use.
  95. * Is it the discrete or integrated device.
  96. */
  97. powerPreference?: GPUPowerPreference;
  98. /**
  99. * Defines the device descriptor used to create a device.
  100. */
  101. deviceDescriptor?: GPUDeviceDescriptor;
  102. /**
  103. * Defines the requested Swap Chain Format.
  104. */
  105. swapChainFormat?: GPUTextureFormat;
  106. /**
  107. * Defines wether MSAA is enabled on the canvas.
  108. */
  109. antialiasing?: boolean;
  110. /**
  111. * Defines wether the stencil buffer should be enabled.
  112. */
  113. stencil?: boolean;
  114. /**
  115. * Defines wether we should generate debug markers in the gpu command lists (can be seen with PIX for eg)
  116. */
  117. enableGPUDebugMarkers?: boolean;
  118. }
  119. /**
  120. * The web GPU engine class provides support for WebGPU version of babylon.js.
  121. */
  122. export class WebGPUEngine extends Engine {
  123. // Default glslang options.
  124. private static readonly _glslangDefaultOptions: GlslangOptions = {
  125. jsPath: "https://preview.babylonjs.com/glslang/glslang.js",
  126. wasmPath: "https://preview.babylonjs.com/glslang/glslang.wasm"
  127. };
  128. // Page Life cycle and constants
  129. private readonly _uploadEncoderDescriptor = { label: "upload" };
  130. private readonly _renderEncoderDescriptor = { label: "render" };
  131. private readonly _renderTargetEncoderDescriptor = { label: "renderTarget" };
  132. private readonly _clearDepthValue = 1;
  133. private readonly _clearReverseDepthValue = 0;
  134. private readonly _clearStencilValue = 0;
  135. private readonly _defaultSampleCount = 4; // Only supported value for now.
  136. // Engine Life Cycle
  137. private _canvas: HTMLCanvasElement;
  138. private _options: WebGPUEngineOptions;
  139. private _glslang: any = null;
  140. private _adapter: GPUAdapter;
  141. private _adapterSupportedExtensions: GPUExtensionName[];
  142. private _device: GPUDevice;
  143. private _deviceEnabledExtensions: GPUExtensionName[];
  144. private _context: GPUCanvasContext;
  145. private _swapChain: GPUSwapChain;
  146. private _swapChainTexture: GPUTexture;
  147. private _mainPassSampleCount: number;
  148. private _textureHelper: WebGPUTextureHelper;
  149. private _bufferManager: WebGPUBufferManager;
  150. private _shaderManager: WebGPUShaderManager;
  151. private _cacheSampler: WebGPUCacheSampler;
  152. private _emptyVertexBuffer: VertexBuffer;
  153. private _lastCachedWrapU: number;
  154. private _lastCachedWrapV: number;
  155. private _lastCachedWrapR: number;
  156. private _mrtAttachments: number[];
  157. private _counters: {
  158. numPipelineDescriptorCreation: number;
  159. numBindGroupsCreation: number;
  160. numVertexInputCacheCreation: number;
  161. } = {
  162. numPipelineDescriptorCreation: 0,
  163. numBindGroupsCreation: 0,
  164. numVertexInputCacheCreation: 0,
  165. };
  166. // Some of the internal state might change during the render pass.
  167. // This happens mainly during clear for the state
  168. // And when the frame starts to swap the target texture from the swap chain
  169. private _mainTexture: GPUTexture;
  170. private _depthTexture: GPUTexture;
  171. private _mainTextureExtends: GPUExtent3D;
  172. private _depthTextureFormat: GPUTextureFormat | undefined;
  173. private _colorFormat: GPUTextureFormat;
  174. // Frame Life Cycle (recreated each frame)
  175. private _uploadEncoder: GPUCommandEncoder;
  176. private _renderEncoder: GPUCommandEncoder;
  177. private _renderTargetEncoder: GPUCommandEncoder;
  178. private _commandBuffers: GPUCommandBuffer[] = [null as any, null as any, null as any];
  179. // Frame Buffer Life Cycle (recreated for each render target pass)
  180. private _currentRenderPass: Nullable<GPURenderPassEncoder> = null;
  181. private _mainRenderPassWrapper: WebGPURenderPassWrapper = new WebGPURenderPassWrapper();
  182. private _rttRenderPassWrapper: WebGPURenderPassWrapper = new WebGPURenderPassWrapper();
  183. private _pendingDebugCommands: Array<[string, Nullable<string>]> = [];
  184. // DrawCall Life Cycle
  185. // Effect is on the parent class
  186. // protected _currentEffect: Nullable<Effect> = null;
  187. private _currentVertexBuffers: Nullable<{ [key: string]: Nullable<VertexBuffer> }> = null;
  188. private _currentIndexBuffer: Nullable<DataBuffer> = null;
  189. private __colorWrite = true;
  190. private _uniformsBuffers: { [name: string]: WebGPUDataBuffer } = {};
  191. private _forceEnableEffect = false;
  192. // TODO WEBGPU remove those variables when code stabilized
  193. /** @hidden */
  194. public dbgShowShaderCode = false;
  195. /** @hidden */
  196. public dbgSanityChecks = false;
  197. /** @hidden */
  198. public dbgGenerateLogs = false;
  199. /** @hidden */
  200. public dbgVerboseLogsForFirstFrames = false;
  201. /** @hidden */
  202. public dbgVerboseLogsNumFrames = 10;
  203. /** @hidden */
  204. public dbgShowWarningsNotImplemented = false;
  205. /**
  206. * Gets a boolean indicating that the engine supports uniform buffers
  207. */
  208. public get supportsUniformBuffers(): boolean {
  209. return true;
  210. }
  211. /** Gets the supported extensions by the WebGPU adapter */
  212. public get supportedExtensions(): Immutable<GPUExtensionName[]> {
  213. return this._adapterSupportedExtensions;
  214. }
  215. /** Gets the currently enabled extensions on the WebGPU device */
  216. public get enabledExtensions(): Immutable<GPUExtensionName[]> {
  217. return this._deviceEnabledExtensions;
  218. }
  219. /**
  220. * Returns the name of the engine
  221. */
  222. public get name(): string {
  223. return "WebGPU";
  224. }
  225. /**
  226. * Returns a string describing the current engine
  227. */
  228. public get description(): string {
  229. let description = this.name + this.version;
  230. return description;
  231. }
  232. /**
  233. * Returns the version of the engine
  234. */
  235. public get version(): number {
  236. return 1;
  237. }
  238. /**
  239. * Create a new instance of the gpu engine.
  240. * @param canvas Defines the canvas to use to display the result
  241. * @param options Defines the options passed to the engine to create the GPU context dependencies
  242. */
  243. public constructor(canvas: HTMLCanvasElement, options: WebGPUEngineOptions = {}) {
  244. super(null);
  245. options.deviceDescriptor = options.deviceDescriptor || { };
  246. options.swapChainFormat = options.swapChainFormat || WebGPUConstants.TextureFormat.BGRA8Unorm;
  247. options.antialiasing = options.antialiasing === undefined ? true : options.antialiasing;
  248. options.stencil = options.stencil ?? true;
  249. options.enableGPUDebugMarkers = options.enableGPUDebugMarkers ?? false;
  250. Logger.Log(`Babylon.js v${Engine.Version} - WebGPU engine`);
  251. if (!navigator.gpu) {
  252. Logger.Error("WebGPU is not supported by your browser.");
  253. return;
  254. }
  255. this._isWebGPU = true;
  256. this._shaderPlatformName = "WEBGPU";
  257. if (options.deterministicLockstep === undefined) {
  258. options.deterministicLockstep = false;
  259. }
  260. if (options.lockstepMaxSteps === undefined) {
  261. options.lockstepMaxSteps = 4;
  262. }
  263. if (options.audioEngine === undefined) {
  264. options.audioEngine = true;
  265. }
  266. this._deterministicLockstep = options.deterministicLockstep;
  267. this._lockstepMaxSteps = options.lockstepMaxSteps;
  268. this._timeStep = options.timeStep || 1 / 60;
  269. this._doNotHandleContextLost = false;
  270. this._canvas = canvas;
  271. this._options = options;
  272. this.premultipliedAlpha = false;
  273. this._hardwareScalingLevel = 1;
  274. this._mainPassSampleCount = options.antialiasing ? this._defaultSampleCount : 1;
  275. this._isStencilEnable = options.stencil;
  276. this._depthCullingState.depthTest = true;
  277. this._depthCullingState.depthFunc = Constants.LEQUAL;
  278. this._depthCullingState.depthMask = true;
  279. this._sharedInit(canvas, !!options.doNotHandleTouchAction, options.audioEngine);
  280. // TODO. WEBGPU. Use real way to do it.
  281. this._canvas.style.transform = "scaleY(-1)";
  282. }
  283. //------------------------------------------------------------------------------
  284. // Initialization
  285. //------------------------------------------------------------------------------
  286. /**
  287. * Initializes the WebGPU context and dependencies.
  288. * @param glslangOptions Defines the GLSLang compiler options if necessary
  289. * @returns a promise notifying the readiness of the engine.
  290. */
  291. public initAsync(glslangOptions?: GlslangOptions): Promise<void> {
  292. return this._initGlslang(glslangOptions)
  293. .then((glslang: any) => {
  294. this._glslang = glslang;
  295. return navigator.gpu!.requestAdapter(this._options);
  296. })
  297. .then((adapter: GPUAdapter | null) => {
  298. this._adapter = adapter!;
  299. this._adapterSupportedExtensions = this._adapter.extensions.slice(0);
  300. const deviceDescriptor = this._options.deviceDescriptor;
  301. if (deviceDescriptor?.extensions) {
  302. const requestedExtensions = deviceDescriptor.extensions;
  303. const validExtensions = [];
  304. const iterator = requestedExtensions[Symbol.iterator]();
  305. while (true) {
  306. const { done, value : extension } = iterator.next();
  307. if (done) {
  308. break;
  309. }
  310. if (this._adapterSupportedExtensions.indexOf(extension) >= 0) {
  311. validExtensions.push(extension);
  312. }
  313. }
  314. deviceDescriptor.extensions = validExtensions;
  315. }
  316. return this._adapter.requestDevice(this._options.deviceDescriptor);
  317. })
  318. .then((device: GPUDevice | null) => {
  319. this._device = device!;
  320. this._deviceEnabledExtensions = this._device.extensions.slice(0);
  321. })
  322. .then(() => {
  323. this._bufferManager = new WebGPUBufferManager(this._device);
  324. this._textureHelper = new WebGPUTextureHelper(this._device, this._glslang, this._bufferManager);
  325. this._shaderManager = new WebGPUShaderManager(this._device);
  326. this._cacheSampler = new WebGPUCacheSampler(this._device);
  327. if (this.dbgVerboseLogsForFirstFrames) {
  328. if ((this as any)._count === undefined) {
  329. (this as any)._count = 0;
  330. console.log("%c frame #" + (this as any)._count + " - begin", "background: #ffff00");
  331. }
  332. }
  333. this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);
  334. this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);
  335. this._renderTargetEncoder = this._device.createCommandEncoder(this._renderTargetEncoderDescriptor);
  336. this._textureHelper.setCommandEncoder(this._uploadEncoder);
  337. this._emptyVertexBuffer = new VertexBuffer(this, [0], "", false, false, 1, false, 0, 1);
  338. this._initializeLimits();
  339. this._initializeContextAndSwapChain();
  340. this._initializeMainAttachments();
  341. this.resize();
  342. })
  343. .catch((e: any) => {
  344. Logger.Error("Can not create WebGPU Device and/or context.");
  345. Logger.Error(e);
  346. });
  347. }
  348. private _initGlslang(glslangOptions?: GlslangOptions): Promise<any> {
  349. glslangOptions = glslangOptions || { };
  350. glslangOptions = {
  351. ...WebGPUEngine._glslangDefaultOptions,
  352. ...glslangOptions
  353. };
  354. if (glslangOptions.glslang) {
  355. return Promise.resolve(glslangOptions.glslang);
  356. }
  357. if ((window as any).glslang) {
  358. return (window as any).glslang(glslangOptions!.wasmPath);
  359. }
  360. if (glslangOptions.jsPath && glslangOptions.wasmPath) {
  361. return Tools.LoadScriptAsync(glslangOptions.jsPath)
  362. .then(() => {
  363. return (window as any).glslang(glslangOptions!.wasmPath);
  364. });
  365. }
  366. return Promise.reject("gslang is not available.");
  367. }
  368. private _initializeLimits(): void {
  369. // Init caps
  370. // TODO WEBGPU Real Capability check once limits will be working.
  371. this._caps = {
  372. maxTexturesImageUnits: 16,
  373. maxVertexTextureImageUnits: 16,
  374. maxCombinedTexturesImageUnits: 32,
  375. maxTextureSize: 2048,
  376. maxCubemapTextureSize: 2048,
  377. maxRenderTextureSize: 2048,
  378. maxVertexAttribs: 16,
  379. maxVaryingVectors: 16,
  380. maxFragmentUniformVectors: 1024,
  381. maxVertexUniformVectors: 1024,
  382. standardDerivatives: true,
  383. astc: null,
  384. s3tc: (this._deviceEnabledExtensions.indexOf(WebGPUConstants.ExtensionName.TextureCompressionBC) >= 0 ? true : undefined) as any,
  385. pvrtc: null,
  386. etc1: null,
  387. etc2: null,
  388. bptc: this._deviceEnabledExtensions.indexOf(WebGPUConstants.ExtensionName.TextureCompressionBC) >= 0 ? true : undefined,
  389. maxAnisotropy: 16, // TODO WEBGPU: Retrieve this smartly
  390. uintIndices: true,
  391. fragmentDepthSupported: true,
  392. highPrecisionShaderSupported: true,
  393. colorBufferFloat: true,
  394. textureFloat: true,
  395. textureFloatLinearFiltering: true,
  396. textureFloatRender: true,
  397. textureHalfFloat: true,
  398. textureHalfFloatLinearFiltering: true,
  399. textureHalfFloatRender: true,
  400. textureLOD: true,
  401. drawBuffersExtension: true,
  402. depthTextureExtension: true,
  403. vertexArrayObject: false,
  404. instancedArrays: true,
  405. timerQuery: undefined,
  406. canUseTimestampForTimerQuery: false,
  407. multiview: false,
  408. oculusMultiview: false,
  409. parallelShaderCompile: undefined,
  410. blendMinMax: true,
  411. maxMSAASamples: 4 // TODO WEBGPU what is the right value?
  412. };
  413. this._caps.parallelShaderCompile = null as any;
  414. this._features = {
  415. forceBitmapOverHTMLImageElement: true,
  416. supportRenderAndCopyToLodForFloatTextures: true,
  417. supportDepthStencilTexture: true,
  418. supportShadowSamplers: true,
  419. uniformBufferHardCheckMatrix: true,
  420. allowTexturePrefiltering: true,
  421. trackUbosInFrame: true,
  422. supportCSM: true,
  423. basisNeedsPOT: false,
  424. support3DTextures: false, // TODO WEBGPU change to true when Chrome supports 3D textures
  425. needTypeSuffixInShaderConstants: true,
  426. supportMSAA: true,
  427. supportSSAO2: true,
  428. supportExtendedTextureFormats: true,
  429. supportSwitchCaseInShader: true,
  430. _collectUbosUpdatedInFrame: true,
  431. };
  432. }
  433. private _initializeContextAndSwapChain(): void {
  434. this._context = this._canvas.getContext('gpupresent') as unknown as GPUCanvasContext;
  435. this._swapChain = this._context.configureSwapChain({
  436. device: this._device,
  437. format: this._options.swapChainFormat!,
  438. usage: WebGPUConstants.TextureUsage.OutputAttachment | WebGPUConstants.TextureUsage.CopySrc,
  439. });
  440. this._colorFormat = this._options.swapChainFormat!;
  441. this._mainRenderPassWrapper.colorAttachmentGPUTextures = [new WebGPUHardwareTexture()];
  442. this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format = this._colorFormat;
  443. if (this.dbgGenerateLogs) {
  444. this._context.getSwapChainPreferredFormat(this._device).then((format) => {
  445. console.log("Swap chain preferred format:", format);
  446. });
  447. }
  448. }
  449. // Set default values as WebGL with depth and stencil attachment for the broadest Compat.
  450. private _initializeMainAttachments(): void {
  451. this._mainTextureExtends = {
  452. width: this.getRenderWidth(),
  453. height: this.getRenderHeight(),
  454. depth: 1
  455. };
  456. let mainColorAttachments: GPURenderPassColorAttachmentDescriptor[];
  457. if (this._options.antialiasing) {
  458. const mainTextureDescriptor: GPUTextureDescriptor = {
  459. size: this._mainTextureExtends,
  460. mipLevelCount: 1,
  461. sampleCount: this._mainPassSampleCount,
  462. dimension: WebGPUConstants.TextureDimension.E2d,
  463. format: this._options.swapChainFormat!,
  464. usage: WebGPUConstants.TextureUsage.OutputAttachment,
  465. };
  466. if (this._mainTexture) {
  467. this._mainTexture.destroy();
  468. }
  469. this._mainTexture = this._device.createTexture(mainTextureDescriptor);
  470. mainColorAttachments = [{
  471. attachment: this._mainTexture.createView(),
  472. loadValue: new Color4(0, 0, 0, 1),
  473. storeOp: WebGPUConstants.StoreOp.Store
  474. }];
  475. }
  476. else {
  477. mainColorAttachments = [{
  478. attachment: undefined as any,
  479. loadValue: new Color4(0, 0, 0, 1),
  480. storeOp: WebGPUConstants.StoreOp.Store
  481. }];
  482. }
  483. this._mainRenderPassWrapper.depthTextureFormat = this.isStencilEnable ? WebGPUConstants.TextureFormat.Depth24PlusStencil8 : WebGPUConstants.TextureFormat.Depth32Float;
  484. this._setDepthTextureFormat(this._mainRenderPassWrapper);
  485. const depthTextureDescriptor: GPUTextureDescriptor = {
  486. size: this._mainTextureExtends,
  487. mipLevelCount: 1,
  488. sampleCount: this._mainPassSampleCount,
  489. dimension: WebGPUConstants.TextureDimension.E2d,
  490. format: this._mainRenderPassWrapper.depthTextureFormat,
  491. usage: WebGPUConstants.TextureUsage.OutputAttachment
  492. };
  493. if (this._depthTexture) {
  494. this._depthTexture.destroy();
  495. }
  496. this._depthTexture = this._device.createTexture(depthTextureDescriptor);
  497. const mainDepthAttachment: GPURenderPassDepthStencilAttachmentDescriptor = {
  498. attachment: this._depthTexture.createView(),
  499. depthLoadValue: this._clearDepthValue,
  500. depthStoreOp: WebGPUConstants.StoreOp.Store,
  501. stencilLoadValue: this._clearStencilValue,
  502. stencilStoreOp: WebGPUConstants.StoreOp.Store,
  503. };
  504. this._mainRenderPassWrapper.renderPassDescriptor = {
  505. colorAttachments: mainColorAttachments,
  506. depthStencilAttachment: mainDepthAttachment
  507. };
  508. if (this._mainRenderPassWrapper.renderPass !== null) {
  509. this._endMainRenderPass();
  510. }
  511. }
  512. /**
  513. * Force a specific size of the canvas
  514. * @param width defines the new canvas' width
  515. * @param height defines the new canvas' height
  516. * @param forceSetSize true to force setting the sizes of the underlying canvas
  517. * @returns true if the size was changed
  518. */
  519. public setSize(width: number, height: number, forceSetSize = false): boolean {
  520. if (!super.setSize(width, height, forceSetSize)) {
  521. return false;
  522. }
  523. if (this.dbgVerboseLogsForFirstFrames) {
  524. if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
  525. console.log("frame #" + (this as any)._count + " - setSize called -", width, height);
  526. }
  527. }
  528. this._initializeMainAttachments();
  529. return true;
  530. }
  531. /**
  532. * Gets a shader processor implementation fitting with the current engine type.
  533. * @returns The shader processor implementation.
  534. */
  535. protected _getShaderProcessor(): Nullable<IShaderProcessor> {
  536. return new WebGPUShaderProcessor();
  537. }
  538. /** @hidden */
  539. public _getShaderProcessingContext(): Nullable<ShaderProcessingContext> {
  540. return new WebGPUShaderProcessingContext();
  541. }
  542. //------------------------------------------------------------------------------
  543. // Static Pipeline WebGPU States
  544. //------------------------------------------------------------------------------
  545. /**
  546. * Force the entire cache to be cleared
  547. * You should not have to use this function unless your engine needs to share the WebGPU context with another engine
  548. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  549. */
  550. public wipeCaches(bruteForce?: boolean): void {
  551. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  552. return;
  553. }
  554. //this._currentEffect = null; // can't reset _currentEffect, else some crashes can occur (for eg in ProceduralTexture which calls bindFrameBuffer (which calls wipeCaches) after having called enableEffect and before drawing into the texture)
  555. // _forceEnableEffect = true assumes the role of _currentEffect = null
  556. this._forceEnableEffect = true;
  557. this._currentIndexBuffer = null;
  558. this._currentVertexBuffers = null;
  559. if (bruteForce) {
  560. this._currentProgram = null;
  561. this._stencilState.reset();
  562. this._depthCullingState.reset();
  563. this._depthCullingState.depthFunc = Constants.LEQUAL;
  564. this._alphaState.reset();
  565. this._alphaMode = Constants.ALPHA_ADD;
  566. this._alphaEquation = Constants.ALPHA_DISABLE;
  567. this.__colorWrite = true;
  568. }
  569. this._cachedVertexBuffers = null;
  570. this._cachedIndexBuffer = null;
  571. this._cachedEffectForVertexBuffers = null;
  572. }
  573. /**
  574. * Enable or disable color writing
  575. * @param enable defines the state to set
  576. */
  577. public setColorWrite(enable: boolean): void {
  578. this.__colorWrite = enable;
  579. }
  580. /**
  581. * Gets a boolean indicating if color writing is enabled
  582. * @returns the current color writing state
  583. */
  584. public getColorWrite(): boolean {
  585. return this.__colorWrite;
  586. }
  587. //------------------------------------------------------------------------------
  588. // Dynamic WebGPU States
  589. //------------------------------------------------------------------------------
  590. private _viewportsCurrent: Array<{ x: number, y: number, w: number, h: number }> = [{ x: 0, y: 0, w: 0, h: 0 }, { x: 0, y: 0, w: 0, h: 0 }];
  591. private _resetCurrentViewport(index: number) {
  592. this._viewportsCurrent[index].x = 0;
  593. this._viewportsCurrent[index].y = 0;
  594. this._viewportsCurrent[index].w = 0;
  595. this._viewportsCurrent[index].h = 0;
  596. }
  597. private _applyViewport(renderPass: GPURenderPassEncoder): void {
  598. const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1;
  599. const x = this._viewportCached.x,
  600. y = this._viewportCached.y,
  601. w = this._viewportCached.z,
  602. h = this._viewportCached.w;
  603. if (this._viewportsCurrent[index].x !== x || this._viewportsCurrent[index].y !== y ||
  604. this._viewportsCurrent[index].w !== w || this._viewportsCurrent[index].h !== h)
  605. {
  606. this._viewportsCurrent[index].x = x;
  607. this._viewportsCurrent[index].y = y;
  608. this._viewportsCurrent[index].w = w;
  609. this._viewportsCurrent[index].h = h;
  610. renderPass.setViewport(x, y, w, h, 0, 1);
  611. if (this.dbgVerboseLogsForFirstFrames) {
  612. if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
  613. console.log("frame #" + (this as any)._count + " - viewport applied - (", x, y, w, h, ") current pass is main pass=" + (renderPass === this._mainRenderPassWrapper.renderPass));
  614. }
  615. }
  616. }
  617. }
  618. /** @hidden */
  619. public _viewport(x: number, y: number, width: number, height: number): void {
  620. this._viewportCached.x = x;
  621. this._viewportCached.y = y;
  622. this._viewportCached.z = width;
  623. this._viewportCached.w = height;
  624. }
  625. private _scissorsCurrent: Array<{ x: number, y: number, w: number, h: number }> = [{ x: 0, y: 0, w: 0, h: 0 }, { x: 0, y: 0, w: 0, h: 0 }];
  626. protected _scissorCached = { x: 0, y: 0, z: 0, w: 0 };
  627. private _resetCurrentScissor(index: number) {
  628. this._scissorsCurrent[index].x = 0;
  629. this._scissorsCurrent[index].y = 0;
  630. this._scissorsCurrent[index].w = 0;
  631. this._scissorsCurrent[index].h = 0;
  632. }
  633. private _applyScissor(renderPass: GPURenderPassEncoder): void {
  634. const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1;
  635. const x = this._scissorCached.x,
  636. y = this._scissorCached.y,
  637. w = this._scissorCached.z,
  638. h = this._scissorCached.w;
  639. if (this._scissorsCurrent[index].x !== x || this._scissorsCurrent[index].y !== y ||
  640. this._scissorsCurrent[index].w !== w || this._scissorsCurrent[index].h !== h)
  641. {
  642. this._scissorsCurrent[index].x = x;
  643. this._scissorsCurrent[index].y = y;
  644. this._scissorsCurrent[index].w = w;
  645. this._scissorsCurrent[index].h = h;
  646. renderPass.setScissorRect(x, y, w, h);
  647. if (this.dbgVerboseLogsForFirstFrames) {
  648. if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
  649. console.log("frame #" + (this as any)._count + " - scissor applied - (", x, y, w, h, ") current pass is main pass=" + (renderPass === this._mainRenderPassWrapper.renderPass));
  650. }
  651. }
  652. }
  653. }
  654. private _scissorIsActive() {
  655. return this._scissorCached.x !== 0 ||
  656. this._scissorCached.y !== 0 ||
  657. (this._scissorCached.z !== this.getRenderWidth() && this._scissorCached.z !== 0) ||
  658. (this._scissorCached.w !== this.getRenderHeight() && this._scissorCached.w !== 0);
  659. }
  660. public enableScissor(x: number, y: number, width: number, height: number): void {
  661. this._scissorCached.x = x;
  662. this._scissorCached.y = y;
  663. this._scissorCached.z = width;
  664. this._scissorCached.w = height;
  665. }
  666. public disableScissor() {
  667. this._scissorCached.x = 0;
  668. this._scissorCached.y = 0;
  669. this._scissorCached.z = this.getRenderWidth();
  670. this._scissorCached.w = this.getRenderHeight();
  671. }
  672. /**
  673. * Clear the current render buffer or the current render target (if any is set up)
  674. * @param color defines the color to use
  675. * @param backBuffer defines if the back buffer must be cleared
  676. * @param depth defines if the depth buffer must be cleared
  677. * @param stencil defines if the stencil buffer must be cleared
  678. */
  679. public clear(color: Nullable<IColor4Like>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  680. // Some PGs are using color3...
  681. if (color && color.a === undefined) {
  682. color.a = 1;
  683. }
  684. if (this.dbgVerboseLogsForFirstFrames) {
  685. if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
  686. console.log("frame #" + (this as any)._count + " - clear called - backBuffer=", backBuffer, " depth=", depth, " stencil=", stencil);
  687. }
  688. }
  689. // We need to recreate the render pass so that the new parameters for clear color / depth / stencil are taken into account
  690. if (this._currentRenderTarget) {
  691. if (this._currentRenderPass) {
  692. this._endRenderTargetRenderPass();
  693. }
  694. this._startRenderTargetRenderPass(this._currentRenderTarget!, backBuffer ? color : null, depth, stencil);
  695. } else {
  696. this._startMainRenderPass(true, backBuffer ? color : null, depth, stencil);
  697. }
  698. }
  699. //------------------------------------------------------------------------------
  700. // Vertex/Index Buffers
  701. //------------------------------------------------------------------------------
  702. /**
  703. * Creates a vertex buffer
  704. * @param data the data for the vertex buffer
  705. * @returns the new buffer
  706. */
  707. public createVertexBuffer(data: DataArray): DataBuffer {
  708. let view: ArrayBufferView;
  709. if (data instanceof Array) {
  710. view = new Float32Array(data);
  711. }
  712. else if (data instanceof ArrayBuffer) {
  713. view = new Uint8Array(data);
  714. }
  715. else {
  716. view = data;
  717. }
  718. const dataBuffer = this._bufferManager.createBuffer(view, WebGPUConstants.BufferUsage.Vertex | WebGPUConstants.BufferUsage.CopyDst);
  719. return dataBuffer;
  720. }
  721. /**
  722. * Creates a vertex buffer
  723. * @param data the data for the dynamic vertex buffer
  724. * @returns the new buffer
  725. */
  726. public createDynamicVertexBuffer(data: DataArray): DataBuffer {
  727. return this.createVertexBuffer(data);
  728. }
  729. /**
  730. * Updates a vertex buffer.
  731. * @param vertexBuffer the vertex buffer to update
  732. * @param data the data used to update the vertex buffer
  733. * @param byteOffset the byte offset of the data
  734. * @param byteLength the byte length of the data
  735. */
  736. public updateDynamicVertexBuffer(vertexBuffer: DataBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  737. const dataBuffer = vertexBuffer as WebGPUDataBuffer;
  738. if (byteOffset === undefined) {
  739. byteOffset = 0;
  740. }
  741. let view: ArrayBufferView;
  742. if (byteLength === undefined) {
  743. if (data instanceof Array) {
  744. view = new Float32Array(data);
  745. }
  746. else if (data instanceof ArrayBuffer) {
  747. view = new Uint8Array(data);
  748. }
  749. else {
  750. view = data;
  751. }
  752. byteLength = view.byteLength;
  753. } else {
  754. if (data instanceof Array) {
  755. view = new Float32Array(data);
  756. }
  757. else if (data instanceof ArrayBuffer) {
  758. view = new Uint8Array(data);
  759. }
  760. else {
  761. view = data;
  762. }
  763. }
  764. this._bufferManager.setSubData(dataBuffer, byteOffset, view, 0, byteLength);
  765. }
  766. /**
  767. * Creates a new index buffer
  768. * @param indices defines the content of the index buffer
  769. * @param updatable defines if the index buffer must be updatable - not used in WebGPU
  770. * @returns a new buffer
  771. */
  772. public createIndexBuffer(indices: IndicesArray, updatable?: boolean): DataBuffer {
  773. let is32Bits = true;
  774. let view: ArrayBufferView;
  775. if (indices instanceof Uint32Array || indices instanceof Int32Array) {
  776. view = indices;
  777. }
  778. else if (indices instanceof Uint16Array) {
  779. view = indices;
  780. is32Bits = false;
  781. }
  782. else {
  783. if (indices.length > 65535) {
  784. view = new Uint32Array(indices);
  785. }
  786. else {
  787. view = new Uint16Array(indices);
  788. is32Bits = false;
  789. }
  790. }
  791. const dataBuffer = this._bufferManager.createBuffer(view, WebGPUConstants.BufferUsage.Index | WebGPUConstants.BufferUsage.CopyDst);
  792. dataBuffer.is32Bits = is32Bits;
  793. return dataBuffer;
  794. }
  795. /**
  796. * Update an index buffer
  797. * @param indexBuffer defines the target index buffer
  798. * @param indices defines the data to update
  799. * @param offset defines the offset in the target index buffer where update should start
  800. */
  801. public updateDynamicIndexBuffer(indexBuffer: DataBuffer, indices: IndicesArray, offset: number = 0): void {
  802. const gpuBuffer = indexBuffer as WebGPUDataBuffer;
  803. var view: ArrayBufferView;
  804. if (indices instanceof Uint16Array) {
  805. if (indexBuffer.is32Bits) {
  806. view = Uint32Array.from(indices);
  807. }
  808. else {
  809. view = indices;
  810. }
  811. }
  812. else if (indices instanceof Uint32Array) {
  813. if (indexBuffer.is32Bits) {
  814. view = indices;
  815. }
  816. else {
  817. view = Uint16Array.from(indices);
  818. }
  819. }
  820. else {
  821. if (indexBuffer.is32Bits) {
  822. view = new Uint32Array(indices);
  823. }
  824. else {
  825. view = new Uint16Array(indices);
  826. }
  827. }
  828. this._bufferManager.setSubData(gpuBuffer, offset, view);
  829. }
  830. /** @hidden */
  831. public bindBuffersDirectly(vertexBuffer: DataBuffer, indexBuffer: DataBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  832. throw "Not implemented on WebGPU so far.";
  833. }
  834. /** @hidden */
  835. public updateAndBindInstancesBuffer(instancesBuffer: DataBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  836. throw "Not implemented on WebGPU so far.";
  837. }
  838. /**
  839. * Bind a list of vertex buffers with the engine
  840. * @param vertexBuffers defines the list of vertex buffers to bind
  841. * @param indexBuffer defines the index buffer to bind
  842. * @param effect defines the effect associated with the vertex buffers
  843. */
  844. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<DataBuffer>, effect: Effect): void {
  845. this._currentIndexBuffer = indexBuffer;
  846. this._currentVertexBuffers = vertexBuffers;
  847. }
  848. /** @hidden */
  849. public _releaseBuffer(buffer: DataBuffer): boolean {
  850. return this._bufferManager.releaseBuffer(buffer);
  851. }
  852. //------------------------------------------------------------------------------
  853. // UBO
  854. //------------------------------------------------------------------------------
  855. public createUniformBuffer(elements: FloatArray): DataBuffer {
  856. let view: Float32Array;
  857. if (elements instanceof Array) {
  858. view = new Float32Array(elements);
  859. }
  860. else {
  861. view = elements;
  862. }
  863. const dataBuffer = this._bufferManager.createBuffer(view, WebGPUConstants.BufferUsage.Uniform | WebGPUConstants.BufferUsage.CopyDst);
  864. return dataBuffer;
  865. }
  866. public createDynamicUniformBuffer(elements: FloatArray): DataBuffer {
  867. return this.createUniformBuffer(elements);
  868. }
  869. public updateUniformBuffer(uniformBuffer: DataBuffer, elements: FloatArray, offset?: number, count?: number): void {
  870. if (offset === undefined) {
  871. offset = 0;
  872. }
  873. const dataBuffer = uniformBuffer as WebGPUDataBuffer;
  874. let view: Float32Array;
  875. if (count === undefined) {
  876. if (elements instanceof Float32Array) {
  877. view = elements;
  878. } else {
  879. view = new Float32Array(elements);
  880. }
  881. count = view.byteLength;
  882. } else {
  883. if (elements instanceof Float32Array) {
  884. view = elements;
  885. } else {
  886. view = new Float32Array(elements);
  887. }
  888. }
  889. this._bufferManager.setSubData(dataBuffer, offset, view, 0, count);
  890. }
  891. public bindUniformBufferBase(buffer: DataBuffer, location: number, name: string): void {
  892. this._uniformsBuffers[name] = buffer as WebGPUDataBuffer;
  893. }
  894. //------------------------------------------------------------------------------
  895. // Effects
  896. //------------------------------------------------------------------------------
  897. /**
  898. * Create a new effect (used to store vertex/fragment shaders)
  899. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  900. * @param attributesNamesOrOptions defines either a list of attribute names or an IEffectCreationOptions object
  901. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  902. * @param samplers defines an array of string used to represent textures
  903. * @param defines defines the string containing the defines to use to compile the shaders
  904. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  905. * @param onCompiled defines a function to call when the effect creation is successful
  906. * @param onError defines a function to call when the effect creation has failed
  907. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  908. * @returns the new Effect
  909. */
  910. public createEffect(baseName: any, attributesNamesOrOptions: string[] | IEffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  911. onCompiled?: Nullable<(effect: Effect) => void>, onError?: Nullable<(effect: Effect, errors: string) => void>, indexParameters?: any): Effect {
  912. const vertex = baseName.vertexElement || baseName.vertex || baseName.vertexToken || baseName.vertexSource || baseName;
  913. const fragment = baseName.fragmentElement || baseName.fragment || baseName.fragmentToken || baseName.fragmentSource || baseName;
  914. const name = vertex + "+" + fragment + "@" + (defines ? defines : (<IEffectCreationOptions>attributesNamesOrOptions).defines);
  915. if (this._compiledEffects[name]) {
  916. var compiledEffect = <Effect>this._compiledEffects[name];
  917. if (onCompiled && compiledEffect.isReady()) {
  918. onCompiled(compiledEffect);
  919. }
  920. return compiledEffect;
  921. }
  922. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name);
  923. this._compiledEffects[name] = effect;
  924. return effect;
  925. }
  926. private _compileRawShaderToSpirV(source: string, type: string): Uint32Array {
  927. return this._glslang.compileGLSL(source, type);
  928. }
  929. private _compileShaderToSpirV(source: string, type: string, defines: Nullable<string>, shaderVersion: string): Uint32Array {
  930. return this._compileRawShaderToSpirV(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  931. }
  932. private _createPipelineStageDescriptor(vertexShader: Uint32Array, fragmentShader: Uint32Array): IWebGPURenderPipelineStageDescriptor {
  933. return {
  934. vertexStage: {
  935. module: this._device.createShaderModule({
  936. code: vertexShader,
  937. }),
  938. entryPoint: "main",
  939. },
  940. fragmentStage: {
  941. module: this._device.createShaderModule({
  942. code: fragmentShader,
  943. }),
  944. entryPoint: "main"
  945. }
  946. };
  947. }
  948. private _compileRawPipelineStageDescriptor(vertexCode: string, fragmentCode: string): IWebGPURenderPipelineStageDescriptor {
  949. var vertexShader = this._compileRawShaderToSpirV(vertexCode, "vertex");
  950. var fragmentShader = this._compileRawShaderToSpirV(fragmentCode, "fragment");
  951. return this._createPipelineStageDescriptor(vertexShader, fragmentShader);
  952. }
  953. private _compilePipelineStageDescriptor(vertexCode: string, fragmentCode: string, defines: Nullable<string>): IWebGPURenderPipelineStageDescriptor {
  954. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  955. var shaderVersion = "#version 450\n";
  956. var vertexShader = this._compileShaderToSpirV(vertexCode, "vertex", defines, shaderVersion);
  957. var fragmentShader = this._compileShaderToSpirV(fragmentCode, "fragment", defines, shaderVersion);
  958. let program = this._createPipelineStageDescriptor(vertexShader, fragmentShader);
  959. this.onAfterShaderCompilationObservable.notifyObservers(this);
  960. return program;
  961. }
  962. /** @hidden */
  963. public createRawShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  964. throw "Not available on WebGPU";
  965. }
  966. /** @hidden */
  967. public createShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  968. throw "Not available on WebGPU";
  969. }
  970. /**
  971. * Creates a new pipeline context
  972. * @param shaderProcessingContext defines the shader processing context used during the processing if available
  973. * @returns the new pipeline
  974. */
  975. public createPipelineContext(shaderProcessingContext: Nullable<ShaderProcessingContext>): IPipelineContext {
  976. var pipelineContext = new WebGPUPipelineContext(shaderProcessingContext! as WebGPUShaderProcessingContext, this);
  977. pipelineContext.engine = this;
  978. return pipelineContext;
  979. }
  980. /** @hidden */
  981. public _preparePipelineContext(pipelineContext: IPipelineContext, vertexSourceCode: string, fragmentSourceCode: string, createAsRaw: boolean, rawVertexSourceCode: string, rawFragmentSourceCode: string,
  982. rebuildRebind: any,
  983. defines: Nullable<string>,
  984. transformFeedbackVaryings: Nullable<string[]>,
  985. key: string) {
  986. const webGpuContext = pipelineContext as WebGPUPipelineContext;
  987. if (this.dbgShowShaderCode) {
  988. console.log(defines);
  989. console.log(vertexSourceCode);
  990. console.log(fragmentSourceCode);
  991. }
  992. webGpuContext.sources = {
  993. fragment: fragmentSourceCode,
  994. vertex: vertexSourceCode,
  995. rawVertex: rawVertexSourceCode,
  996. rawFragment: rawFragmentSourceCode,
  997. };
  998. if (createAsRaw) {
  999. webGpuContext.stages = this._compileRawPipelineStageDescriptor(vertexSourceCode, fragmentSourceCode);
  1000. }
  1001. else {
  1002. webGpuContext.stages = this._compilePipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, defines);
  1003. }
  1004. }
  1005. /**
  1006. * Gets the list of active attributes for a given WebGPU program
  1007. * @param pipelineContext defines the pipeline context to use
  1008. * @param attributesNames defines the list of attribute names to get
  1009. * @returns an array of indices indicating the offset of each attribute
  1010. */
  1011. public getAttributes(pipelineContext: IPipelineContext, attributesNames: string[]): number[] {
  1012. const results = new Array(attributesNames.length);
  1013. const gpuPipelineContext = (pipelineContext as WebGPUPipelineContext);
  1014. // TODO WEBGPU. Hard coded for WebGPU until an introspection lib is available.
  1015. // Should be done at processing time, not need to double the work in here.
  1016. for (let i = 0; i < attributesNames.length; i++) {
  1017. const attributeName = attributesNames[i];
  1018. const attributeLocation = gpuPipelineContext.shaderProcessingContext.availableAttributes[attributeName];
  1019. if (attributeLocation === undefined) {
  1020. continue;
  1021. }
  1022. results[i] = attributeLocation;
  1023. }
  1024. return results;
  1025. }
  1026. /**
  1027. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  1028. * @param effect defines the effect to activate
  1029. */
  1030. public enableEffect(effect: Nullable<Effect>): void {
  1031. if (!effect || effect === this._currentEffect && !this._forceEnableEffect) {
  1032. return;
  1033. }
  1034. this._currentEffect = effect;
  1035. this._forceEnableEffect = false;
  1036. if (effect.onBind) {
  1037. effect.onBind(effect);
  1038. }
  1039. if (effect._onBindObservable) {
  1040. effect._onBindObservable.notifyObservers(effect);
  1041. }
  1042. }
  1043. /** @hidden */
  1044. public _releaseEffect(effect: Effect): void {
  1045. // Effect gets garbage collected without explicit destroy in WebGPU.
  1046. }
  1047. /**
  1048. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  1049. */
  1050. public releaseEffects() {
  1051. // Effect gets garbage collected without explicit destroy in WebGPU.
  1052. }
  1053. public _deletePipelineContext(pipelineContext: IPipelineContext): void {
  1054. const webgpuPipelineContext = pipelineContext as WebGPUPipelineContext;
  1055. if (webgpuPipelineContext) {
  1056. pipelineContext.dispose();
  1057. }
  1058. }
  1059. //------------------------------------------------------------------------------
  1060. // Textures
  1061. //------------------------------------------------------------------------------
  1062. /**
  1063. * Gets a boolean indicating that only power of 2 textures are supported
  1064. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  1065. */
  1066. public get needPOTTextures(): boolean {
  1067. return false;
  1068. }
  1069. /** @hidden */
  1070. public _createHardwareTexture(): HardwareTextureWrapper {
  1071. return new WebGPUHardwareTexture();
  1072. }
  1073. /** @hidden */
  1074. public _releaseTexture(texture: InternalTexture): void {
  1075. const index = this._internalTexturesCache.indexOf(texture);
  1076. if (index !== -1) {
  1077. this._internalTexturesCache.splice(index, 1);
  1078. }
  1079. this._textureHelper.releaseTexture(texture);
  1080. }
  1081. /** @hidden */
  1082. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  1083. return Constants.TEXTUREFORMAT_RGBA;
  1084. }
  1085. public updateTextureComparisonFunction(texture: InternalTexture, comparisonFunction: number): void {
  1086. texture._comparisonFunction = comparisonFunction;
  1087. }
  1088. /**
  1089. * Usually called from Texture.ts.
  1090. * Passed information to create a hardware texture
  1091. * @param url defines a value which contains one of the following:
  1092. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  1093. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  1094. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  1095. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  1096. * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)
  1097. * @param scene needed for loading to the correct scene
  1098. * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)
  1099. * @param onLoad optional callback to be called upon successful completion
  1100. * @param onError optional callback to be called upon failure
  1101. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  1102. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  1103. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  1104. * @param forcedExtension defines the extension to use to pick the right loader
  1105. * @param mimeType defines an optional mime type
  1106. * @param loaderOptions options to be passed to the loader
  1107. * @returns a InternalTexture for assignment back into BABYLON.Texture
  1108. */
  1109. public createTexture(url: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<ISceneLike>, samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  1110. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  1111. buffer: Nullable<string | ArrayBuffer | ArrayBufferView | HTMLImageElement | Blob | ImageBitmap> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null,
  1112. forcedExtension: Nullable<string> = null, mimeType?: string, loaderOptions?: any): InternalTexture {
  1113. return this._createTextureBase(
  1114. url, noMipmap, invertY, scene, samplingMode, onLoad, onError,
  1115. (texture: InternalTexture, extension: string, scene: Nullable<ISceneLike>, img: HTMLImageElement | ImageBitmap | { width: number, height: number }, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  1116. processFunction: (width: number, height: number, img: HTMLImageElement | ImageBitmap | { width: number, height: number }, extension: string, texture: InternalTexture, continuationCallback: () => void) => boolean, samplingMode: number) => {
  1117. const imageBitmap = img as (ImageBitmap | { width: number, height: number}); // we will never get an HTMLImageElement in WebGPU
  1118. texture.baseWidth = imageBitmap.width;
  1119. texture.baseHeight = imageBitmap.height;
  1120. texture.width = imageBitmap.width;
  1121. texture.height = imageBitmap.height;
  1122. texture.format = format ?? -1;
  1123. processFunction(texture.width, texture.height, imageBitmap, extension, texture, () => {});
  1124. if (!texture._hardwareTexture?.underlyingResource) { // the texture could have been created before reaching this point so don't recreate it if already existing
  1125. const gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, imageBitmap.width, imageBitmap.height);
  1126. if (WebGPUTextureHelper.IsImageBitmap(imageBitmap)) {
  1127. this._textureHelper.updateTexture(imageBitmap, gpuTextureWrapper.underlyingResource!, imageBitmap.width, imageBitmap.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0, this._uploadEncoder);
  1128. if (!noMipmap && !isCompressed) {
  1129. this._generateMipmaps(texture, this._uploadEncoder);
  1130. }
  1131. }
  1132. } else if (!noMipmap && !isCompressed) {
  1133. this._generateMipmaps(texture, this._uploadEncoder);
  1134. }
  1135. if (scene) {
  1136. scene._removePendingData(texture);
  1137. }
  1138. texture.isReady = true;
  1139. texture.onLoadedObservable.notifyObservers(texture);
  1140. texture.onLoadedObservable.clear();
  1141. },
  1142. () => false,
  1143. buffer, fallback, format, forcedExtension, mimeType, loaderOptions
  1144. );
  1145. }
  1146. /** @hidden */
  1147. public _setCubeMapTextureParams(texture: InternalTexture, loadMipmap: boolean) {
  1148. texture.samplingMode = loadMipmap ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  1149. texture._cachedWrapU = Constants.TEXTURE_CLAMP_ADDRESSMODE;
  1150. texture._cachedWrapV = Constants.TEXTURE_CLAMP_ADDRESSMODE;
  1151. }
  1152. /**
  1153. * Creates a cube texture
  1154. * @param rootUrl defines the url where the files to load is located
  1155. * @param scene defines the current scene
  1156. * @param files defines the list of files to load (1 per face)
  1157. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  1158. * @param onLoad defines an optional callback raised when the texture is loaded
  1159. * @param onError defines an optional callback raised if there is an issue to load the texture
  1160. * @param format defines the format of the data
  1161. * @param forcedExtension defines the extension to use to pick the right loader
  1162. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  1163. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  1164. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  1165. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  1166. * @param loaderOptions options to be passed to the loader
  1167. * @returns the cube texture as an InternalTexture
  1168. */
  1169. public createCubeTexture(rootUrl: string, scene: Nullable<Scene>, files: Nullable<string[]>, noMipmap?: boolean, onLoad: Nullable<(data?: any) => void> = null,
  1170. onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null, createPolynomials: boolean = false, lodScale: number = 0, lodOffset: number = 0, fallback: Nullable<InternalTexture> = null): InternalTexture {
  1171. return this.createCubeTextureBase(
  1172. rootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback,
  1173. null,
  1174. (texture: InternalTexture, imgs: HTMLImageElement[] | ImageBitmap[]) => {
  1175. const imageBitmaps = imgs as ImageBitmap[]; // we will always get an ImageBitmap array in WebGPU
  1176. const width = imageBitmaps[0].width;
  1177. const height = width;
  1178. this._setCubeMapTextureParams(texture, !noMipmap);
  1179. texture.format = format ?? -1;
  1180. const gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);
  1181. this._textureHelper.updateCubeTextures(imageBitmaps, gpuTextureWrapper.underlyingResource!, width, height, gpuTextureWrapper.format, false, false, 0, 0, this._uploadEncoder);
  1182. if (!noMipmap) {
  1183. this._generateMipmaps(texture, this._uploadEncoder);
  1184. }
  1185. texture.isReady = true;
  1186. texture.onLoadedObservable.notifyObservers(texture);
  1187. texture.onLoadedObservable.clear();
  1188. if (onLoad) {
  1189. onLoad();
  1190. }
  1191. }
  1192. );
  1193. }
  1194. /**
  1195. * Creates a raw texture
  1196. * @param data defines the data to store in the texture
  1197. * @param width defines the width of the texture
  1198. * @param height defines the height of the texture
  1199. * @param format defines the format of the data
  1200. * @param generateMipMaps defines if the engine should generate the mip levels
  1201. * @param invertY defines if data must be stored with Y axis inverted
  1202. * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default)
  1203. * @param compression defines the compression used (null by default)
  1204. * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)
  1205. * @returns the raw texture inside an InternalTexture
  1206. */
  1207. public createRawTexture(data: Nullable<ArrayBufferView>, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  1208. compression: Nullable<string> = null, type: number = Constants.TEXTURETYPE_UNSIGNED_INT): InternalTexture
  1209. {
  1210. const texture = new InternalTexture(this, InternalTextureSource.Raw);
  1211. texture.baseWidth = width;
  1212. texture.baseHeight = height;
  1213. texture.width = width;
  1214. texture.height = height;
  1215. texture.format = format;
  1216. texture.generateMipMaps = generateMipMaps;
  1217. texture.samplingMode = samplingMode;
  1218. texture.invertY = invertY;
  1219. texture._compression = compression;
  1220. texture.type = type;
  1221. if (!this._doNotHandleContextLost) {
  1222. texture._bufferView = data;
  1223. }
  1224. this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);
  1225. this.updateRawTexture(texture, data, format, invertY, compression, type);
  1226. this._internalTexturesCache.push(texture);
  1227. return texture;
  1228. }
  1229. /**
  1230. * Creates a new raw cube texture
  1231. * @param data defines the array of data to use to create each face
  1232. * @param size defines the size of the textures
  1233. * @param format defines the format of the data
  1234. * @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_INT)
  1235. * @param generateMipMaps defines if the engine should generate the mip levels
  1236. * @param invertY defines if data must be stored with Y axis inverted
  1237. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  1238. * @param compression defines the compression used (null by default)
  1239. * @returns the cube texture as an InternalTexture
  1240. */
  1241. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number,
  1242. generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  1243. compression: Nullable<string> = null): InternalTexture
  1244. {
  1245. const texture = new InternalTexture(this, InternalTextureSource.CubeRaw);
  1246. texture.isCube = true;
  1247. texture.format = format === Constants.TEXTUREFORMAT_RGB ? Constants.TEXTUREFORMAT_RGBA : format;
  1248. texture.type = type;
  1249. texture.generateMipMaps = generateMipMaps;
  1250. texture.width = size;
  1251. texture.height = size;
  1252. texture.samplingMode = samplingMode;
  1253. if (!this._doNotHandleContextLost) {
  1254. texture._bufferViewArray = data;
  1255. }
  1256. this._textureHelper.createGPUTextureForInternalTexture(texture);
  1257. if (data) {
  1258. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  1259. }
  1260. return texture;
  1261. }
  1262. /**
  1263. * Creates a new raw cube texture from a specified url
  1264. * @param url defines the url where the data is located
  1265. * @param scene defines the current scene
  1266. * @param size defines the size of the textures
  1267. * @param format defines the format of the data
  1268. * @param type defines the type fo the data (like Engine.TEXTURETYPE_UNSIGNED_INT)
  1269. * @param noMipmap defines if the engine should avoid generating the mip levels
  1270. * @param callback defines a callback used to extract texture data from loaded data
  1271. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  1272. * @param onLoad defines a callback called when texture is loaded
  1273. * @param onError defines a callback called if there is an error
  1274. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  1275. * @param invertY defines if data must be stored with Y axis inverted
  1276. * @returns the cube texture as an InternalTexture
  1277. */
  1278. public createRawCubeTextureFromUrl(url: string, scene: Nullable<Scene>, size: number, format: number, type: number, noMipmap: boolean,
  1279. callback: (ArrayBuffer: ArrayBuffer) => Nullable<ArrayBufferView[]>,
  1280. mipmapGenerator: Nullable<((faces: ArrayBufferView[]) => ArrayBufferView[][])>,
  1281. onLoad: Nullable<() => void> = null,
  1282. onError: Nullable<(message?: string, exception?: any) => void> = null,
  1283. samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  1284. invertY: boolean = false): InternalTexture
  1285. {
  1286. const texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode, null);
  1287. scene?._addPendingData(texture);
  1288. texture.url = url;
  1289. this._internalTexturesCache.push(texture);
  1290. const onerror = (request?: IWebRequest, exception?: any) => {
  1291. scene?._removePendingData(texture);
  1292. if (onError && request) {
  1293. onError(request.status + " " + request.statusText, exception);
  1294. }
  1295. };
  1296. const internalCallback = (data: any) => {
  1297. const width = texture.width;
  1298. const faceDataArrays = callback(data);
  1299. if (!faceDataArrays) {
  1300. return;
  1301. }
  1302. const faces = [0, 2, 4, 1, 3, 5];
  1303. if (mipmapGenerator) {
  1304. const needConversion = format === Constants.TEXTUREFORMAT_RGB;
  1305. const mipData = mipmapGenerator(faceDataArrays);
  1306. const gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1307. const faces = [0, 1, 2, 3, 4, 5];
  1308. for (let level = 0; level < mipData.length; level++) {
  1309. const mipSize = width >> level;
  1310. const allFaces = [];
  1311. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  1312. let mipFaceData = mipData[level][faces[faceIndex]];
  1313. if (needConversion) {
  1314. mipFaceData = _convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  1315. }
  1316. allFaces.push(new Uint8Array(mipFaceData.buffer, mipFaceData.byteOffset, mipFaceData.byteLength));
  1317. }
  1318. this._textureHelper.updateCubeTextures(allFaces, gpuTextureWrapper.underlyingResource!, mipSize, mipSize, gpuTextureWrapper.format, invertY, false, 0, 0, this._uploadEncoder);
  1319. }
  1320. }
  1321. else {
  1322. const allFaces = [];
  1323. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  1324. allFaces.push(faceDataArrays[faces[faceIndex]]);
  1325. }
  1326. this.updateRawCubeTexture(texture, allFaces, format, type, invertY);
  1327. }
  1328. texture.isReady = true;
  1329. scene?._removePendingData(texture);
  1330. if (onLoad) {
  1331. onLoad();
  1332. }
  1333. };
  1334. this._loadFile(url, (data) => {
  1335. internalCallback(data);
  1336. }, undefined, scene?.offlineProvider, true, onerror);
  1337. return texture;
  1338. }
  1339. /**
  1340. * Creates a new raw 2D array texture
  1341. * @param data defines the data used to create the texture
  1342. * @param width defines the width of the texture
  1343. * @param height defines the height of the texture
  1344. * @param depth defines the number of layers of the texture
  1345. * @param format defines the format of the texture
  1346. * @param generateMipMaps defines if the engine must generate mip levels
  1347. * @param invertY defines if data must be stored with Y axis inverted
  1348. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  1349. * @param compression defines the compressed used (can be null)
  1350. * @param textureType defines the compressed used (can be null)
  1351. * @returns a new raw 2D array texture (stored in an InternalTexture)
  1352. */
  1353. public createRawTexture2DArray(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  1354. compression: Nullable<string> = null, textureType: number = Constants.TEXTURETYPE_UNSIGNED_INT): InternalTexture
  1355. {
  1356. var source = InternalTextureSource.Raw2DArray;
  1357. var texture = new InternalTexture(this, source);
  1358. if (this.dbgShowWarningsNotImplemented) {
  1359. console.warn("createRawTexture2DArray not implemented yet in WebGPU");
  1360. }
  1361. return texture;
  1362. }
  1363. /**
  1364. * Creates a new raw 3D texture
  1365. * @param data defines the data used to create the texture
  1366. * @param width defines the width of the texture
  1367. * @param height defines the height of the texture
  1368. * @param depth defines the depth of the texture
  1369. * @param format defines the format of the texture
  1370. * @param generateMipMaps defines if the engine must generate mip levels
  1371. * @param invertY defines if data must be stored with Y axis inverted
  1372. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  1373. * @param compression defines the compressed used (can be null)
  1374. * @param textureType defines the compressed used (can be null)
  1375. * @returns a new raw 3D texture (stored in an InternalTexture)
  1376. */
  1377. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  1378. compression: Nullable<string> = null, textureType: number = Constants.TEXTURETYPE_UNSIGNED_INT): InternalTexture
  1379. {
  1380. const source = InternalTextureSource.Raw3D;
  1381. const texture = new InternalTexture(this, source);
  1382. texture.baseWidth = width;
  1383. texture.baseHeight = height;
  1384. texture.baseDepth = depth;
  1385. texture.width = width;
  1386. texture.height = height;
  1387. texture.depth = depth;
  1388. texture.format = format;
  1389. texture.type = textureType;
  1390. texture.generateMipMaps = generateMipMaps;
  1391. texture.samplingMode = samplingMode;
  1392. texture.is3D = true;
  1393. if (!this._doNotHandleContextLost) {
  1394. texture._bufferView = data;
  1395. }
  1396. this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);
  1397. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  1398. this._internalTexturesCache.push(texture);
  1399. return texture;
  1400. }
  1401. public generateMipMapsForCubemap(texture: InternalTexture, unbind = true) {
  1402. if (texture.generateMipMaps) {
  1403. let gpuTexture = texture._hardwareTexture?.underlyingResource;
  1404. if (!gpuTexture) {
  1405. this._textureHelper.createGPUTextureForInternalTexture(texture);
  1406. }
  1407. this._generateMipmaps(texture, texture.source === InternalTextureSource.RenderTarget || texture.source === InternalTextureSource.MultiRenderTarget ? this._renderTargetEncoder : undefined);
  1408. }
  1409. }
  1410. /**
  1411. * Update the sampling mode of a given texture
  1412. * @param samplingMode defines the required sampling mode
  1413. * @param texture defines the texture to update
  1414. * @param generateMipMaps defines whether to generate mipmaps for the texture
  1415. */
  1416. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture, generateMipMaps: boolean = false): void {
  1417. if (generateMipMaps) {
  1418. texture.generateMipMaps = true;
  1419. this._generateMipmaps(texture);
  1420. }
  1421. texture.samplingMode = samplingMode;
  1422. }
  1423. /**
  1424. * Update the sampling mode of a given texture
  1425. * @param texture defines the texture to update
  1426. * @param wrapU defines the texture wrap mode of the u coordinates
  1427. * @param wrapV defines the texture wrap mode of the v coordinates
  1428. * @param wrapR defines the texture wrap mode of the r coordinates
  1429. */
  1430. public updateTextureWrappingMode(texture: InternalTexture, wrapU: Nullable<number>, wrapV: Nullable<number> = null, wrapR: Nullable<number> = null): void {
  1431. if (wrapU !== null) {
  1432. texture._cachedWrapU = wrapU;
  1433. this._lastCachedWrapU = wrapU;
  1434. }
  1435. if (wrapV !== null) {
  1436. texture._cachedWrapV = wrapV;
  1437. this._lastCachedWrapV = wrapV;
  1438. }
  1439. if ((texture.is2DArray || texture.is3D) && (wrapR !== null)) {
  1440. texture._cachedWrapR = wrapR;
  1441. this._lastCachedWrapR = wrapR;
  1442. }
  1443. }
  1444. /**
  1445. * Update the dimensions of a texture
  1446. * @param texture texture to update
  1447. * @param width new width of the texture
  1448. * @param height new height of the texture
  1449. * @param depth new depth of the texture
  1450. */
  1451. public updateTextureDimensions(texture: InternalTexture, width: number, height: number, depth: number = 1): void {
  1452. if (!texture._hardwareTexture) {
  1453. // the gpu texture is not created yet, so when it is it will be created with the right dimensions
  1454. return;
  1455. }
  1456. if (texture.width === width && texture.height === height && texture.depth === depth) {
  1457. return;
  1458. }
  1459. texture._hardwareTexture.release(); // don't defer the releasing! Else we will release at the end of this frame the gpu texture we are about to create in the next line...
  1460. this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, depth);
  1461. }
  1462. private _setInternalTexture(name: string, internalTexture: Nullable<InternalTexture>, baseName?: string, textureIndex = 0): void {
  1463. baseName = baseName ?? name;
  1464. if (this._currentEffect) {
  1465. const webgpuPipelineContext = this._currentEffect._pipelineContext as WebGPUPipelineContext;
  1466. if (webgpuPipelineContext.textures[name]) {
  1467. if (webgpuPipelineContext.textures[name]!.texture !== internalTexture) {
  1468. // TODO WEBGPU when the bindGroups has a caching mechanism set up, clear this cache
  1469. //webgpuPipelineContext.bindGroups = null as any; // the bind groups need to be rebuilt (at least the bind group owning this texture, but it's easier to just have them all rebuilt)
  1470. }
  1471. webgpuPipelineContext.textures[name]!.texture = internalTexture!;
  1472. }
  1473. else {
  1474. const availableSampler = webgpuPipelineContext.shaderProcessingContext.availableSamplers[baseName];
  1475. if (availableSampler) {
  1476. webgpuPipelineContext.samplers[baseName] = {
  1477. samplerBinding: availableSampler.sampler.bindingIndex,
  1478. firstTextureName: name,
  1479. };
  1480. webgpuPipelineContext.textures[name] = {
  1481. textureBinding: availableSampler.textures[textureIndex].bindingIndex,
  1482. texture: internalTexture!,
  1483. };
  1484. }
  1485. }
  1486. }
  1487. }
  1488. /**
  1489. * Sets a texture to the according uniform.
  1490. * @param channel The texture channel
  1491. * @param unused unused parameter
  1492. * @param texture The texture to apply
  1493. * @param name The name of the uniform in the effect
  1494. */
  1495. public setTexture(channel: number, unused: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>, name: string): void {
  1496. this._setTexture(channel, texture, false, false, name, name);
  1497. }
  1498. /**
  1499. * Sets an array of texture to the WebGPU context
  1500. * @param channel defines the channel where the texture array must be set
  1501. * @param unused unused parameter
  1502. * @param textures defines the array of textures to bind
  1503. * @param name name of the channel
  1504. */
  1505. public setTextureArray(channel: number, unused: Nullable<WebGLUniformLocation>, textures: BaseTexture[], name: string): void {
  1506. for (var index = 0; index < textures.length; index++) {
  1507. this._setTexture(-1, textures[index], true, false, name + index.toString(), name, index);
  1508. }
  1509. }
  1510. protected _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false, name = "", baseName?: string, textureIndex = 0): boolean {
  1511. // name == baseName for a texture that is not part of a texture array
  1512. // Else, name is something like 'myTexture0' / 'myTexture1' / ... and baseName is 'myTexture'
  1513. // baseName is used to look up the sampler in the WebGPUPipelineContext.samplers map
  1514. // name is used to look up the texture in the WebGPUPipelineContext.textures map
  1515. baseName = baseName ?? name;
  1516. if (this._currentEffect) {
  1517. const webgpuPipelineContext = this._currentEffect._pipelineContext as WebGPUPipelineContext;
  1518. if (!texture) {
  1519. if (webgpuPipelineContext.textures[name] && webgpuPipelineContext.textures[name]!.texture) {
  1520. // TODO WEBGPU when the bindGroups has a caching mechanism set up, clear this cache
  1521. //webgpuPipelineContext.bindGroups = null as any; // the bind groups need to be rebuilt (at least the bind group owning this texture, but it's easier to just have them all rebuilt)
  1522. }
  1523. webgpuPipelineContext.textures[name] = null;
  1524. return false;
  1525. }
  1526. // Video
  1527. if ((<VideoTexture>texture).video) {
  1528. (<VideoTexture>texture).update();
  1529. } else if (texture.delayLoadState === Constants.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1530. texture.delayLoad();
  1531. return false;
  1532. }
  1533. let internalTexture: Nullable<InternalTexture> = null;
  1534. if (depthStencilTexture) {
  1535. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  1536. }
  1537. else if (texture.isReady()) {
  1538. internalTexture = <InternalTexture>texture.getInternalTexture();
  1539. }
  1540. else if (texture.isCube) {
  1541. internalTexture = this.emptyCubeTexture;
  1542. }
  1543. else if (texture.is3D) {
  1544. internalTexture = this.emptyTexture3D;
  1545. }
  1546. else if (texture.is2DArray) {
  1547. internalTexture = this.emptyTexture2DArray;
  1548. }
  1549. else {
  1550. internalTexture = this.emptyTexture;
  1551. }
  1552. if (internalTexture && !internalTexture.isMultiview) {
  1553. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1554. if (internalTexture.isCube && internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1555. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1556. const textureWrapMode = (texture.coordinatesMode !== Constants.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Constants.TEXTURE_SKYBOX_MODE) ? Constants.TEXTURE_WRAP_ADDRESSMODE : Constants.TEXTURE_CLAMP_ADDRESSMODE;
  1557. texture.wrapU = textureWrapMode;
  1558. texture.wrapV = textureWrapMode;
  1559. }
  1560. internalTexture._cachedWrapU = texture.wrapU;
  1561. if (this._lastCachedWrapU !== texture.wrapU) {
  1562. this._lastCachedWrapU = texture.wrapU;
  1563. }
  1564. internalTexture._cachedWrapV = texture.wrapV;
  1565. if (this._lastCachedWrapV !== texture.wrapV) {
  1566. this._lastCachedWrapV = texture.wrapV;
  1567. }
  1568. internalTexture._cachedWrapR = texture.wrapR;
  1569. if (internalTexture.is3D && this._lastCachedWrapR !== texture.wrapR) {
  1570. this._lastCachedWrapR = texture.wrapR;
  1571. }
  1572. this._setAnisotropicLevel(0, internalTexture, texture.anisotropicFilteringLevel);
  1573. }
  1574. this._setInternalTexture(name, internalTexture, baseName, textureIndex);
  1575. } else {
  1576. if (this.dbgVerboseLogsForFirstFrames) {
  1577. if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
  1578. console.log("frame #" + (this as any)._count + " - _setTexture called with a null _currentEffect! texture=", texture);
  1579. }
  1580. }
  1581. }
  1582. return true;
  1583. }
  1584. /** @hidden */
  1585. public _setAnisotropicLevel(target: number, internalTexture: InternalTexture, anisotropicFilteringLevel: number) {
  1586. if (internalTexture._cachedAnisotropicFilteringLevel !== anisotropicFilteringLevel) {
  1587. internalTexture._cachedAnisotropicFilteringLevel = Math.min(anisotropicFilteringLevel, this._caps.maxAnisotropy);
  1588. }
  1589. }
  1590. /** @hidden */
  1591. public _bindTexture(channel: number, texture: InternalTexture, name: string): void {
  1592. if (channel === undefined) {
  1593. return;
  1594. }
  1595. if (texture) {
  1596. if (this._lastCachedWrapU !== null) {
  1597. texture._cachedWrapU = this._lastCachedWrapU;
  1598. }
  1599. if (this._lastCachedWrapV !== null) {
  1600. texture._cachedWrapV = this._lastCachedWrapV;
  1601. }
  1602. if (this._lastCachedWrapR !== null) {
  1603. texture._cachedWrapR = this._lastCachedWrapR;
  1604. }
  1605. }
  1606. this._setInternalTexture(name, texture);
  1607. }
  1608. private _generateMipmaps(texture: InternalTexture, commandEncoder?: GPUCommandEncoder) {
  1609. const gpuTexture = texture._hardwareTexture?.underlyingResource;
  1610. if (!gpuTexture) {
  1611. return;
  1612. }
  1613. // try as much as possible to use the command encoder corresponding to the current pass.
  1614. // If not possible (because the pass is started - generateMipmaps itself creates a pass and it's not allowed to have a pass inside a pass), use _uploadEncoder
  1615. commandEncoder = commandEncoder ?? (this._currentRenderTarget && !this._currentRenderPass ? this._renderTargetEncoder : !this._currentRenderPass ? this._renderEncoder : this._uploadEncoder);
  1616. const format = (texture._hardwareTexture as WebGPUHardwareTexture).format;
  1617. const mipmapCount = WebGPUTextureHelper.ComputeNumMipmapLevels(texture.width, texture.height);
  1618. if (this.dbgVerboseLogsForFirstFrames) {
  1619. if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
  1620. console.log("frame #" + (this as any)._count + " - generate mipmaps called - width=", texture.width, "height=", texture.height, "isCube=", texture.isCube);
  1621. }
  1622. }
  1623. if (texture.isCube) {
  1624. this._textureHelper.generateCubeMipmaps(gpuTexture, format, mipmapCount, commandEncoder);
  1625. } else {
  1626. this._textureHelper.generateMipmaps(gpuTexture, format, mipmapCount, 0, commandEncoder);
  1627. }
  1628. }
  1629. /**
  1630. * Update the content of a texture
  1631. * @param texture defines the texture to update
  1632. * @param canvas defines the source containing the data
  1633. * @param invertY defines if data must be stored with Y axis inverted
  1634. * @param premulAlpha defines if alpha is stored as premultiplied
  1635. * @param format defines the format of the data
  1636. * @param forceBindTexture if the texture should be forced to be bound eg. after a graphics context loss (Default: false)
  1637. */
  1638. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement | OffscreenCanvas, invertY: boolean, premulAlpha: boolean = false, format?: number, forceBindTexture?: boolean): void {
  1639. if (!texture) {
  1640. return;
  1641. }
  1642. const width = canvas.width, height = canvas.height;
  1643. let gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1644. if (!texture._hardwareTexture?.underlyingResource) {
  1645. gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);
  1646. }
  1647. createImageBitmap(canvas).then((bitmap) => {
  1648. this._textureHelper.updateTexture(bitmap, gpuTextureWrapper.underlyingResource!, width, height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, premulAlpha, 0, 0, this._uploadEncoder);
  1649. if (texture.generateMipMaps) {
  1650. this._generateMipmaps(texture, this._uploadEncoder);
  1651. }
  1652. texture.isReady = true;
  1653. });
  1654. }
  1655. /**
  1656. * Update a portion of an internal texture
  1657. * @param texture defines the texture to update
  1658. * @param imageData defines the data to store into the texture
  1659. * @param xOffset defines the x coordinates of the update rectangle
  1660. * @param yOffset defines the y coordinates of the update rectangle
  1661. * @param width defines the width of the update rectangle
  1662. * @param height defines the height of the update rectangle
  1663. * @param faceIndex defines the face index if texture is a cube (0 by default)
  1664. * @param lod defines the lod level to update (0 by default)
  1665. */
  1666. public updateTextureData(texture: InternalTexture, imageData: ArrayBufferView, xOffset: number, yOffset: number, width: number, height: number, faceIndex: number = 0, lod: number = 0): void {
  1667. let gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1668. if (!texture._hardwareTexture?.underlyingResource) {
  1669. gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture);
  1670. }
  1671. const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);
  1672. this._textureHelper.updateTexture(data, gpuTextureWrapper.underlyingResource!, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, xOffset, yOffset, this._uploadEncoder);
  1673. }
  1674. /**
  1675. * Update a video texture
  1676. * @param texture defines the texture to update
  1677. * @param video defines the video element to use
  1678. * @param invertY defines if data must be stored with Y axis inverted
  1679. */
  1680. public updateVideoTexture(texture: Nullable<InternalTexture>, video: HTMLVideoElement, invertY: boolean): void {
  1681. if (!texture || texture._isDisabled) {
  1682. return;
  1683. }
  1684. if (this._videoTextureSupported === undefined) {
  1685. this._videoTextureSupported = true;
  1686. }
  1687. let gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1688. if (!texture._hardwareTexture?.underlyingResource) {
  1689. gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture);
  1690. }
  1691. createImageBitmap(video).then((bitmap) => {
  1692. this._textureHelper.updateTexture(bitmap, gpuTextureWrapper.underlyingResource!, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, !invertY, false, 0, 0, this._uploadEncoder);
  1693. if (texture.generateMipMaps) {
  1694. this._generateMipmaps(texture, this._uploadEncoder);
  1695. }
  1696. texture.isReady = true;
  1697. }).catch((msg) => {
  1698. // Sometimes createImageBitmap(video) fails with "Failed to execute 'createImageBitmap' on 'Window': The provided element's player has no current data."
  1699. // Just keep going on
  1700. texture.isReady = true;
  1701. });
  1702. }
  1703. /** @hidden */
  1704. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  1705. let gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1706. if (!texture._hardwareTexture?.underlyingResource) {
  1707. texture.format = internalFormat;
  1708. gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);
  1709. }
  1710. const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);
  1711. this._textureHelper.updateTexture(data, gpuTextureWrapper.underlyingResource!, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, false, false, 0, 0, this._uploadEncoder);
  1712. }
  1713. /** @hidden */
  1714. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0, babylonInternalFormat?: number, useTextureWidthAndHeight = false): void {
  1715. // TODO WEBPU babylonInternalFormat not handled.
  1716. // Note that it is used only by BasisTools.LoadTextureFromTranscodeResult when transcoding could not be done, and in that case the texture format used (TEXTURETYPE_UNSIGNED_SHORT_5_6_5) is not compatible with WebGPU...
  1717. const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E);
  1718. const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E);
  1719. const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  1720. const height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  1721. let gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1722. if (!texture._hardwareTexture?.underlyingResource) {
  1723. gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);
  1724. }
  1725. const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);
  1726. this._textureHelper.updateTexture(data, gpuTextureWrapper.underlyingResource!, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0, this._uploadEncoder);
  1727. }
  1728. /** @hidden */
  1729. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  1730. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  1731. }
  1732. /** @hidden */
  1733. public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement | ImageBitmap, faceIndex: number = 0, lod: number = 0) {
  1734. let gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1735. if (!texture._hardwareTexture?.underlyingResource) {
  1736. gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture);
  1737. }
  1738. const bitmap = image as ImageBitmap; // in WebGPU we will always get an ImageBitmap, not an HTMLImageElement
  1739. const width = Math.ceil(texture.width / (1 << lod));
  1740. const height = Math.ceil(texture.height / (1 << lod));
  1741. this._textureHelper.updateTexture(bitmap, gpuTextureWrapper.underlyingResource!, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0, this._uploadEncoder);
  1742. }
  1743. /**
  1744. * Update a raw texture
  1745. * @param texture defines the texture to update
  1746. * @param bufferView defines the data to store in the texture
  1747. * @param format defines the format of the data
  1748. * @param invertY defines if data must be stored with Y axis inverted
  1749. * @param compression defines the compression used (null by default)
  1750. * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)
  1751. */
  1752. public updateRawTexture(texture: Nullable<InternalTexture>, bufferView: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, type: number = Constants.TEXTURETYPE_UNSIGNED_INT): void {
  1753. if (!texture) {
  1754. return;
  1755. }
  1756. if (!this._doNotHandleContextLost) {
  1757. texture._bufferView = bufferView;
  1758. texture.invertY = invertY;
  1759. texture._compression = compression;
  1760. }
  1761. if (bufferView) {
  1762. const gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1763. const needConversion = format === Constants.TEXTUREFORMAT_RGB;
  1764. if (needConversion) {
  1765. bufferView = _convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, type);
  1766. }
  1767. const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);
  1768. this._textureHelper.updateTexture(data, gpuTextureWrapper.underlyingResource!, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0, this._uploadEncoder);
  1769. if (texture.generateMipMaps) {
  1770. this._generateMipmaps(texture, this._uploadEncoder);
  1771. }
  1772. }
  1773. texture.isReady = true;
  1774. }
  1775. /**
  1776. * Update a raw cube texture
  1777. * @param texture defines the texture to udpdate
  1778. * @param bufferView defines the data to store
  1779. * @param format defines the data format
  1780. * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)
  1781. * @param invertY defines if data must be stored with Y axis inverted
  1782. * @param compression defines the compression used (null by default)
  1783. * @param level defines which level of the texture to update
  1784. */
  1785. public updateRawCubeTexture(texture: InternalTexture, bufferView: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: Nullable<string> = null, level: number = 0): void {
  1786. texture._bufferViewArray = bufferView;
  1787. texture.invertY = invertY;
  1788. texture._compression = compression;
  1789. const gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1790. const needConversion = format === Constants.TEXTUREFORMAT_RGB;
  1791. const data = [];
  1792. for (let i = 0; i < bufferView.length; ++i) {
  1793. let faceData = bufferView[i];
  1794. if (needConversion) {
  1795. faceData = _convertRGBtoRGBATextureData(bufferView[i], texture.width, texture.height, type);
  1796. }
  1797. data.push(new Uint8Array(faceData.buffer, faceData.byteOffset, faceData.byteLength));
  1798. }
  1799. this._textureHelper.updateCubeTextures(data, gpuTextureWrapper.underlyingResource!, texture.width, texture.height, gpuTextureWrapper.format, invertY, false, 0, 0, this._uploadEncoder);
  1800. if (texture.generateMipMaps) {
  1801. this._generateMipmaps(texture, this._uploadEncoder);
  1802. }
  1803. texture.isReady = true;
  1804. }
  1805. /**
  1806. * Update a raw 2D array texture
  1807. * @param texture defines the texture to update
  1808. * @param bufferView defines the data to store
  1809. * @param format defines the data format
  1810. * @param invertY defines if data must be stored with Y axis inverted
  1811. * @param compression defines the used compression (can be null)
  1812. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  1813. */
  1814. public updateRawTexture2DArray(texture: InternalTexture, bufferView: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, textureType: number = Constants.TEXTURETYPE_UNSIGNED_INT): void {
  1815. if (this.dbgShowWarningsNotImplemented) {
  1816. console.warn("updateRawTexture2DArray not implemented yet in WebGPU");
  1817. }
  1818. }
  1819. /**
  1820. * Update a raw 3D texture
  1821. * @param texture defines the texture to update
  1822. * @param bufferView defines the data to store
  1823. * @param format defines the data format
  1824. * @param invertY defines if data must be stored with Y axis inverted
  1825. * @param compression defines the used compression (can be null)
  1826. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  1827. */
  1828. public updateRawTexture3D(texture: InternalTexture, bufferView: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, textureType: number = Constants.TEXTURETYPE_UNSIGNED_INT): void {
  1829. if (!this._doNotHandleContextLost) {
  1830. texture._bufferView = bufferView;
  1831. texture.format = format;
  1832. texture.invertY = invertY;
  1833. texture._compression = compression;
  1834. }
  1835. if (bufferView) {
  1836. const gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1837. const needConversion = format === Constants.TEXTUREFORMAT_RGB;
  1838. if (needConversion) {
  1839. bufferView = _convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, textureType);
  1840. }
  1841. const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);
  1842. this._textureHelper.updateTexture(data, gpuTextureWrapper.underlyingResource!, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0, this._uploadEncoder);
  1843. if (texture.generateMipMaps) {
  1844. this._generateMipmaps(texture, this._uploadEncoder);
  1845. }
  1846. }
  1847. texture.isReady = true;
  1848. }
  1849. /**
  1850. * Reads pixels from the current frame buffer. Please note that this function can be slow
  1851. * @param x defines the x coordinate of the rectangle where pixels must be read
  1852. * @param y defines the y coordinate of the rectangle where pixels must be read
  1853. * @param width defines the width of the rectangle where pixels must be read
  1854. * @param height defines the height of the rectangle where pixels must be read
  1855. * @param hasAlpha defines whether the output should have alpha or not (defaults to true)
  1856. * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels
  1857. * @returns a ArrayBufferView promise (Uint8Array) containing RGBA colors
  1858. */
  1859. public readPixels(x: number, y: number, width: number, height: number, hasAlpha = true, flushRenderer = true): Promise<ArrayBufferView> {
  1860. const renderPassWrapper = this._rttRenderPassWrapper.renderPass ? this._rttRenderPassWrapper : this._mainRenderPassWrapper;
  1861. const gpuTexture = renderPassWrapper.colorAttachmentGPUTextures![0].underlyingResource;
  1862. const gpuTextureFormat = renderPassWrapper.colorAttachmentGPUTextures![0].format;
  1863. if (!gpuTexture) {
  1864. // we are calling readPixels before startMainRenderPass has been called and no RTT is bound, so swapChainTexture is not setup yet!
  1865. return Promise.resolve(new Uint8Array(0));
  1866. }
  1867. if (flushRenderer) {
  1868. this.flushFramebuffer();
  1869. }
  1870. return this._textureHelper.readPixels(gpuTexture, x, y, width, height, gpuTextureFormat);
  1871. }
  1872. /** @hidden */
  1873. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1, level = 0, buffer: Nullable<ArrayBufferView> = null, flushRenderer = true): Promise<ArrayBufferView> {
  1874. let gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1875. if (flushRenderer) {
  1876. this.flushFramebuffer();
  1877. }
  1878. return this._textureHelper.readPixels(gpuTextureWrapper.underlyingResource!, 0, 0, width, height, gpuTextureWrapper.format, faceIndex, level, buffer);
  1879. }
  1880. //------------------------------------------------------------------------------
  1881. // Render Target Textures
  1882. //------------------------------------------------------------------------------
  1883. /**
  1884. * Creates a new render target texture
  1885. * @param size defines the size of the texture
  1886. * @param options defines the options used to create the texture
  1887. * @returns a new render target texture stored in an InternalTexture
  1888. */
  1889. public createRenderTargetTexture(size: any, options: boolean | RenderTargetCreationOptions): InternalTexture {
  1890. let fullOptions = new RenderTargetCreationOptions();
  1891. if (options !== undefined && typeof options === "object") {
  1892. fullOptions.generateMipMaps = options.generateMipMaps;
  1893. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1894. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  1895. fullOptions.type = options.type === undefined ? Constants.TEXTURETYPE_UNSIGNED_INT : options.type;
  1896. fullOptions.samplingMode = options.samplingMode === undefined ? Constants.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  1897. fullOptions.format = options.format === undefined ? Constants.TEXTUREFORMAT_RGBA : options.format;
  1898. fullOptions.samples = options.samples ?? 1;
  1899. } else {
  1900. fullOptions.generateMipMaps = <boolean>options;
  1901. fullOptions.generateDepthBuffer = true;
  1902. fullOptions.generateStencilBuffer = false;
  1903. fullOptions.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  1904. fullOptions.samplingMode = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE;
  1905. fullOptions.format = Constants.TEXTUREFORMAT_RGBA;
  1906. fullOptions.samples = 1;
  1907. }
  1908. const texture = new InternalTexture(this, InternalTextureSource.RenderTarget);
  1909. const width = size.width || size;
  1910. const height = size.height || size;
  1911. const layers = size.layers || 0;
  1912. texture._depthStencilBuffer = {};
  1913. texture._framebuffer = {};
  1914. texture.baseWidth = width;
  1915. texture.baseHeight = height;
  1916. texture.width = width;
  1917. texture.height = height;
  1918. texture.depth = layers;
  1919. texture.isReady = true;
  1920. texture.samples = fullOptions.samples;
  1921. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  1922. texture.samplingMode = fullOptions.samplingMode;
  1923. texture.type = fullOptions.type;
  1924. texture.format = fullOptions.format;
  1925. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  1926. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  1927. texture.is2DArray = layers > 0;
  1928. this._internalTexturesCache.push(texture);
  1929. if (texture._generateDepthBuffer || texture._generateStencilBuffer) {
  1930. texture._depthStencilTexture = this.createDepthStencilTexture({ width, height, layers }, {
  1931. bilinearFiltering:
  1932. fullOptions.samplingMode === undefined ||
  1933. fullOptions.samplingMode === Constants.TEXTURE_BILINEAR_SAMPLINGMODE || fullOptions.samplingMode === Constants.TEXTURE_LINEAR_LINEAR ||
  1934. fullOptions.samplingMode === Constants.TEXTURE_TRILINEAR_SAMPLINGMODE || fullOptions.samplingMode === Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR ||
  1935. fullOptions.samplingMode === Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST || fullOptions.samplingMode === Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR ||
  1936. fullOptions.samplingMode === Constants.TEXTURE_NEAREST_LINEAR || fullOptions.samplingMode === Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST,
  1937. comparisonFunction: 0,
  1938. generateStencil: texture._generateStencilBuffer,
  1939. isCube: texture.isCube,
  1940. samples: texture.samples,
  1941. });
  1942. }
  1943. if (options !== undefined && typeof options === "object" && options.createMipMaps && !fullOptions.generateMipMaps) {
  1944. texture.generateMipMaps = true;
  1945. }
  1946. this._textureHelper.createGPUTextureForInternalTexture(texture);
  1947. if (options !== undefined && typeof options === "object" && options.createMipMaps && !fullOptions.generateMipMaps) {
  1948. texture.generateMipMaps = false;
  1949. }
  1950. return texture;
  1951. }
  1952. /**
  1953. * Create a multi render target texture
  1954. * @param size defines the size of the texture
  1955. * @param options defines the creation options
  1956. * @returns the cube texture as an InternalTexture
  1957. */
  1958. public createMultipleRenderTarget(size: any, options: IMultiRenderTargetOptions): InternalTexture[] {
  1959. let generateMipMaps = false;
  1960. let generateDepthBuffer = true;
  1961. let generateStencilBuffer = false;
  1962. let generateDepthTexture = false;
  1963. let textureCount = 1;
  1964. let defaultType = Constants.TEXTURETYPE_UNSIGNED_INT;
  1965. let defaultSamplingMode = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE;
  1966. let types = new Array<number>();
  1967. let samplingModes = new Array<number>();
  1968. if (options !== undefined) {
  1969. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  1970. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1971. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  1972. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  1973. textureCount = options.textureCount || 1;
  1974. if (options.types) {
  1975. types = options.types;
  1976. }
  1977. if (options.samplingModes) {
  1978. samplingModes = options.samplingModes;
  1979. }
  1980. }
  1981. const width = size.width || size;
  1982. const height = size.height || size;
  1983. let depthStencilTexture = null;
  1984. if (generateDepthBuffer || generateStencilBuffer || generateDepthTexture) {
  1985. depthStencilTexture = this.createDepthStencilTexture({ width, height }, {
  1986. bilinearFiltering: false,
  1987. comparisonFunction: 0,
  1988. generateStencil: generateStencilBuffer,
  1989. isCube: false,
  1990. samples: 1,
  1991. });
  1992. }
  1993. const textures = [];
  1994. const attachments = [];
  1995. for (let i = 0; i < textureCount; i++) {
  1996. let samplingMode = samplingModes[i] || defaultSamplingMode;
  1997. let type = types[i] || defaultType;
  1998. if (type === Constants.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  1999. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2000. samplingMode = Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  2001. }
  2002. else if (type === Constants.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2003. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2004. samplingMode = Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  2005. }
  2006. if (type === Constants.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  2007. type = Constants.TEXTURETYPE_UNSIGNED_INT;
  2008. Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  2009. }
  2010. const texture = new InternalTexture(this, InternalTextureSource.MultiRenderTarget);
  2011. textures.push(texture);
  2012. attachments.push(i + 1);
  2013. texture._depthStencilTexture = i === 0 ? depthStencilTexture : null;
  2014. texture._framebuffer = {};
  2015. texture._depthStencilBuffer = {};
  2016. texture.baseWidth = width;
  2017. texture.baseHeight = height;
  2018. texture.width = width;
  2019. texture.height = height;
  2020. texture.isReady = true;
  2021. texture.samples = 1;
  2022. texture.generateMipMaps = generateMipMaps;
  2023. texture.samplingMode = samplingMode;
  2024. texture.type = type;
  2025. texture._generateDepthBuffer = generateDepthBuffer;
  2026. texture._generateStencilBuffer = generateStencilBuffer ? true : false;
  2027. texture._attachments = attachments;
  2028. texture._textureArray = textures;
  2029. this._internalTexturesCache.push(texture);
  2030. this._textureHelper.createGPUTextureForInternalTexture(texture);
  2031. }
  2032. if (depthStencilTexture) {
  2033. textures.push(depthStencilTexture);
  2034. this._internalTexturesCache.push(depthStencilTexture);
  2035. }
  2036. return textures;
  2037. }
  2038. /**
  2039. * Creates a new render target cube texture
  2040. * @param size defines the size of the texture
  2041. * @param options defines the options used to create the texture
  2042. * @returns a new render target cube texture stored in an InternalTexture
  2043. */
  2044. public createRenderTargetCubeTexture(size: number, options?: Partial<RenderTargetCreationOptions>): InternalTexture {
  2045. let fullOptions = {
  2046. generateMipMaps: true,
  2047. generateDepthBuffer: true,
  2048. generateStencilBuffer: false,
  2049. type: Constants.TEXTURETYPE_UNSIGNED_INT,
  2050. samplingMode: Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  2051. format: Constants.TEXTUREFORMAT_RGBA,
  2052. samples: 1,
  2053. ...options
  2054. };
  2055. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  2056. const texture = new InternalTexture(this, InternalTextureSource.RenderTarget);
  2057. texture.width = size;
  2058. texture.height = size;
  2059. texture.depth = 0;
  2060. texture.isReady = true;
  2061. texture.isCube = true;
  2062. texture.samples = fullOptions.samples;
  2063. texture.generateMipMaps = fullOptions.generateMipMaps;
  2064. texture.samplingMode = fullOptions.samplingMode;
  2065. texture.type = fullOptions.type;
  2066. texture.format = fullOptions.format;
  2067. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  2068. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  2069. this._internalTexturesCache.push(texture);
  2070. if (texture._generateDepthBuffer || texture._generateStencilBuffer) {
  2071. texture._depthStencilTexture = this.createDepthStencilTexture({ width: texture.width, height: texture.height, layers: texture.depth }, {
  2072. bilinearFiltering:
  2073. fullOptions.samplingMode === undefined ||
  2074. fullOptions.samplingMode === Constants.TEXTURE_BILINEAR_SAMPLINGMODE || fullOptions.samplingMode === Constants.TEXTURE_LINEAR_LINEAR ||
  2075. fullOptions.samplingMode === Constants.TEXTURE_TRILINEAR_SAMPLINGMODE || fullOptions.samplingMode === Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR ||
  2076. fullOptions.samplingMode === Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST || fullOptions.samplingMode === Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR ||
  2077. fullOptions.samplingMode === Constants.TEXTURE_NEAREST_LINEAR || fullOptions.samplingMode === Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST,
  2078. comparisonFunction: 0,
  2079. generateStencil: texture._generateStencilBuffer,
  2080. isCube: texture.isCube,
  2081. samples: texture.samples,
  2082. });
  2083. }
  2084. if (options && options.createMipMaps && !fullOptions.generateMipMaps) {
  2085. texture.generateMipMaps = true;
  2086. }
  2087. this._textureHelper.createGPUTextureForInternalTexture(texture);
  2088. if (options && options.createMipMaps && !fullOptions.generateMipMaps) {
  2089. texture.generateMipMaps = false;
  2090. }
  2091. return texture;
  2092. }
  2093. /** @hidden */
  2094. public _setupDepthStencilTexture(internalTexture: InternalTexture, size: number | { width: number, height: number, layers?: number }, generateStencil: boolean, bilinearFiltering: boolean, comparisonFunction: number, samples = 1): void {
  2095. const width = (<{ width: number, height: number, layers?: number }>size).width || <number>size;
  2096. const height = (<{ width: number, height: number, layers?: number }>size).height || <number>size;
  2097. const layers = (<{ width: number, height: number, layers?: number }>size).layers || 0;
  2098. internalTexture.baseWidth = width;
  2099. internalTexture.baseHeight = height;
  2100. internalTexture.width = width;
  2101. internalTexture.height = height;
  2102. internalTexture.is2DArray = layers > 0;
  2103. internalTexture.depth = layers;
  2104. internalTexture.isReady = true;
  2105. internalTexture.samples = samples;
  2106. internalTexture.generateMipMaps = false;
  2107. internalTexture._generateDepthBuffer = true;
  2108. internalTexture._generateStencilBuffer = generateStencil;
  2109. internalTexture.samplingMode = bilinearFiltering ? Constants.TEXTURE_BILINEAR_SAMPLINGMODE : Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  2110. internalTexture.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  2111. internalTexture._comparisonFunction = comparisonFunction;
  2112. }
  2113. /** @hidden */
  2114. public _createDepthStencilTexture(size: number | { width: number, height: number, layers?: number }, options: DepthTextureCreationOptions): InternalTexture {
  2115. const internalTexture = new InternalTexture(this, InternalTextureSource.Depth);
  2116. const internalOptions = {
  2117. bilinearFiltering: false,
  2118. comparisonFunction: 0,
  2119. generateStencil: false,
  2120. samples: 1,
  2121. ...options
  2122. };
  2123. // TODO WEBGPU allow to choose the format?
  2124. internalTexture.format = internalOptions.generateStencil ? Constants.TEXTUREFORMAT_DEPTH24_STENCIL8 : Constants.TEXTUREFORMAT_DEPTH32_FLOAT;
  2125. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples);
  2126. this._textureHelper.createGPUTextureForInternalTexture(internalTexture);
  2127. return internalTexture;
  2128. }
  2129. /** @hidden */
  2130. public _createDepthStencilCubeTexture(size: number, options: DepthTextureCreationOptions): InternalTexture {
  2131. const internalTexture = new InternalTexture(this, InternalTextureSource.Depth);
  2132. internalTexture.isCube = true;
  2133. const internalOptions = {
  2134. bilinearFiltering: false,
  2135. comparisonFunction: 0,
  2136. generateStencil: false,
  2137. samples: 1,
  2138. ...options
  2139. };
  2140. // TODO WEBGPU allow to choose the format?
  2141. internalTexture.format = internalOptions.generateStencil ? Constants.TEXTUREFORMAT_DEPTH24_STENCIL8 : Constants.TEXTUREFORMAT_DEPTH32_FLOAT;
  2142. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples);
  2143. this._textureHelper.createGPUTextureForInternalTexture(internalTexture);
  2144. return internalTexture;
  2145. }
  2146. public updateRenderTargetTextureSampleCount(texture: Nullable<InternalTexture>, samples: number): number {
  2147. if (!texture || texture.samples === samples) {
  2148. return samples;
  2149. }
  2150. samples = Math.min(samples, this.getCaps().maxMSAASamples);
  2151. this._textureHelper.createMSAATexture(texture, samples);
  2152. if (texture._depthStencilTexture) {
  2153. this._textureHelper.createMSAATexture(texture._depthStencilTexture, samples);
  2154. texture._depthStencilTexture.samples = samples;
  2155. }
  2156. texture.samples = samples;
  2157. return samples;
  2158. }
  2159. /**
  2160. * Update the sample count for a given multiple render target texture
  2161. * @param textures defines the textures to update
  2162. * @param samples defines the sample count to set
  2163. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  2164. */
  2165. public updateMultipleRenderTargetTextureSampleCount(textures: Nullable<InternalTexture[]>, samples: number): number {
  2166. if (!textures || textures[0].samples === samples) {
  2167. return samples;
  2168. }
  2169. samples = Math.min(samples, this.getCaps().maxMSAASamples);
  2170. // Note that the last texture of textures is the depth texture (if the depth texture has been generated by the MRT class) and so the MSAA texture
  2171. // will be recreated for this texture too. As a consequence, there's no need to explicitely recreate the MSAA texture for textures[0]._depthStencilTexture
  2172. for (let i = 0; i < textures.length; ++i) {
  2173. const texture = textures[i];
  2174. this._textureHelper.createMSAATexture(texture, samples);
  2175. texture.samples = samples;
  2176. }
  2177. return samples;
  2178. }
  2179. //------------------------------------------------------------------------------
  2180. // Render Commands
  2181. //------------------------------------------------------------------------------
  2182. /**
  2183. * Begin a new frame
  2184. */
  2185. public beginFrame(): void {
  2186. super.beginFrame();
  2187. }
  2188. /**
  2189. * End the current frame
  2190. */
  2191. public endFrame() {
  2192. this._endMainRenderPass();
  2193. this.flushFramebuffer();
  2194. if (this.dbgVerboseLogsForFirstFrames) {
  2195. if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
  2196. console.log("frame #" + (this as any)._count + " - counters - numPipelineDescriptorCreation=", this._counters.numPipelineDescriptorCreation, ", numBindGroupsCreation=", this._counters.numBindGroupsCreation,
  2197. ", numVertexInputCacheCreation=", this._counters.numVertexInputCacheCreation);
  2198. }
  2199. }
  2200. this._textureHelper.destroyDeferredTextures();
  2201. this._bufferManager.destroyDeferredBuffers();
  2202. if (this._features._collectUbosUpdatedInFrame) {
  2203. if (this.dbgVerboseLogsForFirstFrames) {
  2204. if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
  2205. const list: Array<string> = [];
  2206. for (const name in UniformBuffer._updatedUbosInFrame) {
  2207. list.push(name + ":" + UniformBuffer._updatedUbosInFrame[name]);
  2208. }
  2209. console.log("frame #" + (this as any)._count + " - updated ubos -", list.join(", "));
  2210. }
  2211. }
  2212. UniformBuffer._updatedUbosInFrame = {};
  2213. }
  2214. this._counters.numPipelineDescriptorCreation = 0;
  2215. this._counters.numBindGroupsCreation = 0;
  2216. this._counters.numVertexInputCacheCreation = 0;
  2217. this._pendingDebugCommands.length = 0;
  2218. super.endFrame();
  2219. if (this.dbgVerboseLogsForFirstFrames) {
  2220. if ((this as any)._count < this.dbgVerboseLogsNumFrames) {
  2221. console.log("%c frame #" + (this as any)._count + " - end", "background: #ffff00");
  2222. }
  2223. if ((this as any)._count < this.dbgVerboseLogsNumFrames) {
  2224. (this as any)._count++;
  2225. if ((this as any)._count !== this.dbgVerboseLogsNumFrames) {
  2226. console.log("%c frame #" + (this as any)._count + " - begin", "background: #ffff00");
  2227. }
  2228. }
  2229. }
  2230. }
  2231. /**
  2232. * Force a WebGPU flush (ie. a flush of all waiting commands)
  2233. */
  2234. public flushFramebuffer(): void {
  2235. // we need to end the current render pass (main or rtt) if any as we are not allowed to submit the command buffers when being in a pass
  2236. let currentPassType = 0; // 0 if no pass, 1 for rtt, 2 for main pass
  2237. if (this._currentRenderPass) {
  2238. if (this._currentRenderTarget) {
  2239. if (this._currentRenderPass) {
  2240. currentPassType = 1;
  2241. this._endRenderTargetRenderPass();
  2242. }
  2243. } else {
  2244. currentPassType = 2;
  2245. this._endMainRenderPass();
  2246. }
  2247. }
  2248. this._commandBuffers[0] = this._uploadEncoder.finish();
  2249. this._commandBuffers[1] = this._renderTargetEncoder.finish();
  2250. this._commandBuffers[2] = this._renderEncoder.finish();
  2251. this._device.defaultQueue.submit(this._commandBuffers);
  2252. this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);
  2253. this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);
  2254. this._renderTargetEncoder = this._device.createCommandEncoder(this._renderTargetEncoderDescriptor);
  2255. this._textureHelper.setCommandEncoder(this._uploadEncoder);
  2256. // restart the render pass
  2257. if (currentPassType === 1) {
  2258. this._startRenderTargetRenderPass(this._currentRenderTarget!, null, false, false);
  2259. } else if (currentPassType === 2) {
  2260. this._startMainRenderPass(false);
  2261. }
  2262. }
  2263. //------------------------------------------------------------------------------
  2264. // Render Pass
  2265. //------------------------------------------------------------------------------
  2266. private _startRenderTargetRenderPass(internalTexture: InternalTexture, clearColor: Nullable<IColor4Like>, clearDepth: boolean, clearStencil: boolean) {
  2267. const gpuWrapper = internalTexture._hardwareTexture as WebGPUHardwareTexture;
  2268. const gpuTexture = gpuWrapper.underlyingResource!;
  2269. const depthStencilTexture = internalTexture._depthStencilTexture;
  2270. const gpuDepthStencilWrapper = depthStencilTexture?._hardwareTexture as Nullable<WebGPUHardwareTexture>;
  2271. const gpuDepthStencilTexture = gpuDepthStencilWrapper?.underlyingResource as Nullable<GPUTexture>;
  2272. const gpuDepthStencilMSAATexture = gpuDepthStencilWrapper?.msaaTexture;
  2273. const depthTextureView = gpuDepthStencilTexture?.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor!);
  2274. const depthMSAATextureView = gpuDepthStencilMSAATexture?.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor!);
  2275. const colorAttachments: GPURenderPassColorAttachmentDescriptor[] = [];
  2276. if (internalTexture._attachments && internalTexture._textureArray) {
  2277. // multi render targets
  2278. for (let i = 0; i < internalTexture._attachments.length; ++i) {
  2279. const index = internalTexture._attachments[i];
  2280. const mrtTexture = internalTexture._textureArray[index - 1];
  2281. const gpuMRTWrapper = mrtTexture?._hardwareTexture as Nullable<WebGPUHardwareTexture>;
  2282. const gpuMRTTexture = gpuMRTWrapper?.underlyingResource;
  2283. if (gpuMRTWrapper && gpuMRTTexture) {
  2284. const gpuMSAATexture = gpuMRTWrapper.msaaTexture;
  2285. const colorTextureView = gpuMRTTexture.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor!);
  2286. const colorMSAATextureView = gpuMSAATexture?.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor!);
  2287. colorAttachments.push({
  2288. attachment: colorMSAATextureView ? colorMSAATextureView : colorTextureView,
  2289. resolveTarget: gpuMSAATexture ? colorTextureView : undefined,
  2290. loadValue: clearColor !== null ? clearColor : WebGPUConstants.LoadOp.Load,
  2291. storeOp: WebGPUConstants.StoreOp.Store,
  2292. });
  2293. }
  2294. }
  2295. this._mrtAttachments = internalTexture._attachments;
  2296. } else {
  2297. // single render target
  2298. const gpuMSAATexture = gpuWrapper.msaaTexture;
  2299. const colorTextureView = gpuTexture.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor!);
  2300. const colorMSAATextureView = gpuMSAATexture?.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor!);
  2301. colorAttachments.push({
  2302. attachment: colorMSAATextureView ? colorMSAATextureView : colorTextureView,
  2303. resolveTarget: gpuMSAATexture ? colorTextureView : undefined,
  2304. loadValue: clearColor !== null ? clearColor : WebGPUConstants.LoadOp.Load,
  2305. storeOp: WebGPUConstants.StoreOp.Store,
  2306. });
  2307. }
  2308. this._debugPushGroup("render target pass", 1);
  2309. this._rttRenderPassWrapper.renderPassDescriptor = {
  2310. colorAttachments,
  2311. depthStencilAttachment: depthStencilTexture && gpuDepthStencilTexture ? {
  2312. attachment: depthMSAATextureView ? depthMSAATextureView : depthTextureView!,
  2313. depthLoadValue: clearDepth && depthStencilTexture._generateDepthBuffer ? this._clearDepthValue : WebGPUConstants.LoadOp.Load,
  2314. depthStoreOp: WebGPUConstants.StoreOp.Store,
  2315. stencilLoadValue: clearStencil && depthStencilTexture._generateStencilBuffer ? this._clearStencilValue : WebGPUConstants.LoadOp.Load,
  2316. stencilStoreOp: WebGPUConstants.StoreOp.Store,
  2317. } : undefined
  2318. };
  2319. this._rttRenderPassWrapper.renderPass = this._renderTargetEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor);
  2320. if (this.dbgVerboseLogsForFirstFrames) {
  2321. if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
  2322. console.log("frame #" + (this as any)._count + " - render target begin pass - internalTexture.uniqueId=", internalTexture.uniqueId, this._rttRenderPassWrapper.renderPassDescriptor);
  2323. }
  2324. }
  2325. this._currentRenderPass = this._rttRenderPassWrapper.renderPass;
  2326. this._debugFlushPendingCommands();
  2327. this._resetCurrentViewport(1);
  2328. this._resetCurrentScissor(1);
  2329. }
  2330. private _endRenderTargetRenderPass() {
  2331. if (this._currentRenderPass) {
  2332. this._currentRenderPass.endPass();
  2333. if (this.dbgVerboseLogsForFirstFrames) {
  2334. if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
  2335. console.log("frame #" + (this as any)._count + " - render target end pass - internalTexture.uniqueId=", this._currentRenderTarget?.uniqueId);
  2336. }
  2337. }
  2338. this._debugPopGroup(1);
  2339. this._resetCurrentViewport(1);
  2340. this._resetCurrentScissor(1);
  2341. this._currentRenderPass = null;
  2342. this._rttRenderPassWrapper.reset();
  2343. }
  2344. }
  2345. private _getCurrentRenderPass(): GPURenderPassEncoder {
  2346. if (this._currentRenderTarget && !this._currentRenderPass) {
  2347. // delayed creation of the render target pass, but we now need to create it as we are requested the render pass
  2348. this._startRenderTargetRenderPass(this._currentRenderTarget, null, false, false);
  2349. } else if (!this._currentRenderPass) {
  2350. this._startMainRenderPass(false);
  2351. }
  2352. return this._currentRenderPass!;
  2353. }
  2354. private _currentRenderPassIsMRT(): boolean {
  2355. return !!this._currentRenderTarget?._attachments ?? false;
  2356. }
  2357. private _startMainRenderPass(setClearStates: boolean, clearColor?: Nullable<IColor4Like>, clearDepth?: boolean, clearStencil?: boolean): void {
  2358. if (this._mainRenderPassWrapper.renderPass) {
  2359. this._endMainRenderPass();
  2360. }
  2361. if (this.useReverseDepthBuffer) {
  2362. this.setDepthFunctionToGreater();
  2363. }
  2364. const scissorIsActive = this._scissorIsActive();
  2365. if (setClearStates) {
  2366. const colorClearValue = scissorIsActive ? WebGPUConstants.LoadOp.Load : clearColor ? clearColor : WebGPUConstants.LoadOp.Load;
  2367. const depthClearValue = scissorIsActive ? WebGPUConstants.LoadOp.Load : clearDepth ? (this.useReverseDepthBuffer ? this._clearReverseDepthValue : this._clearDepthValue) : WebGPUConstants.LoadOp.Load;
  2368. const stencilClearValue = scissorIsActive ? WebGPUConstants.LoadOp.Load : clearStencil ? this._clearStencilValue : WebGPUConstants.LoadOp.Load;
  2369. (this._mainRenderPassWrapper.renderPassDescriptor!.colorAttachments as GPURenderPassColorAttachmentDescriptor[])[0].loadValue = colorClearValue;
  2370. this._mainRenderPassWrapper.renderPassDescriptor!.depthStencilAttachment!.depthLoadValue = depthClearValue;
  2371. this._mainRenderPassWrapper.renderPassDescriptor!.depthStencilAttachment!.stencilLoadValue = stencilClearValue;
  2372. }
  2373. this._swapChainTexture = this._swapChain.getCurrentTexture();
  2374. this._mainRenderPassWrapper.colorAttachmentGPUTextures![0].set(this._swapChainTexture);
  2375. // Resolve in case of MSAA
  2376. if (this._options.antialiasing) {
  2377. (this._mainRenderPassWrapper.renderPassDescriptor!.colorAttachments as GPURenderPassColorAttachmentDescriptor[])[0].resolveTarget = this._swapChainTexture.createView();
  2378. }
  2379. else {
  2380. (this._mainRenderPassWrapper.renderPassDescriptor!.colorAttachments as GPURenderPassColorAttachmentDescriptor[])[0].attachment = this._swapChainTexture.createView();
  2381. }
  2382. if (this.dbgVerboseLogsForFirstFrames) {
  2383. if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
  2384. console.log("frame #" + (this as any)._count + " - main begin pass - texture width=" + (this._mainTextureExtends as any).width, " height=" + (this._mainTextureExtends as any).height, this._mainRenderPassWrapper.renderPassDescriptor);
  2385. }
  2386. }
  2387. this._debugPushGroup("main pass", 0);
  2388. this._currentRenderPass = this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor!);
  2389. this._mainRenderPassWrapper.renderPass = this._currentRenderPass;
  2390. this._debugFlushPendingCommands();
  2391. this._resetCurrentViewport(0);
  2392. this._resetCurrentScissor(0);
  2393. if (setClearStates && scissorIsActive) {
  2394. this._applyScissor(this._currentRenderPass);
  2395. // TODO WEBGPU cache things, move this code somewhere else
  2396. const pipeline = this._device.createRenderPipeline({
  2397. sampleCount: this._currentRenderTarget ? this._currentRenderTarget.samples : this._mainPassSampleCount,
  2398. primitiveTopology: WebGPUConstants.PrimitiveTopology.TriangleStrip,
  2399. vertexState: {
  2400. indexFormat: WebGPUConstants.IndexFormat.Uint16
  2401. },
  2402. depthStencilState: this._depthTextureFormat === undefined ? undefined : {
  2403. depthWriteEnabled: clearDepth,
  2404. depthCompare: WebGPUConstants.CompareFunction.Always,
  2405. format: this._depthTextureFormat,
  2406. stencilFront: {
  2407. compare: clearStencil ? WebGPUConstants.CompareFunction.Always : WebGPUConstants.CompareFunction.Never,
  2408. passOp: clearStencil ? WebGPUConstants.StencilOperation.Replace : WebGPUConstants.StencilOperation.Keep,
  2409. },
  2410. stencilReadMask: 0xFF,
  2411. stencilWriteMask: clearStencil ? 0xFF : 0,
  2412. },
  2413. colorStates: [{
  2414. format: this._colorFormat,
  2415. writeMask: clearColor ? WebGPUConstants.ColorWrite.All : 0,
  2416. }],
  2417. ...this._shaderManager.getCompiledShaders("clearQuad"),
  2418. });
  2419. const bindGroupLayout = pipeline.getBindGroupLayout(0);
  2420. const buffer = this._bufferManager.createBuffer(4 * 4, WebGPUConstants.BufferUsage.CopyDst | WebGPUConstants.BufferUsage.Uniform) as WebGPUDataBuffer;
  2421. if (clearColor) {
  2422. const data = new Float32Array([clearColor.r, clearColor.g, clearColor.b, clearColor.a]);
  2423. this._bufferManager.setSubData(buffer, 0, data);
  2424. }
  2425. const bindGroup = this._device.createBindGroup({
  2426. layout: bindGroupLayout,
  2427. entries: [{
  2428. binding: 0,
  2429. resource: {
  2430. buffer: buffer.underlyingResource,
  2431. },
  2432. }],
  2433. });
  2434. this._currentRenderPass.setStencilReference(this._clearStencilValue);
  2435. this._currentRenderPass.setPipeline(pipeline);
  2436. this._currentRenderPass.setBindGroup(0, bindGroup);
  2437. this._currentRenderPass.draw(4, 1, 0, 0);
  2438. if (this._stencilState.stencilTest) {
  2439. this._getCurrentRenderPass().setStencilReference(this._stencilState.stencilFuncRef);
  2440. }
  2441. this._bufferManager.releaseBuffer(buffer);
  2442. }
  2443. }
  2444. private _endMainRenderPass(): void {
  2445. if (this._mainRenderPassWrapper.renderPass !== null) {
  2446. this._mainRenderPassWrapper.renderPass.endPass();
  2447. if (this.dbgVerboseLogsForFirstFrames) {
  2448. if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
  2449. console.log("frame #" + (this as any)._count + " - main end pass");
  2450. }
  2451. }
  2452. this._debugPopGroup(0);
  2453. this._resetCurrentViewport(0);
  2454. this._resetCurrentScissor(0);
  2455. if (this._mainRenderPassWrapper.renderPass === this._currentRenderPass) {
  2456. this._currentRenderPass = null;
  2457. }
  2458. this._mainRenderPassWrapper.reset(false);
  2459. }
  2460. }
  2461. /**
  2462. * Restores the WebGPU state to only draw on the main color attachment
  2463. */
  2464. public restoreSingleAttachment(): void {
  2465. this.bindAttachments([]);
  2466. }
  2467. /**
  2468. * Creates a layout object to draw/clear on specific textures in a MRT
  2469. * @param textureStatus textureStatus[i] indicates if the i-th is active
  2470. * @returns A layout to be fed to the engine, calling `bindAttachments`.
  2471. */
  2472. public buildTextureLayout(textureStatus: boolean[]): number[] {
  2473. const result = [];
  2474. for (let i = 0; i < textureStatus.length; i++) {
  2475. if (textureStatus[i]) {
  2476. result.push(i + 1);
  2477. } else {
  2478. result.push(0);
  2479. }
  2480. }
  2481. return result;
  2482. }
  2483. /**
  2484. * Select a subsets of attachments to draw to.
  2485. * @param attachments index of attachments
  2486. */
  2487. public bindAttachments(attachments: number[]): void {
  2488. this._mrtAttachments = attachments;
  2489. }
  2490. /**
  2491. * Binds the frame buffer to the specified texture.
  2492. * @param texture The texture to render to or null for the default canvas
  2493. * @param faceIndex The face of the texture to render to in case of cube texture
  2494. * @param requiredWidth The width of the target to render to
  2495. * @param requiredHeight The height of the target to render to
  2496. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  2497. * @param lodLevel defines the lod level to bind to the frame buffer
  2498. * @param layer defines the 2d array index to bind to frame buffer to
  2499. */
  2500. public bindFramebuffer(texture: InternalTexture, faceIndex: number = 0, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean, lodLevel = 0, layer = 0): void {
  2501. const hardwareTexture = texture._hardwareTexture as Nullable<WebGPUHardwareTexture>;
  2502. const gpuTexture = hardwareTexture?.underlyingResource as Nullable<GPUTexture>;
  2503. if (!hardwareTexture || !gpuTexture) {
  2504. if (this.dbgSanityChecks) {
  2505. console.error("bindFramebuffer: Trying to bind a texture that does not have a hardware texture or that has a webgpu texture empty!", texture, hardwareTexture, gpuTexture);
  2506. }
  2507. return;
  2508. }
  2509. if (this._currentRenderTarget) {
  2510. this.unBindFramebuffer(this._currentRenderTarget);
  2511. }
  2512. this._currentRenderTarget = texture;
  2513. this._rttRenderPassWrapper.colorAttachmentGPUTextures[0] = hardwareTexture;
  2514. this._rttRenderPassWrapper.depthTextureFormat = this._currentRenderTarget._depthStencilTexture ? WebGPUTextureHelper.GetWebGPUTextureFormat(-1, this._currentRenderTarget._depthStencilTexture.format) : undefined;
  2515. this._setDepthTextureFormat(this._rttRenderPassWrapper);
  2516. this._setColorFormat(this._rttRenderPassWrapper);
  2517. this._rttRenderPassWrapper.colorAttachmentViewDescriptor = {
  2518. format: this._colorFormat,
  2519. dimension: WebGPUConstants.TextureViewDimension.E2d,
  2520. mipLevelCount: 1,
  2521. baseArrayLayer: texture.isCube ? layer * 6 + faceIndex : layer,
  2522. baseMipLevel: lodLevel,
  2523. arrayLayerCount: 1,
  2524. aspect: WebGPUConstants.TextureAspect.All
  2525. };
  2526. this._rttRenderPassWrapper.depthAttachmentViewDescriptor = {
  2527. format: this._depthTextureFormat,
  2528. dimension: WebGPUConstants.TextureViewDimension.E2d,
  2529. mipLevelCount: 1,
  2530. baseArrayLayer: texture.isCube ? layer * 6 + faceIndex : layer,
  2531. baseMipLevel: 0,
  2532. arrayLayerCount: 1,
  2533. aspect: WebGPUConstants.TextureAspect.All
  2534. };
  2535. if (this.dbgVerboseLogsForFirstFrames) {
  2536. if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
  2537. console.log("frame #" + (this as any)._count + " - bindFramebuffer called - face=", faceIndex, "lodLevel=", lodLevel, "layer=", layer, this._rttRenderPassWrapper.colorAttachmentViewDescriptor, this._rttRenderPassWrapper.depthAttachmentViewDescriptor);
  2538. }
  2539. }
  2540. this._currentRenderPass = null; // lazy creation of the render pass, hoping the render pass will be created by a call to clear()...
  2541. if (this._cachedViewport && !forceFullscreenViewport) {
  2542. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  2543. } else {
  2544. if (!requiredWidth) {
  2545. requiredWidth = texture.width;
  2546. if (lodLevel) {
  2547. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  2548. }
  2549. }
  2550. if (!requiredHeight) {
  2551. requiredHeight = texture.height;
  2552. if (lodLevel) {
  2553. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  2554. }
  2555. }
  2556. this._viewport(0, 0, requiredWidth, requiredHeight);
  2557. }
  2558. this.wipeCaches();
  2559. }
  2560. /**
  2561. * Unbind the current render target texture from the WebGPU context
  2562. * @param texture defines the render target texture to unbind
  2563. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  2564. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  2565. */
  2566. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  2567. // TODO WEBGPU remove the assert debugging code
  2568. assert(this._currentRenderTarget === null || (this._currentRenderTarget !== null && texture === this._currentRenderTarget), "unBindFramebuffer - the texture we wan't to unbind is not the same than the currentRenderTarget! texture=" + texture + ", this._currentRenderTarget=" + this._currentRenderTarget);
  2569. if (onBeforeUnbind) {
  2570. onBeforeUnbind();
  2571. }
  2572. if (this._currentRenderPass && this._currentRenderPass !== this._mainRenderPassWrapper.renderPass) {
  2573. this._endRenderTargetRenderPass();
  2574. }
  2575. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  2576. this._generateMipmaps(texture);
  2577. }
  2578. this._currentRenderTarget = null;
  2579. this._currentRenderPass = this._mainRenderPassWrapper.renderPass;
  2580. this._setDepthTextureFormat(this._mainRenderPassWrapper);
  2581. this._setColorFormat(this._mainRenderPassWrapper);
  2582. }
  2583. /**
  2584. * Unbind a list of render target textures from the WebGPU context
  2585. * @param textures defines the render target textures to unbind
  2586. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  2587. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  2588. */
  2589. public unBindMultiColorAttachmentFramebuffer(textures: InternalTexture[], disableGenerateMipMaps: boolean = false, onBeforeUnbind?: () => void): void {
  2590. if (onBeforeUnbind) {
  2591. onBeforeUnbind();
  2592. }
  2593. const attachments = textures[0]._attachments!;
  2594. const count = attachments.length;
  2595. if (this._currentRenderPass && this._currentRenderPass !== this._mainRenderPassWrapper.renderPass) {
  2596. this._endRenderTargetRenderPass();
  2597. }
  2598. for (let i = 0; i < count; i++) {
  2599. const texture = textures[i];
  2600. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  2601. this._generateMipmaps(texture);
  2602. }
  2603. }
  2604. this._currentRenderTarget = null;
  2605. this._currentRenderPass = this._mainRenderPassWrapper.renderPass;
  2606. this._setDepthTextureFormat(this._mainRenderPassWrapper);
  2607. this._setColorFormat(this._mainRenderPassWrapper);
  2608. }
  2609. /**
  2610. * Unbind the current render target and bind the default framebuffer
  2611. */
  2612. public restoreDefaultFramebuffer(): void {
  2613. if (this._currentRenderTarget) {
  2614. this.unBindFramebuffer(this._currentRenderTarget);
  2615. } else {
  2616. this._currentRenderPass = this._mainRenderPassWrapper.renderPass;
  2617. this._setDepthTextureFormat(this._mainRenderPassWrapper);
  2618. this._setColorFormat(this._mainRenderPassWrapper);
  2619. }
  2620. if (this._currentRenderPass) {
  2621. if (this._cachedViewport) {
  2622. this.setViewport(this._cachedViewport);
  2623. }
  2624. }
  2625. this.wipeCaches();
  2626. }
  2627. //------------------------------------------------------------------------------
  2628. // Render
  2629. //------------------------------------------------------------------------------
  2630. public setZOffset(value: number): void {
  2631. if (value !== this._depthCullingState.zOffset) {
  2632. this._depthCullingState.zOffset = value;
  2633. }
  2634. }
  2635. private _setColorFormat(wrapper: WebGPURenderPassWrapper): void {
  2636. const format = wrapper.colorAttachmentGPUTextures[0].format;
  2637. if (this._colorFormat === format) {
  2638. return;
  2639. }
  2640. this._colorFormat = format;
  2641. }
  2642. private _setDepthTextureFormat(wrapper: WebGPURenderPassWrapper): void {
  2643. if (this._depthTextureFormat === wrapper.depthTextureFormat) {
  2644. return;
  2645. }
  2646. this._depthTextureFormat = wrapper.depthTextureFormat;
  2647. }
  2648. public setDepthBuffer(enable: boolean): void {
  2649. if (this._depthCullingState.depthTest !== enable) {
  2650. this._depthCullingState.depthTest = enable;
  2651. }
  2652. }
  2653. public setDepthWrite(enable: boolean): void {
  2654. if (this._depthCullingState.depthMask !== enable) {
  2655. this._depthCullingState.depthMask = enable;
  2656. }
  2657. }
  2658. public setStencilBuffer(enable: boolean): void {
  2659. if (this._stencilState.stencilTest !== enable) {
  2660. this._stencilState.stencilTest = enable;
  2661. }
  2662. }
  2663. public setStencilMask(mask: number): void {
  2664. if (this._stencilState.stencilMask !== mask) {
  2665. this._stencilState.stencilMask = mask;
  2666. }
  2667. }
  2668. public setStencilFunction(stencilFunc: number) {
  2669. if (this._stencilState.stencilFunc !== stencilFunc) {
  2670. this._stencilState.stencilFunc = stencilFunc;
  2671. }
  2672. }
  2673. public setStencilFunctionReference(reference: number) {
  2674. if (this._stencilState.stencilFuncRef !== reference) {
  2675. this._stencilState.stencilFuncRef = reference;
  2676. }
  2677. }
  2678. public setStencilFunctionMask(mask: number) {
  2679. if (this._stencilState.stencilFuncMask !== mask) {
  2680. this._stencilState.stencilFuncMask = mask;
  2681. }
  2682. }
  2683. public setStencilOperationFail(operation: number): void {
  2684. if (this._stencilState.stencilOpStencilFail !== operation) {
  2685. this._stencilState.stencilOpStencilFail = operation;
  2686. }
  2687. }
  2688. public setStencilOperationDepthFail(operation: number): void {
  2689. if (this._stencilState.stencilOpDepthFail !== operation) {
  2690. this._stencilState.stencilOpDepthFail = operation;
  2691. }
  2692. }
  2693. public setStencilOperationPass(operation: number): void {
  2694. if (this._stencilState.stencilOpStencilDepthPass !== operation) {
  2695. this._stencilState.stencilOpStencilDepthPass = operation;
  2696. }
  2697. }
  2698. public setDitheringState(value: boolean): void {
  2699. // Does not exist in WebGPU
  2700. }
  2701. public setRasterizerState(value: boolean): void {
  2702. // Does not exist in WebGPU
  2703. }
  2704. public setDepthFunction(depthFunc: number) {
  2705. if (this._depthCullingState.depthFunc !== depthFunc) {
  2706. this._depthCullingState.depthFunc = depthFunc;
  2707. }
  2708. }
  2709. public setDepthFunctionToGreater(): void {
  2710. if (this._depthCullingState.depthFunc !== Constants.GREATER) {
  2711. this._depthCullingState.depthFunc = Constants.GREATER;
  2712. }
  2713. }
  2714. public setDepthFunctionToGreaterOrEqual(): void {
  2715. if (this._depthCullingState.depthFunc !== Constants.GEQUAL) {
  2716. this._depthCullingState.depthFunc = Constants.GEQUAL;
  2717. }
  2718. }
  2719. public setDepthFunctionToLess(): void {
  2720. if (this._depthCullingState.depthFunc !== Constants.LESS) {
  2721. this._depthCullingState.depthFunc = Constants.LESS;
  2722. }
  2723. }
  2724. public setDepthFunctionToLessOrEqual(): void {
  2725. if (this._depthCullingState.depthFunc !== Constants.LEQUAL) {
  2726. this._depthCullingState.depthFunc = Constants.LEQUAL;
  2727. }
  2728. }
  2729. private _indexFormatInRenderPass(topology: GPUPrimitiveTopology): boolean {
  2730. return topology === WebGPUConstants.PrimitiveTopology.PointList ||
  2731. topology === WebGPUConstants.PrimitiveTopology.LineList ||
  2732. topology === WebGPUConstants.PrimitiveTopology.TriangleList;
  2733. }
  2734. private _getTopology(fillMode: number): GPUPrimitiveTopology {
  2735. switch (fillMode) {
  2736. // Triangle views
  2737. case Constants.MATERIAL_TriangleFillMode:
  2738. return WebGPUConstants.PrimitiveTopology.TriangleList;
  2739. case Constants.MATERIAL_PointFillMode:
  2740. return WebGPUConstants.PrimitiveTopology.PointList;
  2741. case Constants.MATERIAL_WireFrameFillMode:
  2742. return WebGPUConstants.PrimitiveTopology.LineList;
  2743. // Draw modes
  2744. case Constants.MATERIAL_PointListDrawMode:
  2745. return WebGPUConstants.PrimitiveTopology.PointList;
  2746. case Constants.MATERIAL_LineListDrawMode:
  2747. return WebGPUConstants.PrimitiveTopology.LineList;
  2748. case Constants.MATERIAL_LineLoopDrawMode:
  2749. // return this._gl.LINE_LOOP;
  2750. // TODO WEBGPU. Line Loop Mode Fallback at buffer load time.
  2751. throw "LineLoop is an unsupported fillmode in WebGPU";
  2752. case Constants.MATERIAL_LineStripDrawMode:
  2753. return WebGPUConstants.PrimitiveTopology.LineStrip;
  2754. case Constants.MATERIAL_TriangleStripDrawMode:
  2755. return WebGPUConstants.PrimitiveTopology.TriangleStrip;
  2756. case Constants.MATERIAL_TriangleFanDrawMode:
  2757. // return this._gl.TRIANGLE_FAN;
  2758. // TODO WEBGPU. Triangle Fan Mode Fallback at buffer load time.
  2759. throw "TriangleFan is an unsupported fillmode in WebGPU";
  2760. default:
  2761. return WebGPUConstants.PrimitiveTopology.TriangleList;
  2762. }
  2763. }
  2764. private _getOpFunction(operation: Nullable<number>, defaultOp: GPUStencilOperation): GPUStencilOperation {
  2765. switch (operation) {
  2766. case Constants.KEEP:
  2767. return WebGPUConstants.StencilOperation.Keep;
  2768. case Constants.ZERO:
  2769. return WebGPUConstants.StencilOperation.Zero;
  2770. case Constants.REPLACE:
  2771. return WebGPUConstants.StencilOperation.Replace;
  2772. case Constants.INVERT:
  2773. return WebGPUConstants.StencilOperation.Invert;
  2774. case Constants.INCR:
  2775. return WebGPUConstants.StencilOperation.IncrementClamp;
  2776. case Constants.DECR:
  2777. return WebGPUConstants.StencilOperation.DecrementClamp;
  2778. case Constants.INCR_WRAP:
  2779. return WebGPUConstants.StencilOperation.IncrementWrap;
  2780. case Constants.DECR_WRAP:
  2781. return WebGPUConstants.StencilOperation.DecrementWrap;
  2782. default:
  2783. return defaultOp;
  2784. }
  2785. }
  2786. private _getDepthStencilStateDescriptor(): GPUDepthStencilStateDescriptor | undefined {
  2787. if (this._depthTextureFormat === undefined) {
  2788. return undefined;
  2789. }
  2790. const stencilFrontBack: GPUStencilStateFaceDescriptor = {
  2791. compare: WebGPUTextureHelper.GetCompareFunction(this._stencilState.stencilFunc),
  2792. depthFailOp: this._getOpFunction(this._stencilState.stencilOpDepthFail, WebGPUConstants.StencilOperation.Keep),
  2793. failOp: this._getOpFunction(this._stencilState.stencilOpStencilFail, WebGPUConstants.StencilOperation.Keep),
  2794. passOp: this._getOpFunction(this._stencilState.stencilOpStencilDepthPass, WebGPUConstants.StencilOperation.Replace)
  2795. };
  2796. return {
  2797. depthWriteEnabled: this.getDepthWrite(),
  2798. depthCompare: this.getDepthBuffer() ? WebGPUTextureHelper.GetCompareFunction(this.getDepthFunction()) : WebGPUConstants.CompareFunction.Always,
  2799. format: this._depthTextureFormat,
  2800. stencilFront: stencilFrontBack,
  2801. stencilBack: stencilFrontBack,
  2802. stencilReadMask: this._stencilState.stencilFuncMask,
  2803. stencilWriteMask: this._stencilState.stencilMask,
  2804. };
  2805. }
  2806. /**
  2807. * Set various states to the context
  2808. * @param culling defines backface culling state
  2809. * @param zOffset defines the value to apply to zOffset (0 by default)
  2810. * @param force defines if states must be applied even if cache is up to date
  2811. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  2812. */
  2813. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  2814. // Culling
  2815. if (this._depthCullingState.cull !== culling || force) {
  2816. this._depthCullingState.cull = culling;
  2817. }
  2818. // Cull face
  2819. // var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  2820. var cullFace = this.cullBackFaces ? 1 : 2;
  2821. if (this._depthCullingState.cullFace !== cullFace || force) {
  2822. this._depthCullingState.cullFace = cullFace;
  2823. }
  2824. // Z offset
  2825. this.setZOffset(zOffset);
  2826. // Front face
  2827. // var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  2828. var frontFace = reverseSide ? 1 : 2;
  2829. if (this._depthCullingState.frontFace !== frontFace || force) {
  2830. this._depthCullingState.frontFace = frontFace;
  2831. }
  2832. }
  2833. private _getFrontFace(): GPUFrontFace {
  2834. switch (this._depthCullingState.frontFace) {
  2835. case 1:
  2836. return WebGPUConstants.FrontFace.CCW;
  2837. default:
  2838. return WebGPUConstants.FrontFace.CW;
  2839. }
  2840. }
  2841. private _getCullMode(): GPUCullMode {
  2842. if (this._depthCullingState.cull === false) {
  2843. return WebGPUConstants.CullMode.None;
  2844. }
  2845. if (this._depthCullingState.cullFace === 2) {
  2846. return WebGPUConstants.CullMode.Front;
  2847. }
  2848. else {
  2849. return WebGPUConstants.CullMode.Back;
  2850. }
  2851. }
  2852. private _getRasterizationStateDescriptor(): GPURasterizationStateDescriptor {
  2853. return {
  2854. frontFace: this._getFrontFace(),
  2855. cullMode: this._getCullMode(),
  2856. depthBias: 0,
  2857. depthBiasClamp: 0,
  2858. depthBiasSlopeScale: this._depthCullingState.zOffset,
  2859. };
  2860. }
  2861. private _getWriteMask(): number {
  2862. if (this.__colorWrite) {
  2863. return WebGPUConstants.ColorWrite.All;
  2864. }
  2865. return 0;
  2866. }
  2867. /**
  2868. * Sets the current alpha mode
  2869. * @param mode defines the mode to use (one of the Engine.ALPHA_XXX)
  2870. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  2871. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  2872. */
  2873. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  2874. if (this._alphaMode === mode) {
  2875. return;
  2876. }
  2877. switch (mode) {
  2878. case Engine.ALPHA_DISABLE:
  2879. this._alphaState.alphaBlend = false;
  2880. break;
  2881. case Engine.ALPHA_PREMULTIPLIED:
  2882. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2883. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0303, 1, 1);
  2884. this._alphaState.alphaBlend = true;
  2885. break;
  2886. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  2887. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2888. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0303, 1, 0x0303);
  2889. this._alphaState.alphaBlend = true;
  2890. break;
  2891. case Engine.ALPHA_COMBINE:
  2892. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2893. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 0x0303, 1, 1);
  2894. this._alphaState.alphaBlend = true;
  2895. break;
  2896. case Engine.ALPHA_ONEONE:
  2897. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2898. this._alphaState.setAlphaBlendFunctionParameters(1, 1, 0, 1);
  2899. this._alphaState.alphaBlend = true;
  2900. break;
  2901. case Engine.ALPHA_ADD:
  2902. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2903. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 1, 0, 1);
  2904. this._alphaState.alphaBlend = true;
  2905. break;
  2906. case Engine.ALPHA_SUBTRACT:
  2907. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2908. this._alphaState.setAlphaBlendFunctionParameters(0, 0x0301, 1, 1);
  2909. this._alphaState.alphaBlend = true;
  2910. break;
  2911. case Engine.ALPHA_MULTIPLY:
  2912. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  2913. this._alphaState.setAlphaBlendFunctionParameters(0x0306, 0, 1, 1);
  2914. this._alphaState.alphaBlend = true;
  2915. break;
  2916. case Engine.ALPHA_MAXIMIZED:
  2917. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2918. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 0x0301, 1, 1);
  2919. this._alphaState.alphaBlend = true;
  2920. break;
  2921. case Engine.ALPHA_INTERPOLATE:
  2922. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  2923. this._alphaState.setAlphaBlendFunctionParameters(0x8001, 0x8002, 0x8003, 0x8004);
  2924. this._alphaState.alphaBlend = true;
  2925. break;
  2926. case Engine.ALPHA_SCREENMODE:
  2927. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2928. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0301, 1, 0x0303);
  2929. this._alphaState.alphaBlend = true;
  2930. break;
  2931. }
  2932. if (!noDepthWriteChange) {
  2933. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  2934. }
  2935. this._alphaMode = mode;
  2936. }
  2937. private _getAphaBlendOperation(operation: Nullable<number>): GPUBlendOperation {
  2938. switch (operation) {
  2939. case 0x8006:
  2940. return WebGPUConstants.BlendOperation.Add;
  2941. case 0x800A:
  2942. return WebGPUConstants.BlendOperation.Subtract;
  2943. case 0x800B:
  2944. return WebGPUConstants.BlendOperation.ReverseSubtract;
  2945. default:
  2946. return WebGPUConstants.BlendOperation.Add;
  2947. }
  2948. }
  2949. private _getAphaBlendFactor(factor: Nullable<number>): GPUBlendFactor {
  2950. switch (factor) {
  2951. case 0:
  2952. return WebGPUConstants.BlendFactor.Zero;
  2953. case 1:
  2954. return WebGPUConstants.BlendFactor.One;
  2955. case 0x0300:
  2956. return WebGPUConstants.BlendFactor.SrcColor;
  2957. case 0x0301:
  2958. return WebGPUConstants.BlendFactor.OneMinusSrcColor;
  2959. case 0x0302:
  2960. return WebGPUConstants.BlendFactor.SrcAlpha;
  2961. case 0x0303:
  2962. return WebGPUConstants.BlendFactor.OneMinusSrcAlpha;
  2963. case 0x0304:
  2964. return WebGPUConstants.BlendFactor.DstAlpha;
  2965. case 0x0305:
  2966. return WebGPUConstants.BlendFactor.OneMinusDstAlpha;
  2967. case 0x0306:
  2968. return WebGPUConstants.BlendFactor.DstColor;
  2969. case 0x0307:
  2970. return WebGPUConstants.BlendFactor.OneMinusDstColor;
  2971. case 0x0308:
  2972. return WebGPUConstants.BlendFactor.SrcAlphaSaturated;
  2973. case 0x8001:
  2974. return WebGPUConstants.BlendFactor.BlendColor;
  2975. case 0x8002:
  2976. return WebGPUConstants.BlendFactor.OneMinusBlendColor;
  2977. case 0x8003:
  2978. return WebGPUConstants.BlendFactor.BlendColor;
  2979. case 0x8004:
  2980. return WebGPUConstants.BlendFactor.OneMinusBlendColor;
  2981. default:
  2982. return WebGPUConstants.BlendFactor.One;
  2983. }
  2984. }
  2985. private _getAphaBlendState(): GPUBlendDescriptor {
  2986. if (!this._alphaState.alphaBlend) {
  2987. return { };
  2988. }
  2989. return {
  2990. srcFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[2]),
  2991. dstFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[3]),
  2992. operation: this._getAphaBlendOperation(this._alphaState._blendEquationParameters[1]),
  2993. };
  2994. }
  2995. private _getColorBlendState(): GPUBlendDescriptor {
  2996. if (!this._alphaState.alphaBlend) {
  2997. return { };
  2998. }
  2999. return {
  3000. srcFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[0]),
  3001. dstFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[1]),
  3002. operation: this._getAphaBlendOperation(this._alphaState._blendEquationParameters[0]),
  3003. };
  3004. }
  3005. private _getColorStateDescriptors(): GPUColorStateDescriptor[] {
  3006. const descriptors: GPUColorStateDescriptor[] = [];
  3007. const alphaBlend = this._getAphaBlendState();
  3008. const colorBlend = this._getColorBlendState();
  3009. const writeMask = this._getWriteMask();
  3010. if (this._currentRenderPassIsMRT()) {
  3011. const textureArray = this._currentRenderTarget!._textureArray!;
  3012. for (let i = 0; i < this._mrtAttachments.length; ++i) {
  3013. const index = this._mrtAttachments[i];
  3014. if (index > 0) {
  3015. const mrtTexture = textureArray[index - 1];
  3016. const gpuMRTWrapper = mrtTexture?._hardwareTexture as Nullable<WebGPUHardwareTexture>;
  3017. const gpuMRTTexture = gpuMRTWrapper?.underlyingResource as Nullable<WebGPUHardwareTexture>;
  3018. descriptors.push({
  3019. format: gpuMRTTexture?.format ?? this._colorFormat,
  3020. alphaBlend,
  3021. colorBlend,
  3022. writeMask,
  3023. });
  3024. } else {
  3025. // TODO WEBGPU what to do when this._mrtAttachments[i] === 0? The corresponding texture should be bound as an "empty" texture
  3026. }
  3027. }
  3028. } else {
  3029. descriptors.push({
  3030. format: this._colorFormat,
  3031. alphaBlend,
  3032. colorBlend,
  3033. writeMask,
  3034. });
  3035. }
  3036. return descriptors;
  3037. }
  3038. private _getStages(): IWebGPURenderPipelineStageDescriptor {
  3039. const webgpuPipelineContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  3040. return webgpuPipelineContext.stages!;
  3041. }
  3042. private _getVertexInputDescriptorFormat(vertexBuffer: VertexBuffer): GPUVertexFormat {
  3043. const kind = vertexBuffer.getKind();
  3044. const type = vertexBuffer.type;
  3045. const normalized = vertexBuffer.normalized;
  3046. const size = vertexBuffer.getSize();
  3047. switch (type) {
  3048. case VertexBuffer.BYTE:
  3049. switch (size) {
  3050. case 1:
  3051. case 2:
  3052. return normalized ? WebGPUConstants.VertexFormat.Char2Norm : WebGPUConstants.VertexFormat.Char2;
  3053. case 3:
  3054. case 4:
  3055. return normalized ? WebGPUConstants.VertexFormat.Char4Norm : WebGPUConstants.VertexFormat.Char4;
  3056. }
  3057. break;
  3058. case VertexBuffer.UNSIGNED_BYTE:
  3059. switch (size) {
  3060. case 1:
  3061. case 2:
  3062. return normalized ? WebGPUConstants.VertexFormat.Uchar2Norm : WebGPUConstants.VertexFormat.Uchar2;
  3063. case 3:
  3064. case 4:
  3065. return normalized ? WebGPUConstants.VertexFormat.Uchar4Norm : WebGPUConstants.VertexFormat.Uchar4;
  3066. }
  3067. break;
  3068. case VertexBuffer.SHORT:
  3069. switch (size) {
  3070. case 1:
  3071. case 2:
  3072. return normalized ? WebGPUConstants.VertexFormat.Short2Norm : WebGPUConstants.VertexFormat.Short2;
  3073. case 3:
  3074. case 4:
  3075. return normalized ? WebGPUConstants.VertexFormat.Short4Norm : WebGPUConstants.VertexFormat.Short4;
  3076. }
  3077. break;
  3078. case VertexBuffer.UNSIGNED_SHORT:
  3079. switch (size) {
  3080. case 1:
  3081. case 2:
  3082. return normalized ? WebGPUConstants.VertexFormat.Ushort2Norm : WebGPUConstants.VertexFormat.Ushort2;
  3083. case 3:
  3084. case 4:
  3085. return normalized ? WebGPUConstants.VertexFormat.Ushort4Norm : WebGPUConstants.VertexFormat.Ushort4;
  3086. }
  3087. break;
  3088. case VertexBuffer.INT:
  3089. switch (size) {
  3090. case 1:
  3091. return WebGPUConstants.VertexFormat.Int;
  3092. case 2:
  3093. return WebGPUConstants.VertexFormat.Int2;
  3094. case 3:
  3095. return WebGPUConstants.VertexFormat.Int3;
  3096. case 4:
  3097. return WebGPUConstants.VertexFormat.Int4;
  3098. }
  3099. break;
  3100. case VertexBuffer.UNSIGNED_INT:
  3101. switch (size) {
  3102. case 1:
  3103. return WebGPUConstants.VertexFormat.Uint;
  3104. case 2:
  3105. return WebGPUConstants.VertexFormat.Uint2;
  3106. case 3:
  3107. return WebGPUConstants.VertexFormat.Uint3;
  3108. case 4:
  3109. return WebGPUConstants.VertexFormat.Uint4;
  3110. }
  3111. break;
  3112. case VertexBuffer.FLOAT:
  3113. switch (size) {
  3114. case 1:
  3115. return WebGPUConstants.VertexFormat.Float;
  3116. case 2:
  3117. return WebGPUConstants.VertexFormat.Float2;
  3118. case 3:
  3119. return WebGPUConstants.VertexFormat.Float3;
  3120. case 4:
  3121. return WebGPUConstants.VertexFormat.Float4;
  3122. }
  3123. break;
  3124. }
  3125. throw new Error(`Invalid Format '${kind}' - type=${type}, normalized=${normalized}, size=${size}`);
  3126. }
  3127. private _getVertexInputDescriptor(topology: GPUPrimitiveTopology): GPUVertexStateDescriptor {
  3128. const descriptors: GPUVertexBufferLayoutDescriptor[] = [];
  3129. const effect = this._currentEffect!;
  3130. const attributes = effect.getAttributesNames();
  3131. for (var index = 0; index < attributes.length; index++) {
  3132. const location = effect.getAttributeLocation(index);
  3133. if (location >= 0) {
  3134. let vertexBuffer = this._currentVertexBuffers![attributes[index]];
  3135. if (!vertexBuffer) {
  3136. // In WebGL it's valid to not bind a vertex buffer to an attribute, but it's not valid in WebGPU
  3137. // So we must bind a dummy buffer when we are not given one for a specific attribute
  3138. vertexBuffer = this._emptyVertexBuffer;
  3139. }
  3140. const positionAttributeDescriptor: GPUVertexAttributeDescriptor = {
  3141. shaderLocation: location,
  3142. offset: 0, // not available in WebGL
  3143. format: this._getVertexInputDescriptorFormat(vertexBuffer),
  3144. };
  3145. // TODO WEBGPU. Factorize the one with the same underlying buffer.
  3146. const vertexBufferDescriptor: GPUVertexBufferLayoutDescriptor = {
  3147. arrayStride: vertexBuffer.byteStride,
  3148. stepMode: vertexBuffer.getIsInstanced() ? WebGPUConstants.InputStepMode.Instance : WebGPUConstants.InputStepMode.Vertex,
  3149. attributes: [positionAttributeDescriptor]
  3150. };
  3151. descriptors.push(vertexBufferDescriptor);
  3152. }
  3153. }
  3154. if (!this._currentIndexBuffer) {
  3155. return {
  3156. indexFormat: !this._indexFormatInRenderPass(topology) ? WebGPUConstants.IndexFormat.Uint32 : undefined,
  3157. vertexBuffers: descriptors
  3158. };
  3159. }
  3160. const inputStateDescriptor: GPUVertexStateDescriptor = {
  3161. vertexBuffers: descriptors
  3162. };
  3163. if (!this._indexFormatInRenderPass(topology)) {
  3164. inputStateDescriptor.indexFormat = this._currentIndexBuffer!.is32Bits ? WebGPUConstants.IndexFormat.Uint32 : WebGPUConstants.IndexFormat.Uint16;
  3165. }
  3166. return inputStateDescriptor;
  3167. }
  3168. private _getPipelineLayout(): GPUPipelineLayout {
  3169. const bindGroupLayouts: GPUBindGroupLayout[] = [];
  3170. const webgpuPipelineContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  3171. for (let i = 0; i < webgpuPipelineContext.shaderProcessingContext.orderedUBOsAndSamplers.length; i++) {
  3172. const setDefinition = webgpuPipelineContext.shaderProcessingContext.orderedUBOsAndSamplers[i];
  3173. if (setDefinition === undefined) {
  3174. const entries: GPUBindGroupLayoutEntry[] = [];
  3175. const uniformsBindGroupLayout = this._device.createBindGroupLayout({
  3176. entries,
  3177. });
  3178. bindGroupLayouts[i] = uniformsBindGroupLayout;
  3179. continue;
  3180. }
  3181. const entries: GPUBindGroupLayoutEntry[] = [];
  3182. for (let j = 0; j < setDefinition.length; j++) {
  3183. const bindingDefinition = webgpuPipelineContext.shaderProcessingContext.orderedUBOsAndSamplers[i][j];
  3184. if (bindingDefinition === undefined) {
  3185. continue;
  3186. }
  3187. let visibility = 0;
  3188. if (bindingDefinition.usedInVertex) {
  3189. visibility = visibility | WebGPUConstants.ShaderStage.Vertex;
  3190. }
  3191. if (bindingDefinition.usedInFragment) {
  3192. visibility = visibility | WebGPUConstants.ShaderStage.Fragment;
  3193. }
  3194. if (bindingDefinition.isSampler) {
  3195. entries.push({
  3196. binding: j,
  3197. visibility,
  3198. type: bindingDefinition.isComparisonSampler ? WebGPUConstants.BindingType.ComparisonSampler : WebGPUConstants.BindingType.Sampler
  3199. });
  3200. } else if (bindingDefinition.isTexture) {
  3201. entries.push({
  3202. binding: j,
  3203. visibility,
  3204. type: WebGPUConstants.BindingType.SampledTexture,
  3205. viewDimension: bindingDefinition.textureDimension,
  3206. textureComponentType: bindingDefinition.componentType,
  3207. // TODO WEBGPU.
  3208. // hasDynamicOffset?: boolean;
  3209. // storageTextureFormat?: GPUTextureFormat;
  3210. // minBufferBindingSize?: number;
  3211. });
  3212. } else {
  3213. entries.push({
  3214. binding: j,
  3215. visibility,
  3216. type: WebGPUConstants.BindingType.UniformBuffer,
  3217. });
  3218. }
  3219. }
  3220. if (entries.length > 0) {
  3221. const uniformsBindGroupLayout = this._device.createBindGroupLayout({
  3222. entries,
  3223. });
  3224. bindGroupLayouts[i] = uniformsBindGroupLayout;
  3225. }
  3226. }
  3227. webgpuPipelineContext.bindGroupLayouts = bindGroupLayouts;
  3228. return this._device.createPipelineLayout({ bindGroupLayouts });
  3229. }
  3230. private _getRenderPipeline(topology: GPUPrimitiveTopology, createLayout = true): GPURenderPipeline {
  3231. this._counters.numPipelineDescriptorCreation++;
  3232. // Unsupported at the moment but needs to be extracted from the MSAA param.
  3233. const rasterizationStateDescriptor = this._getRasterizationStateDescriptor();
  3234. const depthStateDescriptor = this._getDepthStencilStateDescriptor();
  3235. const colorStateDescriptors = this._getColorStateDescriptors();
  3236. const stages = this._getStages();
  3237. const inputStateDescriptor = this._getVertexInputDescriptor(topology);
  3238. const pipelineLayout = createLayout ? this._getPipelineLayout() : undefined;
  3239. return this._device.createRenderPipeline({
  3240. sampleCount: this._currentRenderTarget ? this._currentRenderTarget.samples : this._mainPassSampleCount,
  3241. primitiveTopology: topology,
  3242. rasterizationState: rasterizationStateDescriptor,
  3243. depthStencilState: depthStateDescriptor,
  3244. colorStates: colorStateDescriptors,
  3245. ...stages,
  3246. vertexState: inputStateDescriptor,
  3247. layout: pipelineLayout,
  3248. });
  3249. }
  3250. private _getVertexInputsToRender(): IWebGPUPipelineContextVertexInputsCache {
  3251. const effect = this._currentEffect!;
  3252. this._counters.numVertexInputCacheCreation++;
  3253. let vertexInputs: IWebGPUPipelineContextVertexInputsCache = {
  3254. indexBuffer: null,
  3255. indexOffset: 0,
  3256. vertexStartSlot: 0,
  3257. vertexBuffers: [],
  3258. vertexOffsets: [],
  3259. };
  3260. if (this._currentIndexBuffer) {
  3261. // TODO WEBGPU. Check if cache would be worth it.
  3262. vertexInputs.indexBuffer = this._currentIndexBuffer.underlyingResource;
  3263. vertexInputs.indexOffset = 0;
  3264. }
  3265. else {
  3266. vertexInputs.indexBuffer = null;
  3267. }
  3268. const attributes = effect.getAttributesNames();
  3269. for (var index = 0; index < attributes.length; index++) {
  3270. const order = effect.getAttributeLocation(index);
  3271. if (order >= 0) {
  3272. let vertexBuffer = this._currentVertexBuffers![attributes[index]];
  3273. if (!vertexBuffer) {
  3274. // In WebGL it's valid to not bind a vertex buffer to an attribute, but it's not valid in WebGPU
  3275. // So we must bind a dummy buffer when we are not given one for a specific attribute
  3276. vertexBuffer = this._emptyVertexBuffer;
  3277. }
  3278. var buffer = vertexBuffer.getBuffer();
  3279. if (buffer) {
  3280. vertexInputs.vertexBuffers.push(buffer.underlyingResource);
  3281. vertexInputs.vertexOffsets.push(vertexBuffer.byteOffset);
  3282. }
  3283. }
  3284. }
  3285. // TODO WEBGPU. Optimize buffer reusability and types as more are now allowed.
  3286. return vertexInputs;
  3287. }
  3288. private _getBindGroupsToRender(): GPUBindGroup[] {
  3289. const webgpuPipelineContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  3290. let bindGroups: GPUBindGroup[] = [];
  3291. this._counters.numBindGroupsCreation++;
  3292. if (webgpuPipelineContext.uniformBuffer) {
  3293. this.bindUniformBufferBase(webgpuPipelineContext.uniformBuffer.getBuffer()!, 0, "LeftOver");
  3294. webgpuPipelineContext.uniformBuffer.update();
  3295. }
  3296. const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts;
  3297. for (let i = 0; i < webgpuPipelineContext.shaderProcessingContext.orderedUBOsAndSamplers.length; i++) {
  3298. const setDefinition = webgpuPipelineContext.shaderProcessingContext.orderedUBOsAndSamplers[i];
  3299. if (setDefinition === undefined) {
  3300. let groupLayout = bindGroupLayouts[i];
  3301. bindGroups[i] = this._device.createBindGroup({
  3302. layout: groupLayout,
  3303. entries: [],
  3304. });
  3305. continue;
  3306. }
  3307. const entries: GPUBindGroupEntry[] = [];
  3308. for (let j = 0; j < setDefinition.length; j++) {
  3309. const bindingDefinition = webgpuPipelineContext.shaderProcessingContext.orderedUBOsAndSamplers[i][j];
  3310. if (bindingDefinition === undefined) {
  3311. continue;
  3312. }
  3313. if (bindingDefinition.isSampler) {
  3314. const bindingInfo = webgpuPipelineContext.samplers[bindingDefinition.name];
  3315. if (bindingInfo) {
  3316. const texture = webgpuPipelineContext.textures[bindingInfo.firstTextureName]?.texture;
  3317. if (!texture) {
  3318. Logger.Error(`Could not create the gpu sampler "${bindingDefinition.name}" because no texture can be looked up for the name "${bindingInfo.firstTextureName}". bindingInfo=${JSON.stringify(bindingInfo)}, webgpuPipelineContext.textures=${webgpuPipelineContext.textures}`, 50);
  3319. continue;
  3320. }
  3321. entries.push({
  3322. binding: bindingInfo.samplerBinding,
  3323. resource: this._cacheSampler.getSampler(texture),
  3324. });
  3325. } else {
  3326. Logger.Error(`Sampler "${bindingDefinition.name}" could not be bound. bindingDefinition=${JSON.stringify(bindingDefinition)}, webgpuPipelineContext.samplers=${JSON.stringify(webgpuPipelineContext.samplers)}`, 50);
  3327. }
  3328. } else if (bindingDefinition.isTexture) {
  3329. const bindingInfo = webgpuPipelineContext.textures[bindingDefinition.name];
  3330. if (bindingInfo) {
  3331. if (this.dbgSanityChecks && bindingInfo.texture === null) {
  3332. Logger.Error(`Trying to bind a null texture! bindingDefinition=${JSON.stringify(bindingDefinition)}, bindingInfo=${JSON.stringify(bindingInfo, (key: string, value: any) => key === 'texture' ? '<no dump>' : value)}`, 50);
  3333. continue;
  3334. }
  3335. const hardwareTexture = bindingInfo.texture._hardwareTexture as WebGPUHardwareTexture;
  3336. if (this.dbgSanityChecks && !hardwareTexture.view) {
  3337. Logger.Error(`Trying to bind a null gpu texture! bindingDefinition=${JSON.stringify(bindingDefinition)}, bindingInfo=${JSON.stringify(bindingInfo, (key: string, value: any) => key === 'texture' ? '<no dump>' : value)}, isReady=${bindingInfo.texture.isReady}`, 50);
  3338. continue;
  3339. }
  3340. entries.push({
  3341. binding: bindingInfo.textureBinding,
  3342. resource: hardwareTexture.view!,
  3343. });
  3344. } else {
  3345. Logger.Error(`Texture "${bindingDefinition.name}" could not be bound. bindingDefinition=${JSON.stringify(bindingDefinition)}, webgpuPipelineContext.textures=${JSON.stringify(webgpuPipelineContext.textures, (key: string, value: any) => key === 'texture' ? '<no dump>' : value)}`, 50);
  3346. }
  3347. } else {
  3348. const dataBuffer = this._uniformsBuffers[bindingDefinition.name];
  3349. if (dataBuffer) {
  3350. const webgpuBuffer = dataBuffer.underlyingResource as GPUBuffer;
  3351. entries.push({
  3352. binding: j,
  3353. resource: {
  3354. buffer: webgpuBuffer,
  3355. offset: 0,
  3356. size: dataBuffer.capacity,
  3357. },
  3358. });
  3359. } else {
  3360. Logger.Error(`UBO "${bindingDefinition.name}. bindingDefinition=${JSON.stringify(bindingDefinition)}, _uniformsBuffers=${JSON.stringify(this._uniformsBuffers)}`, 50);
  3361. }
  3362. }
  3363. }
  3364. if (entries.length > 0) {
  3365. let groupLayout = bindGroupLayouts[i];
  3366. bindGroups[i] = this._device.createBindGroup({
  3367. layout: groupLayout,
  3368. entries,
  3369. });
  3370. }
  3371. }
  3372. return bindGroups;
  3373. }
  3374. private _bindVertexInputs(vertexInputs: IWebGPUPipelineContextVertexInputsCache): void {
  3375. const renderPass = this._bundleEncoder || this._getCurrentRenderPass();
  3376. if (vertexInputs.indexBuffer) {
  3377. // TODO WEBGPU. Check if cache would be worth it.
  3378. renderPass.setIndexBuffer(vertexInputs.indexBuffer, this._currentIndexBuffer!.is32Bits ? WebGPUConstants.IndexFormat.Uint32 : WebGPUConstants.IndexFormat.Uint16, vertexInputs.indexOffset);
  3379. }
  3380. // TODO WEBGPU. Optimize buffer reusability and types as more are now allowed.
  3381. for (let i = 0; i < vertexInputs.vertexBuffers.length; i++) {
  3382. const buf = vertexInputs.vertexBuffers[i];
  3383. if (buf) {
  3384. renderPass.setVertexBuffer(vertexInputs.vertexStartSlot + i, buf, vertexInputs.vertexOffsets[i]);
  3385. }
  3386. }
  3387. }
  3388. private _setRenderBindGroups(bindGroups: GPUBindGroup[]): void {
  3389. // TODO WEBGPU. Only set groups if changes happened.
  3390. const renderPass = this._bundleEncoder || this._getCurrentRenderPass();
  3391. for (let i = 0; i < bindGroups.length; i++) {
  3392. renderPass.setBindGroup(i, bindGroups[i]);
  3393. }
  3394. }
  3395. private _setRenderPipeline(fillMode: number): void {
  3396. const renderPass = this._bundleEncoder || this._getCurrentRenderPass();
  3397. const topology = this._getTopology(fillMode);
  3398. const pipeline = this._getRenderPipeline(topology);
  3399. renderPass.setPipeline(pipeline);
  3400. const vertexInputs = this._getVertexInputsToRender();
  3401. this._bindVertexInputs(vertexInputs);
  3402. const bindGroups = this._getBindGroupsToRender();
  3403. this._setRenderBindGroups(bindGroups);
  3404. // TODO WEBGPU add dirty mechanism as for _alphaState._blendConstants
  3405. if (this._stencilState.stencilTest && renderPass !== this._bundleEncoder) {
  3406. this._getCurrentRenderPass().setStencilReference(this._stencilState.stencilFuncRef);
  3407. }
  3408. // TODO WebGPU add back the dirty mechanism, but we need to distinguish between the main render pass and the RTT pass (if any)
  3409. if (this._alphaState.alphaBlend /* && this._alphaState._isBlendConstantsDirty*/ && renderPass !== this._bundleEncoder) {
  3410. this._getCurrentRenderPass().setBlendColor(this._alphaState._blendConstants as any);
  3411. }
  3412. if (renderPass !== this._bundleEncoder) {
  3413. this._applyViewport(renderPass as GPURenderPassEncoder);
  3414. this._applyScissor(renderPass as GPURenderPassEncoder);
  3415. }
  3416. }
  3417. /**
  3418. * Draw a list of indexed primitives
  3419. * @param fillMode defines the primitive to use
  3420. * @param indexStart defines the starting index
  3421. * @param indexCount defines the number of index to draw
  3422. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  3423. */
  3424. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount: number = 1): void {
  3425. const renderPass = this._bundleEncoder || this._getCurrentRenderPass();
  3426. this._setRenderPipeline(fillMode);
  3427. renderPass.drawIndexed(indexCount, instancesCount || 1, indexStart, 0, 0);
  3428. this._reportDrawCall();
  3429. }
  3430. /**
  3431. * Draw a list of unindexed primitives
  3432. * @param fillMode defines the primitive to use
  3433. * @param verticesStart defines the index of first vertex to draw
  3434. * @param verticesCount defines the count of vertices to draw
  3435. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  3436. */
  3437. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount: number = 1): void {
  3438. const renderPass = this._bundleEncoder || this._getCurrentRenderPass();
  3439. this._currentIndexBuffer = null;
  3440. this._setRenderPipeline(fillMode);
  3441. renderPass.draw(verticesCount, instancesCount || 1, verticesStart, 0);
  3442. this._reportDrawCall();
  3443. }
  3444. //------------------------------------------------------------------------------
  3445. // Render Bundle
  3446. //------------------------------------------------------------------------------
  3447. private _bundleEncoder: Nullable<GPURenderBundleEncoder>;
  3448. /**
  3449. * Start recording all the gpu calls into a bundle.
  3450. */
  3451. public startRecordBundle(): void {
  3452. // TODO. WebGPU. options should be dynamic.
  3453. this._bundleEncoder = this._device.createRenderBundleEncoder({
  3454. colorFormats: [ WebGPUConstants.TextureFormat.BGRA8Unorm ],
  3455. depthStencilFormat: WebGPUConstants.TextureFormat.Depth24PlusStencil8,
  3456. sampleCount: this._mainPassSampleCount,
  3457. });
  3458. }
  3459. /**
  3460. * Stops recording the bundle.
  3461. * @returns the recorded bundle
  3462. */
  3463. public stopRecordBundle(): GPURenderBundle {
  3464. const bundle = this._bundleEncoder!.finish();
  3465. this._bundleEncoder = null;
  3466. return bundle;
  3467. }
  3468. /**
  3469. * Execute the previously recorded bundle.
  3470. * @param bundles defines the bundle to replay
  3471. */
  3472. public executeBundles(bundles: GPURenderBundle[]): void {
  3473. const renderPass = this._getCurrentRenderPass();
  3474. renderPass.executeBundles(bundles);
  3475. }
  3476. //------------------------------------------------------------------------------
  3477. // Dispose
  3478. //------------------------------------------------------------------------------
  3479. /**
  3480. * Dispose and release all associated resources
  3481. */
  3482. public dispose(): void {
  3483. if (this._mainTexture) {
  3484. this._mainTexture.destroy();
  3485. }
  3486. if (this._depthTexture) {
  3487. this._depthTexture.destroy();
  3488. }
  3489. super.dispose();
  3490. }
  3491. //------------------------------------------------------------------------------
  3492. // Misc
  3493. //------------------------------------------------------------------------------
  3494. /**
  3495. * Gets the current render width
  3496. * @param useScreen defines if screen size must be used (or the current render target if any)
  3497. * @returns a number defining the current render width
  3498. */
  3499. public getRenderWidth(useScreen = false): number {
  3500. if (!useScreen && this._currentRenderTarget) {
  3501. return this._currentRenderTarget.width;
  3502. }
  3503. return this._canvas.width;
  3504. }
  3505. /**
  3506. * Gets the current render height
  3507. * @param useScreen defines if screen size must be used (or the current render target if any)
  3508. * @returns a number defining the current render height
  3509. */
  3510. public getRenderHeight(useScreen = false): number {
  3511. if (!useScreen && this._currentRenderTarget) {
  3512. return this._currentRenderTarget.height;
  3513. }
  3514. return this._canvas.height;
  3515. }
  3516. /**
  3517. * Gets the HTML canvas attached with the current WebGPU context
  3518. * @returns a HTML canvas
  3519. */
  3520. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  3521. return this._canvas;
  3522. }
  3523. /** @hidden */
  3524. public _debugPushGroup(groupName: string, targetObject?: number): void {
  3525. if (!this._options.enableGPUDebugMarkers) {
  3526. return;
  3527. }
  3528. if (targetObject === 0 || targetObject === 1) {
  3529. const encoder = targetObject === 0 ? this._renderEncoder : this._renderTargetEncoder;
  3530. encoder.pushDebugGroup(groupName);
  3531. } else if (this._currentRenderPass) {
  3532. this._currentRenderPass.pushDebugGroup(groupName);
  3533. } else {
  3534. this._pendingDebugCommands.push(["push", groupName]);
  3535. }
  3536. }
  3537. /** @hidden */
  3538. public _debugPopGroup(targetObject?: number): void {
  3539. if (!this._options.enableGPUDebugMarkers) {
  3540. return;
  3541. }
  3542. if (targetObject === 0 || targetObject === 1) {
  3543. const encoder = targetObject === 0 ? this._renderEncoder : this._renderTargetEncoder;
  3544. encoder.popDebugGroup();
  3545. } else if (this._currentRenderPass) {
  3546. this._currentRenderPass.popDebugGroup();
  3547. } else {
  3548. this._pendingDebugCommands.push(["pop", null]);
  3549. }
  3550. }
  3551. /** @hidden */
  3552. public _debugInsertMarker(text: string, targetObject?: number): void {
  3553. if (!this._options.enableGPUDebugMarkers) {
  3554. return;
  3555. }
  3556. if (targetObject === 0 || targetObject === 1) {
  3557. const encoder = targetObject === 0 ? this._renderEncoder : this._renderTargetEncoder;
  3558. encoder.insertDebugMarker(text);
  3559. } else if (this._currentRenderPass) {
  3560. this._currentRenderPass.insertDebugMarker(text);
  3561. } else {
  3562. this._pendingDebugCommands.push(["insert", text]);
  3563. }
  3564. }
  3565. private _debugFlushPendingCommands(): void {
  3566. for (let i = 0; i < this._pendingDebugCommands.length; ++i) {
  3567. const [name, param] = this._pendingDebugCommands[i];
  3568. switch (name) {
  3569. case "push":
  3570. this._debugPushGroup(param!);
  3571. break;
  3572. case "pop":
  3573. this._debugPopGroup();
  3574. break;
  3575. case "insert":
  3576. this._debugInsertMarker(param!);
  3577. break;
  3578. }
  3579. }
  3580. this._pendingDebugCommands.length = 0;
  3581. }
  3582. //------------------------------------------------------------------------------
  3583. // Errors
  3584. //------------------------------------------------------------------------------
  3585. /**
  3586. * Get the current error code of the WebGPU context
  3587. * @returns the error code
  3588. */
  3589. public getError(): number {
  3590. // TODO WEBGPU. from the webgpu errors.
  3591. return 0;
  3592. }
  3593. //------------------------------------------------------------------------------
  3594. // Unused WebGPU
  3595. //------------------------------------------------------------------------------
  3596. /** @hidden */
  3597. public bindSamplers(effect: Effect): void { }
  3598. /** @hidden */
  3599. public _bindTextureDirectly(target: number, texture: InternalTexture, forTextureDataUpdate = false, force = false): boolean {
  3600. return false;
  3601. }
  3602. /** @hidden */
  3603. public _releaseFramebufferObjects(texture: InternalTexture): void { }
  3604. /** @hidden */
  3605. public applyStates() { }
  3606. /**
  3607. * Gets a boolean indicating if all created effects are ready
  3608. * @returns always true - No parallel shader compilation
  3609. */
  3610. public areAllEffectsReady(): boolean {
  3611. return true;
  3612. }
  3613. /** @hidden */
  3614. public _executeWhenRenderingStateIsCompiled(pipelineContext: IPipelineContext, action: () => void) {
  3615. // No parallel shader compilation.
  3616. // No Async, so direct launch
  3617. action();
  3618. }
  3619. /** @hidden */
  3620. public _isRenderingStateCompiled(pipelineContext: IPipelineContext): boolean {
  3621. // No parallel shader compilation.
  3622. return true;
  3623. }
  3624. /** @hidden */
  3625. public _getUnpackAlignement(): number {
  3626. return 1;
  3627. }
  3628. /** @hidden */
  3629. public _unpackFlipY(value: boolean) { }
  3630. // TODO WEBGPU. All of the below should go once engine split with baseEngine.
  3631. /** @hidden */
  3632. public _getSamplingParameters(samplingMode: number, generateMipMaps: boolean): { min: number; mag: number } {
  3633. throw "_getSamplingParameters is not available in WebGPU";
  3634. }
  3635. /** @hidden */
  3636. public bindUniformBlock(pipelineContext: IPipelineContext, blockName: string, index: number): void {
  3637. }
  3638. /** @hidden */
  3639. public getUniforms(pipelineContext: IPipelineContext, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  3640. return [];
  3641. }
  3642. /** @hidden */
  3643. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): boolean {
  3644. return false;
  3645. }
  3646. /** @hidden */
  3647. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): boolean {
  3648. return false;
  3649. }
  3650. /** @hidden */
  3651. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): boolean {
  3652. return false;
  3653. }
  3654. /** @hidden */
  3655. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): boolean {
  3656. return false;
  3657. }
  3658. /** @hidden */
  3659. public setArray(uniform: WebGLUniformLocation, array: number[]): boolean {
  3660. return false;
  3661. }
  3662. /** @hidden */
  3663. public setArray2(uniform: WebGLUniformLocation, array: number[]): boolean {
  3664. return false;
  3665. }
  3666. /** @hidden */
  3667. public setArray3(uniform: WebGLUniformLocation, array: number[]): boolean {
  3668. return false;
  3669. }
  3670. /** @hidden */
  3671. public setArray4(uniform: WebGLUniformLocation, array: number[]): boolean {
  3672. return false;
  3673. }
  3674. /** @hidden */
  3675. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): boolean {
  3676. return false;
  3677. }
  3678. /** @hidden */
  3679. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): boolean {
  3680. return false;
  3681. }
  3682. /** @hidden */
  3683. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): boolean {
  3684. return false;
  3685. }
  3686. /** @hidden */
  3687. public setFloat(uniform: WebGLUniformLocation, value: number): boolean {
  3688. return false;
  3689. }
  3690. /** @hidden */
  3691. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): boolean {
  3692. return false;
  3693. }
  3694. /** @hidden */
  3695. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): boolean {
  3696. return false;
  3697. }
  3698. /** @hidden */
  3699. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): boolean {
  3700. return false;
  3701. }
  3702. }
  3703. /** @hidden */
  3704. function _convertRGBtoRGBATextureData(rgbData: any, width: number, height: number, textureType: number): ArrayBufferView {
  3705. // Create new RGBA data container.
  3706. var rgbaData: any;
  3707. if (textureType === Constants.TEXTURETYPE_FLOAT) {
  3708. rgbaData = new Float32Array(width * height * 4);
  3709. }
  3710. else {
  3711. rgbaData = new Uint32Array(width * height * 4);
  3712. }
  3713. // Convert each pixel.
  3714. for (let x = 0; x < width; x++) {
  3715. for (let y = 0; y < height; y++) {
  3716. let index = (y * width + x) * 3;
  3717. let newIndex = (y * width + x) * 4;
  3718. // Map Old Value to new value.
  3719. rgbaData[newIndex + 0] = rgbData[index + 0];
  3720. rgbaData[newIndex + 1] = rgbData[index + 1];
  3721. rgbaData[newIndex + 2] = rgbData[index + 2];
  3722. // Add fully opaque alpha channel.
  3723. rgbaData[newIndex + 3] = 1;
  3724. }
  3725. }
  3726. return rgbaData;
  3727. }