webgpuEngine.ts 168 KB

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