webgpuEngine.ts 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460
  1. import { Logger } from "../Misc/logger";
  2. import { Nullable, DataArray, IndicesArray, FloatArray } from "../types";
  3. import { Scene } from "../scene";
  4. import { Matrix, Color3, Color4 } from "../Maths/math";
  5. import { Scalar } from "../Maths/math.scalar";
  6. import { Engine, EngineCapabilities, InstancingAttributeInfo } from "../Engines/engine";
  7. import { RenderTargetCreationOptions } from "../Materials/Textures/renderTargetCreationOptions";
  8. import { InternalTexture } from "../Materials/Textures/internalTexture";
  9. import { EffectCreationOptions, EffectFallbacks, Effect } from "../Materials/effect";
  10. import { _TimeToken } from "../Instrumentation/timeToken";
  11. import { _DepthCullingState, _StencilState, _AlphaState } from "../States/index";
  12. import { Constants } from "./constants";
  13. import { WebGPUConstants } from "./WebGPU/webgpuConstants";
  14. import { VertexBuffer } from "../Meshes/buffer";
  15. import { WebGPUPipelineContext, IWebGPUPipelineContextVertexInputsCache } from './WebGPU/webgpuPipelineContext';
  16. import { IPipelineContext } from './IPipelineContext';
  17. import { DataBuffer } from '../Meshes/dataBuffer';
  18. import { WebGPUDataBuffer } from '../Meshes/WebGPU/webgpuDataBuffer';
  19. import { IInternalTextureLoader } from "../Materials/Textures/internalTextureLoader";
  20. import { BaseTexture } from "../Materials/Textures/baseTexture";
  21. import { IShaderProcessor } from "./Processors/iShaderProcessor";
  22. import { WebGPUShaderProcessor } from "./WebGPU/webgpuShaderProcessors";
  23. import { ShaderProcessingContext } from "./Processors/shaderProcessingOptions";
  24. import { WebGPUShaderProcessingContext } from "./WebGPU/webgpuShaderProcessingContext";
  25. /**
  26. * Options to create the WebGPU engine
  27. */
  28. export interface WebGPUEngineOptions extends GPURequestAdapterOptions {
  29. /**
  30. * If delta time between frames should be constant
  31. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  32. */
  33. deterministicLockstep?: boolean;
  34. /**
  35. * Maximum about of steps between frames (Default: 4)
  36. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  37. */
  38. lockstepMaxSteps?: number;
  39. /**
  40. * Defines that engine should ignore modifying touch action attribute and style
  41. * If not handle, you might need to set it up on your side for expected touch devices behavior.
  42. */
  43. doNotHandleTouchAction?: boolean;
  44. /**
  45. * Defines if webaudio should be initialized as well
  46. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  47. */
  48. audioEngine?: boolean;
  49. /**
  50. * Defines the category of adapter to use.
  51. * Is it the discrete or integrated device.
  52. */
  53. powerPreference?: GPUPowerPreference;
  54. /**
  55. * Defines the device descriptor used to create a device.
  56. */
  57. deviceDescriptor?: GPUDeviceDescriptor;
  58. /**
  59. * Defines the requested Swap Chain Format.
  60. */
  61. swapChainFormat?: GPUTextureFormat;
  62. }
  63. /**
  64. * The web GPU engine class provides support for WebGPU version of babylon.js.
  65. */
  66. export class WebGPUEngine extends Engine {
  67. // Page Life cycle and constants
  68. private readonly _uploadEncoderDescriptor = { label: "upload" };
  69. private readonly _renderEncoderDescriptor = { label: "render" };
  70. private readonly _blitDescriptor = { label: "upload" };
  71. private readonly _clearDepthValue = 1;
  72. private readonly _clearStencilValue = 0;
  73. private readonly _defaultSampleCount = 1;
  74. // Engine Life Cycle
  75. private _canvas: HTMLCanvasElement;
  76. private _options: WebGPUEngineOptions;
  77. private _shaderc: any = null;
  78. private _adapter: GPUAdapter;
  79. private _device: GPUDevice;
  80. private _context: GPUCanvasContext;
  81. private _swapChain: GPUSwapChain;
  82. // Some of the internal state might change during the render pass.
  83. // This happens mainly during clear for the state
  84. // And when the frame starts to swap the target texture from the swap chain
  85. private _mainTexture: GPUTexture;
  86. private _depthTexture: GPUTexture;
  87. private _mainTextureCopyView: GPUTextureCopyView;
  88. private _mainColorAttachments: GPURenderPassColorAttachmentDescriptor[];
  89. private _mainTextureExtends: GPUExtent3D;
  90. private _mainDepthAttachment: GPURenderPassDepthStencilAttachmentDescriptor;
  91. // Frame Life Cycle (recreated each frame)
  92. private _uploadEncoder: GPUCommandEncoder;
  93. private _renderEncoder: GPUCommandEncoder;
  94. private _blitEncoder: GPUCommandEncoder;
  95. private _commandBuffers: GPUCommandBuffer[] = [null as any, null as any];
  96. // Frame Buffer Life Cycle (recreated for each render target pass)
  97. private _currentRenderPass: Nullable<GPURenderPassEncoder> = null;
  98. // DrawCall Life Cycle
  99. // Effect is on the parent class
  100. // protected _currentEffect: Nullable<Effect> = null;
  101. private _currentVertexBuffers: Nullable<{ [key: string]: Nullable<VertexBuffer> }> = null;
  102. private _currentIndexBuffer: Nullable<DataBuffer> = null;
  103. private __colorWrite = true;
  104. private _uniformsBuffers: { [name: string]: WebGPUDataBuffer } = {};
  105. // Caches
  106. private _compiledShaders: { [key: string]: {
  107. stages: GPURenderPipelineStageDescriptor,
  108. availableAttributes: { [key: string]: number },
  109. availableUBOs: { [key: string]: { setIndex: number, bindingIndex: number} },
  110. availableSamplers: { [key: string]: { setIndex: number, bindingIndex: number} },
  111. orderedAttributes: string[],
  112. orderedUBOsAndSamplers: { name: string, isSampler: boolean }[][],
  113. leftOverUniforms: { name: string, type: string, length: number }[],
  114. leftOverUniformsByName: { [name: string]: string },
  115. sources: {
  116. vertex: string
  117. fragment: string,
  118. }
  119. } } = {};
  120. // TODO WEBGPU. Texture Management. Temporary...
  121. private _decodeCanvas = document.createElement("canvas");
  122. private _decodeEngine = new Engine(this._decodeCanvas, false, {
  123. alpha: true,
  124. premultipliedAlpha: false,
  125. }, false);
  126. /**
  127. * Gets a boolean indicating that the engine supports uniform buffers
  128. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  129. */
  130. public get supportsUniformBuffers(): boolean {
  131. return true;
  132. }
  133. /**
  134. * Create a new instance of the gpu engine.
  135. * @param canvas Defines the canvas to use to display the result
  136. * @param options Defines the options passed to the engine to create the GPU context dependencies
  137. */
  138. public constructor(canvas: HTMLCanvasElement, options: WebGPUEngineOptions = {}) {
  139. super(null);
  140. options.deviceDescriptor = options.deviceDescriptor || { };
  141. options.swapChainFormat = options.swapChainFormat || WebGPUConstants.GPUTextureFormat_bgra8unorm;
  142. this._decodeEngine.getCaps().textureFloat = false;
  143. this._decodeEngine.getCaps().textureFloatRender = false;
  144. this._decodeEngine.getCaps().textureHalfFloat = false;
  145. this._decodeEngine.getCaps().textureHalfFloatRender = false;
  146. Logger.Log(`Babylon.js v${Engine.Version} - WebGPU engine`);
  147. if (!navigator.gpu) {
  148. // TODO WEBGPU Fall back to webgl.
  149. Logger.Error("WebGPU is not supported by your browser.");
  150. return;
  151. }
  152. this._isWebGPU = true;
  153. this._shaderPlatformName = "WEBGPU";
  154. if (options.deterministicLockstep === undefined) {
  155. options.deterministicLockstep = false;
  156. }
  157. if (options.lockstepMaxSteps === undefined) {
  158. options.lockstepMaxSteps = 4;
  159. }
  160. if (options.audioEngine === undefined) {
  161. options.audioEngine = true;
  162. }
  163. this._deterministicLockstep = options.deterministicLockstep;
  164. this._lockstepMaxSteps = options.lockstepMaxSteps;
  165. this._doNotHandleContextLost = true;
  166. this._canvas = canvas;
  167. this._options = options;
  168. // TODO WEBGPU. RESIZE and SCALING.
  169. this._hardwareScalingLevel = 1;
  170. this._sharedInit(canvas, !!options.doNotHandleTouchAction, options.audioEngine);
  171. }
  172. //------------------------------------------------------------------------------
  173. // Initialization
  174. //------------------------------------------------------------------------------
  175. /**
  176. * Initializes the WebGPU context and dependencies.
  177. * @param shadercOptions Defines the ShaderC compiler options if necessary
  178. * @returns a promise notifying the readiness of the engine.
  179. */
  180. public initEngineAsync(shadercOptions: any = null): Promise<void> {
  181. // TODO WEBGPU. Rename to initAsync.
  182. return (window as any).Shaderc(shadercOptions)
  183. .then((shaderc: any) => {
  184. this._shaderc = shaderc;
  185. return navigator.gpu!.requestAdapter(this._options);
  186. })
  187. .then((adapter: GPUAdapter) => {
  188. this._adapter = adapter;
  189. return this._adapter.requestDevice(this._options.deviceDescriptor);
  190. })
  191. .then((device: GPUDevice) => this._device = device)
  192. .then(() => {
  193. this._initializeLimits();
  194. this._initializeContextAndSwapChain();
  195. // this._initializeMainAttachments();
  196. // Initialization is in the resize :-)
  197. this.resize();
  198. })
  199. .catch((e: any) => {
  200. Logger.Error("Can not create WebGPU Device and/or context.");
  201. Logger.Error(e);
  202. });
  203. }
  204. private _initializeLimits(): void {
  205. // Init caps
  206. // TODO WEBGPU Real Capability check once limits will be working.
  207. this._caps = new EngineCapabilities();
  208. this._caps.maxTexturesImageUnits = 16;
  209. this._caps.maxVertexTextureImageUnits = 16;
  210. this._caps.maxTextureSize = 2048;
  211. this._caps.maxCubemapTextureSize = 2048;
  212. this._caps.maxRenderTextureSize = 2048;
  213. this._caps.maxVertexAttribs = 16;
  214. this._caps.maxVaryingVectors = 16;
  215. this._caps.maxFragmentUniformVectors = 1024;
  216. this._caps.maxVertexUniformVectors = 1024;
  217. // Extensions
  218. this._caps.standardDerivatives = true;
  219. this._caps.astc = null;
  220. this._caps.s3tc = null;
  221. this._caps.pvrtc = null;
  222. this._caps.etc1 = null;
  223. this._caps.etc2 = null;
  224. this._caps.textureAnisotropicFilterExtension = null;
  225. this._caps.maxAnisotropy = 0;
  226. this._caps.uintIndices = true;
  227. this._caps.fragmentDepthSupported = false;
  228. this._caps.highPrecisionShaderSupported = true;
  229. this._caps.colorBufferFloat = true;
  230. this._caps.textureFloat = false;
  231. this._caps.textureFloatLinearFiltering = false;
  232. this._caps.textureFloatRender = false;
  233. this._caps.textureHalfFloat = false;
  234. this._caps.textureHalfFloatLinearFiltering = false;
  235. this._caps.textureHalfFloatRender = false;
  236. this._caps.textureLOD = true;
  237. this._caps.drawBuffersExtension = true;
  238. this._caps.depthTextureExtension = true;
  239. // TODO WEBGPU. No need here but could be use to create descriptors ???
  240. this._caps.vertexArrayObject = false;
  241. this._caps.instancedArrays = true;
  242. // TODO WEBGPU. Unused for now.
  243. // this._caps.parallelShaderCompile = null;
  244. }
  245. private _initializeContextAndSwapChain(): void {
  246. this._context = this._canvas.getContext('gpupresent') as unknown as GPUCanvasContext;
  247. this._swapChain = this._context.configureSwapChain({
  248. device: this._device,
  249. format: this._options.swapChainFormat!,
  250. usage: WebGPUConstants.GPUTextureUsage_TRANSFER_DST,
  251. });
  252. }
  253. // Set default values as WebGL with depth and stencil attachment for the broadest Compat.
  254. // TODO WEBGPU. Reinit on resize.
  255. private _initializeMainAttachments(): void {
  256. this._mainTextureExtends = {
  257. width: this.getRenderWidth(),
  258. height: this.getRenderHeight(),
  259. depth: 1
  260. };
  261. const mainTextureDescriptor = {
  262. size: this._mainTextureExtends,
  263. arrayLayerCount: 1,
  264. mipLevelCount: 1,
  265. sampleCount: this._defaultSampleCount,
  266. dimension: WebGPUConstants.GPUTextureDimension_2d,
  267. format: WebGPUConstants.GPUTextureFormat_bgra8unorm,
  268. usage: WebGPUConstants.GPUTextureUsage_OUTPUT_ATTACHMENT | WebGPUConstants.GPUTextureUsage_TRANSFER_SRC,
  269. };
  270. if (this._mainTexture) {
  271. this._mainTexture.destroy();
  272. }
  273. this._mainTexture = this._device.createTexture(mainTextureDescriptor);
  274. const mainTextureView = this._mainTexture.createDefaultView();
  275. this._mainTextureCopyView = {
  276. texture: this._mainTexture,
  277. origin: {
  278. x: 0,
  279. y: 0,
  280. z: 0
  281. },
  282. mipLevel: 0,
  283. arrayLayer: 0,
  284. };
  285. this._mainColorAttachments = [{
  286. attachment: mainTextureView,
  287. loadValue: new Color4(0, 0, 0, 1),
  288. storeOp: WebGPUConstants.GPUStoreOp_store
  289. }];
  290. const depthTextureDescriptor = {
  291. size: this._mainTextureExtends,
  292. arrayLayerCount: 1,
  293. mipLevelCount: 1,
  294. sampleCount: this._defaultSampleCount,
  295. dimension: WebGPUConstants.GPUTextureDimension_2d,
  296. format: WebGPUConstants.GPUTextureFormat_depth24plusStencil8,
  297. usage: WebGPUConstants.GPUTextureUsage_OUTPUT_ATTACHMENT
  298. };
  299. if (this._depthTexture) {
  300. this._depthTexture.destroy();
  301. }
  302. this._depthTexture = this._device.createTexture(depthTextureDescriptor);
  303. this._mainDepthAttachment = {
  304. attachment: this._depthTexture.createDefaultView(),
  305. depthLoadValue: this._clearDepthValue,
  306. depthStoreOp: WebGPUConstants.GPUStoreOp_store,
  307. stencilLoadValue: this._clearStencilValue,
  308. stencilStoreOp: WebGPUConstants.GPUStoreOp_store,
  309. };
  310. }
  311. /**
  312. * Gets a shader processor implementation fitting with the current engine type.
  313. * @returns The shader processor implementation.
  314. */
  315. protected _getShaderProcessor(): Nullable<IShaderProcessor> {
  316. return new WebGPUShaderProcessor();
  317. }
  318. /** @hidden */
  319. public _getShaderProcessingContext(): Nullable<ShaderProcessingContext> {
  320. return new WebGPUShaderProcessingContext();
  321. }
  322. //------------------------------------------------------------------------------
  323. // Static Pipeline WebGPU States
  324. //------------------------------------------------------------------------------
  325. public wipeCaches(bruteForce?: boolean): void {
  326. if (this.preventCacheWipeBetweenFrames) {
  327. return;
  328. }
  329. this.resetTextureCache();
  330. this._currentEffect = null;
  331. this._currentIndexBuffer = null;
  332. this._currentVertexBuffers = null;
  333. if (bruteForce) {
  334. this._currentProgram = null;
  335. this._stencilState.reset();
  336. this._depthCullingState.reset();
  337. this._alphaState.reset();
  338. }
  339. this._cachedVertexBuffers = null;
  340. this._cachedIndexBuffer = null;
  341. this._cachedEffectForVertexBuffers = null;
  342. }
  343. public setColorWrite(enable: boolean): void {
  344. this.__colorWrite = enable;
  345. }
  346. public getColorWrite(): boolean {
  347. return this.__colorWrite;
  348. }
  349. //------------------------------------------------------------------------------
  350. // Dynamic WebGPU States
  351. //------------------------------------------------------------------------------
  352. public _viewport(x: number, y: number, width: number, height: number): void {
  353. // TODO WEBGPU. Cache.
  354. // if (x !== this._viewportCached.x ||
  355. // y !== this._viewportCached.y ||
  356. // width !== this._viewportCached.z ||
  357. // height !== this._viewportCached.w) {
  358. // this._viewportCached.x = x;
  359. // this._viewportCached.y = y;
  360. // this._viewportCached.z = width;
  361. // this._viewportCached.w = height;
  362. // this._gl.viewport(x, y, width, height);
  363. // }
  364. if (!this._currentRenderPass) {
  365. this._startMainRenderPass();
  366. }
  367. // TODO WEBGPU. Viewport.
  368. // Use 0 1 like the default webgl values.
  369. // this._currentRenderPass!.setViewport(x, y, width, height, 0, 1);
  370. }
  371. public enableScissor(x: number, y: number, width: number, height: number): void {
  372. if (!this._currentRenderPass) {
  373. this._startMainRenderPass();
  374. }
  375. // TODO WEBGPU. Scissor.
  376. //this._currentRenderPass!.setScissorRect(x, y, width, height);
  377. }
  378. public disableScissor() {
  379. if (!this._currentRenderPass) {
  380. this._startMainRenderPass();
  381. }
  382. // TODO WEBGPU. Scissor.
  383. //this._currentRenderPass!.setScissorRect(0, 0, this.getRenderWidth(), this.getRenderHeight());
  384. }
  385. public clear(color: Color4, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  386. this._mainColorAttachments[0].loadValue = backBuffer ? color : WebGPUConstants.GPULoadOp_load;
  387. this._mainDepthAttachment.depthLoadValue = depth ? this._clearDepthValue : WebGPUConstants.GPULoadOp_load;
  388. this._mainDepthAttachment.stencilLoadValue = stencil ? this._clearStencilValue : WebGPUConstants.GPULoadOp_load;
  389. // TODO WEBGPU. Where to store GPUOpStore ???
  390. // TODO WEBGPU. Should be main or rtt with a frame buffer like object.
  391. this._startMainRenderPass();
  392. }
  393. //------------------------------------------------------------------------------
  394. // WebGPU Buffers
  395. //------------------------------------------------------------------------------
  396. private _createBuffer(view: ArrayBufferView, flags: GPUBufferUsageFlags): DataBuffer {
  397. const padding = view.byteLength % 4;
  398. const verticesBufferDescriptor = {
  399. size: view.byteLength + padding,
  400. usage: flags
  401. };
  402. const buffer = this._device.createBuffer(verticesBufferDescriptor);
  403. const dataBuffer = new WebGPUDataBuffer(buffer);
  404. dataBuffer.references = 1;
  405. dataBuffer.capacity = view.byteLength;
  406. this._setSubData(dataBuffer, 0, view);
  407. return dataBuffer;
  408. }
  409. private _setSubData(dataBuffer: WebGPUDataBuffer, dstByteOffset: number, src: ArrayBufferView, srcByteOffset = 0, byteLength = 0): void {
  410. const buffer = dataBuffer.underlyingResource as GPUBuffer;
  411. byteLength = byteLength || src.byteLength;
  412. byteLength = Math.min(byteLength, dataBuffer.capacity - dstByteOffset);
  413. // After Migration to Canary
  414. // This would do from PR #261
  415. let chunkStart = src.byteOffset + srcByteOffset;
  416. let chunkEnd = chunkStart + byteLength;
  417. // 4 bytes alignments for upload
  418. const padding = byteLength % 4;
  419. if (padding !== 0) {
  420. const tempView = new Uint8Array(src.buffer.slice(chunkStart, chunkEnd));
  421. src = new Uint8Array(byteLength + padding);
  422. tempView.forEach((element, index) => {
  423. (src as Uint8Array)[index] = element;
  424. });
  425. srcByteOffset = 0;
  426. chunkStart = 0;
  427. chunkEnd = byteLength + padding;
  428. byteLength = byteLength + padding;
  429. }
  430. // Chunk
  431. const maxChunk = 1024 * 1024 * 15;
  432. let offset = 0;
  433. while ((chunkEnd - (chunkStart + offset)) > maxChunk) {
  434. // TODO WEBGPU.
  435. // Deprecated soon to be removed... replace by mappedBuffers
  436. buffer.setSubData(dstByteOffset + offset, src, srcByteOffset + offset, maxChunk);
  437. offset += maxChunk;
  438. }
  439. // TODO WEBGPU.
  440. // Deprecated soon to be removed... replace by mappedBuffers
  441. buffer.setSubData(dstByteOffset + offset, src, srcByteOffset + offset, byteLength - offset);
  442. }
  443. //------------------------------------------------------------------------------
  444. // Vertex/Index Buffers
  445. //------------------------------------------------------------------------------
  446. public createVertexBuffer(data: DataArray): DataBuffer {
  447. let view: ArrayBufferView;
  448. if (data instanceof Array) {
  449. view = new Float32Array(data);
  450. }
  451. else if (data instanceof ArrayBuffer) {
  452. view = new Uint8Array(data);
  453. }
  454. else {
  455. view = data;
  456. }
  457. const dataBuffer = this._createBuffer(view, WebGPUConstants.GPUBufferUsage_VERTEX | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  458. return dataBuffer;
  459. }
  460. public createDynamicVertexBuffer(data: DataArray): DataBuffer {
  461. // TODO WEBGPU.
  462. return this.createVertexBuffer(data);
  463. }
  464. public updateDynamicVertexBuffer(vertexBuffer: DataBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  465. const dataBuffer = vertexBuffer as WebGPUDataBuffer;
  466. if (byteOffset === undefined) {
  467. byteOffset = 0;
  468. }
  469. let view: ArrayBufferView;
  470. if (byteLength === undefined) {
  471. if (data instanceof Array) {
  472. view = new Float32Array(data);
  473. }
  474. else if (data instanceof ArrayBuffer) {
  475. view = new Uint8Array(data);
  476. }
  477. else {
  478. view = data;
  479. }
  480. byteLength = view.byteLength;
  481. } else {
  482. if (data instanceof Array) {
  483. view = new Float32Array(data);
  484. }
  485. else if (data instanceof ArrayBuffer) {
  486. view = new Uint8Array(data);
  487. }
  488. else {
  489. view = data;
  490. }
  491. }
  492. this._setSubData(dataBuffer, byteOffset, view, 0, byteLength);
  493. }
  494. public createIndexBuffer(data: IndicesArray): DataBuffer {
  495. let is32Bits = true;
  496. let view: ArrayBufferView;
  497. if (data instanceof Uint32Array || data instanceof Int32Array) {
  498. view = data;
  499. }
  500. else if (data instanceof Uint16Array) {
  501. view = data;
  502. is32Bits = false;
  503. }
  504. else {
  505. if (data.length > 65535) {
  506. view = new Uint32Array(data);
  507. }
  508. else {
  509. view = new Uint16Array(data);
  510. is32Bits = false;
  511. }
  512. }
  513. const dataBuffer = this._createBuffer(view, WebGPUConstants.GPUBufferUsage_INDEX | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  514. dataBuffer.is32Bits = is32Bits;
  515. return dataBuffer;
  516. }
  517. public updateDynamicIndexBuffer(indexBuffer: DataBuffer, indices: IndicesArray, offset: number = 0): void {
  518. const gpuBuffer = indexBuffer as WebGPUDataBuffer;
  519. // TODO WEBGPU. Manage buffer morphing from small int to bigint.
  520. var view: ArrayBufferView;
  521. if (indices instanceof Uint16Array) {
  522. if (indexBuffer.is32Bits) {
  523. view = Uint32Array.from(indices);
  524. }
  525. else {
  526. view = indices;
  527. }
  528. }
  529. else if (indices instanceof Uint32Array) {
  530. if (indexBuffer.is32Bits) {
  531. view = indices;
  532. }
  533. else {
  534. view = Uint16Array.from(indices);
  535. }
  536. }
  537. else {
  538. if (indexBuffer.is32Bits) {
  539. view = new Uint32Array(indices);
  540. }
  541. else {
  542. view = new Uint16Array(indices);
  543. }
  544. }
  545. // TODO WEBGPU. check if offset is in bytes ???
  546. this._setSubData(gpuBuffer, offset, view);
  547. }
  548. public bindBuffersDirectly(vertexBuffer: DataBuffer, indexBuffer: DataBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  549. throw "Not implemented on WebGPU so far.";
  550. }
  551. public updateAndBindInstancesBuffer(instancesBuffer: DataBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  552. throw "Not implemented on WebGPU so far.";
  553. }
  554. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<DataBuffer>, effect: Effect): void {
  555. this._currentIndexBuffer = indexBuffer;
  556. this._currentVertexBuffers = vertexBuffers;
  557. }
  558. /** @hidden */
  559. public _releaseBuffer(buffer: DataBuffer): boolean {
  560. buffer.references--;
  561. if (buffer.references === 0) {
  562. (buffer.underlyingResource as GPUBuffer).destroy();
  563. return true;
  564. }
  565. return false;
  566. }
  567. //------------------------------------------------------------------------------
  568. // UBO
  569. //------------------------------------------------------------------------------
  570. public createUniformBuffer(elements: FloatArray): DataBuffer {
  571. let view: Float32Array;
  572. if (elements instanceof Array) {
  573. view = new Float32Array(elements);
  574. }
  575. else {
  576. view = elements;
  577. }
  578. const dataBuffer = this._createBuffer(view, WebGPUConstants.GPUBufferUsage_UNIFORM | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  579. return dataBuffer;
  580. }
  581. public createDynamicUniformBuffer(elements: FloatArray): DataBuffer {
  582. // TODO WEBGPU. Implement dynamic buffers.
  583. return this.createUniformBuffer(elements);
  584. }
  585. public updateUniformBuffer(uniformBuffer: DataBuffer, elements: FloatArray, offset?: number, count?: number): void {
  586. if (offset === undefined) {
  587. offset = 0;
  588. }
  589. const dataBuffer = uniformBuffer as WebGPUDataBuffer;
  590. let view: Float32Array;
  591. if (count === undefined) {
  592. if (elements instanceof Float32Array) {
  593. view = elements;
  594. } else {
  595. view = new Float32Array(elements);
  596. }
  597. count = view.byteLength;
  598. } else {
  599. if (elements instanceof Float32Array) {
  600. view = elements;
  601. } else {
  602. view = new Float32Array(elements);
  603. }
  604. }
  605. // TODO WEBGPU. Check count and offset are in bytes.
  606. this._setSubData(dataBuffer, offset, view, 0, count);
  607. }
  608. public bindUniformBufferBase(buffer: DataBuffer, location: number, name: string): void {
  609. this._uniformsBuffers[name] = buffer as WebGPUDataBuffer;
  610. }
  611. //------------------------------------------------------------------------------
  612. // Effects
  613. //------------------------------------------------------------------------------
  614. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  615. onCompiled?: Nullable<(effect: Effect) => void>, onError?: Nullable<(effect: Effect, errors: string) => void>, indexParameters?: any): Effect {
  616. const vertex = baseName.vertexElement || baseName.vertex || baseName;
  617. const fragment = baseName.fragmentElement || baseName.fragment || baseName;
  618. const name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  619. const shader = this._compiledShaders[name];
  620. if (shader) {
  621. return new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name, shader.sources);
  622. }
  623. else {
  624. return new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name);
  625. }
  626. }
  627. private _compileRawShaderToSpirV(source: string, type: string): Uint32Array {
  628. const Shaderc = this._shaderc;
  629. const compiler = new Shaderc.Compiler();
  630. const opts = new Shaderc.CompileOptions();
  631. const result = compiler.CompileGlslToSpv(source,
  632. type === "fragment" ? Shaderc.shader_kind.fragment :
  633. type === "vertex" ? Shaderc.shader_kind.vertex :
  634. type === "compute" ? Shaderc.shader_kind.compute : null,
  635. "tempCompilation.glsl", "main", opts);
  636. const error = result.GetErrorMessage();
  637. if (error) {
  638. Logger.Error(error);
  639. throw new Error("Something went wrong while compile the shader.");
  640. }
  641. return result.GetBinary().slice();
  642. }
  643. private _compileShaderToSpirV(source: string, type: string, defines: Nullable<string>, shaderVersion: string): Uint32Array {
  644. return this._compileRawShaderToSpirV(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  645. }
  646. private _createPipelineStageDescriptor(vertexShader: Uint32Array, fragmentShader: Uint32Array): GPURenderPipelineStageDescriptor {
  647. return {
  648. vertexStage: {
  649. module: this._device.createShaderModule({
  650. code: vertexShader,
  651. }),
  652. entryPoint: "main",
  653. },
  654. fragmentStage: {
  655. module: this._device.createShaderModule({
  656. code: fragmentShader,
  657. }),
  658. entryPoint: "main"
  659. }
  660. };
  661. }
  662. private _compileRawPipelineStageDescriptor(vertexCode: string, fragmentCode: string): GPURenderPipelineStageDescriptor {
  663. var vertexShader = this._compileRawShaderToSpirV(vertexCode, "vertex");
  664. var fragmentShader = this._compileRawShaderToSpirV(fragmentCode, "fragment");
  665. return this._createPipelineStageDescriptor(vertexShader, fragmentShader);
  666. }
  667. private _compilePipelineStageDescriptor(vertexCode: string, fragmentCode: string, defines: Nullable<string>): GPURenderPipelineStageDescriptor {
  668. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  669. var shaderVersion = "#version 450\n";
  670. var vertexShader = this._compileShaderToSpirV(vertexCode, "vertex", defines, shaderVersion);
  671. var fragmentShader = this._compileShaderToSpirV(fragmentCode, "fragment", defines, shaderVersion);
  672. let program = this._createPipelineStageDescriptor(vertexShader, fragmentShader);
  673. this.onAfterShaderCompilationObservable.notifyObservers(this);
  674. return program;
  675. }
  676. public createRawShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  677. throw "Not available on WebGPU";
  678. }
  679. public createShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  680. throw "Not available on WebGPU";
  681. }
  682. public createPipelineContext(shaderProcessingContext: Nullable<ShaderProcessingContext>): IPipelineContext {
  683. var pipelineContext = new WebGPUPipelineContext(shaderProcessingContext! as WebGPUShaderProcessingContext, this);
  684. pipelineContext.engine = this;
  685. return pipelineContext;
  686. }
  687. /** @hidden */
  688. public _preparePipelineContext(pipelineContext: IPipelineContext, vertexSourceCode: string, fragmentSourceCode: string, createAsRaw: boolean,
  689. rebuildRebind: any,
  690. defines: Nullable<string>,
  691. transformFeedbackVaryings: Nullable<string[]>,
  692. key: string) {
  693. const webGpuContext = pipelineContext as WebGPUPipelineContext;
  694. // TODO WEBGPU. Check if caches could be reuse from piepline ???
  695. const shader = this._compiledShaders[key];
  696. if (shader) {
  697. webGpuContext.stages = shader.stages;
  698. webGpuContext.availableAttributes = shader.availableAttributes;
  699. webGpuContext.availableUBOs = shader.availableUBOs;
  700. webGpuContext.availableSamplers = shader.availableSamplers;
  701. webGpuContext.orderedAttributes = shader.orderedAttributes;
  702. webGpuContext.orderedUBOsAndSamplers = shader.orderedUBOsAndSamplers;
  703. webGpuContext.leftOverUniforms = shader.leftOverUniforms;
  704. webGpuContext.leftOverUniformsByName = shader.leftOverUniformsByName;
  705. webGpuContext.sources = shader.sources;
  706. }
  707. else {
  708. if (createAsRaw) {
  709. webGpuContext.stages = this._compileRawPipelineStageDescriptor(vertexSourceCode, fragmentSourceCode);
  710. }
  711. else {
  712. webGpuContext.stages = this._compilePipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, defines);
  713. }
  714. this._compiledShaders[key] = {
  715. stages: webGpuContext.stages,
  716. availableAttributes: webGpuContext.availableAttributes,
  717. availableUBOs: webGpuContext.availableUBOs,
  718. availableSamplers: webGpuContext.availableSamplers,
  719. orderedAttributes: webGpuContext.orderedAttributes,
  720. orderedUBOsAndSamplers: webGpuContext.orderedUBOsAndSamplers,
  721. leftOverUniforms: webGpuContext.leftOverUniforms,
  722. leftOverUniformsByName: webGpuContext.leftOverUniformsByName,
  723. sources: {
  724. fragment: fragmentSourceCode,
  725. vertex: vertexSourceCode
  726. }
  727. };
  728. }
  729. }
  730. public getAttributes(pipelineContext: IPipelineContext, attributesNames: string[]): number[] {
  731. const results = new Array(attributesNames.length);
  732. const gpuPipelineContext = (pipelineContext as WebGPUPipelineContext);
  733. // TODO WEBGPU.
  734. // Hard coded for WebGPU until an introspection lib is available.
  735. // Should be done at processing time, not need to double the work in here.
  736. for (let i = 0; i < attributesNames.length; i++) {
  737. const attributeName = attributesNames[i];
  738. const attributeLocation = gpuPipelineContext.availableAttributes[attributeName];
  739. if (attributeLocation === undefined) {
  740. continue;
  741. }
  742. results[i] = attributeLocation;
  743. }
  744. return results;
  745. }
  746. public enableEffect(effect: Effect): void {
  747. this._currentEffect = effect;
  748. if (effect.onBind) {
  749. effect.onBind(effect);
  750. }
  751. if (effect._onBindObservable) {
  752. effect._onBindObservable.notifyObservers(effect);
  753. }
  754. }
  755. public _releaseEffect(effect: Effect): void {
  756. // Effect gets garbage collected without explicit destroy in WebGPU.
  757. }
  758. /**
  759. * 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
  760. */
  761. public releaseEffects() {
  762. // Effect gets garbage collected without explicit destroy in WebGPU.
  763. }
  764. public _deletePipelineContext(pipelineContext: IPipelineContext): void {
  765. const webgpuPipelineContext = pipelineContext as WebGPUPipelineContext;
  766. if (webgpuPipelineContext) {
  767. // TODO WEBGPU. Spector like cleanup.
  768. // TODO WEBGPU. Any pipeline required cleanup.
  769. }
  770. }
  771. //------------------------------------------------------------------------------
  772. // Textures
  773. //------------------------------------------------------------------------------
  774. // TODO WEBGPU. SHOULD not be possible to return gl unwrapped from Engine.
  775. /** @hidden */
  776. public _createTexture(): WebGLTexture {
  777. return { };
  778. }
  779. /** @hidden */
  780. public _releaseTexture(texture: InternalTexture): void {
  781. // TODO WEBGPU. check if it is all to release.
  782. if (texture._webGPUTexture) {
  783. texture._webGPUTexture.destroy();
  784. }
  785. }
  786. private _uploadMipMapsFromWebglTexture(mipMaps: number, webglEngineTexture: InternalTexture, gpuTexture: GPUTexture, width: number, height: number, face: number) {
  787. this._uploadFromWebglTexture(webglEngineTexture, gpuTexture, width, height, face);
  788. let faceWidth = width;
  789. let faceHeight = height;
  790. for (let mip = 1; mip <= mipMaps; mip++) {
  791. faceWidth = Math.max(Math.floor(faceWidth / 2), 1);
  792. faceHeight = Math.max(Math.floor(faceHeight / 2), 1);
  793. this._uploadFromWebglTexture(webglEngineTexture, gpuTexture, faceWidth, faceHeight, face, mip);
  794. }
  795. }
  796. private _uploadFromWebglTexture(webglEngineTexture: InternalTexture, gpuTexture: GPUTexture, width: number, height: number, face: number, mip: number = 0): void {
  797. let pixels = this._decodeEngine._readTexturePixels(webglEngineTexture, width, height, face, mip);
  798. if (pixels instanceof Float32Array) {
  799. const newPixels = new Uint8ClampedArray(pixels.length);
  800. pixels.forEach((value, index) => newPixels[index] = value * 255);
  801. pixels = newPixels;
  802. }
  803. const textureView: GPUTextureCopyView = {
  804. texture: gpuTexture,
  805. origin: {
  806. x: 0,
  807. y: 0,
  808. z: 0
  809. },
  810. mipLevel: mip,
  811. arrayLayer: Math.max(face, 0),
  812. };
  813. const textureExtent = {
  814. width,
  815. height,
  816. depth: 1
  817. };
  818. const commandEncoder = this._device.createCommandEncoder({});
  819. const rowPitch = Math.ceil(width * 4 / 256) * 256;
  820. let dataBuffer: DataBuffer;
  821. if (rowPitch == width * 4) {
  822. dataBuffer = this._createBuffer(pixels, WebGPUConstants.GPUBufferUsage_TRANSFER_SRC | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  823. const bufferView: GPUBufferCopyView = {
  824. buffer: dataBuffer.underlyingResource,
  825. rowPitch: rowPitch,
  826. imageHeight: height,
  827. offset: 0,
  828. };
  829. commandEncoder.copyBufferToTexture(bufferView, textureView, textureExtent);
  830. } else {
  831. const alignedPixels = new Uint8Array(rowPitch * height);
  832. let pixelsIndex = 0;
  833. for (let y = 0; y < height; ++y) {
  834. for (let x = 0; x < width; ++x) {
  835. let i = x * 4 + y * rowPitch;
  836. alignedPixels[i] = (pixels as any)[pixelsIndex];
  837. alignedPixels[i + 1] = (pixels as any)[pixelsIndex + 1];
  838. alignedPixels[i + 2] = (pixels as any)[pixelsIndex + 2];
  839. alignedPixels[i + 3] = (pixels as any)[pixelsIndex + 3];
  840. pixelsIndex += 4;
  841. }
  842. }
  843. dataBuffer = this._createBuffer(alignedPixels, WebGPUConstants.GPUBufferUsage_TRANSFER_SRC | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  844. const bufferView: GPUBufferCopyView = {
  845. buffer: dataBuffer.underlyingResource,
  846. rowPitch: rowPitch,
  847. imageHeight: height,
  848. offset: 0,
  849. };
  850. commandEncoder.copyBufferToTexture(bufferView, textureView, textureExtent);
  851. }
  852. this._device.getQueue().submit([commandEncoder.finish()]);
  853. this._releaseBuffer(dataBuffer);
  854. }
  855. private _getSamplerFilterDescriptor(internalTexture: InternalTexture): {
  856. magFilter: GPUFilterMode,
  857. minFilter: GPUFilterMode,
  858. mipmapFilter: GPUFilterMode
  859. } {
  860. let magFilter: GPUFilterMode, minFilter: GPUFilterMode, mipmapFilter: GPUFilterMode;
  861. switch (internalTexture.samplingMode) {
  862. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  863. magFilter = WebGPUConstants.GPUFilterMode_linear;
  864. minFilter = WebGPUConstants.GPUFilterMode_linear;
  865. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  866. break;
  867. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  868. magFilter = WebGPUConstants.GPUFilterMode_linear;
  869. minFilter = WebGPUConstants.GPUFilterMode_linear;
  870. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  871. break;
  872. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  873. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  874. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  875. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  876. break;
  877. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  878. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  879. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  880. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  881. break;
  882. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  883. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  884. minFilter = WebGPUConstants.GPUFilterMode_linear;
  885. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  886. break;
  887. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  888. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  889. minFilter = WebGPUConstants.GPUFilterMode_linear;
  890. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  891. break;
  892. case Engine.TEXTURE_NEAREST_LINEAR:
  893. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  894. minFilter = WebGPUConstants.GPUFilterMode_linear;
  895. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  896. break;
  897. case Engine.TEXTURE_NEAREST_NEAREST:
  898. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  899. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  900. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  901. break;
  902. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  903. magFilter = WebGPUConstants.GPUFilterMode_linear;
  904. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  905. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  906. break;
  907. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  908. magFilter = WebGPUConstants.GPUFilterMode_linear;
  909. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  910. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  911. break;
  912. case Engine.TEXTURE_LINEAR_LINEAR:
  913. magFilter = WebGPUConstants.GPUFilterMode_linear;
  914. minFilter = WebGPUConstants.GPUFilterMode_linear;
  915. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  916. break;
  917. case Engine.TEXTURE_LINEAR_NEAREST:
  918. magFilter = WebGPUConstants.GPUFilterMode_linear;
  919. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  920. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  921. break;
  922. default:
  923. magFilter = WebGPUConstants.GPUFilterMode_linear;
  924. minFilter = WebGPUConstants.GPUFilterMode_linear;
  925. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  926. break;
  927. }
  928. return {
  929. magFilter,
  930. minFilter,
  931. mipmapFilter
  932. };
  933. }
  934. private _getWrappingMode(mode: number): GPUAddressMode {
  935. switch (mode) {
  936. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  937. return WebGPUConstants.GPUAddressMode_repeat;
  938. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  939. return WebGPUConstants.GPUAddressMode_clampToEdge;
  940. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  941. return WebGPUConstants.GPUAddressMode_mirrorRepeat;
  942. }
  943. return WebGPUConstants.GPUAddressMode_repeat;
  944. }
  945. private _getSamplerWrappingDescriptor(internalTexture: InternalTexture): {
  946. addressModeU: GPUAddressMode,
  947. addressModeV: GPUAddressMode,
  948. addressModeW: GPUAddressMode
  949. } {
  950. return {
  951. addressModeU: this._getWrappingMode(internalTexture._cachedWrapU!),
  952. addressModeV: this._getWrappingMode(internalTexture._cachedWrapV!),
  953. addressModeW: this._getWrappingMode(internalTexture._cachedWrapR!),
  954. };
  955. }
  956. private _getSamplerDescriptor(internalTexture: InternalTexture): GPUSamplerDescriptor {
  957. return {
  958. ...this._getSamplerFilterDescriptor(internalTexture),
  959. ...this._getSamplerWrappingDescriptor(internalTexture),
  960. };
  961. }
  962. public createTexture(urlArg: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE, onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null, buffer: Nullable<ArrayBuffer | HTMLImageElement> = null, fallBack?: InternalTexture, format?: number): InternalTexture {
  963. const texture = new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  964. const url = String(urlArg);
  965. // TODO WEBGPU. Find a better way.
  966. // TODO WEBGPU. this._options.textureSize
  967. texture.url = url;
  968. texture.generateMipMaps = !noMipmap;
  969. texture.samplingMode = samplingMode;
  970. texture.invertY = invertY;
  971. if (format) {
  972. texture.format = format;
  973. }
  974. let webglEngineTexture: InternalTexture;
  975. const onLoadInternal = () => {
  976. texture.isReady = webglEngineTexture.isReady;
  977. const width = webglEngineTexture.width;
  978. const height = webglEngineTexture.height;
  979. texture.width = width;
  980. texture.height = height;
  981. texture.baseWidth = width;
  982. texture.baseHeight = height;
  983. texture._isRGBD = webglEngineTexture._isRGBD;
  984. texture._sphericalPolynomial = webglEngineTexture._sphericalPolynomial;
  985. let mipMaps = Scalar.Log2(Math.max(width, height));
  986. mipMaps = Math.round(mipMaps);
  987. const textureExtent = {
  988. width,
  989. height,
  990. depth: 1
  991. };
  992. const textureDescriptor: GPUTextureDescriptor = {
  993. dimension: WebGPUConstants.GPUTextureDimension_2d,
  994. format: WebGPUConstants.GPUTextureFormat_rgba8unorm,
  995. arrayLayerCount: 1,
  996. mipLevelCount: noMipmap ? 1 : mipMaps + 1,
  997. sampleCount: 1,
  998. size: textureExtent,
  999. usage: WebGPUConstants.GPUTextureUsage_TRANSFER_DST | WebGPUConstants.GPUTextureUsage_SAMPLED
  1000. };
  1001. const gpuTexture = this._device.createTexture(textureDescriptor);
  1002. texture._webGPUTexture = gpuTexture;
  1003. if (noMipmap) {
  1004. this._uploadFromWebglTexture(webglEngineTexture, gpuTexture, width, height, -1);
  1005. }
  1006. else {
  1007. this._uploadMipMapsFromWebglTexture(mipMaps, webglEngineTexture, gpuTexture, width, height, -1);
  1008. }
  1009. texture._webGPUTextureView = gpuTexture.createDefaultView();
  1010. webglEngineTexture.dispose();
  1011. texture.onLoadedObservable.notifyObservers(texture);
  1012. texture.onLoadedObservable.clear();
  1013. if (onLoad) {
  1014. onLoad();
  1015. }
  1016. };
  1017. webglEngineTexture = this._decodeEngine.createTexture(urlArg, noMipmap, invertY, scene, samplingMode,
  1018. onLoadInternal, onError, buffer, fallBack, format);
  1019. this._internalTexturesCache.push(texture);
  1020. return texture;
  1021. }
  1022. public createCubeTexture(rootUrl: string, scene: Nullable<Scene>, files: Nullable<string[]>, noMipmap?: boolean, onLoad: Nullable<(data?: any) => void> = null, 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, excludeLoaders: Array<IInternalTextureLoader> = []): InternalTexture {
  1023. var texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  1024. texture.isCube = true;
  1025. texture.url = rootUrl;
  1026. texture.generateMipMaps = !noMipmap;
  1027. // TODO WEBGPU. Cube Texture Sampling Mode.
  1028. texture.samplingMode = noMipmap ? Constants.TEXTURE_BILINEAR_SAMPLINGMODE : Constants.TEXTURE_TRILINEAR_SAMPLINGMODE;
  1029. texture._lodGenerationScale = lodScale;
  1030. texture._lodGenerationOffset = lodOffset;
  1031. if (!this._doNotHandleContextLost) {
  1032. texture._extension = forcedExtension;
  1033. texture._files = files;
  1034. }
  1035. let webglEngineTexture: InternalTexture;
  1036. const onLoadInternal = () => {
  1037. texture.isReady = webglEngineTexture.isReady;
  1038. const width = webglEngineTexture.width;
  1039. const height = webglEngineTexture.height;
  1040. const depth = 1;
  1041. texture.width = width;
  1042. texture.height = height;
  1043. texture.baseWidth = width;
  1044. texture.baseHeight = height;
  1045. texture.depth = depth;
  1046. texture.baseDepth = depth;
  1047. texture._isRGBD = webglEngineTexture._isRGBD;
  1048. texture._sphericalPolynomial = webglEngineTexture._sphericalPolynomial;
  1049. let mipMaps = Scalar.Log2(width);
  1050. mipMaps = Math.round(mipMaps);
  1051. const textureExtent = {
  1052. width,
  1053. height,
  1054. depth,
  1055. };
  1056. const textureDescriptor: GPUTextureDescriptor = {
  1057. dimension: WebGPUConstants.GPUTextureDimension_2d,
  1058. format: WebGPUConstants.GPUTextureFormat_rgba8unorm,
  1059. arrayLayerCount: 6,
  1060. mipLevelCount: noMipmap ? 1 : mipMaps + 1,
  1061. sampleCount: 1,
  1062. size: textureExtent,
  1063. usage: WebGPUConstants.GPUTextureUsage_TRANSFER_DST | WebGPUConstants.GPUTextureUsage_SAMPLED
  1064. };
  1065. const gpuTexture = this._device.createTexture(textureDescriptor);
  1066. texture._webGPUTexture = gpuTexture;
  1067. const faces = [0, 1, 2, 3, 4, 5];
  1068. for (let face of faces) {
  1069. if (noMipmap) {
  1070. this._uploadFromWebglTexture(webglEngineTexture, gpuTexture, width, height, face);
  1071. }
  1072. else {
  1073. this._uploadMipMapsFromWebglTexture(mipMaps, webglEngineTexture, gpuTexture, width, height, face);
  1074. }
  1075. }
  1076. texture._webGPUTextureView = gpuTexture.createView({
  1077. arrayLayerCount: 6,
  1078. dimension: WebGPUConstants.GPUTextureViewDimension_cube,
  1079. format: WebGPUConstants.GPUTextureFormat_rgba8unorm,
  1080. mipLevelCount: noMipmap ? 1 : mipMaps + 1,
  1081. baseArrayLayer: 0,
  1082. baseMipLevel: 0,
  1083. aspect: WebGPUConstants.GPUTextureAspect_all
  1084. } as any);
  1085. webglEngineTexture.dispose();
  1086. onLoad && onLoad();
  1087. };
  1088. webglEngineTexture = this._decodeEngine.createCubeTexture(rootUrl, scene, files, noMipmap, onLoadInternal, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, excludeLoaders);
  1089. this._internalTexturesCache.push(texture);
  1090. return texture;
  1091. }
  1092. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  1093. texture.samplingMode = samplingMode;
  1094. }
  1095. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  1096. // TODO WEBGPU.
  1097. throw "Unimplemented updateDynamicTexture on WebGPU so far";
  1098. }
  1099. public setTexture(channel: number, _: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>, name: string): void {
  1100. if (this._currentEffect) {
  1101. const pipeline = this._currentEffect._pipelineContext as WebGPUPipelineContext;
  1102. if (!texture) {
  1103. pipeline.samplers[name] = null;
  1104. return;
  1105. }
  1106. const internalTexture = texture!.getInternalTexture();
  1107. if (internalTexture) {
  1108. internalTexture._cachedWrapU = texture.wrapU;
  1109. internalTexture._cachedWrapV = texture.wrapV;
  1110. internalTexture._cachedWrapR = texture.wrapR;
  1111. }
  1112. if (pipeline.samplers[name]) {
  1113. pipeline.samplers[name]!.texture = internalTexture!;
  1114. }
  1115. else {
  1116. // TODO WEBGPU. GC + 121 mapping samplers <-> availableSamplers
  1117. const availableSampler = pipeline.availableSamplers[name];
  1118. if (availableSampler) {
  1119. pipeline.samplers[name] = {
  1120. setIndex: availableSampler.setIndex,
  1121. textureBinding: availableSampler.bindingIndex,
  1122. samplerBinding: availableSampler.bindingIndex + 1,
  1123. texture: internalTexture!
  1124. };
  1125. }
  1126. }
  1127. }
  1128. }
  1129. public bindSamplers(effect: Effect): void { }
  1130. public _bindTextureDirectly(target: number, texture: InternalTexture): boolean {
  1131. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  1132. this._boundTexturesCache[this._activeChannel] = texture;
  1133. return true;
  1134. }
  1135. return false;
  1136. }
  1137. /** @hidden */
  1138. public _bindTexture(channel: number, texture: InternalTexture): void {
  1139. if (channel < 0) {
  1140. return;
  1141. }
  1142. this._bindTextureDirectly(0, texture);
  1143. }
  1144. /** @hidden */
  1145. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  1146. }
  1147. /** @hidden */
  1148. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  1149. }
  1150. /** @hidden */
  1151. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  1152. }
  1153. /** @hidden */
  1154. public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement, faceIndex: number = 0, lod: number = 0) {
  1155. }
  1156. //------------------------------------------------------------------------------
  1157. // Render Target Textures
  1158. //------------------------------------------------------------------------------
  1159. public createRenderTargetTexture(size: any, options: boolean | RenderTargetCreationOptions): InternalTexture {
  1160. let fullOptions = new RenderTargetCreationOptions();
  1161. if (options !== undefined && typeof options === "object") {
  1162. fullOptions.generateMipMaps = options.generateMipMaps;
  1163. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1164. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  1165. fullOptions.type = options.type === undefined ? Constants.TEXTURETYPE_UNSIGNED_INT : options.type;
  1166. fullOptions.samplingMode = options.samplingMode === undefined ? Constants.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  1167. } else {
  1168. fullOptions.generateMipMaps = <boolean>options;
  1169. fullOptions.generateDepthBuffer = true;
  1170. fullOptions.generateStencilBuffer = false;
  1171. fullOptions.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  1172. fullOptions.samplingMode = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE;
  1173. }
  1174. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  1175. var width = size.width || size;
  1176. var height = size.height || size;
  1177. texture._depthStencilBuffer = {};
  1178. texture._framebuffer = {};
  1179. texture.baseWidth = width;
  1180. texture.baseHeight = height;
  1181. texture.width = width;
  1182. texture.height = height;
  1183. texture.isReady = true;
  1184. texture.samples = 1;
  1185. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  1186. texture.samplingMode = fullOptions.samplingMode;
  1187. texture.type = fullOptions.type;
  1188. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  1189. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  1190. this._internalTexturesCache.push(texture);
  1191. return texture;
  1192. }
  1193. //------------------------------------------------------------------------------
  1194. // Render Commands
  1195. //------------------------------------------------------------------------------
  1196. /**
  1197. * Begin a new frame
  1198. */
  1199. public beginFrame(): void {
  1200. super.beginFrame();
  1201. this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);
  1202. this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);
  1203. this._blitEncoder = this._device.createCommandEncoder(this._blitDescriptor);
  1204. }
  1205. private _freezeCommands: boolean = false;
  1206. private _frozenCommands: Nullable<GPUCommandBuffer[]> = null;
  1207. public _shouldOnlyUpdateCameras(): boolean {
  1208. return this._frozenCommands !== null;
  1209. }
  1210. /**
  1211. * End the current frame
  1212. */
  1213. public endFrame(): void {
  1214. this._endRenderPass();
  1215. if (this._freezeCommands && this._frozenCommands) {
  1216. this._commandBuffers[0] = this._frozenCommands[0];
  1217. this._commandBuffers[1] = this._frozenCommands[1];
  1218. }
  1219. else {
  1220. this._commandBuffers[0] = this._uploadEncoder.finish();
  1221. this._commandBuffers[1] = this._renderEncoder.finish();
  1222. }
  1223. if (this._freezeCommands && !this._frozenCommands) {
  1224. this._frozenCommands = [ ];
  1225. this._frozenCommands[0] = this._commandBuffers[0];
  1226. this._frozenCommands[1] = this._commandBuffers[1];
  1227. }
  1228. // TODO WEBGPU. GC.
  1229. this._blitEncoder.copyTextureToTexture(this._mainTextureCopyView, {
  1230. texture: this._swapChain.getCurrentTexture(),
  1231. origin: {
  1232. x: 0,
  1233. y: 0,
  1234. z: 0
  1235. },
  1236. mipLevel: 0,
  1237. arrayLayer: 0,
  1238. },
  1239. this._mainTextureExtends);
  1240. this._commandBuffers[2] = this._blitEncoder.finish();
  1241. this._device.getQueue().submit(this._commandBuffers);
  1242. super.endFrame();
  1243. }
  1244. /**
  1245. * Freezes the current list of commands to speed up rendering of sub sequent frames.
  1246. */
  1247. public freezeCommands(): void {
  1248. this._freezeCommands = true;
  1249. this._frozenCommands = null;
  1250. }
  1251. /**
  1252. * Freezes the current list of commands to speed up rendering of sub sequent frames.
  1253. */
  1254. public unFreezeCommands(): void {
  1255. this._freezeCommands = false;
  1256. this._frozenCommands = null;
  1257. }
  1258. //------------------------------------------------------------------------------
  1259. // Render Pass
  1260. //------------------------------------------------------------------------------
  1261. private _startMainRenderPass(): void {
  1262. if (this._currentRenderPass) {
  1263. this._endRenderPass();
  1264. }
  1265. // this._mainColorAttachments[0].attachment = this._swapChain.getCurrentTexture().createDefaultView();
  1266. this._currentRenderPass = this._renderEncoder.beginRenderPass({
  1267. colorAttachments: this._mainColorAttachments,
  1268. depthStencilAttachment: this._mainDepthAttachment
  1269. });
  1270. }
  1271. private _endRenderPass(): void {
  1272. if (this._currentRenderPass) {
  1273. this._currentRenderPass.endPass();
  1274. this._currentRenderPass = null;
  1275. }
  1276. }
  1277. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean): void {
  1278. if (this._currentRenderTarget) {
  1279. this.unBindFramebuffer(this._currentRenderTarget);
  1280. }
  1281. this._currentRenderTarget = texture;
  1282. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  1283. if (this._cachedViewport && !forceFullscreenViewport) {
  1284. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1285. }
  1286. }
  1287. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1288. this._currentRenderTarget = null;
  1289. if (onBeforeUnbind) {
  1290. if (texture._MSAAFramebuffer) {
  1291. this._currentFramebuffer = texture._framebuffer;
  1292. }
  1293. onBeforeUnbind();
  1294. }
  1295. this._currentFramebuffer = null;
  1296. }
  1297. //------------------------------------------------------------------------------
  1298. // Render
  1299. //------------------------------------------------------------------------------
  1300. private _getTopology(fillMode: number): GPUPrimitiveTopology {
  1301. switch (fillMode) {
  1302. // Triangle views
  1303. case Constants.MATERIAL_TriangleFillMode:
  1304. return WebGPUConstants.GPUPrimitiveTopology_triangleList;
  1305. case Constants.MATERIAL_PointFillMode:
  1306. return WebGPUConstants.GPUPrimitiveTopology_pointList;
  1307. case Constants.MATERIAL_WireFrameFillMode:
  1308. return WebGPUConstants.GPUPrimitiveTopology_lineList;
  1309. // Draw modes
  1310. case Constants.MATERIAL_PointListDrawMode:
  1311. return WebGPUConstants.GPUPrimitiveTopology_pointList;
  1312. case Constants.MATERIAL_LineListDrawMode:
  1313. return WebGPUConstants.GPUPrimitiveTopology_lineList;
  1314. case Constants.MATERIAL_LineLoopDrawMode:
  1315. // return this._gl.LINE_LOOP;
  1316. // TODO WEBGPU. Line Loop Mode
  1317. throw "LineLoop is an unsupported fillmode in WebGPU";
  1318. case Constants.MATERIAL_LineStripDrawMode:
  1319. return WebGPUConstants.GPUPrimitiveTopology_lineStrip;
  1320. case Constants.MATERIAL_TriangleStripDrawMode:
  1321. return WebGPUConstants.GPUPrimitiveTopology_triangleStrip;
  1322. case Constants.MATERIAL_TriangleFanDrawMode:
  1323. // return this._gl.TRIANGLE_FAN;
  1324. // TODO WEBGPU. Triangle Fan Mode
  1325. throw "TriangleFan is an unsupported fillmode in WebGPU";
  1326. default:
  1327. return WebGPUConstants.GPUPrimitiveTopology_triangleList;
  1328. }
  1329. }
  1330. private _getCompareFunction(compareFunction: Nullable<number>): GPUCompareFunction {
  1331. switch (compareFunction) {
  1332. case Constants.ALWAYS:
  1333. return WebGPUConstants.GPUCompareFunction_always;
  1334. case Constants.EQUAL:
  1335. return WebGPUConstants.GPUCompareFunction_equal;
  1336. case Constants.GREATER:
  1337. return WebGPUConstants.GPUCompareFunction_greater;
  1338. case Constants.GEQUAL:
  1339. return WebGPUConstants.GPUCompareFunction_greaterEqual;
  1340. case Constants.LESS:
  1341. return WebGPUConstants.GPUCompareFunction_less;
  1342. case Constants.LEQUAL:
  1343. return WebGPUConstants.GPUCompareFunction_lessEqual;
  1344. case Constants.NEVER:
  1345. return WebGPUConstants.GPUCompareFunction_never;
  1346. case Constants.NOTEQUAL:
  1347. return WebGPUConstants.GPUCompareFunction_notEqual;
  1348. default:
  1349. return WebGPUConstants.GPUCompareFunction_less;
  1350. }
  1351. }
  1352. private _getOpFunction(operation: Nullable<number>, defaultOp: GPUStencilOperation): GPUStencilOperation {
  1353. switch (operation) {
  1354. case Constants.KEEP:
  1355. return WebGPUConstants.GPUStencilOperation_keep;
  1356. case Constants.ZERO:
  1357. return WebGPUConstants.GPUStencilOperation_zero;
  1358. case Constants.REPLACE:
  1359. return WebGPUConstants.GPUStencilOperation_replace;
  1360. case Constants.INVERT:
  1361. return WebGPUConstants.GPUStencilOperation_invert;
  1362. case Constants.INCR:
  1363. return WebGPUConstants.GPUStencilOperation_incrementClamp;
  1364. case Constants.DECR:
  1365. return WebGPUConstants.GPUStencilOperation_decrementClamp;
  1366. case Constants.INCR_WRAP:
  1367. return WebGPUConstants.GPUStencilOperation_incrementWrap;
  1368. case Constants.DECR_WRAP:
  1369. return WebGPUConstants.GPUStencilOperation_decrementWrap;
  1370. default:
  1371. return defaultOp;
  1372. }
  1373. }
  1374. private _getDepthStencilStateDescriptor(): GPUDepthStencilStateDescriptor {
  1375. // TODO WEBGPU. Depth State according to the cached state.
  1376. // And the current render pass attachment setup.
  1377. const stencilFrontBack: GPUStencilStateFaceDescriptor = {
  1378. compare: this._getCompareFunction(this._stencilState.stencilFunc),
  1379. depthFailOp: this._getOpFunction(this._stencilState.stencilOpDepthFail, WebGPUConstants.GPUStencilOperation_keep),
  1380. failOp: this._getOpFunction(this._stencilState.stencilOpStencilFail, WebGPUConstants.GPUStencilOperation_keep),
  1381. passOp: this._getOpFunction(this._stencilState.stencilOpStencilDepthPass, WebGPUConstants.GPUStencilOperation_replace)
  1382. };
  1383. return {
  1384. depthWriteEnabled: this.getDepthWrite(),
  1385. depthCompare: this._getCompareFunction(this.getDepthFunction()),
  1386. format: WebGPUConstants.GPUTextureFormat_depth24plusStencil8,
  1387. stencilFront: stencilFrontBack,
  1388. stencilBack: stencilFrontBack,
  1389. stencilReadMask: this._stencilState.stencilFuncMask,
  1390. stencilWriteMask: this._stencilState.stencilMask,
  1391. };
  1392. }
  1393. /**
  1394. * Set various states to the webGL context
  1395. * @param culling defines backface culling state
  1396. * @param zOffset defines the value to apply to zOffset (0 by default)
  1397. * @param force defines if states must be applied even if cache is up to date
  1398. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  1399. */
  1400. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  1401. // Culling
  1402. if (this._depthCullingState.cull !== culling || force) {
  1403. this._depthCullingState.cull = culling;
  1404. }
  1405. // Cull face
  1406. // var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  1407. var cullFace = this.cullBackFaces ? 1 : 2;
  1408. if (this._depthCullingState.cullFace !== cullFace || force) {
  1409. this._depthCullingState.cullFace = cullFace;
  1410. }
  1411. // Z offset
  1412. this.setZOffset(zOffset);
  1413. // Front face
  1414. // var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  1415. var frontFace = reverseSide ? 1 : 2;
  1416. if (this._depthCullingState.frontFace !== frontFace || force) {
  1417. this._depthCullingState.frontFace = frontFace;
  1418. }
  1419. }
  1420. private _getFrontFace(): GPUFrontFace {
  1421. switch (this._depthCullingState.frontFace) {
  1422. case 1:
  1423. return WebGPUConstants.GPUFrontFace_cw;
  1424. default:
  1425. return WebGPUConstants.GPUFrontFace_ccw;
  1426. }
  1427. }
  1428. private _getCullMode(): GPUCullMode {
  1429. if (this._depthCullingState.cull === false) {
  1430. return WebGPUConstants.GPUCullMode_none;
  1431. }
  1432. if (this._depthCullingState.cullFace === 2) {
  1433. return WebGPUConstants.GPUCullMode_front;
  1434. }
  1435. else {
  1436. return WebGPUConstants.GPUCullMode_back;
  1437. }
  1438. }
  1439. private _getRasterizationStateDescriptor(): GPURasterizationStateDescriptor {
  1440. // TODO WEBGPU. Cull State according to the cached state.
  1441. // And the current render pass attachment setup.
  1442. return {
  1443. frontFace: this._getFrontFace(),
  1444. cullMode: this._getCullMode(),
  1445. depthBias: this._depthCullingState.zOffset,
  1446. // depthBiasClamp: 0,
  1447. // depthBiasSlopeScale: 0,
  1448. };
  1449. }
  1450. private _getWriteMask(): number {
  1451. if (this.__colorWrite) {
  1452. return WebGPUConstants.GPUColorWriteBits_ALL;
  1453. }
  1454. return WebGPUConstants.GPUColorWriteBits_NONE;
  1455. }
  1456. /**
  1457. * Sets the current alpha mode
  1458. * @param mode defines the mode to use (one of the Engine.ALPHA_XXX)
  1459. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  1460. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  1461. */
  1462. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  1463. if (this._alphaMode === mode) {
  1464. return;
  1465. }
  1466. switch (mode) {
  1467. case Engine.ALPHA_DISABLE:
  1468. this._alphaState.alphaBlend = false;
  1469. break;
  1470. case Engine.ALPHA_PREMULTIPLIED:
  1471. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1472. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0303, 1, 1);
  1473. this._alphaState.alphaBlend = true;
  1474. break;
  1475. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  1476. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  1477. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0303, 1, 0x0303);
  1478. this._alphaState.alphaBlend = true;
  1479. break;
  1480. case Engine.ALPHA_COMBINE:
  1481. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1482. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 0x0303, 1, 1);
  1483. this._alphaState.alphaBlend = true;
  1484. break;
  1485. case Engine.ALPHA_ONEONE:
  1486. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1487. this._alphaState.setAlphaBlendFunctionParameters(1, 1, 0, 1);
  1488. this._alphaState.alphaBlend = true;
  1489. break;
  1490. case Engine.ALPHA_ADD:
  1491. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1492. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 1, 0, 1);
  1493. this._alphaState.alphaBlend = true;
  1494. break;
  1495. case Engine.ALPHA_SUBTRACT:
  1496. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1497. this._alphaState.setAlphaBlendFunctionParameters(0, 0x0301, 1, 1);
  1498. this._alphaState.alphaBlend = true;
  1499. break;
  1500. case Engine.ALPHA_MULTIPLY:
  1501. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  1502. this._alphaState.setAlphaBlendFunctionParameters(0x0306, 0, 1, 1);
  1503. this._alphaState.alphaBlend = true;
  1504. break;
  1505. case Engine.ALPHA_MAXIMIZED:
  1506. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1507. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 0x0301, 1, 1);
  1508. this._alphaState.alphaBlend = true;
  1509. break;
  1510. case Engine.ALPHA_INTERPOLATE:
  1511. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  1512. this._alphaState.setAlphaBlendFunctionParameters(0x8001, 0x8002, 0x8003, 0x8004);
  1513. this._alphaState.alphaBlend = true;
  1514. break;
  1515. case Engine.ALPHA_SCREENMODE:
  1516. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  1517. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0301, 1, 0x0303);
  1518. this._alphaState.alphaBlend = true;
  1519. break;
  1520. }
  1521. if (!noDepthWriteChange) {
  1522. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  1523. }
  1524. this._alphaMode = mode;
  1525. }
  1526. private _getAphaBlendOperation(operation: Nullable<number>): GPUBlendOperation {
  1527. switch (operation) {
  1528. case 0x8006:
  1529. return WebGPUConstants.GPUBlendOperation_add;
  1530. case 0x800A:
  1531. return WebGPUConstants.GPUBlendOperation_substract;
  1532. case 0x800B:
  1533. return WebGPUConstants.GPUBlendOperation_reverseSubtract;
  1534. default:
  1535. return WebGPUConstants.GPUBlendOperation_add;
  1536. }
  1537. }
  1538. private _getAphaBlendFactor(factor: Nullable<number>): GPUBlendFactor {
  1539. switch (factor) {
  1540. case 0:
  1541. return WebGPUConstants.GPUBlendFactor_zero;
  1542. case 1:
  1543. return WebGPUConstants.GPUBlendFactor_one;
  1544. case 0x0300:
  1545. return WebGPUConstants.GPUBlendFactor_srcColor;
  1546. case 0x0301:
  1547. return WebGPUConstants.GPUBlendFactor_oneMinusSrcColor;
  1548. case 0x0302:
  1549. return WebGPUConstants.GPUBlendFactor_srcAlpha;
  1550. case 0x0303:
  1551. return WebGPUConstants.GPUBlendFactor_oneMinusSrcAlpha;
  1552. case 0x0304:
  1553. return WebGPUConstants.GPUBlendFactor_dstAlpha;
  1554. case 0x0305:
  1555. return WebGPUConstants.GPUBlendFactor_oneMinusDstAlpha;
  1556. case 0x0306:
  1557. return WebGPUConstants.GPUBlendFactor_dstColor;
  1558. case 0x0307:
  1559. return WebGPUConstants.GPUBlendFactor_oneMinusDstColor;
  1560. case 0x0308:
  1561. return WebGPUConstants.GPUBlendFactor_srcAlphaSaturated;
  1562. case 0x8001:
  1563. return WebGPUConstants.GPUBlendFactor_blendColor;
  1564. case 0x8002:
  1565. return WebGPUConstants.GPUBlendFactor_oneMinusBlendColor;
  1566. case 0x8003:
  1567. return WebGPUConstants.GPUBlendFactor_blendColor;
  1568. case 0x8004:
  1569. return WebGPUConstants.GPUBlendFactor_oneMinusBlendColor;
  1570. default:
  1571. return WebGPUConstants.GPUBlendFactor_one;
  1572. }
  1573. }
  1574. private _getAphaBlendState(): GPUBlendDescriptor {
  1575. if (!this._alphaState.alphaBlend) {
  1576. return { };
  1577. }
  1578. return {
  1579. srcFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[2]),
  1580. dstFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[3]),
  1581. operation: this._getAphaBlendOperation(this._alphaState._blendEquationParameters[1]),
  1582. };
  1583. }
  1584. private _getColorBlendState(): GPUBlendDescriptor {
  1585. if (!this._alphaState.alphaBlend) {
  1586. return { };
  1587. }
  1588. return {
  1589. srcFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[0]),
  1590. dstFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[1]),
  1591. operation: this._getAphaBlendOperation(this._alphaState._blendEquationParameters[0]),
  1592. };
  1593. }
  1594. private _getColorStateDescriptors(): GPUColorStateDescriptor[] {
  1595. // TODO WEBGPU. Manage Multi render target.
  1596. return [{
  1597. format: this._options.swapChainFormat!,
  1598. alphaBlend: this._getAphaBlendState(),
  1599. colorBlend: this._getColorBlendState(),
  1600. writeMask: this._getWriteMask(),
  1601. }];
  1602. }
  1603. private _getStages(): GPURenderPipelineStageDescriptor {
  1604. const gpuPipeline = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1605. return gpuPipeline.stages!;
  1606. }
  1607. private _getVertexInputDescriptorFormat(kind: string, type: number, normalized: boolean): GPUVertexFormat {
  1608. switch (kind) {
  1609. case VertexBuffer.UVKind:
  1610. case VertexBuffer.UV2Kind:
  1611. case VertexBuffer.UV3Kind:
  1612. case VertexBuffer.UV4Kind:
  1613. case VertexBuffer.UV5Kind:
  1614. case VertexBuffer.UV6Kind:
  1615. switch (type) {
  1616. case VertexBuffer.BYTE:
  1617. return normalized ? WebGPUConstants.GPUVertexFormat_char2norm : WebGPUConstants.GPUVertexFormat_char2;
  1618. case VertexBuffer.UNSIGNED_BYTE:
  1619. return normalized ? WebGPUConstants.GPUVertexFormat_uchar2norm : WebGPUConstants.GPUVertexFormat_uchar2;
  1620. case VertexBuffer.SHORT:
  1621. return normalized ? WebGPUConstants.GPUVertexFormat_short2norm : WebGPUConstants.GPUVertexFormat_short2;
  1622. case VertexBuffer.UNSIGNED_SHORT:
  1623. return normalized ? WebGPUConstants.GPUVertexFormat_ushort2norm : WebGPUConstants.GPUVertexFormat_ushort2;
  1624. case VertexBuffer.INT:
  1625. return WebGPUConstants.GPUVertexFormat_int2;
  1626. case VertexBuffer.UNSIGNED_INT:
  1627. return WebGPUConstants.GPUVertexFormat_uint2;
  1628. case VertexBuffer.FLOAT:
  1629. return WebGPUConstants.GPUVertexFormat_float2;
  1630. }
  1631. case VertexBuffer.NormalKind:
  1632. case VertexBuffer.PositionKind:
  1633. switch (type) {
  1634. // TODO WEBGPU...
  1635. // case VertexBuffer.BYTE:
  1636. // return normalized ? WebGPUConstants.GPUVertexFormat_char3norm : WebGPUConstants.GPUVertexFormat_char3;
  1637. // case VertexBuffer.UNSIGNED_BYTE:
  1638. // return normalized ? WebGPUConstants.GPUVertexFormat_uchar3norm : WebGPUConstants.GPUVertexFormat_uchar3;
  1639. // case VertexBuffer.SHORT:
  1640. // return normalized ? WebGPUConstants.GPUVertexFormat_short3norm : WebGPUConstants.GPUVertexFormat_short3;
  1641. // case VertexBuffer.UNSIGNED_SHORT:
  1642. // return normalized ? WebGPUConstants.GPUVertexFormat_ushort3norm : WebGPUConstants.GPUVertexFormat_ushort3;
  1643. case VertexBuffer.INT:
  1644. return WebGPUConstants.GPUVertexFormat_int3;
  1645. case VertexBuffer.UNSIGNED_INT:
  1646. return WebGPUConstants.GPUVertexFormat_uint3;
  1647. case VertexBuffer.FLOAT:
  1648. return WebGPUConstants.GPUVertexFormat_float3;
  1649. default:
  1650. throw "Unsupported vertex type " + type;
  1651. }
  1652. case VertexBuffer.ColorKind:
  1653. case VertexBuffer.MatricesIndicesKind:
  1654. case VertexBuffer.MatricesIndicesExtraKind:
  1655. case VertexBuffer.MatricesWeightsKind:
  1656. case VertexBuffer.MatricesWeightsExtraKind:
  1657. case VertexBuffer.TangentKind:
  1658. case "world0":
  1659. case "world1":
  1660. case "world2":
  1661. case "world3":
  1662. switch (type) {
  1663. case VertexBuffer.BYTE:
  1664. return normalized ? WebGPUConstants.GPUVertexFormat_char4norm : WebGPUConstants.GPUVertexFormat_char4;
  1665. case VertexBuffer.UNSIGNED_BYTE:
  1666. return normalized ? WebGPUConstants.GPUVertexFormat_uchar4norm : WebGPUConstants.GPUVertexFormat_uchar4;
  1667. case VertexBuffer.SHORT:
  1668. return normalized ? WebGPUConstants.GPUVertexFormat_short4norm : WebGPUConstants.GPUVertexFormat_short4;
  1669. case VertexBuffer.UNSIGNED_SHORT:
  1670. return normalized ? WebGPUConstants.GPUVertexFormat_ushort4norm : WebGPUConstants.GPUVertexFormat_ushort4;
  1671. case VertexBuffer.INT:
  1672. return WebGPUConstants.GPUVertexFormat_int4;
  1673. case VertexBuffer.UNSIGNED_INT:
  1674. return WebGPUConstants.GPUVertexFormat_uint4;
  1675. case VertexBuffer.FLOAT:
  1676. return WebGPUConstants.GPUVertexFormat_float4;
  1677. }
  1678. }
  1679. // MorphTargets
  1680. if (kind.indexOf("position") === 0 ||
  1681. kind.indexOf("normal") === 0 ||
  1682. kind.indexOf("tangent") === 0) {
  1683. switch (type) {
  1684. // TODO WEBGPU...
  1685. // case VertexBuffer.BYTE:
  1686. // return normalized ? WebGPUConstants.GPUVertexFormat_char3norm : WebGPUConstants.GPUVertexFormat_char3;
  1687. // case VertexBuffer.UNSIGNED_BYTE:
  1688. // return normalized ? WebGPUConstants.GPUVertexFormat_uchar3norm : WebGPUConstants.GPUVertexFormat_uchar3;
  1689. // case VertexBuffer.SHORT:
  1690. // return normalized ? WebGPUConstants.GPUVertexFormat_short3norm : WebGPUConstants.GPUVertexFormat_short3;
  1691. // case VertexBuffer.UNSIGNED_SHORT:
  1692. // return normalized ? WebGPUConstants.GPUVertexFormat_ushort3norm : WebGPUConstants.GPUVertexFormat_ushort3;
  1693. case VertexBuffer.INT:
  1694. return WebGPUConstants.GPUVertexFormat_int3;
  1695. case VertexBuffer.UNSIGNED_INT:
  1696. return WebGPUConstants.GPUVertexFormat_uint3;
  1697. case VertexBuffer.FLOAT:
  1698. return WebGPUConstants.GPUVertexFormat_float3;
  1699. default:
  1700. throw "Unsupported vertex type " + type;
  1701. }
  1702. }
  1703. if (kind.indexOf("uv_") === 0) {
  1704. switch (type) {
  1705. case VertexBuffer.BYTE:
  1706. return normalized ? WebGPUConstants.GPUVertexFormat_char2norm : WebGPUConstants.GPUVertexFormat_char2;
  1707. case VertexBuffer.UNSIGNED_BYTE:
  1708. return normalized ? WebGPUConstants.GPUVertexFormat_uchar2norm : WebGPUConstants.GPUVertexFormat_uchar2;
  1709. case VertexBuffer.SHORT:
  1710. return normalized ? WebGPUConstants.GPUVertexFormat_short2norm : WebGPUConstants.GPUVertexFormat_short2;
  1711. case VertexBuffer.UNSIGNED_SHORT:
  1712. return normalized ? WebGPUConstants.GPUVertexFormat_ushort2norm : WebGPUConstants.GPUVertexFormat_ushort2;
  1713. case VertexBuffer.INT:
  1714. return WebGPUConstants.GPUVertexFormat_int2;
  1715. case VertexBuffer.UNSIGNED_INT:
  1716. return WebGPUConstants.GPUVertexFormat_uint2;
  1717. case VertexBuffer.FLOAT:
  1718. return WebGPUConstants.GPUVertexFormat_float2;
  1719. }
  1720. }
  1721. // TODO WEBGPU. Manages Custom Attributes.
  1722. throw new Error("Invalid kind '" + kind + "'");
  1723. }
  1724. private _getVertexInputDescriptor(): GPUVertexInputDescriptor {
  1725. const descriptors: GPUVertexBufferDescriptor[] = [];
  1726. const effect = this._currentEffect!;
  1727. const attributes = effect.getAttributesNames();
  1728. for (var index = 0; index < attributes.length; index++) {
  1729. const location = effect.getAttributeLocation(index);
  1730. if (location >= 0) {
  1731. const vertexBuffer = this._currentVertexBuffers![attributes[index]];
  1732. if (!vertexBuffer) {
  1733. continue;
  1734. }
  1735. const positionAttributeDescriptor: GPUVertexAttributeDescriptor = {
  1736. shaderLocation: location,
  1737. offset: 0, // not available in WebGL
  1738. format: this._getVertexInputDescriptorFormat(vertexBuffer.getKind(), vertexBuffer.type, vertexBuffer.normalized),
  1739. };
  1740. // TODO WEBGPU. Factorize the one with the same underlying buffer.
  1741. // manage interleaved and instances.
  1742. const vertexBufferDescriptor: GPUVertexBufferDescriptor = {
  1743. stride: vertexBuffer.byteStride,
  1744. stepMode: vertexBuffer.getIsInstanced() ? WebGPUConstants.GPUInputStepMode_instance : WebGPUConstants.GPUInputStepMode_vertex,
  1745. attributeSet: [positionAttributeDescriptor]
  1746. };
  1747. descriptors.push(vertexBufferDescriptor);
  1748. }
  1749. }
  1750. if (!this._currentIndexBuffer) {
  1751. return {
  1752. indexFormat: WebGPUConstants.GPUIndexFormat_uint32,
  1753. vertexBuffers: descriptors
  1754. };
  1755. }
  1756. const inputStateDescriptor: GPUVertexInputDescriptor = {
  1757. indexFormat: this._currentIndexBuffer!.is32Bits ? WebGPUConstants.GPUIndexFormat_uint32 : WebGPUConstants.GPUIndexFormat_uint16,
  1758. vertexBuffers: descriptors
  1759. };
  1760. return inputStateDescriptor;
  1761. }
  1762. private _getPipelineLayout(): GPUPipelineLayout {
  1763. const bindGroupLayouts: GPUBindGroupLayout[] = [];
  1764. const webgpuPipelineContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1765. for (let i = 0; i < webgpuPipelineContext.orderedUBOsAndSamplers.length; i++) {
  1766. const setDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i];
  1767. if (setDefinition === undefined) {
  1768. continue;
  1769. }
  1770. const bindings: GPUBindGroupLayoutBinding[] = [];
  1771. for (let j = 0; j < setDefinition.length; j++) {
  1772. const bindingDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i][j];
  1773. if (bindingDefinition === undefined) {
  1774. continue;
  1775. }
  1776. // TODO WEBGPU. Authorize shared samplers and Vertex Textures.
  1777. if (bindingDefinition.isSampler) {
  1778. bindings.push({
  1779. binding: j,
  1780. visibility: WebGPUConstants.GPUShaderStageBit_FRAGMENT,
  1781. type: WebGPUConstants.GPUBindingType_sampledTexture,
  1782. }, {
  1783. // TODO WEBGPU. No Magic + 1.
  1784. binding: j + 1,
  1785. visibility: WebGPUConstants.GPUShaderStageBit_FRAGMENT,
  1786. type: WebGPUConstants.GPUBindingType_sampler
  1787. });
  1788. }
  1789. else {
  1790. bindings.push({
  1791. binding: j,
  1792. visibility: WebGPUConstants.GPUShaderStageBit_VERTEX | WebGPUConstants.GPUShaderStageBit_FRAGMENT,
  1793. type: WebGPUConstants.GPUBindingType_uniformBuffer,
  1794. });
  1795. }
  1796. }
  1797. if (bindings.length > 0) {
  1798. const uniformsBindGroupLayout = this._device.createBindGroupLayout({
  1799. bindings,
  1800. });
  1801. bindGroupLayouts[i] = uniformsBindGroupLayout;
  1802. }
  1803. }
  1804. webgpuPipelineContext.bindGroupLayouts = bindGroupLayouts;
  1805. return this._device.createPipelineLayout({ bindGroupLayouts });
  1806. }
  1807. private _getRenderPipeline(fillMode: number): GPURenderPipeline {
  1808. // This is wrong to cache this way but workarounds the need of cache in the simple demo context.
  1809. const gpuPipeline = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1810. if (gpuPipeline.renderPipeline) {
  1811. return gpuPipeline.renderPipeline;
  1812. }
  1813. // Unsupported at the moment but needs to be extracted from the MSAA param.
  1814. const sampleCount = this._defaultSampleCount;
  1815. const topology = this._getTopology(fillMode);
  1816. const rasterizationStateDescriptor = this._getRasterizationStateDescriptor();
  1817. const depthStateDescriptor = this._getDepthStencilStateDescriptor();
  1818. const colorStateDescriptors = this._getColorStateDescriptors();
  1819. const stages = this._getStages();
  1820. const inputStateDescriptor = this._getVertexInputDescriptor();
  1821. const pipelineLayout = this._getPipelineLayout();
  1822. gpuPipeline.renderPipeline = this._device.createRenderPipeline({
  1823. sampleCount,
  1824. primitiveTopology: topology,
  1825. rasterizationState: rasterizationStateDescriptor,
  1826. depthStencilState: depthStateDescriptor,
  1827. colorStates: colorStateDescriptors,
  1828. ...stages,
  1829. vertexInput: inputStateDescriptor,
  1830. layout: pipelineLayout,
  1831. });
  1832. return gpuPipeline.renderPipeline;
  1833. }
  1834. private _getVertexInputsToRender(): IWebGPUPipelineContextVertexInputsCache {
  1835. const effect = this._currentEffect!;
  1836. const gpuContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1837. let vertexInputs = gpuContext.vertexInputs;
  1838. if (vertexInputs) {
  1839. return vertexInputs;
  1840. }
  1841. vertexInputs = {
  1842. indexBuffer: null,
  1843. indexOffset: 0,
  1844. vertexStartSlot: 0,
  1845. vertexBuffers: [],
  1846. vertexOffsets: [],
  1847. };
  1848. gpuContext.vertexInputs = vertexInputs;
  1849. if (this._currentIndexBuffer) {
  1850. // TODO WEBGPU. Check if cache would be worth it.
  1851. vertexInputs.indexBuffer = this._currentIndexBuffer.underlyingResource;
  1852. vertexInputs.indexOffset = 0;
  1853. }
  1854. else {
  1855. vertexInputs.indexBuffer = null;
  1856. }
  1857. const attributes = effect.getAttributesNames();
  1858. for (var index = 0; index < attributes.length; index++) {
  1859. const order = effect.getAttributeLocation(index);
  1860. if (order >= 0) {
  1861. const vertexBuffer = this._currentVertexBuffers![attributes[index]];
  1862. if (!vertexBuffer) {
  1863. continue;
  1864. }
  1865. var buffer = vertexBuffer.getBuffer();
  1866. if (buffer) {
  1867. vertexInputs.vertexBuffers.push(buffer.underlyingResource);
  1868. vertexInputs.vertexOffsets.push(vertexBuffer.byteOffset);
  1869. }
  1870. }
  1871. }
  1872. // TODO WEBGPU. Optimize buffer reusability and types as more are now allowed.
  1873. return vertexInputs;
  1874. }
  1875. private _getBindGroupsToRender(): GPUBindGroup[] {
  1876. const webgpuPipelineContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1877. let bindGroups = webgpuPipelineContext.bindGroups;
  1878. if (bindGroups) {
  1879. if (webgpuPipelineContext.uniformBuffer) {
  1880. webgpuPipelineContext.uniformBuffer.update();
  1881. }
  1882. return bindGroups;
  1883. }
  1884. if (webgpuPipelineContext.uniformBuffer) {
  1885. this.bindUniformBufferBase(webgpuPipelineContext.uniformBuffer.getBuffer()!, 0, "LeftOver");
  1886. webgpuPipelineContext.uniformBuffer.update();
  1887. }
  1888. bindGroups = [];
  1889. webgpuPipelineContext.bindGroups = bindGroups;
  1890. const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts;
  1891. for (let i = 0; i < webgpuPipelineContext.orderedUBOsAndSamplers.length; i++) {
  1892. const setDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i];
  1893. if (setDefinition === undefined) {
  1894. continue;
  1895. }
  1896. const bindings: GPUBindGroupBinding[] = [];
  1897. for (let j = 0; j < setDefinition.length; j++) {
  1898. const bindingDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i][j];
  1899. if (bindingDefinition === undefined) {
  1900. continue;
  1901. }
  1902. // TODO WEBGPU. Authorize shared samplers and Vertex Textures.
  1903. if (bindingDefinition.isSampler) {
  1904. const bindingInfo = webgpuPipelineContext.samplers[bindingDefinition.name];
  1905. if (bindingInfo) {
  1906. if (!bindingInfo.texture._webGPUSampler) {
  1907. const samplerDescriptor: GPUSamplerDescriptor = this._getSamplerDescriptor(bindingInfo.texture!);
  1908. const gpuSampler = this._device.createSampler(samplerDescriptor);
  1909. bindingInfo.texture._webGPUSampler = gpuSampler;
  1910. }
  1911. bindings.push({
  1912. binding: bindingInfo.textureBinding,
  1913. resource: bindingInfo.texture._webGPUTextureView!,
  1914. }, {
  1915. binding: bindingInfo.samplerBinding,
  1916. resource: bindingInfo.texture._webGPUSampler!,
  1917. });
  1918. }
  1919. else {
  1920. Logger.Error("Sampler has not been bound: " + bindingDefinition.name);
  1921. }
  1922. }
  1923. else {
  1924. const dataBuffer = this._uniformsBuffers[bindingDefinition.name];
  1925. if (dataBuffer) {
  1926. const webgpuBuffer = dataBuffer.underlyingResource as GPUBuffer;
  1927. bindings.push({
  1928. binding: j,
  1929. resource: {
  1930. buffer: webgpuBuffer,
  1931. offset: 0,
  1932. size: dataBuffer.capacity,
  1933. },
  1934. });
  1935. }
  1936. else {
  1937. Logger.Error("UBO has not been bound: " + bindingDefinition.name);
  1938. }
  1939. }
  1940. }
  1941. const groupLayout = bindGroupLayouts[i];
  1942. if (groupLayout) {
  1943. bindGroups[i] = this._device.createBindGroup({
  1944. layout: groupLayout,
  1945. bindings,
  1946. });
  1947. }
  1948. }
  1949. return bindGroups;
  1950. }
  1951. private _bindVertexInputs(vertexInputs: IWebGPUPipelineContextVertexInputsCache): void {
  1952. const renderPass = this._currentRenderPass!;
  1953. if (vertexInputs.indexBuffer) {
  1954. // TODO WEBGPU. Check if cache would be worth it.
  1955. renderPass.setIndexBuffer(vertexInputs.indexBuffer, vertexInputs.indexOffset);
  1956. }
  1957. // TODO WEBGPU. Optimize buffer reusability and types as more are now allowed.
  1958. this._currentRenderPass!.setVertexBuffers(vertexInputs.vertexStartSlot, vertexInputs.vertexBuffers, vertexInputs.vertexOffsets);
  1959. }
  1960. private _setRenderBindGroups(bindGroups: GPUBindGroup[]): void {
  1961. // TODO WEBGPU. Only set groups if changes happened.
  1962. const renderPass = this._currentRenderPass!;
  1963. for (let i = 0; i < bindGroups.length; i++) {
  1964. renderPass.setBindGroup(i, bindGroups[i]);
  1965. }
  1966. }
  1967. private _setRenderPipeline(fillMode: number): void {
  1968. // TODO WEBGPU. Add dynamicity to the data.
  1969. const pipeline = this._getRenderPipeline(fillMode);
  1970. this._currentRenderPass!.setPipeline(pipeline);
  1971. const vertexInputs = this._getVertexInputsToRender();
  1972. this._bindVertexInputs(vertexInputs);
  1973. const bindGroups = this._getBindGroupsToRender();
  1974. this._setRenderBindGroups(bindGroups);
  1975. if (this._alphaState.alphaBlend && this._alphaState._isBlendConstantsDirty) {
  1976. this._currentRenderPass!.setBlendColor(this._alphaState._blendConstants as any);
  1977. }
  1978. }
  1979. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount: number = 1): void {
  1980. this._setRenderPipeline(fillMode);
  1981. this._currentRenderPass!.drawIndexed(indexCount, instancesCount, indexStart, 0, 0);
  1982. }
  1983. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount: number = 1): void {
  1984. this._currentIndexBuffer = null;
  1985. this._setRenderPipeline(fillMode);
  1986. this._currentRenderPass!.draw(verticesCount, instancesCount, verticesStart, 0);
  1987. }
  1988. /**
  1989. * Force a specific size of the canvas
  1990. * @param width defines the new canvas' width
  1991. * @param height defines the new canvas' height
  1992. */
  1993. public setSize(width: number, height: number): void {
  1994. super.setSize(width, height);
  1995. // TODO WEBGPU. Disposeold attachements.
  1996. this._initializeMainAttachments();
  1997. }
  1998. //------------------------------------------------------------------------------
  1999. // Dispose
  2000. //------------------------------------------------------------------------------
  2001. /**
  2002. * Dispose and release all associated resources
  2003. */
  2004. public dispose(): void {
  2005. this._decodeEngine.dispose();
  2006. this._compiledShaders = { };
  2007. if (this._mainTexture) {
  2008. this._mainTexture.destroy();
  2009. }
  2010. if (this._depthTexture) {
  2011. this._depthTexture.destroy();
  2012. }
  2013. super.dispose();
  2014. }
  2015. //------------------------------------------------------------------------------
  2016. // Misc
  2017. //------------------------------------------------------------------------------
  2018. public getRenderWidth(useScreen = false): number {
  2019. if (!useScreen && this._currentRenderTarget) {
  2020. return this._currentRenderTarget.width;
  2021. }
  2022. return this._canvas.width;
  2023. }
  2024. public getRenderHeight(useScreen = false): number {
  2025. if (!useScreen && this._currentRenderTarget) {
  2026. return this._currentRenderTarget.height;
  2027. }
  2028. return this._canvas.height;
  2029. }
  2030. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  2031. return this._canvas;
  2032. }
  2033. //------------------------------------------------------------------------------
  2034. // Errors
  2035. //------------------------------------------------------------------------------
  2036. public getError(): number {
  2037. // TODO WEBGPU. from the webgpu errors.
  2038. return 0;
  2039. }
  2040. //------------------------------------------------------------------------------
  2041. // Unused WebGPU
  2042. //------------------------------------------------------------------------------
  2043. public areAllEffectsReady(): boolean {
  2044. // TODO WEBGPU.
  2045. // No parallel shader compilation.
  2046. return true;
  2047. }
  2048. public _executeWhenRenderingStateIsCompiled(pipelineContext: IPipelineContext, action: () => void) {
  2049. // TODO WEBGPU.
  2050. // No parallel shader compilation.
  2051. // No Async, so direct launch
  2052. action();
  2053. }
  2054. public _isRenderingStateCompiled(pipelineContext: IPipelineContext): boolean {
  2055. // TODO WEBGPU.
  2056. // No parallel shader compilation.
  2057. return true;
  2058. }
  2059. public _getUnpackAlignement(): number {
  2060. return 1;
  2061. }
  2062. public _unpackFlipY(value: boolean) { }
  2063. // TODO WEBGPU. All of this should go once engine split with baseEngine.
  2064. public applyStates() {
  2065. // TODO WEBGPU. Apply States dynamically.
  2066. // This is done at the pipeline creation level for the moment...
  2067. }
  2068. /** @hidden */
  2069. public _getSamplingParameters(samplingMode: number, generateMipMaps: boolean): { min: number; mag: number } {
  2070. throw "_getSamplingParameters is not available in WebGPU";
  2071. }
  2072. public bindUniformBlock(pipelineContext: IPipelineContext, blockName: string, index: number): void {
  2073. }
  2074. public getUniforms(pipelineContext: IPipelineContext, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  2075. return [];
  2076. }
  2077. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
  2078. }
  2079. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
  2080. }
  2081. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
  2082. }
  2083. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
  2084. }
  2085. public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
  2086. }
  2087. public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
  2088. }
  2089. public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
  2090. }
  2091. public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
  2092. }
  2093. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  2094. }
  2095. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  2096. }
  2097. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  2098. }
  2099. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  2100. }
  2101. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  2102. }
  2103. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  2104. }
  2105. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  2106. }
  2107. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  2108. }
  2109. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  2110. }
  2111. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  2112. }
  2113. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  2114. }
  2115. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  2116. }
  2117. }