webgpuEngine.ts 100 KB

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