webgpuEngine.ts 138 KB

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