webgpuEngine.ts 100 KB

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