webgpuEngine.ts 102 KB

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