From f5c4dee6db5224f5fff9ba6027820255a5c8e391 Mon Sep 17 00:00:00 2001 From: Zeqiang Li Date: Fri, 16 Sep 2022 10:20:52 +0800 Subject: [PATCH] Wgpu 3.6.2 WGPU_CI_ON (#12731) --- .eslintignore | 3 + @types/url.d.ts | 9 + cc.config.json | 13 + cocos/core/game.ts | 8 +- cocos/core/gfx/device-manager.ts | 7 +- cocos/core/gfx/index.ems.ts | 64 + cocos/core/gfx/webgpu/override.ts | 56 + cocos/core/gfx/webgpu/webgpu-define.ts | 561 +++++++ cocos/core/pipeline/instanced-buffer.ts | 10 +- cocos/core/pipeline/pipeline-ubo.ts | 2 +- cocos/core/pipeline/shadow/shadow-flow.ts | 12 +- cocos/webgpu/glslang.js | 137 ++ cocos/webgpu/instantiated.ts | 89 ++ cocos/webgpu/webgpu_wasm.js | 16 + editor/engine-features/render-config.json | 2 +- editor/engine-features/schema.json | 9 +- editor/engine-features/types.ts | 1 + editor/i18n/en/localization.js | 20 +- editor/i18n/zh/localization.js | 12 +- gulp/util/api-docs-build.js | 6 +- native/cmake/predefine.cmake | 1 + native/cocos/base/StringUtil.cpp | 8 +- native/cocos/base/TypeDef.h | 2 +- .../renderer/gfx-base/GFXDescriptorSet.h | 2 +- native/cocos/renderer/gfx-wgpu/CMakeLists.txt | 28 +- native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp | 51 +- native/cocos/renderer/gfx-wgpu/WGPUBuffer.h | 48 +- .../renderer/gfx-wgpu/WGPUCommandBuffer.cpp | 425 ++++-- .../renderer/gfx-wgpu/WGPUCommandBuffer.h | 35 +- native/cocos/renderer/gfx-wgpu/WGPUDef.h | 502 +++---- .../renderer/gfx-wgpu/WGPUDescriptorSet.cpp | 216 ++- .../renderer/gfx-wgpu/WGPUDescriptorSet.h | 37 +- .../gfx-wgpu/WGPUDescriptorSetLayout.cpp | 200 ++- .../gfx-wgpu/WGPUDescriptorSetLayout.h | 27 +- native/cocos/renderer/gfx-wgpu/WGPUDevice.cpp | 638 ++++++-- native/cocos/renderer/gfx-wgpu/WGPUDevice.h | 155 +- .../cocos/renderer/gfx-wgpu/WGPUEMSImpl.cpp | 161 +++ native/cocos/renderer/gfx-wgpu/WGPUExports.h | 1283 ++++------------- .../renderer/gfx-wgpu/WGPUFrameBuffer.cpp | 6 +- .../cocos/renderer/gfx-wgpu/WGPUFrameBuffer.h | 14 +- .../renderer/gfx-wgpu/WGPUInputAssembler.cpp | 25 +- .../renderer/gfx-wgpu/WGPUInputAssembler.h | 16 +- native/cocos/renderer/gfx-wgpu/WGPUObject.h | 193 ++- .../renderer/gfx-wgpu/WGPUPipelineLayout.cpp | 33 +- .../renderer/gfx-wgpu/WGPUPipelineLayout.h | 28 +- .../renderer/gfx-wgpu/WGPUPipelineState.cpp | 259 +++- .../renderer/gfx-wgpu/WGPUPipelineState.h | 18 +- .../cocos/renderer/gfx-wgpu/WGPUQueryPool.cpp | 8 +- native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp | 37 +- native/cocos/renderer/gfx-wgpu/WGPUQueue.h | 19 +- .../renderer/gfx-wgpu/WGPURenderPass.cpp | 12 +- .../cocos/renderer/gfx-wgpu/WGPURenderPass.h | 11 +- .../cocos/renderer/gfx-wgpu/WGPUSampler.cpp | 40 +- native/cocos/renderer/gfx-wgpu/WGPUSampler.h | 15 +- native/cocos/renderer/gfx-wgpu/WGPUShader.cpp | 121 +- native/cocos/renderer/gfx-wgpu/WGPUShader.h | 20 +- .../cocos/renderer/gfx-wgpu/WGPUSwapchain.cpp | 47 +- .../cocos/renderer/gfx-wgpu/WGPUSwapchain.h | 5 +- .../cocos/renderer/gfx-wgpu/WGPUTexture.cpp | 55 +- native/cocos/renderer/gfx-wgpu/WGPUTexture.h | 21 +- native/cocos/renderer/gfx-wgpu/WGPUUtils.cpp | 49 + native/cocos/renderer/gfx-wgpu/WGPUUtils.h | 58 +- .../gfx-wgpu/states/WGPUBufferBarrier.cpp | 39 + .../gfx-wgpu/states/WGPUBufferBarrier.h | 45 + .../gfx-wgpu/states/WGPUGeneralBarrier.cpp | 39 + .../gfx-wgpu/states/WGPUGeneralBarrier.h | 45 + .../gfx-wgpu/states/WGPUTextureBarrier.cpp | 39 + .../gfx-wgpu/states/WGPUTextureBarrier.h | 42 + scripts/build-engine/.vscode/launch.json | 3 +- scripts/build-engine/src/constant-manager.ts | 2 +- scripts/build-engine/src/index.ts | 10 +- .../src/rollup-plugins/asset-url.ts | 65 + .../tests/stats-query/cc.config.json | 1 + templates/cmake/emscripten.cmake | 0 tests/general/sealed-global-variables.json | 38 +- tsconfig.json | 1 + 76 files changed, 4155 insertions(+), 2180 deletions(-) create mode 100644 @types/url.d.ts create mode 100644 cocos/core/gfx/index.ems.ts create mode 100644 cocos/core/gfx/webgpu/override.ts create mode 100644 cocos/core/gfx/webgpu/webgpu-define.ts create mode 100644 cocos/webgpu/glslang.js create mode 100644 cocos/webgpu/instantiated.ts create mode 100644 cocos/webgpu/webgpu_wasm.js create mode 100644 native/cocos/renderer/gfx-wgpu/WGPUEMSImpl.cpp create mode 100644 native/cocos/renderer/gfx-wgpu/WGPUUtils.cpp create mode 100644 native/cocos/renderer/gfx-wgpu/states/WGPUBufferBarrier.cpp create mode 100644 native/cocos/renderer/gfx-wgpu/states/WGPUBufferBarrier.h create mode 100644 native/cocos/renderer/gfx-wgpu/states/WGPUGeneralBarrier.cpp create mode 100644 native/cocos/renderer/gfx-wgpu/states/WGPUGeneralBarrier.h create mode 100644 native/cocos/renderer/gfx-wgpu/states/WGPUTextureBarrier.cpp create mode 100644 native/cocos/renderer/gfx-wgpu/states/WGPUTextureBarrier.h create mode 100644 scripts/build-engine/src/rollup-plugins/asset-url.ts create mode 100644 templates/cmake/emscripten.cmake diff --git a/.eslintignore b/.eslintignore index ff804edfa6..ba715aa1c5 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1 +1,4 @@ *.jsb.ts +**/*.ems.ts +cocos/core/gfx/webgpu/**/* +cocos/webgpu/**/* \ No newline at end of file diff --git a/@types/url.d.ts b/@types/url.d.ts new file mode 100644 index 0000000000..5c529fa545 --- /dev/null +++ b/@types/url.d.ts @@ -0,0 +1,9 @@ +declare module 'url:native/external/emscripten/webgpu/webgpu_wasm.wasm' { + const url: string; + export default url; +} + +declare module 'url:native/external/emscripten/webgpu/glslang.wasm' { + const url: string; + export default url; +} diff --git a/cc.config.json b/cc.config.json index 97e542bf08..dacad28ce8 100644 --- a/cc.config.json +++ b/cc.config.json @@ -202,6 +202,13 @@ "cocos/3d/misc/create-mesh.ts":"cocos/3d/misc/create-mesh.jsb.ts" } }, + { + "test": "context.buildTimeConstants && context.buildTimeConstants.WEBGPU", + "isVirtualModule": false, + "overrides": { + "cocos/core/gfx/index.ts": "cocos/core/gfx/index.ems.ts" + } + }, { "test": "context.buildTimeConstants && context.buildTimeConstants.HTML5", "isVirtualModule": true, @@ -465,6 +472,12 @@ "type": "number", "value": 0, "internal": false + }, + "WEBGPU": { + "comment": "Running with webgpu rendering backend.", + "type": "boolean", + "value": false, + "internal": true } } } diff --git a/cocos/core/game.ts b/cocos/core/game.ts index d778fdd609..d0a3d02df7 100644 --- a/cocos/core/game.ts +++ b/cocos/core/game.ts @@ -24,7 +24,7 @@ THE SOFTWARE. */ -import { BUILD, DEBUG, EDITOR, HTML5, JSB, NATIVE, PREVIEW, RUNTIME_BASED, TEST } from 'internal:constants'; +import { BUILD, DEBUG, EDITOR, HTML5, JSB, NATIVE, PREVIEW, RUNTIME_BASED, TEST, WEBGPU } from 'internal:constants'; import { systemInfo } from 'pal/system-info'; import { findCanvas, loadJsFile } from 'pal/env'; import { Pacer } from 'pal/pacer'; @@ -84,7 +84,7 @@ export interface IGameConfig { * You can pass in parameters in game.init or override them in the [game.onPostBaseInitDelegate] event callback. * Note: you need to specify this option in the application.js template or add a delegate callback. */ - overrideSettings : Partial<{ [ k in Settings.Category[keyof Settings.Category] ]: Record }> + overrideSettings: Partial<{ [k in Settings.Category[keyof Settings.Category]]: Record }> /** * @zh @@ -602,8 +602,8 @@ export class Game extends EventTarget { public on (type: string, callback: () => void, target?: any, once?: boolean): any { // Make sure EVENT_ENGINE_INITED callbacks to be invoked if ((this._engineInited && type === Game.EVENT_ENGINE_INITED) - || (this._inited && type === Game.EVENT_GAME_INITED) - || (this._rendererInitialized && type === Game.EVENT_RENDERER_INITED)) { + || (this._inited && type === Game.EVENT_GAME_INITED) + || (this._rendererInitialized && type === Game.EVENT_RENDERER_INITED)) { callback.call(target); } return this.eventTargetOn(type, callback, target, once); diff --git a/cocos/core/gfx/device-manager.ts b/cocos/core/gfx/device-manager.ts index 797a8ceb97..b1be249b71 100644 --- a/cocos/core/gfx/device-manager.ts +++ b/cocos/core/gfx/device-manager.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-len */ /* Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. @@ -23,7 +24,7 @@ THE SOFTWARE. */ -import { JSB } from 'internal:constants'; +import { JSB, WEBGPU } from 'internal:constants'; import { legacyCC } from '../global-exports'; import { error, getError } from '../platform/debug'; import { sys } from '../platform/sys'; @@ -88,6 +89,7 @@ export enum RenderType { /** * @internal */ + export class DeviceManager { private initialized = false; private _gfxDevice!: Device; @@ -127,6 +129,9 @@ export class DeviceManager { } const deviceCtors: Constructor[] = []; + if (WEBGPU) { + deviceCtors.push(legacyCC.WebGPUDevice); + } if (useWebGL2 && legacyCC.WebGL2Device) { deviceCtors.push(legacyCC.WebGL2Device); } diff --git a/cocos/core/gfx/index.ems.ts b/cocos/core/gfx/index.ems.ts new file mode 100644 index 0000000000..099d9db83a --- /dev/null +++ b/cocos/core/gfx/index.ems.ts @@ -0,0 +1,64 @@ +/* + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +/** + * @packageDocumentation + * @module gfx + */ + +import { legacyCC } from '../global-exports'; +import { gfx, webgpuAdapter } from '../../webgpu/instantiated'; + +import './deprecated-3.0.0'; + +export { BlendState, PipelineStateInfo, RasterizerState, DepthStencilState, BlendTarget } from './base/pipeline-state' +export * from './base/define'; +export * from './device-manager'; + + +const polyfillCC: Record = { ...gfx }; +polyfillCC.Device = gfx.CCWGPUDevice; +polyfillCC.Swapchain = gfx.CCWGPUSwapchain; +polyfillCC.Buffer = gfx.CCWGPUBuffer; +polyfillCC.Texture = gfx.CCWGPUTexture; +polyfillCC.Sampler = gfx.CCWGPUSampler; +polyfillCC.Shader = gfx.CCWGPUShader; +polyfillCC.InputAssembler = gfx.CCWGPUInputAssembler; +polyfillCC.RenderPass = gfx.CCWGPURenderPass; +polyfillCC.Framebuffer = gfx.CCWGPUFramebuffer; +polyfillCC.DescriptorSet = gfx.CCWGPUDescriptorSet; +polyfillCC.DescriptorSetLayout = gfx.CCWGPUDescriptorSetLayout; +polyfillCC.PipelineLayout = gfx.CCWGPUPipelineLayout; +polyfillCC.PipelineState = gfx.CCWGPUPipelineState; +polyfillCC.CommandBuffer = gfx.CCWGPUCommandBuffer; +polyfillCC.Queue = gfx.CCWGPUQueue; +legacyCC.gfx = polyfillCC; + +export * from './webgpu/override'; +export * from './webgpu/webgpu-define' + +export const WGPU_WASM = true; + +console.log(gfx.Device); diff --git a/cocos/core/gfx/webgpu/override.ts b/cocos/core/gfx/webgpu/override.ts new file mode 100644 index 0000000000..c5a7cd92ed --- /dev/null +++ b/cocos/core/gfx/webgpu/override.ts @@ -0,0 +1,56 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions */ +/* eslint-disable import/no-mutable-exports */ +import { WEBGPU } from 'internal:constants'; +import { gfx, promiseForWebGPUInstantiation } from '../../../webgpu/instantiated'; + +export let Device: any; +export let WebGPUDevice: any; +export let Queue: any; +export let Swapchain: any; +export let Buffer: any; +export let Texture: any; +export let Shader: any; +export let Sampler: any; +export let InputAssembler: any; +export let RenderPass: any; +export let Framebuffer: any; +export let DescriptorSet: any; +export let DescriptorSetLayout: any; +export let PipelineLayout: any; +export let PipelineState: any; +export let CommandBuffer: any; +export let GeneralBarrier: any; +export let TextureBarrier: any; +export let BufferBarrier: any; + +WEBGPU && promiseForWebGPUInstantiation.then(() => { + Device = gfx.CCWGPUDevice; + WebGPUDevice = gfx.CCWGPUDevice; + Queue = gfx.CCWGPUQueue; + Swapchain = gfx.CCWGPUSwapchain; + Buffer = gfx.CCWGPUBuffer; + Texture = gfx.CCWGPUTexture; + Shader = gfx.CCWGPUShader; + Sampler = gfx.CCWGPUSampler; + InputAssembler = gfx.CCWGPUInputAssembler; + RenderPass = gfx.CCWGPURenderPass; + Framebuffer = gfx.CCWGPUFramebuffer; + DescriptorSet = gfx.CCWGPUDescriptorSet; + DescriptorSetLayout = gfx.CCWGPUDescriptorSetLayout; + PipelineLayout = gfx.CCWGPUPipelineLayout; + PipelineState = gfx.CCWGPUPipelineState; + CommandBuffer = gfx.CCWGPUCommandBuffer; + GeneralBarrier = gfx.WGPUGeneralBarrier; + TextureBarrier = gfx.WGPUTextureBarrier; + BufferBarrier = gfx.WGPUBufferBarrier; + + // immutable excluded + [Device, Queue, Swapchain, Buffer, Texture, Shader, InputAssembler, RenderPass, Framebuffer, DescriptorSet, + DescriptorSetLayout, PipelineState, CommandBuffer].forEach((ele) => { + const oldDestroy = ele.prototype.destroy; + ele.prototype.destroy = function () { + oldDestroy.call(this); + this.delete(); + }; + }); +}); diff --git a/cocos/core/gfx/webgpu/webgpu-define.ts b/cocos/core/gfx/webgpu/webgpu-define.ts new file mode 100644 index 0000000000..b10b631264 --- /dev/null +++ b/cocos/core/gfx/webgpu/webgpu-define.ts @@ -0,0 +1,561 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions */ +/* eslint-disable max-len */ +/* eslint-disable @typescript-eslint/no-unsafe-return */ +/* eslint-disable func-names */ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +import { WEBGPU } from 'internal:constants'; +import { gfx, webgpuAdapter, glslalgWasmModule, promiseForWebGPUInstantiation } from '../../../webgpu/instantiated'; +import { + Texture, CommandBuffer, DescriptorSet, Device, InputAssembler, Buffer, +} from './override'; +import { + DeviceInfo, BufferTextureCopy, ShaderInfo, ShaderStageFlagBit, TextureViewInfo, TextureInfo, DrawInfo, BufferViewInfo, BufferInfo, +} from '../base/define'; + +WEBGPU && promiseForWebGPUInstantiation.then(() => { + const originDeviceInitializeFunc = Device.prototype.initialize; + Device.prototype.initialize = function (info: DeviceInfo) { + const adapter = webgpuAdapter.adapter; + const device = webgpuAdapter.device; + gfx.preinitializedWebGPUDevice = device; + device.lost.then((info) => { + console.error('Device was lost.', info); + throw new Error('Something bad happened'); + }); + console.log(adapter); + + originDeviceInitializeFunc.call(this, info); + + return true; + }; + + Device.prototype.flushCommands = function () { + }; + + const oldCreateTexture = Device.prototype.createTexture; + Device.prototype.createTexture = function (info: TextureInfo | TextureViewInfo) { + if ('texture' in info) { + return this.createTextureView(info); + } else { + return oldCreateTexture.call(this, info); + } + }; + + const oldCreateBuffer = Device.prototype.createBuffer; + Device.prototype.createBuffer = function (info: BufferInfo | BufferViewInfo) { + if ('buffer' in info) { + return this.createBufferView(info); + } else { + return oldCreateBuffer.call(this, info); + } + }; + + const oldDraw = CommandBuffer.prototype.draw; + CommandBuffer.prototype.draw = function (info: DrawInfo | typeof InputAssembler) { + if ('attributesHash' in info) { + return this.draw(info.drawInfo); + } else { + return this.drawByInfo(info); + } + }; + + const oldUpdateBuffer = Buffer.prototype.update; + Buffer.prototype.update = function (data: BufferSource, size?: number) { + const updateSize = size === undefined ? data.byteLength : size; + if ('buffer' in data) { + oldUpdateBuffer.call(this, new Uint8Array(data.buffer, data.byteOffset, data.byteLength), updateSize); + } else { + oldUpdateBuffer.call(this, new Uint8Array(data), updateSize); + } + }; + + const oldCmdUpdateBuffer = CommandBuffer.prototype.updateBuffer; + CommandBuffer.prototype.updateBuffer = function (buffer: typeof Buffer, data: BufferSource, size?: number) { + const updateSize = size === undefined ? data.byteLength : size; + + if ('buffer' in data) { + oldCmdUpdateBuffer.call(this, buffer, new Uint8Array(data.buffer, data.byteOffset, data.byteLength), updateSize); + } else { + oldCmdUpdateBuffer.call(this, buffer, new Uint8Array(data), updateSize); + } + }; + + const oldBindDescriptorSet = CommandBuffer.prototype.bindDescriptorSet; + CommandBuffer.prototype.bindDescriptorSet = function (set: number, descriptorSet: typeof DescriptorSet, dynamicOffsets?: Readonly) { + if (dynamicOffsets === undefined) { + oldBindDescriptorSet.call(this, set, descriptorSet, []); + } else if ('buffer' in dynamicOffsets) { + oldBindDescriptorSet.call(this, set, descriptorSet, new Uint32Array((dynamicOffsets as any).buffer, (dynamicOffsets as any).byteOffset, (dynamicOffsets as any).byteLength)); + } else { + oldBindDescriptorSet.call(this, set, descriptorSet, new Uint32Array(dynamicOffsets)); + } + }; + + const oldCmdCopyBuffersToTexture = CommandBuffer.prototype.copyBuffersToTexture; + CommandBuffer.prototype.copyBuffersToTexture = function (buffers: Readonly, texture: typeof Texture, regions: Readonly) { + const ucharBuffers: Uint8Array[] = []; + for (let i = 0; i < buffers.length; ++i) { + const buffer = buffers[i]; + if ('buffer' in buffer) { + ucharBuffers.push(new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)); + } else { + ucharBuffers.push(new Uint8Array(buffer as any)); + } + } + oldCmdCopyBuffersToTexture.call(this, ucharBuffers, texture, regions); + }; + + const oldDeviceCopyBuffersToTexture = Device.prototype.copyBuffersToTexture; + Device.prototype.copyBuffersToTexture = function (buffers: Readonly, texture: typeof Texture, regions: Readonly) { + const ucharBuffers: Uint8Array[] = []; + for (let i = 0; i < buffers.length; ++i) { + const buffer = buffers[i]; + if ('buffer' in buffer) { + ucharBuffers.push(new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)); + } else { + ucharBuffers.push(new Uint8Array(buffer as any)); + } + } + oldDeviceCopyBuffersToTexture.call(this, ucharBuffers, texture, regions); + }; + + Device.prototype.copyTexImagesToTexture = function (texImages: TexImageSource[], texture: typeof Texture, regions: BufferTextureCopy[]) { + const buffers: Uint8Array[] = []; + for (let i = 0; i < regions.length; i++) { + if ('getContext' in texImages[i]) { + const canvasElem = texImages[i] as HTMLCanvasElement; + const imageData = canvasElem.getContext('2d')?.getImageData(0, 0, texImages[i].width, texImages[i].height); + const buff = imageData!.data.buffer; + let data; + let rawBuffer; + if ('buffer' in buff) { + // es-lint as any + data = new Uint8Array((buff as any).buffer, (buff as any).byteOffset, (buff as any).byteLength); + } else { + rawBuffer = buff; + data = new Uint8Array(rawBuffer); + } + buffers[i] = data; + } else if (texImages[i] instanceof HTMLImageElement) { + const img = texImages[i] as HTMLImageElement; + const canvas = document.createElement('canvas'); + canvas.width = img.width; + canvas.height = img.height; + const ctx = canvas.getContext('2d'); + ctx?.drawImage(img, 0, 0); + const imageData = ctx?.getImageData(0, 0, img.width, img.height); + const buff = imageData!.data.buffer; + let data; + let rawBuffer; + if ('buffer' in buff) { + // es-lint as any + data = new Uint8Array((buff as any).buffer, (buff as any).byteOffset, (buff as any).byteLength); + } else { + rawBuffer = buff; + data = new Uint8Array(rawBuffer); + } + buffers[i] = data; + } else { + console.log('imageBmp copy not impled!'); + } + } + + oldDeviceCopyBuffersToTexture.call(this, buffers, texture, regions); + }; + + function seperateCombinedSamplerTexture (shaderSource: string) { + // sampler and texture + const samplerTexturArr = shaderSource.match(/(.*?)\(set = \d+, binding = \d+\) uniform(.*?)sampler\w* \w+;/g); + const count = samplerTexturArr?.length ? samplerTexturArr?.length : 0; + let code = shaderSource; + + const referredFuncMap = new Map(); + const samplerSet = new Set(); + samplerTexturArr?.every((str) => { + let textureName = str.match(/(?<=uniform(.*?)sampler\w* )(\w+)(?=;)/g)!.toString(); + let samplerStr = str.replace(textureName, `${textureName}Sampler`); + let samplerFunc = samplerStr.match(/(?<=uniform(.*?))sampler(\w*)/g)!.toString(); + samplerFunc = samplerFunc.replace('sampler', ''); + if (samplerFunc === '') { + textureName = textureName.replace('Sampler', ''); + } else { + samplerStr = samplerStr.replace(/(?<=uniform(.*?))(sampler\w*)/g, 'sampler'); + + // layout (set = a, binding = b) uniform sampler2D cctex; + // to: + // layout (set = a, binding = b) uniform sampler cctexSampler; + // layout (set = a, binding = b + maxTextureNum) uniform texture2D cctex; + const samplerReg = /(?<=binding = )(\d+)(?=\))/g; + const samplerBindingStr = str.match(samplerReg)!.toString(); + const samplerBinding = Number(samplerBindingStr) + 16; + samplerStr = samplerStr.replace(samplerReg, samplerBinding.toString()); + + const textureStr = str.replace(/(?<=uniform(.*?))(sampler)(?=\w*)/g, 'texture'); + code = code.replace(str, `${textureStr}\n${samplerStr}`); + } + + if (!samplerSet.has(`${textureName}Sampler`)) { + samplerSet.add(`${textureName}Sampler`); + // gathering referred func + let referredFuncStr = `([\\w]+)[\\s]*\\([0-9a-zA-Z_\\s,]*?sampler${samplerFunc}[^\\)]+\\)[\\s]*{`; + if (samplerFunc === '') { + referredFuncStr = `([\\w]+)[\\s]*\\([0-9a-zA-Z_\\s,]*?sampler([\\S]+)[^\\)]+\\)[\\s]*{`; + } + const referredFuncRe = new RegExp(referredFuncStr, 'g'); + let reArr = referredFuncRe.exec(code); + while (reArr) { + // first to see if it's wrapped by #if 0 \n ... \n #ndif + let smpFunc = samplerFunc; + if (smpFunc === '') { + smpFunc = reArr[2]; + } + const searchTarget = code.slice(0, reArr.index); + const defValQueue: { str: string, b: boolean, condition: RegExpExecArray }[] = []; + let searchIndex = 1; + + while (searchIndex > 0) { + let ifIndex = searchTarget.indexOf('#if', searchIndex); + let elseIndex = searchTarget.indexOf('#else', searchIndex); + let endIndex = searchTarget.indexOf('#endif', searchIndex); + + if (ifIndex === -1 && elseIndex === -1 && endIndex === -1) { + break; + } + + if (ifIndex === -1) ifIndex = Number.MAX_SAFE_INTEGER; + if (elseIndex === -1) elseIndex = Number.MAX_SAFE_INTEGER; + if (endIndex === -1) endIndex = Number.MAX_SAFE_INTEGER; + + // next start with '#' is #if(def) + if (ifIndex < elseIndex && ifIndex < endIndex) { + const ifdef = (new RegExp(`#if(def)?[\\s]+(!)?([\\S]+)([\\s+]?(==)?(!=)[\\s+]?([\\S]+))?`, 'gm')).exec(searchTarget.slice(ifIndex))!; + defValQueue[defValQueue.length] = { str: ifdef[3], b: true, condition: ifdef }; + searchIndex = ifIndex + 1; + continue; + } + + if (elseIndex < endIndex && elseIndex < ifIndex) { + defValQueue[defValQueue.length - 1].b = false; + searchIndex = elseIndex + 1; + continue; + } + + if (endIndex < elseIndex && endIndex < ifIndex) { + defValQueue.pop(); + searchIndex = endIndex + 1; + continue; + } + } + + let defCheck = true; + for (let i = 0; i < defValQueue.length; i++) { + const ifdef = defValQueue[i].condition; + let evalRes = false; + if (ifdef[1]) { + evalRes = !!(new RegExp(`#define[\\s]+${ifdef[3]}`, 'gm')).exec(searchTarget); + } else { + const defVal = (new RegExp(`#define[\\s]+${ifdef[3]}[\\s]+([\\S]+).*`, 'gm')).exec(searchTarget)![1]; + if (ifdef[4]) { + const conditionVal = ifdef[7]; + evalRes = ifdef[5] ? defVal === conditionVal : defVal !== conditionVal; + } else if (ifdef[3]) { + evalRes = (defVal !== '0' && !ifdef[2]); + } + } + + if (defValQueue[i].b !== evalRes) { + defCheck = false; + break; + } + } + + const key = `${reArr[1]}_${smpFunc}_${textureName}Sampler`; + if (!referredFuncMap.has(key) && defCheck) { + referredFuncMap.set(key, [reArr[1], smpFunc, `${textureName}Sampler`]); + } + reArr = referredFuncRe.exec(code); + } + } + + // cctex in main() called directly + // .*?texture\( + const regStr = `texture\\(\\b(${textureName})\\b`; + const re = new RegExp(regStr); + let reArr = re.exec(code); + while (reArr) { + code = code.replace(re, `texture(sampler${samplerFunc}(${textureName},${textureName}Sampler)`); + reArr = re.exec(code); + } + return true; + }); + + const functionTemplates = new Map(); + const functionDeps = new Map(); + let forwardDecls = ''; + // function + referredFuncMap.forEach((pair) => { + //pre: if existed, replace + //getVec3DisplacementFromTexture\(cc_TangentDisplacements[^\\n]+ + const textureStr = pair[2].slice(0, -7); + const codePieceStr = `${pair[0]}\\((.*?)${textureStr}[^\\n]+`; + const codePieceRe = new RegExp(codePieceStr); + let res = codePieceRe.exec(code); + while (res) { + let replaceStr = res[0].replace(`${pair[0]}(`, `${pair[0]}_${pair[1]}_${pair[2]}_specialized(`); + replaceStr = replaceStr.replace(`${textureStr},`, ''); + code = code.replace(codePieceRe, replaceStr); + res = codePieceRe.exec(code); + } + + // 1. fn definition + const fnDeclReStr = `[\\n|\\W][\\w]+[\\W]+${pair[0]}[\\s]*\\((.*?)sampler${pair[1]}[^{]+`; + const fnDeclRe = new RegExp(fnDeclReStr); + const fnDecl = fnDeclRe.exec(code); + + let redefFunc = ''; + if (!functionTemplates.has(`${pair[0]}_${pair[1]}`)) { + const funcBodyStart = code.slice(fnDecl!.index); + + const funcRedefine = (funcStr: string) => { + const samplerType = `sampler${pair[1]}`; + const textureRe = (new RegExp(`.*?${samplerType}[\\s]+([\\S]+)[,\\)]`)).exec(funcStr)!; + const textureName = textureRe[1]; + const paramReStr = `${samplerType}[\\s]+${textureName}`; + let funcDef = funcStr.replace(new RegExp(paramReStr), `texture${pair[1]} ${textureName}`); + funcDef = funcDef.replace(pair[0], `${pair[0]}SAMPLER_SPEC`); + // 2. texture(...) inside, builtin funcs + const textureOpArr = ['texture', 'textureSize', 'texelFetch', 'textureLod']; + for (let i = 0; i < textureOpArr.length; i++) { + const texFuncReStr = `(${textureOpArr[i]})\\(${textureName},`; + const texFuncRe = new RegExp(texFuncReStr, 'g'); + funcDef = funcDef.replace(texFuncRe, `$1(${samplerType}(${textureName}TEXTURE_HOLDER, ${textureName}SAMPLER_HOLDER),`); + } + return funcDef; + }; + + const firstIfStatement = funcBodyStart.indexOf('#if'); + const firstElseStatement = funcBodyStart.indexOf('#e'); //#endif, #else, #elif maybe? + if ((firstElseStatement !== -1 && firstIfStatement > firstElseStatement) || (firstElseStatement === -1 && firstElseStatement !== -1)) { // ooops, now func body starts in a #if statement. + let startIndex = 0; + let count = 1; // already in #if + while (count > 0 && startIndex < funcBodyStart.length) { + const nextSymbolIdx = funcBodyStart.indexOf('#', startIndex); + const startSliceIdx = startIndex === 0 ? startIndex : startIndex - 1; + if (funcBodyStart[nextSymbolIdx + 1] === 'i') { // #if + count++; + redefFunc += funcBodyStart.slice(startSliceIdx, nextSymbolIdx); + } else if (funcBodyStart[nextSymbolIdx + 1] === 'e' && funcBodyStart[nextSymbolIdx + 2] === 'l') { //#elif, #else + if (count === 1) { + const tempFuncStr = funcBodyStart.slice(startSliceIdx, nextSymbolIdx - 1); + const funcDefStr = funcRedefine(tempFuncStr); + redefFunc += `\n${funcDefStr}`; + } else { + redefFunc += `\n${funcBodyStart.slice(startSliceIdx, nextSymbolIdx)}`; + } + } else if (funcBodyStart[nextSymbolIdx + 1] === 'e' && funcBodyStart[nextSymbolIdx + 2] === 'n') { //#endif + count--; + if (count === 0) { + const tempFuncStr = funcBodyStart.slice(startSliceIdx, nextSymbolIdx - 1); + const funcDefStr = funcRedefine(tempFuncStr); + redefFunc += `\n${funcDefStr}`; + } else { + redefFunc += `\n${funcBodyStart.slice(startSliceIdx, nextSymbolIdx)}`; + } + } else { // #define, dont care + redefFunc += funcBodyStart.slice(startSliceIdx, nextSymbolIdx); + } + startIndex = nextSymbolIdx + 1; + } + + //`(?:.(?!layout))+${pair[2]};` + const searchTarget = code.slice(0, fnDecl!.index); + const res = (new RegExp(`#if.+[\\s]*$`)).exec(searchTarget); + redefFunc = `${res![0]}${redefFunc}\n#endif`; + } else { + let count = 0; + let matchBegin = false; + let startIndex = 0; + let endIndex = 0; + for (let i = 0; i < funcBodyStart.length; ++i) { + if (funcBodyStart[i] === '{') { + ++count; + if (!matchBegin) { + matchBegin = true; + startIndex = i; + } + } else if (funcBodyStart[i] === '}') { + --count; + } + + if (matchBegin && count === 0) { + endIndex = i; + break; + } + } + const rawFunc = `${fnDecl![0]}${funcBodyStart.slice(startIndex, endIndex + 1)}`; + redefFunc = funcRedefine(rawFunc); + } + + functionTemplates.set(`${pair[0]}_${pair[1]}`, redefFunc); + } else { + redefFunc = functionTemplates.get(`${pair[0]}_${pair[1]}`)!; + } + + const depsFuncs: string[] = []; + + const iterator = referredFuncMap.values(); + let val = iterator.next().value; + while (val) { + const funcDepReStr = `\\b(${val[0] as string})\\b`; + if (redefFunc.search(funcDepReStr) !== -1) { + depsFuncs[depsFuncs.length] = val[0]; + } + val = iterator.next().value; + } + // for (let i = 0; i < referredFuncMap.values.length; ++i) { + // const funcDepReStr = `\\b(${referredFuncMap.values[i].fnName as string})\\b`; + // if (redefFunc.search(funcDepReStr) !== -1) { + // depsFuncs[depsFuncs.length] = referredFuncMap.values[i].fnName; + // } + // } + functionDeps.set(`${pair[0]}_${pair[1]}`, depsFuncs); + + const specializedFuncs = new Map(); + const specialize = (funcs: string[]) => { + funcs.every((str) => { + if (!specializedFuncs.has(`${pair[0]}_${pair[2]}_specialized`)) { + const samplerReStr = `(\\w+)SAMPLER_HOLDER`; + const textureName = pair[2].slice(0, pair[2].length - 7); // xxxxSampler + const textureStr = `(\\w+)TEXTURE_HOLDER`; + let funcTemplate = functionTemplates.get(str); + funcTemplate = funcTemplate!.replace(new RegExp(samplerReStr, 'g'), pair[2]); + funcTemplate = funcTemplate.replace(new RegExp(textureStr, 'g'), textureName); + funcTemplate = funcTemplate.replace(new RegExp('SAMPLER_SPEC', 'g'), `_${pair[1]}_${pair[2]}_specialized`); + funcTemplate = funcTemplate.replace(new RegExp(`texture${pair[1]}\\s+\\w+,`, 'g'), ''); + // funcTemplate = funcTemplate.replace('SAMPLER_SPEC', `_${pair[2]}_specialized`); + + for (let i = 0; i < depsFuncs.length; ++i) { + const depFuncStr = `${depsFuncs[i]}([\\W]?)*\\([^,)]+(,)?`; + funcTemplate = funcTemplate.replace(new RegExp(depFuncStr, 'g'), `${depsFuncs[i]}_${pair[1]}_${pair[2]}_specialized(`); + } + + let declStr = fnDecl![0].replace(pair[0], `${str}_${pair[2]}_specialized`); + declStr = declStr.replace(new RegExp(`sampler${pair[1]}[^,)]+(,)?`, 'g'), ``); + declStr += `;`; + specializedFuncs.set(declStr, funcTemplate); + } else { + return specialize(functionDeps.get(str)!); + } + return true; + }); + return true; + }; + specialize([`${pair[0]}_${pair[1]}`]); + //(?:.(?!layout))+cc_PositionDisplacementsSampler; + const samplerDefReStr = `(?:.(?!layout))+${pair[2]};`; + const samplerDef = (new RegExp(samplerDefReStr)).exec(code); + + let funcImpls = ''; + for (const [key, value] of specializedFuncs) { + forwardDecls += `\n${key}\n`; + funcImpls += `\n${value}\n`; + } + + code = code.replace(samplerDef![0], `${samplerDef![0]}\n${funcImpls}`); + }); + + // some function appears before it's defined so forward declaration is needed + forwardDecls += '\nvec3 SRGBToLinear (vec3 gamma);\nfloat getDisplacementWeight(int index);\n'; + + const highpIdx = code.indexOf('precision highp'); + const mediumpIdx = code.indexOf('precision mediump'); + const lowpIdx = code.indexOf('precision lowp'); + + /////////////////////////////////////////////////////////// + // isNan, isInf has been removed in dawn:tint + + let functionDefs = ''; + const precisionKeyWord = 'highp'; + + // const getPrecision = (idx: number) => { + // if (highpIdx !== -1 && highpIdx < idx) { + // precisionKeyWord = 'highp'; + // } else if (mediumpIdx !== -1 && mediumpIdx < idx && highpIdx < mediumpIdx) { + // precisionKeyWord = 'mediump'; + // } else if (lowpIdx !== -1 && lowpIdx < idx && mediumpIdx < lowpIdx && highpIdx < lowpIdx) { + // precisionKeyWord = 'lowp'; + // } + // }; + + const isNanIndex = code.indexOf('isnan'); + if (isNanIndex !== -1) { + // getPrecision(isNanIndex); + functionDefs += `\n + bool isNan(${precisionKeyWord} float val) { + return (val < 0.0 || 0.0 < val || val == 0.0) ? false : true; + } + \n`; + code = code.replace(/isnan\(/gi, 'isNan('); + } + + const isInfIndex = code.indexOf('isinf'); + if (isInfIndex !== -1) { + // getPrecision(isInfIndex); + functionDefs += `\n + bool isInf(${precisionKeyWord} float x) { + return x == x * 2.0 && x != 0.0; + } + \n`; + code = code.replace(/isinf\(/gi, 'isInf('); + } + + /////////////////////////////////////////////////////////// + + let firstPrecisionIdx = code.indexOf('precision'); + firstPrecisionIdx = code.indexOf(';', firstPrecisionIdx); + firstPrecisionIdx += 1; + code = `${code.slice(0, firstPrecisionIdx)}\n${forwardDecls}\n${functionDefs}\n${code.slice(firstPrecisionIdx)}`; + + return code; + } + + const createShader = Device.prototype.createShader; + Device.prototype.createShader = function (shaderInfo: ShaderInfo) { + const spvDatas: any = []; + for (let i = 0; i < shaderInfo.stages.length; ++i) { + shaderInfo.stages[i].source = seperateCombinedSamplerTexture(shaderInfo.stages[i].source); + const stageStr = shaderInfo.stages[i].stage === ShaderStageFlagBit.VERTEX ? 'vertex' + : shaderInfo.stages[i].stage === ShaderStageFlagBit.FRAGMENT ? 'fragment' : 'compute'; + const sourceCode = `#version 450\n${shaderInfo.stages[i].source}`; + const spv = glslalgWasmModule.glslang.compileGLSL(sourceCode, stageStr, true, '1.3'); + spvDatas.push(spv); + } + + const shader = this.createShaderNative(shaderInfo, spvDatas); + return shader; + }; +}); diff --git a/cocos/core/pipeline/instanced-buffer.ts b/cocos/core/pipeline/instanced-buffer.ts index a238225418..342fbc63a1 100644 --- a/cocos/core/pipeline/instanced-buffer.ts +++ b/cocos/core/pipeline/instanced-buffer.ts @@ -70,17 +70,17 @@ export class InstancedBuffer { if (!stride) { return; } // we assume per-instance attributes are always present const sourceIA = subModel.inputAssembler; const lightingMap = subModel.descriptorSet.getTexture(UNIFORM_LIGHTMAP_TEXTURE_BINDING); - let shader = shaderImplant; + let shader = shaderImplant; if (!shader) { shader = subModel.shaders[passIdx]; } const descriptorSet = subModel.descriptorSet; for (let i = 0; i < this.instances.length; ++i) { const instance = this.instances[i]; - if (instance.ia.indexBuffer !== sourceIA.indexBuffer || instance.count >= MAX_CAPACITY) { continue; } + if (instance.ia.indexBuffer?.objectID !== sourceIA.indexBuffer?.objectID || instance.count >= MAX_CAPACITY) { continue; } // check same binding - if (instance.lightingMap !== lightingMap) { + if (instance.lightingMap.objectID !== lightingMap.objectID) { continue; } @@ -97,8 +97,8 @@ export class InstancedBuffer { instance.data.set(oldData); instance.vb.resize(newSize); } - if (instance.shader !== shader) { instance.shader = shader; } - if (instance.descriptorSet !== descriptorSet) { instance.descriptorSet = descriptorSet; } + if (instance.shader?.objectID !== shader.objectID) { instance.shader = shader; } + if (instance.descriptorSet.objectID !== descriptorSet.objectID) { instance.descriptorSet = descriptorSet; } instance.data.set(attrs.buffer, instance.stride * instance.count++); this.hasPendingModels = true; return; diff --git a/cocos/core/pipeline/pipeline-ubo.ts b/cocos/core/pipeline/pipeline-ubo.ts index 4dcc51158d..ca666b865a 100644 --- a/cocos/core/pipeline/pipeline-ubo.ts +++ b/cocos/core/pipeline/pipeline-ubo.ts @@ -514,7 +514,7 @@ export class PipelineUBO { globalDS.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); globalDS.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); globalDS.update(); - globalDS.getBuffer(UBOShadow.BINDING).update(this._shadowUBO); + this._pipeline.commandBuffers[0].updateBuffer(globalDS.getBuffer(UBOShadow.BINDING), this._shadowUBO); } public updateShadowUBORange (offset: number, data: Mat4 | Color) { diff --git a/cocos/core/pipeline/shadow/shadow-flow.ts b/cocos/core/pipeline/shadow/shadow-flow.ts index bfc9f2e0f5..092ec4e24b 100644 --- a/cocos/core/pipeline/shadow/shadow-flow.ts +++ b/cocos/core/pipeline/shadow/shadow-flow.ts @@ -298,12 +298,9 @@ export class ShadowFlow extends RenderFlow { const shadowFrameBufferMap = pipeline.pipelineSceneData.shadowFrameBufferMap; const format = supportsR32FloatTexture(device) ? Format.R32F : Format.RGBA8; - const it = shadowFrameBufferMap.values(); - let res = it.next(); - while (!res.done) { - const frameBuffer = res.value; + for (const key of shadowFrameBufferMap.keys()) { + const frameBuffer = shadowFrameBufferMap.get(key); if (!frameBuffer) { - res = it.next(); continue; } @@ -321,13 +318,12 @@ export class ShadowFlow extends RenderFlow { const shadowRenderPass = frameBuffer.renderPass; frameBuffer.destroy(); - frameBuffer.initialize(new FramebufferInfo( + const newFrameBuffer = device.createFramebuffer(new FramebufferInfo( shadowRenderPass, renderTargets, depth, )); - - res = it.next(); + shadowFrameBufferMap.set(key, newFrameBuffer); } shadows.shadowMapDirty = false; diff --git a/cocos/webgpu/glslang.js b/cocos/webgpu/glslang.js new file mode 100644 index 0000000000..c5759a65e6 --- /dev/null +++ b/cocos/webgpu/glslang.js @@ -0,0 +1,137 @@ +var Module = (function() { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + + return ( + function(Module) { + Module = Module || {}; + + var c;c||(c=typeof Module !== 'undefined' ? Module : {}); + c.compileGLSLZeroCopy=function(a,b,d,e){d=!!d;switch(b){case "vertex":var g=0;break;case "fragment":g=4;break;case "compute":g=5;break;default:throw Error("shader_stage must be 'vertex', 'fragment', or 'compute'.");}switch(e||"1.0"){case "1.0":var f=65536;break;case "1.1":f=65792;break;case "1.2":f=66048;break;case "1.3":f=66304;break;case "1.4":f=66560;break;case "1.5":f=66816;break;default:throw Error("spirv_version must be '1.0' ~ '1.5'.");}e=c._malloc(4);b=c._malloc(4);var h=aa([a,g,d,f,e,b]); + d=k(e);a=k(b);c._free(e);c._free(b);if(0===h)throw Error("GLSL compilation failed");e={};d/=4;e.data=c.HEAPU32.subarray(d,d+a);e.free=function(){c._destroy_output_buffer(h)};return e};c.compileGLSL=function(a,b,d,e){a=c.compileGLSLZeroCopy(a,b,d,e);b=a.data.slice();a.free();return b};var p={},q;for(q in c)c.hasOwnProperty(q)&&(p[q]=c[q]);var r="./this.program",t=!1,u=!1;t="object"===typeof window;u="function"===typeof importScripts;var v="",w; + if(t||u)u?v=self.location.href:document.currentScript&&(v=document.currentScript.src),_scriptDir&&(v=_scriptDir),0!==v.indexOf("blob:")?v=v.substr(0,v.lastIndexOf("/")+1):v="",u&&(w=function(a){var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)});var x=c.print||console.log.bind(console),y=c.printErr||console.warn.bind(console);for(q in p)p.hasOwnProperty(q)&&(c[q]=p[q]);p=null;c.thisProgram&&(r=c.thisProgram);var A; + c.wasmBinary&&(A=c.wasmBinary);"object"!==typeof WebAssembly&&y("no native wasm support detected");function k(a){var b="i32";"*"===b.charAt(b.length-1)&&(b="i32");switch(b){case "i1":return B[a>>0];case "i8":return B[a>>0];case "i16":return ba[a>>1];case "i32":return C[a>>2];case "i64":return C[a>>2];case "float":return ca[a>>2];case "double":return da[a>>3];default:D("invalid type for getValue: "+b)}return null}var E,ea=new WebAssembly.Table({initial:859,maximum:859,element:"anyfunc"}),fa=!1; + function ha(){var a=c._convert_glsl_to_spirv;a||D("Assertion failed: Cannot call unknown function convert_glsl_to_spirv, make sure it is exported");return a} + function aa(a){var b="string number boolean number number number".split(" "),d={string:function(a){var b=0;if(null!==a&&void 0!==a&&0!==a){var d=(a.length<<2)+1;b=G(d);ia(a,H,b,d)}return b},array:function(a){var b=G(a.length);B.set(a,b);return b}},e=ha(),g=[],f=0;if(a)for(var h=0;h=e);)++d;if(16g?e+=String.fromCharCode(g):(g-=65536,e+=String.fromCharCode(55296|g>>10,56320|g&1023))}}else e+=String.fromCharCode(g)}return e} + function ia(a,b,d,e){if(0=f){var h=a.charCodeAt(++g);f=65536+((f&1023)<<10)|h&1023}if(127>=f){if(d>=e)break;b[d++]=f}else{if(2047>=f){if(d+1>=e)break;b[d++]=192|f>>6}else{if(65535>=f){if(d+2>=e)break;b[d++]=224|f>>12}else{if(d+3>=e)break;b[d++]=240|f>>18;b[d++]=128|f>>12&63}b[d++]=128|f>>6&63}b[d++]=128|f&63}}b[d]=0}}"undefined"!==typeof TextDecoder&&new TextDecoder("utf-16le");var J,B,H,ba,C,ca,da; + function ma(a){J=a;c.HEAP8=B=new Int8Array(a);c.HEAP16=ba=new Int16Array(a);c.HEAP32=C=new Int32Array(a);c.HEAPU8=H=new Uint8Array(a);c.HEAPU16=new Uint16Array(a);c.HEAPU32=new Uint32Array(a);c.HEAPF32=ca=new Float32Array(a);c.HEAPF64=da=new Float64Array(a)}var na=c.TOTAL_MEMORY||16777216;c.wasmMemory?E=c.wasmMemory:E=new WebAssembly.Memory({initial:na/65536});E&&(J=E.buffer);na=J.byteLength;ma(J);C[84916]=5582704; + function K(a){for(;0>2]}var Q={},Ba={}; + function Ca(){if(!R){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"===typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:r},b;for(b in Ba)a[b]=Ba[b];var d=[];for(b in a)d.push(b+"="+a[b]);R=d}return R}var R;function S(a){return 0===a%4&&(0!==a%100||0===a%400)}function T(a,b){for(var d=0,e=0;e<=b;d+=a[e++]);return d}var U=[31,29,31,30,31,30,31,31,30,31,30,31],W=[31,28,31,30,31,30,31,31,30,31,30,31]; + function X(a,b){for(a=new Date(a.getTime());0e-a.getDate())b-=e-a.getDate()+1,a.setDate(1),11>d?a.setMonth(d+1):(a.setMonth(0),a.setFullYear(a.getFullYear()+1));else{a.setDate(a.getDate()+b);break}}return a} + function Da(a,b,d,e){function g(a,b,d){for(a="number"===typeof a?a.toString():a||"";a.lengtha?-1:0=h(n(new Date(a.getFullYear(),0,4)),a)?0>=h(b,a)?a.getFullYear()+1:a.getFullYear():a.getFullYear()-1}var m=C[e+40>>2];e={N:C[e>>2],M:C[e+4>>2],D:C[e+8>>2],C:C[e+12>>2],B:C[e+16>>2],A:C[e+20>>2],F:C[e+24>>2],G:C[e+28>>2],X:C[e+32>>2],L:C[e+36>>2],O:m?m?I(H,m,void 0): + "":""};d=d?I(H,d,void 0):"";m={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var l in m)d=d.replace(new RegExp(l,"g"),m[l]);var F="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), + va="January February March April May June July August September October November December".split(" ");m={"%a":function(a){return F[a.F].substring(0,3)},"%A":function(a){return F[a.F]},"%b":function(a){return va[a.B].substring(0,3)},"%B":function(a){return va[a.B]},"%C":function(a){return f((a.A+1900)/100|0,2)},"%d":function(a){return f(a.C,2)},"%e":function(a){return g(a.C,2," ")},"%g":function(a){return z(a).toString().substring(2)},"%G":function(a){return z(a)},"%H":function(a){return f(a.D,2)}, + "%I":function(a){a=a.D;0==a?a=12:12a.D?"AM":"PM"},"%S":function(a){return f(a.N,2)},"%t":function(){return"\t"},"%u":function(a){return a.F||7},"%U":function(a){var b=new Date(a.A+1900,0,1),d=0===b.getDay()?b:X(b,7-b.getDay());a=new Date(a.A+1900,a.B,a.C);return 0>h(d,a)?f(Math.ceil((31- + d.getDate()+(T(S(a.getFullYear())?U:W,a.getMonth()-1)-31)+a.getDate())/7),2):0===h(d,b)?"01":"00"},"%V":function(a){var b=n(new Date(a.A+1900,0,4)),d=n(new Date(a.A+1901,0,4)),e=X(new Date(a.A+1900,0,1),a.G);return 0>h(e,b)?"53":0>=h(d,e)?"01":f(Math.ceil((b.getFullYear()h(d,a)?f(Math.ceil((31- + d.getDate()+(T(S(a.getFullYear())?U:W,a.getMonth()-1)-31)+a.getDate())/7),2):0===h(d,b)?"01":"00"},"%y":function(a){return(a.A+1900).toString().substring(2)},"%Y":function(a){return a.A+1900},"%z":function(a){a=a.L;var b=0<=a;a=Math.abs(a)/60;return(b?"+":"-")+String("0000"+(a/60*100+a%60)).slice(-4)},"%Z":function(a){return a.O},"%%":function(){return"%"}};for(l in m)0<=d.indexOf(l)&&(d=d.replace(new RegExp(l,"g"),m[l](e)));l=Ea(d);if(l.length>b)return 0;B.set(l,a);return l.length-1} + function Ea(a){for(var b=0,d=0;d=e&&(e=65536+((e&1023)<<10)|a.charCodeAt(++d)&1023);127>=e?++b:b=2047>=e?b+2:65535>=e?b+3:b+4}b=Array(b+1);ia(a,b,0,b.length);return b} + var Ga={f:function(){},c:function(){c.___errno_location&&(C[c.___errno_location()>>2]=63);return-1},n:function(a,b){P=b;try{var d=Aa();var e=Aa();if(-1===d||0===e)var g=-28;else{var f=Q.K[d];if(f&&e===f.U){var h=(void 0).T(f.S);Q.R(d,h,e,f.flags,f.offset);(void 0).W(h);Q.K[d]=null;f.P&&Fa(f.V)}g=0}return g}catch(n){return D(n),-n.I}},a:function(){},b:function(){D()},k:function(a,b,d){H.set(H.subarray(b,b+d),a)},l:function(a){var b=B.length;if(2147418112=d;d*=2){var e=b*(1+ + .2/d);e=Math.min(e,a+100663296);e=Math.max(16777216,a,e);0>16);ma(E.buffer);var g=1;break a}catch(f){}g=void 0}if(g)return!0}return!1},d:function(a,b){var d=0;Ca().forEach(function(e,g){var f=b+d;g=C[a+4*g>>2]=f;for(f=0;f>0]=e.charCodeAt(f);B[g>>0]=0;d+=e.length+1});return 0},e:function(a,b){var d=Ca();C[a>>2]=d.length;var e=0;d.forEach(function(a){e+=a.length+1});C[b>>2]=e;return 0},h:function(){return 0}, + j:function(){return 0},g:function(a,b,d,e){try{for(var g=0,f=0;f>2],n=C[b+(8*f+4)>>2],z=0;z>2]=g;return 0}catch(F){return D(F),F.I}},memory:E,o:function(){},i:function(){},m:function(a,b,d,e){return Da(a,b,d,e)},table:ea},Ha=function(){function a(a){c.asm=a.exports;L--;c.monitorRunDependencies&&c.monitorRunDependencies(L);0==L&&(null!==M&&(clearInterval(M),M=null),N&&(a=N,N=null, + a()))}function b(b){a(b.instance)}function d(a){return xa().then(function(a){return WebAssembly.instantiate(a,e)}).then(a,function(a){y("failed to asynchronously prepare wasm: "+a);D(a)})}var e={env:Ga,wasi_snapshot_preview1:Ga};L++;c.monitorRunDependencies&&c.monitorRunDependencies(L);if(c.instantiateWasm)try{return c.instantiateWasm(e,a)}catch(g){return y("Module.instantiateWasm callback failed with error: "+g),!1}(function(){if(A||"function"!==typeof WebAssembly.instantiateStreaming||ta()||"function"!== + typeof fetch)return d(b);fetch(O,{credentials:"same-origin"}).then(function(a){return WebAssembly.instantiateStreaming(a,e).then(b,function(a){y("wasm streaming compile failed: "+a);y("falling back to ArrayBuffer instantiation");d(b)})})})();return{}}();c.asm=Ha;var ya=c.___wasm_call_ctors=function(){return(ya=c.___wasm_call_ctors=c.asm.p).apply(null,arguments)};c._convert_glsl_to_spirv=function(){return(c._convert_glsl_to_spirv=c.asm.q).apply(null,arguments)}; + c._destroy_output_buffer=function(){return(c._destroy_output_buffer=c.asm.r).apply(null,arguments)};c._malloc=function(){return(c._malloc=c.asm.s).apply(null,arguments)};var Fa=c._free=function(){return(Fa=c._free=c.asm.t).apply(null,arguments)},ja=c.stackSave=function(){return(ja=c.stackSave=c.asm.u).apply(null,arguments)},G=c.stackAlloc=function(){return(G=c.stackAlloc=c.asm.v).apply(null,arguments)},ka=c.stackRestore=function(){return(ka=c.stackRestore=c.asm.w).apply(null,arguments)}; + c.dynCall_vi=function(){return(c.dynCall_vi=c.asm.x).apply(null,arguments)};c.dynCall_v=function(){return(c.dynCall_v=c.asm.y).apply(null,arguments)};c.asm=Ha;var Y;c.then=function(a){if(Y)a(c);else{var b=c.onRuntimeInitialized;c.onRuntimeInitialized=function(){b&&b();a(c)}}return c};N=function Ia(){Y||Z();Y||(N=Ia)}; + function Z(){function a(){if(!Y&&(Y=!0,!fa)){K(pa);K(qa);if(c.onRuntimeInitialized)c.onRuntimeInitialized();if(c.postRun)for("function"==typeof c.postRun&&(c.postRun=[c.postRun]);c.postRun.length;){var a=c.postRun.shift();ra.unshift(a)}K(ra)}}if(!(0 { + // const initialize = () => { + // return new Promise(resolve => { + // Module({ + // locateFile() { + // const i = import.meta.url.lastIndexOf('/') + // return import.meta.url.substring(0, i) + '/glslang.wasm'; + // }, + // onRuntimeInitialized() { + // resolve({ + // compileGLSLZeroCopy: this.compileGLSLZeroCopy, + // compileGLSL: this.compileGLSL, + // }); + // }, + // }); + // }); + // }; + + // let instance; + // return () => { + // if (!instance) { + // instance = initialize(); + // } + // return instance; + // }; + // })(); + // (function tryToExport(root, factory) { + // if (typeof exports === 'object' && typeof module === 'object') + // module.exports = factory(); + // else if (typeof define === 'function' && define.amd) + // define("glslang", [], factory); + // else if (typeof exports === 'object') + // exports["glslang"] = factory(); + // else + // root["glslang"] = factory(); + // })(typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : this, () => { + // const initialize = (wasmPath) => { + // wasmPath = 'http://localhost:7456/glslang.wasm' + // return new Promise(resolve => { + // Module({ + // locateFile() { + // return wasmPath; + // }, + // onRuntimeInitialized() { + // resolve({ + // compileGLSLZeroCopy: this.compileGLSLZeroCopy, + // compileGLSL: this.compileGLSL, + // }); + // }, + // }); + // }); + // }; + + // let instance; + // return (wasmPath) => { + // if (!instance) { + // instance = initialize(wasmPath); + // } + // return instance; + // }; + // }); + + + const initialize = (wasmPath) => { + return new Promise(resolve => { + Module({ + locateFile() { + return wasmPath; + }, + onRuntimeInitialized() { + resolve({ + compileGLSLZeroCopy: this.compileGLSLZeroCopy, + compileGLSL: this.compileGLSL, + }); + }, + }); + }); + }; + + let instance; + export default (wasmPath) => { + if (!instance) { + instance = initialize(wasmPath); + } + return instance; + }; \ No newline at end of file diff --git a/cocos/webgpu/instantiated.ts b/cocos/webgpu/instantiated.ts new file mode 100644 index 0000000000..ef9a10fb09 --- /dev/null +++ b/cocos/webgpu/instantiated.ts @@ -0,0 +1,89 @@ +/* eslint-disable @typescript-eslint/no-floating-promises */ +/* eslint-disable no-void */ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ +import { WEBGPU } from 'internal:constants'; +import webgpuUrl from 'url:native/external/emscripten/webgpu/webgpu_wasm.wasm'; +import glslangUrl from 'url:native/external/emscripten/webgpu/glslang.wasm'; +import wasmDevice from './webgpu_wasm.js'; +import glslangLoader from './glslang.js'; +import { legacyCC } from '../core/global-exports'; + +export const glslalgWasmModule: any = { + glslang: null, +}; + +export const gfx: any = legacyCC.gfx = { + wasmBinary: null, + nativeDevice: null, +}; + +export const webgpuAdapter: any = { + adapter: null, + device: null, +}; + +export const promiseForWebGPUInstantiation = (() => { + if (WEBGPU) { + return Promise.all([ + // @ts-expect-error The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'. + glslangLoader(new URL(glslangUrl, import.meta.url).href).then((res) => { + glslalgWasmModule.glslang = res; + }), + new Promise((resolve) => { + // @ts-expect-error The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'. + fetch(new URL(webgpuUrl, import.meta.url).href).then((response) => { + response.arrayBuffer().then((buffer) => { + gfx.wasmBinary = buffer; + wasmDevice(gfx).then(() => { + legacyCC.WebGPUDevice = gfx.CCWGPUDevice; + resolve(); + }); + }); + }); + }), + new Promise((resolve) => { + (navigator as any).gpu.requestAdapter().then((adapter) => { + adapter.requestDevice().then((device) => { + webgpuAdapter.adapter = adapter; + webgpuAdapter.device = device; + console.log(gfx); + resolve(); + }); + }); + }), + ]).then(() => Promise.resolve()); + } + return Promise.resolve(); +})(); + +if (WEBGPU) { + const intervalId = setInterval(() => { + if (legacyCC.game) { + legacyCC.game.onPreInfrastructureInitDelegate.add(() => promiseForWebGPUInstantiation); + clearInterval(intervalId); + } + }, 10); +} diff --git a/cocos/webgpu/webgpu_wasm.js b/cocos/webgpu/webgpu_wasm.js new file mode 100644 index 0000000000..219ee598e5 --- /dev/null +++ b/cocos/webgpu/webgpu_wasm.js @@ -0,0 +1,16 @@ + +var wasmDevice = (() => { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + + return ( +function(wasmDevice) { + wasmDevice = wasmDevice || {}; + +var Module=typeof wasmDevice!="undefined"?wasmDevice:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=true;var ENVIRONMENT_IS_WORKER=false;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=(url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=title=>document.title=title}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var POINTER_SIZE=4;var tempRet0=0;var setTempRet0=value=>{tempRet0=value};var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(text)}}var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heapOrArray,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){{if(Module["onAbort"]){Module["onAbort"](what)}}what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}var wasmBinaryFile;wasmBinaryFile="webgpu_wasm.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch=="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(wasmBinaryFile)})}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["_a"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module["asm"]["ab"];addOnInit(Module["asm"]["$a"]);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(function(instance){return instance}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(wasmBinaryFile)&&typeof fetch=="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiationResult,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiationResult)})})}else{return instantiateArrayBuffer(receiveInstantiationResult)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){callbacks.shift()(Module)}}function handleException(e){if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)}var structRegistrations={};function runDestructors(destructors){while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}}function simpleReadValueFromPointer(pointer){return this["fromWireType"](HEAP32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var char_0=48;var char_9=57;function makeLegalFunctionName(name){if(undefined===name){return"_unknown"}name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return"_"+name}return name}function createNamedFunction(name,body){name=makeLegalFunctionName(name);return new Function("body","return function "+name+"() {\n"+' "use strict";'+" return body.apply(this, arguments);\n"+"};\n")(body)}function extendError(baseErrorType,errorName){var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return this.name+": "+this.message}};return errorClass}var InternalError=undefined;function throwInternalError(message){throw new InternalError(message)}function whenDependentTypesAreResolved(myTypes,dependentTypes,getTypeConverters){myTypes.forEach(function(type){typeDependencies[type]=dependentTypes});function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i{if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}});if(0===unregisteredTypes.length){onComplete(typeConverters)}}function __embind_finalize_value_object(structType){var reg=structRegistrations[structType];delete structRegistrations[structType];var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;var fieldRecords=reg.fields;var fieldTypes=fieldRecords.map(field=>field.getterReturnType).concat(fieldRecords.map(field=>field.setterArgumentType));whenDependentTypesAreResolved([structType],fieldTypes,fieldTypes=>{var fields={};fieldRecords.forEach((field,i)=>{var fieldName=field.fieldName;var getterReturnType=fieldTypes[i];var getter=field.getter;var getterContext=field.getterContext;var setterArgumentType=fieldTypes[i+fieldRecords.length];var setter=field.setter;var setterContext=field.setterContext;fields[fieldName]={read:ptr=>{return getterReturnType["fromWireType"](getter(getterContext,ptr))},write:(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType["toWireType"](destructors,o));runDestructors(destructors)}}});return[{name:reg.name,"fromWireType":function(ptr){var rv={};for(var i in fields){rv[i]=fields[i].read(ptr)}rawDestructor(ptr);return rv},"toWireType":function(destructors,o){for(var fieldName in fields){if(!(fieldName in o)){throw new TypeError('Missing field: "'+fieldName+'"')}}var ptr=rawConstructor();for(fieldName in fields){fields[fieldName].write(ptr,o[fieldName])}if(destructors!==null){destructors.push(rawDestructor,ptr)}return ptr},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:rawDestructor}]})}function __embind_register_bigint(primitiveType,name,size,minRange,maxRange){}function getShiftFromSize(size){switch(size){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+size)}}function embind_init_charCodes(){var codes=new Array(256);for(var i=0;i<256;++i){codes[i]=String.fromCharCode(i)}embind_charCodes=codes}var embind_charCodes=undefined;function readLatin1String(ptr){var ret="";var c=ptr;while(HEAPU8[c]){ret+=embind_charCodes[HEAPU8[c++]]}return ret}var BindingError=undefined;function throwBindingError(message){throw new BindingError(message)}function registerType(rawType,registeredInstance,options={}){if(!("argPackAdvance"in registeredInstance)){throw new TypeError("registerType registeredInstance requires argPackAdvance")}var name=registeredInstance.name;if(!rawType){throwBindingError('type "'+name+'" must have a positive integer typeid pointer')}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError("Cannot register type '"+name+"' twice")}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function __embind_register_bool(rawType,name,size,trueValue,falseValue){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(wt){return!!wt},"toWireType":function(destructors,o){return o?trueValue:falseValue},"argPackAdvance":8,"readValueFromPointer":function(pointer){var heap;if(size===1){heap=HEAP8}else if(size===2){heap=HEAP16}else if(size===4){heap=HEAP32}else{throw new TypeError("Unknown boolean type size: "+name)}return this["fromWireType"](heap[pointer>>shift])},destructorFunction:null})}function ClassHandle_isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right}function shallowCopyInternalPointer(o){return{count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType}}function throwInstanceAlreadyDeleted(obj){function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")}var finalizationRegistry=false;function detachFinalizer(handle){}function runDestructor($$){if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}}function releaseClassHandle($$){$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}}function downcastPointer(ptr,ptrClass,desiredClass){if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)}var registeredPointers={};function getInheritedInstanceCount(){return Object.keys(registeredInstances).length}function getLiveInheritedInstances(){var rv=[];for(var k in registeredInstances){if(registeredInstances.hasOwnProperty(k)){rv.push(registeredInstances[k])}}return rv}var deletionQueue=[];function flushPendingDeletes(){while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}}var delayFunction=undefined;function setDelayFunction(fn){delayFunction=fn;if(deletionQueue.length&&delayFunction){delayFunction(flushPendingDeletes)}}function init_embind(){Module["getInheritedInstanceCount"]=getInheritedInstanceCount;Module["getLiveInheritedInstances"]=getLiveInheritedInstances;Module["flushPendingDeletes"]=flushPendingDeletes;Module["setDelayFunction"]=setDelayFunction}var registeredInstances={};function getBasestPointer(class_,ptr){if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr}function getInheritedInstance(class_,ptr){ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]}function makeClassHandle(prototype,record){if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record}}))}function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr:ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}function attachFinalizer(handle){if("undefined"===typeof FinalizationRegistry){attachFinalizer=handle=>handle;return handle}finalizationRegistry=new FinalizationRegistry(info=>{releaseClassHandle(info.$$)});attachFinalizer=handle=>{var $$=handle.$$;var hasSmartPtr=!!$$.smartPtr;if(hasSmartPtr){var info={$$:$$};finalizationRegistry.register(handle,info,handle)}return handle};detachFinalizer=handle=>finalizationRegistry.unregister(handle);return attachFinalizer(handle)}function ClassHandle_clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}}function ClassHandle_delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}}function ClassHandle_isDeleted(){return!this.$$.ptr}function ClassHandle_deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}function init_ClassHandle(){ClassHandle.prototype["isAliasOf"]=ClassHandle_isAliasOf;ClassHandle.prototype["clone"]=ClassHandle_clone;ClassHandle.prototype["delete"]=ClassHandle_delete;ClassHandle.prototype["isDeleted"]=ClassHandle_isDeleted;ClassHandle.prototype["deleteLater"]=ClassHandle_deleteLater}function ClassHandle(){}function ensureOverloadTable(proto,methodName,humanName){if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(){if(!proto[methodName].overloadTable.hasOwnProperty(arguments.length)){throwBindingError("Function '"+humanName+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+proto[methodName].overloadTable+")!")}return proto[methodName].overloadTable[arguments.length].apply(this,arguments)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}}function exposePublicSymbol(name,value,numArguments){if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError("Cannot register public name '"+name+"' twice")}ensureOverloadTable(Module,name,name);if(Module.hasOwnProperty(numArguments)){throwBindingError("Cannot register multiple overloads of a function with the same number of arguments ("+numArguments+")!")}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;if(undefined!==numArguments){Module[name].numArguments=numArguments}}}function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}function upcastPointer(ptr,ptrClass,desiredClass){while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError("Expected null or instance of "+desiredClass.name+", got an instance of "+ptrClass.name)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr}function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}return 0}if(!handle.$$){throwBindingError('Cannot pass "'+embindRepr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle.$$){throwBindingError('Cannot pass "'+embindRepr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError("Cannot convert argument of type "+(handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name)+" to parameter type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError("Cannot convert argument of type "+(handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name)+" to parameter type "+this.name)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,Emval.toHandle(function(){clonedHandle["delete"]()}));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupporting sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}return 0}if(!handle.$$){throwBindingError('Cannot pass "'+embindRepr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}if(handle.$$.ptrType.isConst){throwBindingError("Cannot convert argument of type "+handle.$$.ptrType.name+" to parameter type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function RegisteredPointer_getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr}function RegisteredPointer_destructor(ptr){if(this.rawDestructor){this.rawDestructor(ptr)}}function RegisteredPointer_deleteObject(handle){if(handle!==null){handle["delete"]()}}function init_RegisteredPointer(){RegisteredPointer.prototype.getPointee=RegisteredPointer_getPointee;RegisteredPointer.prototype.destructor=RegisteredPointer_destructor;RegisteredPointer.prototype["argPackAdvance"]=8;RegisteredPointer.prototype["readValueFromPointer"]=simpleReadValueFromPointer;RegisteredPointer.prototype["deleteObject"]=RegisteredPointer_deleteObject;RegisteredPointer.prototype["fromWireType"]=RegisteredPointer_fromWireType}function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&®isteredClass.baseClass===undefined){if(isConst){this["toWireType"]=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this["toWireType"]=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this["toWireType"]=genericPointerToWireType}}function replacePublicSymbol(name,value,numArguments){if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistant public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}}function dynCallLegacy(sig,ptr,args){var f=Module["dynCall_"+sig];return args&&args.length?f.apply(null,[ptr].concat(args)):f.call(null,ptr)}var wasmTableMirror=[];function getWasmTableEntry(funcPtr){var func=wasmTableMirror[funcPtr];if(!func){if(funcPtr>=wasmTableMirror.length)wasmTableMirror.length=funcPtr+1;wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func}function dynCall(sig,ptr,args){if(sig.includes("j")){return dynCallLegacy(sig,ptr,args)}var rtn=getWasmTableEntry(ptr).apply(null,args);return rtn}function getDynCaller(sig,ptr){var argCache=[];return function(){argCache.length=0;Object.assign(argCache,arguments);return dynCall(sig,ptr,argCache)}}function embind__requireFunction(signature,rawFunction){signature=readLatin1String(signature);function makeDynCaller(){if(signature.includes("j")){return getDynCaller(signature,rawFunction)}return getWasmTableEntry(rawFunction)}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError("unknown function pointer with signature "+signature+": "+rawFunction)}return fp}var UnboundTypeError=undefined;function getTypeName(type){var ptr=___getTypeName(type);var rv=readLatin1String(ptr);_free(ptr);return rv}function throwUnboundTypeError(message,types){var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(message+": "+unboundTypes.map(getTypeName).join([", "]))}function __embind_register_class(rawType,rawPointerType,rawConstPointerType,baseClassRawType,getActualTypeSignature,getActualType,upcastSignature,upcast,downcastSignature,downcast,name,destructorSignature,rawDestructor){name=readLatin1String(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);if(upcast){upcast=embind__requireFunction(upcastSignature,upcast)}if(downcast){downcast=embind__requireFunction(downcastSignature,downcast)}rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);var legalFunctionName=makeLegalFunctionName(name);exposePublicSymbol(legalFunctionName,function(){throwUnboundTypeError("Cannot construct "+name+" due to unbound types",[baseClassRawType])});whenDependentTypesAreResolved([rawType,rawPointerType,rawConstPointerType],baseClassRawType?[baseClassRawType]:[],function(base){base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(legalFunctionName,function(){if(Object.getPrototypeOf(this)!==instancePrototype){throw new BindingError("Use 'new' to construct "+name)}if(undefined===registeredClass.constructor_body){throw new BindingError(name+" has no accessible constructor")}var body=registeredClass.constructor_body[arguments.length];if(undefined===body){throw new BindingError("Tried to invoke ctor of "+name+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(registeredClass.constructor_body).toString()+") parameters instead!")}return body.apply(this,arguments)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);var referenceConverter=new RegisteredPointer(name,registeredClass,true,false,false);var pointerConverter=new RegisteredPointer(name+"*",registeredClass,false,false,false);var constPointerConverter=new RegisteredPointer(name+" const*",registeredClass,false,true,false);registeredPointers[rawType]={pointerType:pointerConverter,constPointerType:constPointerConverter};replacePublicSymbol(legalFunctionName,constructor);return[referenceConverter,pointerConverter,constPointerConverter]})}function new_(constructor,argumentList){if(!(constructor instanceof Function)){throw new TypeError("new_ called with constructor type "+typeof constructor+" which is not a function")}var dummy=createNamedFunction(constructor.name||"unknownFunctionName",function(){});dummy.prototype=constructor.prototype;var obj=new dummy;var r=constructor.apply(obj,argumentList);return r instanceof Object?r:obj}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=false;for(var i=1;i0?", ":"")+argsListWired}invokerFnBody+=(returns?"var rv = ":"")+"invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i>2])}return array}function __embind_register_class_class_function(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,fn){var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=readLatin1String(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker);whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName=classType.name+"."+methodName;function unboundTypesHandler(){throwUnboundTypeError("Cannot call "+humanName+" due to unbound types",rawArgTypes)}if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}var proto=classType.registeredClass.constructor;if(undefined===proto[methodName]){unboundTypesHandler.argCount=argCount-1;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-1]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));var func=craftInvokerFunction(humanName,invokerArgsArray,null,rawInvoker,fn);if(undefined===proto[methodName].overloadTable){func.argCount=argCount-1;proto[methodName]=func}else{proto[methodName].overloadTable[argCount-1]=func}return[]});return[]})}function __embind_register_class_constructor(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor){assert(argCount>0);var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName="constructor "+classType.name;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError("Cannot register multiple constructors with identical number of parameters ("+(argCount-1)+") for class '"+classType.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!")}classType.registeredClass.constructor_body[argCount-1]=()=>{throwUnboundTypeError("Cannot construct "+classType.name+" due to unbound types",rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})}function __embind_register_class_function(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual){var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=readLatin1String(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker);whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName=classType.name+"."+methodName;if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}if(isPureVirtual){classType.registeredClass.pureVirtualFunctions.push(methodName)}function unboundTypesHandler(){throwUnboundTypeError("Cannot call "+humanName+" due to unbound types",rawArgTypes)}var proto=classType.registeredClass.instancePrototype;var method=proto[methodName];if(undefined===method||undefined===method.overloadTable&&method.className!==classType.name&&method.argCount===argCount-2){unboundTypesHandler.argCount=argCount-2;unboundTypesHandler.className=classType.name;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-2]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})}function validateThis(this_,classType,humanName){if(!(this_ instanceof Object)){throwBindingError(humanName+' with invalid "this": '+this_)}if(!(this_ instanceof classType.registeredClass.constructor)){throwBindingError(humanName+' incompatible with "this" of type '+this_.constructor.name)}if(!this_.$$.ptr){throwBindingError("cannot call emscripten binding method "+humanName+" on deleted object")}return upcastPointer(this_.$$.ptr,this_.$$.ptrType.registeredClass,classType.registeredClass)}function __embind_register_class_property(classType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){fieldName=readLatin1String(fieldName);getter=embind__requireFunction(getterSignature,getter);whenDependentTypesAreResolved([],[classType],function(classType){classType=classType[0];var humanName=classType.name+"."+fieldName;var desc={get:function(){throwUnboundTypeError("Cannot access "+humanName+" due to unbound types",[getterReturnType,setterArgumentType])},enumerable:true,configurable:true};if(setter){desc.set=()=>{throwUnboundTypeError("Cannot access "+humanName+" due to unbound types",[getterReturnType,setterArgumentType])}}else{desc.set=v=>{throwBindingError(humanName+" is a read-only property")}}Object.defineProperty(classType.registeredClass.instancePrototype,fieldName,desc);whenDependentTypesAreResolved([],setter?[getterReturnType,setterArgumentType]:[getterReturnType],function(types){var getterReturnType=types[0];var desc={get:function(){var ptr=validateThis(this,classType,humanName+" getter");return getterReturnType["fromWireType"](getter(getterContext,ptr))},enumerable:true};if(setter){setter=embind__requireFunction(setterSignature,setter);var setterArgumentType=types[1];desc.set=function(v){var ptr=validateThis(this,classType,humanName+" setter");var destructors=[];setter(setterContext,ptr,setterArgumentType["toWireType"](destructors,v));runDestructors(destructors)}}Object.defineProperty(classType.registeredClass.instancePrototype,fieldName,desc);return[]});return[]})}var emval_free_list=[];var emval_handle_array=[{},{value:undefined},{value:null},{value:true},{value:false}];function __emval_decref(handle){if(handle>4&&0===--emval_handle_array[handle].refcount){emval_handle_array[handle]=undefined;emval_free_list.push(handle)}}function count_emval_handles(){var count=0;for(var i=5;i{if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handle_array[handle].value},toHandle:value=>{switch(value){case undefined:return 1;case null:return 2;case true:return 3;case false:return 4;default:{var handle=emval_free_list.length?emval_free_list.pop():emval_handle_array.length;emval_handle_array[handle]={refcount:1,value:value};return handle}}}};function __embind_register_emval(rawType,name){name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(handle){var rv=Emval.toValue(handle);__emval_decref(handle);return rv},"toWireType":function(destructors,value){return Emval.toHandle(value)},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:null})}function embindRepr(v){if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}}function floatReadValueFromPointer(name,shift){switch(shift){case 2:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 3:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError("Unknown float type: "+name)}}function __embind_register_float(rawType,name,size){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(value){return value},"toWireType":function(destructors,value){return value},"argPackAdvance":8,"readValueFromPointer":floatReadValueFromPointer(name,shift),destructorFunction:null})}function integerReadValueFromPointer(name,shift,signed){switch(shift){case 0:return signed?function readS8FromPointer(pointer){return HEAP8[pointer]}:function readU8FromPointer(pointer){return HEAPU8[pointer]};case 1:return signed?function readS16FromPointer(pointer){return HEAP16[pointer>>1]}:function readU16FromPointer(pointer){return HEAPU16[pointer>>1]};case 2:return signed?function readS32FromPointer(pointer){return HEAP32[pointer>>2]}:function readU32FromPointer(pointer){return HEAPU32[pointer>>2]};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_integer(primitiveType,name,size,minRange,maxRange){name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var shift=getShiftFromSize(size);var fromWireType=value=>value;if(minRange===0){var bitshift=32-8*size;fromWireType=value=>value<>>bitshift}var isUnsignedType=name.includes("unsigned");var checkAssertions=(value,toTypeName)=>{};var toWireType;if(isUnsignedType){toWireType=function(destructors,value){checkAssertions(value,this.name);return value>>>0}}else{toWireType=function(destructors,value){checkAssertions(value,this.name);return value}}registerType(primitiveType,{name:name,"fromWireType":fromWireType,"toWireType":toWireType,"argPackAdvance":8,"readValueFromPointer":integerReadValueFromPointer(name,shift,minRange!==0),destructorFunction:null})}function __embind_register_memory_view(rawType,dataTypeIndex,name){var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){handle=handle>>2;var heap=HEAPU32;var size=heap[handle];var data=heap[handle+1];return new TA(buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":decodeMemoryView,"argPackAdvance":8,"readValueFromPointer":decodeMemoryView},{ignoreDuplicateRegistrations:true})}function __embind_register_std_string(rawType,name){name=readLatin1String(name);var stdStringIsUTF8=name==="std::string";registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){var decodeStartPtr=payload;for(var i=0;i<=length;++i){var currentBytePtr=payload+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr,length+1)}else{if(valueIsOfTypeString){for(var i=0;i255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}else{for(var i=0;i>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder){return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr))}else{var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str}}function stringToUTF16(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr}function lengthBytesUTF16(str){return str.length*2}function UTF32ToString(ptr,maxBytesToRead){var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str}function stringToUTF32(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr}function lengthBytesUTF32(str){var len=0;for(var i=0;i=55296&&codeUnit<=57343)++i;len+=4}return len}function __embind_register_std_wstring(rawType,charSize,name){name=readLatin1String(name);var decodeString,encodeString,getHeap,lengthBytesUTF,shift;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16;getHeap=()=>HEAPU16;shift=1}else if(charSize===4){decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32;getHeap=()=>HEAPU32;shift=2}registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var HEAP=getHeap();var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||HEAP[currentBytePtr>>shift]==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},"toWireType":function(destructors,value){if(!(typeof value=="string")){throwBindingError("Cannot pass non-string to C++ string type "+name)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length>>shift;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:function(ptr){_free(ptr)}})}function __embind_register_value_object(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor){structRegistrations[rawType]={name:readLatin1String(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}}function __embind_register_value_object_field(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){structRegistrations[structType].fields.push({fieldName:readLatin1String(fieldName),getterReturnType:getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext:getterContext,setterArgumentType:setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext:setterContext})}function __embind_register_void(rawType,name){name=readLatin1String(name);registerType(rawType,{isVoid:true,name:name,"argPackAdvance":0,"fromWireType":function(){return undefined},"toWireType":function(destructors,o){return undefined}})}function requireRegisteredType(rawType,humanName){var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(humanName+" has unknown type "+getTypeName(rawType))}return impl}function __emval_as(handle,returnType,destructorsRef){handle=Emval.toValue(handle);returnType=requireRegisteredType(returnType,"emval::as");var destructors=[];var rd=Emval.toHandle(destructors);HEAPU32[destructorsRef>>2]=rd;return returnType["toWireType"](destructors,handle)}var emval_symbols={};function getStringOrSymbol(address){var symbol=emval_symbols[address];if(symbol===undefined){return readLatin1String(address)}return symbol}var emval_methodCallers=[];function __emval_call_void_method(caller,handle,methodName,args){caller=emval_methodCallers[caller];handle=Emval.toValue(handle);methodName=getStringOrSymbol(methodName);caller(handle,methodName,null,args)}function emval_addMethodCaller(caller){var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id}function emval_lookupTypes(argCount,argTypes){var a=new Array(argCount);for(var i=0;i>2],"parameter "+i)}return a}var emval_registeredMethods=[];function __emval_get_method_caller(argCount,argTypes){var types=emval_lookupTypes(argCount,argTypes);var retType=types[0];var signatureName=retType.name+"_$"+types.slice(1).map(function(t){return t.name}).join("_")+"$";var returnId=emval_registeredMethods[signatureName];if(returnId!==undefined){return returnId}var params=["retType"];var args=[retType];var argsList="";for(var i=0;i4){emval_handle_array[handle].refcount+=1}}function __emval_new_array(){return Emval.toHandle([])}function __emval_new_cstring(v){return Emval.toHandle(getStringOrSymbol(v))}function __emval_run_destructors(handle){var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)}function __emval_set_property(handle,key,value){handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value}function __emval_take_value(type,arg){type=requireRegisteredType(type,"_emval_take_value");var v=type["readValueFromPointer"](arg);return Emval.toHandle(v)}function _abort(){abort("")}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function getHeapMax(){return 2147483648}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}let alignUp=(x,multiple)=>x+(multiple-x%multiple)%multiple;for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var WebGPU={initManagers:function(){if(WebGPU.mgrDevice)return;function Manager(){this.objects={};this.nextId=1;this.create=function(object,wrapper){wrapper=wrapper||{};var id=this.nextId++;wrapper.refcount=1;wrapper.object=object;this.objects[id]=wrapper;return id};this.get=function(id){if(!id)return undefined;var o=this.objects[id];return o.object};this.reference=function(id){var o=this.objects[id];o.refcount++};this.release=function(id){var o=this.objects[id];o.refcount--;if(o.refcount<=0){delete this.objects[id]}}}WebGPU.mgrSurface=WebGPU.mgrSurface||new Manager;WebGPU.mgrSwapChain=WebGPU.mgrSwapChain||new Manager;WebGPU.mgrAdapter=WebGPU.mgrAdapter||new Manager;WebGPU.mgrDevice=WebGPU.mgrDevice||new Manager;WebGPU.mgrQueue=WebGPU.mgrQueue||new Manager;WebGPU.mgrCommandBuffer=WebGPU.mgrCommandBuffer||new Manager;WebGPU.mgrCommandEncoder=WebGPU.mgrCommandEncoder||new Manager;WebGPU.mgrRenderPassEncoder=WebGPU.mgrRenderPassEncoder||new Manager;WebGPU.mgrComputePassEncoder=WebGPU.mgrComputePassEncoder||new Manager;WebGPU.mgrBindGroup=WebGPU.mgrBindGroup||new Manager;WebGPU.mgrBuffer=WebGPU.mgrBuffer||new Manager;WebGPU.mgrSampler=WebGPU.mgrSampler||new Manager;WebGPU.mgrTexture=WebGPU.mgrTexture||new Manager;WebGPU.mgrTextureView=WebGPU.mgrTextureView||new Manager;WebGPU.mgrQuerySet=WebGPU.mgrQuerySet||new Manager;WebGPU.mgrBindGroupLayout=WebGPU.mgrBindGroupLayout||new Manager;WebGPU.mgrPipelineLayout=WebGPU.mgrPipelineLayout||new Manager;WebGPU.mgrRenderPipeline=WebGPU.mgrRenderPipeline||new Manager;WebGPU.mgrComputePipeline=WebGPU.mgrComputePipeline||new Manager;WebGPU.mgrShaderModule=WebGPU.mgrShaderModule||new Manager;WebGPU.mgrRenderBundleEncoder=WebGPU.mgrRenderBundleEncoder||new Manager;WebGPU.mgrRenderBundle=WebGPU.mgrRenderBundle||new Manager},makeColor:function(ptr){return{"r":HEAPF64[ptr>>3],"g":HEAPF64[ptr+8>>3],"b":HEAPF64[ptr+16>>3],"a":HEAPF64[ptr+24>>3]}},makeExtent3D:function(ptr){return{"width":HEAPU32[ptr>>2],"height":HEAPU32[ptr+4>>2],"depthOrArrayLayers":HEAPU32[ptr+8>>2]}},makeOrigin3D:function(ptr){return{"x":HEAPU32[ptr>>2],"y":HEAPU32[ptr+4>>2],"z":HEAPU32[ptr+8>>2]}},makeImageCopyTexture:function(ptr){return{"texture":WebGPU.mgrTexture.get(HEAPU32[ptr+4>>2]),"mipLevel":HEAPU32[ptr+8>>2],"origin":WebGPU.makeOrigin3D(ptr+12),"aspect":WebGPU.TextureAspect[HEAPU32[ptr+24>>2]]}},makeTextureDataLayout:function(ptr){var bytesPerRow=HEAPU32[ptr+16>>2];var rowsPerImage=HEAPU32[ptr+20>>2];return{"offset":HEAPU32[ptr+4+8>>2]*4294967296+HEAPU32[ptr+8>>2],"bytesPerRow":bytesPerRow===4294967295?undefined:bytesPerRow,"rowsPerImage":rowsPerImage===4294967295?undefined:rowsPerImage}},makeImageCopyBuffer:function(ptr){var layoutPtr=ptr+8;var bufferCopyView=WebGPU.makeTextureDataLayout(layoutPtr);bufferCopyView["buffer"]=WebGPU.mgrBuffer.get(HEAPU32[ptr+32>>2]);return bufferCopyView},makePipelineConstants:function(constantCount,constantsPtr){if(!constantCount)return;var constants={};for(var i=0;i>2]);constants[key]=HEAPF64[entryPtr+8>>3]}return constants},makeProgrammableStageDescriptor:function(ptr){if(!ptr)return undefined;return{"module":WebGPU.mgrShaderModule.get(HEAPU32[ptr+4>>2]),"entryPoint":UTF8ToString(HEAPU32[ptr+8>>2]),"constants":WebGPU.makePipelineConstants(HEAPU32[ptr+12>>2],HEAPU32[ptr+16>>2])}},DeviceLostReason:{undefined:0,destroyed:1},PreferredFormat:{rgba8unorm:18,bgra8unorm:23},AddressMode:["repeat","mirror-repeat","clamp-to-edge"],BlendFactor:["zero","one","src","one-minus-src","src-alpha","one-minus-src-alpha","dst","one-minus-dst","dst-alpha","one-minus-dst-alpha","src-alpha-saturated","constant","one-minus-constant"],BlendOperation:["add","subtract","reverse-subtract","min","max"],BufferBindingType:[,"uniform","storage","read-only-storage"],CompareFunction:[,"never","less","less-equal","greater","greater-equal","equal","not-equal","always"],CompilationInfoRequestStatus:["success","error","device-lost","unknown"],ComputePassTimestampLocation:["beginning","end"],CullMode:["none","front","back"],ErrorFilter:["validation","out-of-memory"],FeatureName:{0:undefined,1:"depth-clip-control",2:"depth24unorm-stencil8",3:"depth32float-stencil8",4:"timestamp-query",5:"pipeline-statistics-query",6:"texture-compression-bc",7:"texture-compression-etc2",8:"texture-compression-astc",9:"indirect-first-instance",1e3:"depth-clamping"},FilterMode:["nearest","linear"],FrontFace:["ccw","cw"],IndexFormat:[,"uint16","uint32"],LoadOp:[,"clear","load"],PipelineStatisticName:["vertex-shader-invocations","clipper-invocations","clipper-primitives-out","fragment-shader-invocations","compute-shader-invocations"],PowerPreference:[,"low-power","high-performance"],PredefinedColorSpace:[,"srgb"],PrimitiveTopology:["point-list","line-list","line-strip","triangle-list","triangle-strip"],QueryType:["occlusion","pipeline-statistics","timestamp"],RenderPassTimestampLocation:["beginning","end"],SamplerBindingType:[,"filtering","non-filtering","comparison"],StencilOperation:["keep","zero","replace","invert","increment-clamp","decrement-clamp","increment-wrap","decrement-wrap"],StorageTextureAccess:[,"write-only"],StoreOp:[,"store","discard"],TextureAspect:["all","stencil-only","depth-only"],TextureComponentType:["float","sint","uint","depth-comparison"],TextureDimension:["1d","2d","3d"],TextureFormat:[,"r8unorm","r8snorm","r8uint","r8sint","r16uint","r16sint","r16float","rg8unorm","rg8snorm","rg8uint","rg8sint","r32float","r32uint","r32sint","rg16uint","rg16sint","rg16float","rgba8unorm","rgba8unorm-srgb","rgba8snorm","rgba8uint","rgba8sint","bgra8unorm","bgra8unorm-srgb","rgb10a2unorm","rg11b10ufloat","rgb9e5ufloat","rg32float","rg32uint","rg32sint","rgba16uint","rgba16sint","rgba16float","rgba32float","rgba32uint","rgba32sint","stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth24unorm-stencil8","depth32float","depth32float-stencil8","bc1-rgba-unorm","bc1-rgba-unorm-srgb","bc2-rgba-unorm","bc2-rgba-unorm-srgb","bc3-rgba-unorm","bc3-rgba-unorm-srgb","bc4-r-unorm","bc4-r-snorm","bc5-rg-unorm","bc5-rg-snorm","bc6h-rgb-ufloat","bc6h-rgb-float","bc7-rgba-unorm","bc7-rgba-unorm-srgb","etc2-rgb8unorm","etc2-rgb8unorm-srgb","etc2-rgb8a1unorm","etc2-rgb8a1unorm-srgb","etc2-rgba8unorm","etc2-rgba8unorm-srgb","eac-r11unorm","eac-r11snorm","eac-rg11unorm","eac-rg11snorm","astc-4x4-unorm","astc-4x4-unorm-srgb","astc-5x4-unorm","astc-5x4-unorm-srgb","astc-5x5-unorm","astc-5x5-unorm-srgb","astc-6x5-unorm","astc-6x5-unorm-srgb","astc-6x6-unorm","astc-6x6-unorm-srgb","astc-8x5-unorm","astc-8x5-unorm-srgb","astc-8x6-unorm","astc-8x6-unorm-srgb","astc-8x8-unorm","astc-8x8-unorm-srgb","astc-10x5-unorm","astc-10x5-unorm-srgb","astc-10x6-unorm","astc-10x6-unorm-srgb","astc-10x8-unorm","astc-10x8-unorm-srgb","astc-10x10-unorm","astc-10x10-unorm-srgb","astc-12x10-unorm","astc-12x10-unorm-srgb","astc-12x12-unorm","astc-12x12-unorm-srgb"],TextureSampleType:[,"float","unfilterable-float","depth","sint","uint"],TextureViewDimension:[,"1d","2d","2d-array","cube","cube-array","3d"],VertexFormat:[,"uint8x2","uint8x4","sint8x2","sint8x4","unorm8x2","unorm8x4","snorm8x2","snorm8x4","uint16x2","uint16x4","sint16x2","sint16x4","unorm16x2","unorm16x4","snorm16x2","snorm16x4","float16x2","float16x4","float32","float32x2","float32x3","float32x4","uint32","uint32x2","uint32x3","uint32x4","sint32","sint32x2","sint32x3","sint32x4"],VertexStepMode:["vertex","instance"],FeatureNameString2Enum:{undefined:"0","depth-clip-control":"1","depth24unorm-stencil8":"2","depth32float-stencil8":"3","timestamp-query":"4","pipeline-statistics-query":"5","texture-compression-bc":"6","texture-compression-etc2":"7","texture-compression-astc":"8","indirect-first-instance":"9","depth-clamping":"1000"}};function _emscripten_webgpu_get_device(){var device=Module["preinitializedWebGPUDevice"];var deviceWrapper={queueId:WebGPU.mgrQueue.create(device["queue"])};return WebGPU.mgrDevice.create(device,deviceWrapper)}var ENV={};function getExecutableName(){return thisProgram||"./this.program"}function getEnvStrings(){if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={"USER":"web_user","LOGNAME":"web_user","PATH":"/","PWD":"/","HOME":"/home/web_user","LANG":lang,"_":getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(x+"="+env[x])}getEnvStrings.strings=strings}return getEnvStrings.strings}function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}var SYSCALLS={varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret}};function _environ_get(__environ,environ_buf){var bufSize=0;getEnvStrings().forEach(function(string,i){var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;writeAsciiToMemory(string,ptr);bufSize+=string.length+1});return 0}function _environ_sizes_get(penviron_count,penviron_buf_size){var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(function(string){bufSize+=string.length+1});HEAPU32[penviron_buf_size>>2]=bufSize;return 0}var printCharBuffers=[null,[],[]];function printChar(stream,curr){var buffer=printCharBuffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}}function _fd_write(fd,iov,iovcnt,pnum){var num=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;for(var j=0;j>2]=num;return 0}function _setTempRet0(val){setTempRet0(val)}function _wgpuAdapterGetProperties(adapterId,properties){HEAP32[properties+4>>2]=0;HEAP32[properties+8>>2]=0;HEAP32[properties+12>>2]=0;HEAP32[properties+16>>2]=0;HEAP32[properties+20>>2]=3;HEAP32[properties+24>>2]=1}function _wgpuAdapterHasFeature(adapterId,featureEnumValue){var adapter=WebGPU.mgrAdapter.get(adapterId);return adapter.features.has(WebGPU.FeatureName[featureEnumValue])}function _wgpuAdapterRelease(id){WebGPU.mgrAdapter.release(id)}function _wgpuBindGroupRelease(id){WebGPU.mgrBindGroup.release(id)}function _wgpuBufferDestroy(bufferId){WebGPU.mgrBuffer.get(bufferId)["destroy"]()}function _wgpuBufferGetMappedRange(bufferId,offset,size){var bufferWrapper=WebGPU.mgrBuffer.objects[bufferId];if(size===0)warnOnce("getMappedRange size=0 no longer means WGPU_WHOLE_MAP_SIZE");size=size>>>0;if(size===4294967295)size=undefined;if(bufferWrapper.mapMode!==2){return 0}var mapped;try{mapped=bufferWrapper.object["getMappedRange"](offset,size)}catch(ex){return 0}var data=_malloc(mapped.byteLength);HEAPU8.fill(0,data,mapped.byteLength);bufferWrapper.onUnmap.push(function(){new Uint8Array(mapped).set(HEAPU8.subarray(data,data+mapped.byteLength));_free(data)});return data}function _wgpuBufferRelease(id){WebGPU.mgrBuffer.release(id)}function _wgpuBufferUnmap(bufferId){var bufferWrapper=WebGPU.mgrBuffer.objects[bufferId];if(!bufferWrapper.onUnmap){return}for(var i=0;i>2]),"queryIndex":HEAPU32[twPtr+4>>2],"location":WebGPU.ComputePassTimestampLocation[HEAPU32[twPtr+8>>2]]}}function makeComputePassTimestampWrites(count,twPtr){var timestampWrites=[];for(var i=0;i>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var timestampWriteCount=HEAPU32[descriptor+8>>2];if(timestampWriteCount){desc["timestampWrites"]=makeComputePassTimestampWrites(timestampWriteCount,HEAPU32[descriptor+12>>2])}}var commandEncoder=WebGPU.mgrCommandEncoder.get(encoderId);return WebGPU.mgrComputePassEncoder.create(commandEncoder["beginComputePass"](desc))}function _wgpuCommandEncoderBeginRenderPass(encoderId,descriptor){function makeColorAttachment(caPtr){var viewPtr=HEAPU32[caPtr>>2];if(viewPtr===0){return undefined}var loadOpInt=HEAPU32[caPtr+8>>2];var storeOpInt=HEAPU32[caPtr+12>>2];var clearValue=WebGPU.makeColor(caPtr+16);return{"view":WebGPU.mgrTextureView.get(viewPtr),"resolveTarget":WebGPU.mgrTextureView.get(HEAPU32[caPtr+4>>2]),"clearValue":clearValue,"loadOp":WebGPU.LoadOp[loadOpInt],"storeOp":WebGPU.StoreOp[storeOpInt]}}function makeColorAttachments(count,caPtr){var attachments=[];for(var i=0;i>2]),"depthClearValue":HEAPF32[dsaPtr+12>>2],"depthLoadOp":WebGPU.LoadOp[HEAPU32[dsaPtr+4>>2]],"depthStoreOp":WebGPU.StoreOp[HEAPU32[dsaPtr+8>>2]],"depthReadOnly":HEAP8[dsaPtr+16>>0]!==0,"stencilClearValue":HEAPU32[dsaPtr+28>>2],"stencilLoadOp":WebGPU.LoadOp[HEAPU32[dsaPtr+20>>2]],"stencilStoreOp":WebGPU.StoreOp[HEAPU32[dsaPtr+24>>2]],"stencilReadOnly":HEAP8[dsaPtr+32>>0]!==0}}function makeRenderPassTimestampWrite(twPtr){return{"querySet":WebGPU.mgrQuerySet.get(HEAPU32[twPtr>>2]),"queryIndex":HEAPU32[twPtr+4>>2],"location":WebGPU.RenderPassTimestampLocation[HEAPU32[twPtr+8>>2]]}}function makeRenderPassTimestampWrites(count,twPtr){var timestampWrites=[];for(var i=0;i>2],HEAPU32[descriptor+12>>2]),"depthStencilAttachment":makeDepthStencilAttachment(HEAPU32[descriptor+16>>2]),"occlusionQuerySet":WebGPU.mgrQuerySet.get(HEAPU32[descriptor+20>>2])};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var timestampWriteCount=HEAPU32[descriptor+24>>2];if(timestampWriteCount){desc["timestampWrites"]=makeRenderPassTimestampWrites(timestampWriteCount,HEAPU32[descriptor+28>>2])}return desc}var desc=makeRenderPassDescriptor(descriptor);var commandEncoder=WebGPU.mgrCommandEncoder.get(encoderId);return WebGPU.mgrRenderPassEncoder.create(commandEncoder["beginRenderPass"](desc))}function _wgpuCommandEncoderCopyBufferToBuffer(encoderId,srcId,srcOffset_low,srcOffset_high,dstId,dstOffset_low,dstOffset_high,size_low,size_high){var commandEncoder=WebGPU.mgrCommandEncoder.get(encoderId);var src=WebGPU.mgrBuffer.get(srcId);var dst=WebGPU.mgrBuffer.get(dstId);commandEncoder["copyBufferToBuffer"](src,srcOffset_high*4294967296+srcOffset_low,dst,dstOffset_high*4294967296+dstOffset_low,size_high*4294967296+size_low)}function _wgpuCommandEncoderCopyBufferToTexture(encoderId,srcPtr,dstPtr,copySizePtr){var commandEncoder=WebGPU.mgrCommandEncoder.get(encoderId);var copySize=WebGPU.makeExtent3D(copySizePtr);commandEncoder["copyBufferToTexture"](WebGPU.makeImageCopyBuffer(srcPtr),WebGPU.makeImageCopyTexture(dstPtr),copySize)}function _wgpuCommandEncoderCopyTextureToTexture(encoderId,srcPtr,dstPtr,copySizePtr){var commandEncoder=WebGPU.mgrCommandEncoder.get(encoderId);var copySize=WebGPU.makeExtent3D(copySizePtr);commandEncoder["copyTextureToTexture"](WebGPU.makeImageCopyTexture(srcPtr),WebGPU.makeImageCopyTexture(dstPtr),copySize)}function _wgpuCommandEncoderFinish(encoderId){var commandEncoder=WebGPU.mgrCommandEncoder.get(encoderId);return WebGPU.mgrCommandBuffer.create(commandEncoder["finish"]())}function _wgpuCommandEncoderRelease(id){WebGPU.mgrCommandEncoder.release(id)}function _wgpuComputePassEncoderDispatchWorkgroups(passId,x,y,z){var pass=WebGPU.mgrComputePassEncoder.get(passId);if(pass["dispatchWorkgroups"]){pass["dispatchWorkgroups"](x,y,z)}else{pass["dispatch"](x,y,z)}}function _wgpuComputePassEncoderDispatchWorkgroupsIndirect(passId,indirectBufferId,indirectOffset_low,indirectOffset_high){var indirectBuffer=WebGPU.mgrBuffer.get(indirectBufferId);var indirectOffset=indirectOffset_high*4294967296+indirectOffset_low;var pass=WebGPU.mgrComputePassEncoder.get(passId);if(pass["dispatchWorkgroupsIndirect"]){pass["dispatchWorkgroupsIndirect"](indirectBuffer,indirectOffset)}else{pass["dispatchIndirect"](indirectBuffer,indirectOffset)}}function _wgpuComputePassEncoderEnd(passId){var pass=WebGPU.mgrComputePassEncoder.get(passId);pass["end"]()}function _wgpuComputePassEncoderRelease(id){WebGPU.mgrComputePassEncoder.release(id)}function _wgpuComputePassEncoderSetBindGroup(passId,groupIndex,groupId,dynamicOffsetCount,dynamicOffsetsPtr){var pass=WebGPU.mgrComputePassEncoder.get(passId);var group=WebGPU.mgrBindGroup.get(groupId);if(dynamicOffsetCount==0){pass["setBindGroup"](groupIndex,group)}else{var offsets=[];for(var i=0;i>2])}pass["setBindGroup"](groupIndex,group,offsets)}}function _wgpuComputePassEncoderSetPipeline(passId,pipelineId){var pass=WebGPU.mgrComputePassEncoder.get(passId);var pipeline=WebGPU.mgrComputePipeline.get(pipelineId);pass["setPipeline"](pipeline)}function _wgpuComputePipelineRelease(id){WebGPU.mgrComputePipeline.release(id)}function _wgpuDeviceCreateBindGroup(deviceId,descriptor){function makeEntry(entryPtr){var bufferId=HEAPU32[entryPtr+8>>2];var samplerId=HEAPU32[entryPtr+32>>2];var textureViewId=HEAPU32[entryPtr+36>>2];var binding=HEAPU32[entryPtr+4>>2];if(bufferId){var size_low=HEAPU32[entryPtr+24>>2];var size_high=HEAPU32[entryPtr+28>>2];var size=size_high===-1&&size_low===-1?undefined:size_high*4294967296+size_low;return{"binding":binding,"resource":{"buffer":WebGPU.mgrBuffer.get(bufferId),"offset":HEAPU32[entryPtr+4+16>>2]*4294967296+HEAPU32[entryPtr+16>>2],"size":size}}}else if(samplerId){return{"binding":binding,"resource":WebGPU.mgrSampler.get(samplerId)}}else{return{"binding":binding,"resource":WebGPU.mgrTextureView.get(textureViewId)}}}function makeEntries(count,entriesPtrs){var entries=[];for(var i=0;i>2]),"entries":makeEntries(HEAPU32[descriptor+12>>2],HEAPU32[descriptor+16>>2])};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrBindGroup.create(device["createBindGroup"](desc))}function _wgpuDeviceCreateBindGroupLayout(deviceId,descriptor){function makeBufferEntry(entryPtr){var typeInt=HEAPU32[entryPtr+4>>2];if(!typeInt)return undefined;return{"type":WebGPU.BufferBindingType[typeInt],"hasDynamicOffset":HEAP8[entryPtr+8>>0]!==0,"minBindingSize":HEAPU32[entryPtr+4+16>>2]*4294967296+HEAPU32[entryPtr+16>>2]}}function makeSamplerEntry(entryPtr){var typeInt=HEAPU32[entryPtr+4>>2];if(!typeInt)return undefined;return{"type":WebGPU.SamplerBindingType[typeInt]}}function makeTextureEntry(entryPtr){var sampleTypeInt=HEAPU32[entryPtr+4>>2];if(!sampleTypeInt)return undefined;return{"sampleType":WebGPU.TextureSampleType[sampleTypeInt],"viewDimension":WebGPU.TextureViewDimension[HEAPU32[entryPtr+8>>2]],"multisampled":HEAP8[entryPtr+12>>0]!==0}}function makeStorageTextureEntry(entryPtr){var accessInt=HEAPU32[entryPtr+4>>2];if(!accessInt)return undefined;return{"access":WebGPU.StorageTextureAccess[accessInt],"format":WebGPU.TextureFormat[HEAPU32[entryPtr+8>>2]],"viewDimension":WebGPU.TextureViewDimension[HEAPU32[entryPtr+12>>2]]}}function makeEntry(entryPtr){return{"binding":HEAPU32[entryPtr+4>>2],"visibility":HEAPU32[entryPtr+8>>2],"buffer":makeBufferEntry(entryPtr+16),"sampler":makeSamplerEntry(entryPtr+40),"texture":makeTextureEntry(entryPtr+48),"storageTexture":makeStorageTextureEntry(entryPtr+64)}}function makeEntries(count,entriesPtrs){var entries=[];for(var i=0;i>2],HEAPU32[descriptor+12>>2])};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrBindGroupLayout.create(device["createBindGroupLayout"](desc))}function _wgpuDeviceCreateBuffer(deviceId,descriptor){var mappedAtCreation=HEAP8[descriptor+24>>0]!==0;var desc={"label":undefined,"usage":HEAPU32[descriptor+8>>2],"size":HEAPU32[descriptor+4+16>>2]*4294967296+HEAPU32[descriptor+16>>2],"mappedAtCreation":mappedAtCreation};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var device=WebGPU.mgrDevice.get(deviceId);var bufferWrapper={};var id=WebGPU.mgrBuffer.create(device["createBuffer"](desc),bufferWrapper);if(mappedAtCreation){bufferWrapper.mapMode=2;bufferWrapper.onUnmap=[]}return id}function _wgpuDeviceCreateCommandEncoder(deviceId,descriptor){var desc;if(descriptor){desc={"label":undefined};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr)}var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrCommandEncoder.create(device["createCommandEncoder"](desc))}function _wgpuDeviceCreateComputePipeline(deviceId,descriptor){var desc={"label":undefined,"layout":WebGPU.mgrPipelineLayout.get(HEAPU32[descriptor+8>>2]),"compute":WebGPU.makeProgrammableStageDescriptor(descriptor+12)};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrComputePipeline.create(device["createComputePipeline"](desc))}function _wgpuDeviceCreatePipelineLayout(deviceId,descriptor){var bglCount=HEAPU32[descriptor+8>>2];var bglPtr=HEAPU32[descriptor+12>>2];var bgls=[];for(var i=0;i>2]))}var desc={"label":undefined,"bindGroupLayouts":bgls};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrPipelineLayout.create(device["createPipelineLayout"](desc))}function _wgpuDeviceCreateRenderPipeline(deviceId,descriptor){function makePrimitiveState(rsPtr){if(!rsPtr)return undefined;return{"topology":WebGPU.PrimitiveTopology[HEAPU32[rsPtr+4>>2]],"stripIndexFormat":WebGPU.IndexFormat[HEAPU32[rsPtr+8>>2]],"frontFace":WebGPU.FrontFace[HEAPU32[rsPtr+12>>2]],"cullMode":WebGPU.CullMode[HEAPU32[rsPtr+16>>2]]}}function makeBlendComponent(bdPtr){if(!bdPtr)return undefined;return{"operation":WebGPU.BlendOperation[HEAPU32[bdPtr>>2]],"srcFactor":WebGPU.BlendFactor[HEAPU32[bdPtr+4>>2]],"dstFactor":WebGPU.BlendFactor[HEAPU32[bdPtr+8>>2]]}}function makeBlendState(bsPtr){if(!bsPtr)return undefined;return{"alpha":makeBlendComponent(bsPtr+12),"color":makeBlendComponent(bsPtr+0)}}function makeColorState(csPtr){var formatInt=HEAPU32[csPtr+4>>2];return formatInt===0?undefined:{"format":WebGPU.TextureFormat[formatInt],"blend":makeBlendState(HEAPU32[csPtr+8>>2]),"writeMask":HEAPU32[csPtr+12>>2]}}function makeColorStates(count,csArrayPtr){var states=[];for(var i=0;i>2]],"failOp":WebGPU.StencilOperation[HEAPU32[ssfPtr+4>>2]],"depthFailOp":WebGPU.StencilOperation[HEAPU32[ssfPtr+8>>2]],"passOp":WebGPU.StencilOperation[HEAPU32[ssfPtr+12>>2]]}}function makeDepthStencilState(dssPtr){if(!dssPtr)return undefined;return{"format":WebGPU.TextureFormat[HEAPU32[dssPtr+4>>2]],"depthWriteEnabled":HEAP8[dssPtr+8>>0]!==0,"depthCompare":WebGPU.CompareFunction[HEAPU32[dssPtr+12>>2]],"stencilFront":makeStencilStateFace(dssPtr+16),"stencilBack":makeStencilStateFace(dssPtr+32),"stencilReadMask":HEAPU32[dssPtr+48>>2],"stencilWriteMask":HEAPU32[dssPtr+52>>2],"depthBias":HEAPU32[dssPtr+56>>2],"depthBiasSlopeScale":HEAPF32[dssPtr+60>>2],"depthBiasClamp":HEAPF32[dssPtr+64>>2]}}function makeVertexAttribute(vaPtr){return{"format":WebGPU.VertexFormat[HEAPU32[vaPtr>>2]],"offset":HEAPU32[vaPtr+4+8>>2]*4294967296+HEAPU32[vaPtr+8>>2],"shaderLocation":HEAPU32[vaPtr+16>>2]}}function makeVertexAttributes(count,vaArrayPtr){var vas=[];for(var i=0;i>2]*4294967296+HEAPU32[vbPtr>>2],"stepMode":WebGPU.VertexStepMode[HEAPU32[vbPtr+8>>2]],"attributes":makeVertexAttributes(HEAPU32[vbPtr+12>>2],HEAPU32[vbPtr+16>>2])}}function makeVertexBuffers(count,vbArrayPtr){if(!count)return undefined;var vbs=[];for(var i=0;i>2]),"entryPoint":UTF8ToString(HEAPU32[viPtr+8>>2]),"constants":WebGPU.makePipelineConstants(HEAPU32[viPtr+12>>2],HEAPU32[viPtr+16>>2]),"buffers":makeVertexBuffers(HEAPU32[viPtr+20>>2],HEAPU32[viPtr+24>>2])}}function makeMultisampleState(msPtr){if(!msPtr)return undefined;return{"count":HEAPU32[msPtr+4>>2],"mask":HEAPU32[msPtr+8>>2],"alphaToCoverageEnabled":HEAP8[msPtr+12>>0]!==0}}function makeFragmentState(fsPtr){if(!fsPtr)return undefined;return{"module":WebGPU.mgrShaderModule.get(HEAPU32[fsPtr+4>>2]),"entryPoint":UTF8ToString(HEAPU32[fsPtr+8>>2]),"constants":WebGPU.makePipelineConstants(HEAPU32[fsPtr+12>>2],HEAPU32[fsPtr+16>>2]),"targets":makeColorStates(HEAPU32[fsPtr+20>>2],HEAPU32[fsPtr+24>>2])}}var desc={"label":undefined,"layout":WebGPU.mgrPipelineLayout.get(HEAPU32[descriptor+8>>2]),"vertex":makeVertexState(descriptor+12),"primitive":makePrimitiveState(descriptor+40),"depthStencil":makeDepthStencilState(HEAPU32[descriptor+60>>2]),"multisample":makeMultisampleState(descriptor+64),"fragment":makeFragmentState(HEAPU32[descriptor+80>>2])};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrRenderPipeline.create(device["createRenderPipeline"](desc))}function _wgpuDeviceCreateSampler(deviceId,descriptor){var desc={"label":undefined,"addressModeU":WebGPU.AddressMode[HEAPU32[descriptor+8>>2]],"addressModeV":WebGPU.AddressMode[HEAPU32[descriptor+12>>2]],"addressModeW":WebGPU.AddressMode[HEAPU32[descriptor+16>>2]],"magFilter":WebGPU.FilterMode[HEAPU32[descriptor+20>>2]],"minFilter":WebGPU.FilterMode[HEAPU32[descriptor+24>>2]],"mipmapFilter":WebGPU.FilterMode[HEAPU32[descriptor+28>>2]],"lodMinClamp":HEAPF32[descriptor+32>>2],"lodMaxClamp":HEAPF32[descriptor+36>>2],"compare":WebGPU.CompareFunction[HEAPU32[descriptor+40>>2]]};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrSampler.create(device["createSampler"](desc))}function _wgpuDeviceCreateShaderModule(deviceId,descriptor){var nextInChainPtr=HEAPU32[descriptor>>2];var sType=HEAPU32[nextInChainPtr+4>>2];var desc={"label":undefined,"code":""};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);switch(sType){case 5:{var count=HEAPU32[nextInChainPtr+8>>2];var start=HEAPU32[nextInChainPtr+12>>2];desc["code"]=HEAPU32.subarray(start>>2,(start>>2)+count);break}case 6:{var sourcePtr=HEAPU32[nextInChainPtr+8>>2];if(sourcePtr){desc["code"]=UTF8ToString(sourcePtr)}break}}var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrShaderModule.create(device["createShaderModule"](desc))}function _wgpuDeviceCreateSwapChain(deviceId,surfaceId,descriptor){var device=WebGPU.mgrDevice.get(deviceId);var context=WebGPU.mgrSurface.get(surfaceId);var canvasSize=[HEAPU32[descriptor+16>>2],HEAPU32[descriptor+20>>2]];if(canvasSize[0]!==0){context["canvas"]["width"]=canvasSize[0]}if(canvasSize[1]!==0){context["canvas"]["height"]=canvasSize[1]}var configuration={"device":device,"format":WebGPU.TextureFormat[HEAPU32[descriptor+12>>2]],"usage":HEAPU32[descriptor+8>>2],"alphaMode":"opaque"};context["configure"](configuration);return WebGPU.mgrSwapChain.create(context)}function _wgpuDeviceCreateTexture(deviceId,descriptor){var desc={"label":undefined,"size":WebGPU.makeExtent3D(descriptor+16),"mipLevelCount":HEAPU32[descriptor+32>>2],"sampleCount":HEAPU32[descriptor+36>>2],"dimension":WebGPU.TextureDimension[HEAPU32[descriptor+12>>2]],"format":WebGPU.TextureFormat[HEAPU32[descriptor+28>>2]],"usage":HEAPU32[descriptor+8>>2]};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var viewFormatCount=HEAPU32[descriptor+40>>2];if(viewFormatCount){var viewFormatsPtr=HEAPU32[descriptor+44>>2];desc["viewFormats"]=Array.from(HEAP32.subarray(viewFormatsPtr>>2,(viewFormatsPtr>>2)+viewFormatCount),function(format){return WebGPU.TextureFormat[format]})}var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrTexture.create(device["createTexture"](desc))}function _wgpuDeviceGetQueue(deviceId){var queueId=WebGPU.mgrDevice.objects[deviceId].queueId;WebGPU.mgrQueue.reference(queueId);return queueId}function _wgpuDeviceRelease(id){WebGPU.mgrDevice.release(id)}function maybeCStringToJsString(cString){return cString>2?UTF8ToString(cString):cString}var specialHTMLTargets=[0,document,window];function findEventTarget(target){target=maybeCStringToJsString(target);var domElement=specialHTMLTargets[target]||document.querySelector(target);return domElement}function findCanvasEventTarget(target){return findEventTarget(target)}function _wgpuInstanceCreateSurface(instanceId,descriptor){var nextInChainPtr=HEAPU32[descriptor>>2];var descriptorFromCanvasHTMLSelector=nextInChainPtr;var selectorPtr=HEAPU32[descriptorFromCanvasHTMLSelector+8>>2];var canvas=findCanvasEventTarget(selectorPtr);var context=canvas.getContext("webgpu");if(!context)return 0;var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)context.surfaceLabelWebGPU=UTF8ToString(labelPtr);return WebGPU.mgrSurface.create(context)}function _wgpuInstanceRelease(){}function callUserCallback(func){if(ABORT){return}try{func()}catch(e){handleException(e)}}function allocateUTF8(str){var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8Array(str,HEAP8,ret,size);return ret}function _wgpuInstanceRequestAdapter(instanceId,options,callback,userdata){var opts;if(options){opts={"powerPreference":WebGPU.PowerPreference[HEAPU32[options+8>>2]],"forceFallbackAdapter":HEAP8[options+12>>0]!==0}}if(!("gpu"in navigator)){var messagePtr=allocateUTF8("WebGPU not available on this browser (navigator.gpu is not available)");getWasmTableEntry(callback)(1,0,messagePtr,userdata);_free(messagePtr);return}navigator["gpu"]["requestAdapter"](opts).then(function(adapter){callUserCallback(function(){if(adapter){var adapterId=WebGPU.mgrAdapter.create(adapter);getWasmTableEntry(callback)(0,adapterId,0,userdata)}else{var messagePtr=allocateUTF8("WebGPU not available on this system (requestAdapter returned null)");getWasmTableEntry(callback)(1,0,messagePtr,userdata);_free(messagePtr)}})},function(ex){callUserCallback(function(){var messagePtr=allocateUTF8(ex.message);getWasmTableEntry(callback)(2,0,messagePtr,userdata);_free(messagePtr)})})}function _wgpuPipelineLayoutRelease(id){WebGPU.mgrPipelineLayout.release(id)}function _wgpuQuerySetDestroy(querySetId){WebGPU.mgrQuerySet.get(querySetId)["destroy"]()}function _wgpuQuerySetRelease(id){WebGPU.mgrQuerySet.release(id)}function _wgpuQueueOnSubmittedWorkDone(queueId,signalValue_low,signalValue_high,callback,userdata){var queue=WebGPU.mgrQueue.get(queueId);queue["onSubmittedWorkDone"]().then(function(){callUserCallback(function(){getWasmTableEntry(callback)(0,userdata)})},function(){callUserCallback(function(){getWasmTableEntry(callback)(1,userdata)})})}function _wgpuQueueRelease(id){WebGPU.mgrQueue.release(id)}function _wgpuQueueSubmit(queueId,commandCount,commands){var queue=WebGPU.mgrQueue.get(queueId);var cmds=Array.from(HEAP32.subarray(commands>>2,(commands>>2)+commandCount),function(id){return WebGPU.mgrCommandBuffer.get(id)});queue["submit"](cmds)}function _wgpuQueueWriteBuffer(queueId,bufferId,bufferOffset_low,bufferOffset_high,data,size){var queue=WebGPU.mgrQueue.get(queueId);var buffer=WebGPU.mgrBuffer.get(bufferId);var bufferOffset=bufferOffset_high*4294967296+bufferOffset_low;var subarray=HEAPU8.subarray(data,data+size);queue["writeBuffer"](buffer,bufferOffset,subarray,0,size)}function _wgpuQueueWriteTexture(queueId,destinationPtr,data,dataSize,dataLayoutPtr,writeSizePtr){var queue=WebGPU.mgrQueue.get(queueId);var destination=WebGPU.makeImageCopyTexture(destinationPtr);var dataLayout=WebGPU.makeTextureDataLayout(dataLayoutPtr);var writeSize=WebGPU.makeExtent3D(writeSizePtr);var subarray=HEAPU8.subarray(data,data+dataSize);queue["writeTexture"](destination,subarray,dataLayout,writeSize)}function _wgpuRenderPassEncoderDraw(passId,vertexCount,instanceCount,firstVertex,firstInstance){var pass=WebGPU.mgrRenderPassEncoder.get(passId);pass["draw"](vertexCount,instanceCount,firstVertex,firstInstance)}function _wgpuRenderPassEncoderDrawIndexed(passId,indexCount,instanceCount,firstIndex,baseVertex,firstInstance){var pass=WebGPU.mgrRenderPassEncoder.get(passId);pass["drawIndexed"](indexCount,instanceCount,firstIndex,baseVertex,firstInstance)}function _wgpuRenderPassEncoderDrawIndirect(passId,indirectBufferId,indirectOffset_low,indirectOffset_high){var indirectBuffer=WebGPU.mgrBuffer.get(indirectBufferId);var indirectOffset=indirectOffset_high*4294967296+indirectOffset_low;var pass=WebGPU.mgrRenderPassEncoder.get(passId);pass["drawIndirect"](indirectBuffer,indirectOffset)}function _wgpuRenderPassEncoderEnd(passId){var pass=WebGPU.mgrRenderPassEncoder.get(passId);pass["end"]()}function _wgpuRenderPassEncoderRelease(id){WebGPU.mgrRenderPassEncoder.release(id)}function _wgpuRenderPassEncoderSetBindGroup(passId,groupIndex,groupId,dynamicOffsetCount,dynamicOffsetsPtr){var pass=WebGPU.mgrRenderPassEncoder.get(passId);var group=WebGPU.mgrBindGroup.get(groupId);if(dynamicOffsetCount==0){pass["setBindGroup"](groupIndex,group)}else{var offsets=[];for(var i=0;i>2])}pass["setBindGroup"](groupIndex,group,offsets)}}function _wgpuRenderPassEncoderSetBlendConstant(passId,colorPtr){var pass=WebGPU.mgrRenderPassEncoder.get(passId);var color=WebGPU.makeColor(colorPtr);pass["setBlendConstant"](color)}function _wgpuRenderPassEncoderSetIndexBuffer(passId,bufferId,format,offset_low,offset_high,size_low,size_high){var pass=WebGPU.mgrRenderPassEncoder.get(passId);var buffer=WebGPU.mgrBuffer.get(bufferId);var offset=offset_high*4294967296+offset_low;var size=size_high===-1&&size_low===-1?undefined:size_high*4294967296+size_low;pass["setIndexBuffer"](buffer,WebGPU.IndexFormat[format],offset,size)}function _wgpuRenderPassEncoderSetPipeline(passId,pipelineId){var pass=WebGPU.mgrRenderPassEncoder.get(passId);var pipeline=WebGPU.mgrRenderPipeline.get(pipelineId);pass["setPipeline"](pipeline)}function _wgpuRenderPassEncoderSetScissorRect(passId,x,y,w,h){var pass=WebGPU.mgrRenderPassEncoder.get(passId);pass["setScissorRect"](x,y,w,h)}function _wgpuRenderPassEncoderSetStencilReference(passId,reference){var pass=WebGPU.mgrRenderPassEncoder.get(passId);pass["setStencilReference"](reference)}function _wgpuRenderPassEncoderSetVertexBuffer(passId,slot,bufferId,offset_low,offset_high,size_low,size_high){var pass=WebGPU.mgrRenderPassEncoder.get(passId);var buffer=WebGPU.mgrBuffer.get(bufferId);var offset=offset_high*4294967296+offset_low;var size=size_high===-1&&size_low===-1?undefined:size_high*4294967296+size_low;pass["setVertexBuffer"](slot,buffer,offset,size)}function _wgpuRenderPassEncoderSetViewport(passId,x,y,w,h,minDepth,maxDepth){var pass=WebGPU.mgrRenderPassEncoder.get(passId);pass["setViewport"](x,y,w,h,minDepth,maxDepth)}function _wgpuRenderPipelineRelease(id){WebGPU.mgrRenderPipeline.release(id)}function _wgpuSamplerRelease(id){WebGPU.mgrSampler.release(id)}function _wgpuShaderModuleRelease(id){WebGPU.mgrShaderModule.release(id)}function _wgpuSurfaceRelease(id){WebGPU.mgrSurface.release(id)}function _wgpuSwapChainGetCurrentTextureView(swapChainId){var context=WebGPU.mgrSwapChain.get(swapChainId);return WebGPU.mgrTextureView.create(context["getCurrentTexture"]()["createView"]())}function _wgpuSwapChainRelease(id){WebGPU.mgrSwapChain.release(id)}function _wgpuTextureCreateView(textureId,descriptor){var desc;if(descriptor){var mipLevelCount=HEAPU32[descriptor+20>>2];var arrayLayerCount=HEAPU32[descriptor+28>>2];desc={"format":WebGPU.TextureFormat[HEAPU32[descriptor+8>>2]],"dimension":WebGPU.TextureViewDimension[HEAPU32[descriptor+12>>2]],"baseMipLevel":HEAPU32[descriptor+16>>2],"mipLevelCount":mipLevelCount===4294967295?undefined:mipLevelCount,"baseArrayLayer":HEAPU32[descriptor+24>>2],"arrayLayerCount":arrayLayerCount===4294967295?undefined:arrayLayerCount,"aspect":WebGPU.TextureAspect[HEAPU32[descriptor+32>>2]]};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr)}var texture=WebGPU.mgrTexture.get(textureId);return WebGPU.mgrTextureView.create(texture["createView"](desc))}function _wgpuTextureDestroy(textureId){WebGPU.mgrTexture.get(textureId)["destroy"]()}function _wgpuTextureRelease(id){WebGPU.mgrTexture.release(id)}function _wgpuTextureViewRelease(id){WebGPU.mgrTextureView.release(id)}function warnOnce(text){if(!warnOnce.shown)warnOnce.shown={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;err(text)}}InternalError=Module["InternalError"]=extendError(Error,"InternalError");embind_init_charCodes();BindingError=Module["BindingError"]=extendError(Error,"BindingError");init_ClassHandle();init_embind();init_RegisteredPointer();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");init_emval();WebGPU.initManagers();var asmLibraryArg={"h":__embind_finalize_value_object,"Ta":__embind_register_bigint,"na":__embind_register_bool,"m":__embind_register_class,"K":__embind_register_class_class_function,"q":__embind_register_class_constructor,"c":__embind_register_class_function,"d":__embind_register_class_property,"ma":__embind_register_emval,"Q":__embind_register_float,"s":__embind_register_integer,"r":__embind_register_memory_view,"R":__embind_register_std_string,"D":__embind_register_std_wstring,"i":__embind_register_value_object,"a":__embind_register_value_object_field,"oa":__embind_register_void,"k":__emval_as,"V":__emval_call_void_method,"b":__emval_decref,"W":__emval_get_method_caller,"g":__emval_get_property,"l":__emval_incref,"p":__emval_new_array,"n":__emval_new_cstring,"j":__emval_run_destructors,"o":__emval_set_property,"f":__emval_take_value,"e":_abort,"ka":_emscripten_memcpy_big,"C":_emscripten_resize_heap,"Ba":_emscripten_webgpu_get_device,"ha":_environ_get,"ia":_environ_sizes_get,"ja":_fd_write,"P":_setTempRet0,"Ga":_wgpuAdapterGetProperties,"J":_wgpuAdapterHasFeature,"Da":_wgpuAdapterRelease,"Ha":_wgpuBindGroupRelease,"ca":_wgpuBufferDestroy,"O":_wgpuBufferGetMappedRange,"ba":_wgpuBufferRelease,"B":_wgpuBufferUnmap,"N":_wgpuCommandBufferRelease,"Ja":_wgpuCommandEncoderBeginComputePass,"pa":_wgpuCommandEncoderBeginRenderPass,"Wa":_wgpuCommandEncoderCopyBufferToBuffer,"da":_wgpuCommandEncoderCopyBufferToTexture,"Ka":_wgpuCommandEncoderCopyTextureToTexture,"u":_wgpuCommandEncoderFinish,"x":_wgpuCommandEncoderRelease,"Ia":_wgpuComputePassEncoderDispatchWorkgroups,"Va":_wgpuComputePassEncoderDispatchWorkgroupsIndirect,"ya":_wgpuComputePassEncoderEnd,"wa":_wgpuComputePassEncoderRelease,"Sa":_wgpuComputePassEncoderSetBindGroup,"Ra":_wgpuComputePassEncoderSetPipeline,"S":_wgpuComputePipelineRelease,"M":_wgpuDeviceCreateBindGroup,"L":_wgpuDeviceCreateBindGroupLayout,"v":_wgpuDeviceCreateBuffer,"y":_wgpuDeviceCreateCommandEncoder,"va":_wgpuDeviceCreateComputePipeline,"xa":_wgpuDeviceCreatePipelineLayout,"ua":_wgpuDeviceCreateRenderPipeline,"ta":_wgpuDeviceCreateSampler,"G":_wgpuDeviceCreateShaderModule,"qa":_wgpuDeviceCreateSwapChain,"E":_wgpuDeviceCreateTexture,"Y":_wgpuDeviceGetQueue,"Ca":_wgpuDeviceRelease,"Aa":_wgpuInstanceCreateSurface,"Ea":_wgpuInstanceRelease,"za":_wgpuInstanceRequestAdapter,"U":_wgpuPipelineLayoutRelease,"_":_wgpuQuerySetDestroy,"Z":_wgpuQuerySetRelease,"Ua":_wgpuQueueOnSubmittedWorkDone,"I":_wgpuQueueRelease,"z":_wgpuQueueSubmit,"ga":_wgpuQueueWriteBuffer,"X":_wgpuQueueWriteTexture,"La":_wgpuRenderPassEncoderDraw,"ea":_wgpuRenderPassEncoderDrawIndexed,"Xa":_wgpuRenderPassEncoderDrawIndirect,"la":_wgpuRenderPassEncoderEnd,"Za":_wgpuRenderPassEncoderRelease,"A":_wgpuRenderPassEncoderSetBindGroup,"Pa":_wgpuRenderPassEncoderSetBlendConstant,"Ya":_wgpuRenderPassEncoderSetIndexBuffer,"Qa":_wgpuRenderPassEncoderSetPipeline,"Na":_wgpuRenderPassEncoderSetScissorRect,"Ma":_wgpuRenderPassEncoderSetStencilReference,"fa":_wgpuRenderPassEncoderSetVertexBuffer,"Oa":_wgpuRenderPassEncoderSetViewport,"T":_wgpuRenderPipelineRelease,"sa":_wgpuSamplerRelease,"H":_wgpuShaderModuleRelease,"Fa":_wgpuSurfaceRelease,"F":_wgpuSwapChainGetCurrentTextureView,"ra":_wgpuSwapChainRelease,"w":_wgpuTextureCreateView,"aa":_wgpuTextureDestroy,"$":_wgpuTextureRelease,"t":_wgpuTextureViewRelease};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["$a"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["bb"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["cb"]).apply(null,arguments)};var ___getTypeName=Module["___getTypeName"]=function(){return(___getTypeName=Module["___getTypeName"]=Module["asm"]["db"]).apply(null,arguments)};var ___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=function(){return(___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=Module["asm"]["eb"]).apply(null,arguments)};var dynCall_jii=Module["dynCall_jii"]=function(){return(dynCall_jii=Module["dynCall_jii"]=Module["asm"]["fb"]).apply(null,arguments)};var dynCall_viij=Module["dynCall_viij"]=function(){return(dynCall_viij=Module["dynCall_viij"]=Module["asm"]["gb"]).apply(null,arguments)};var dynCall_jiji=Module["dynCall_jiji"]=function(){return(dynCall_jiji=Module["dynCall_jiji"]=Module["asm"]["hb"]).apply(null,arguments)};var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run(); + + + return wasmDevice.ready +} +); +})(); +export default wasmDevice; \ No newline at end of file diff --git a/editor/engine-features/render-config.json b/editor/engine-features/render-config.json index 6f2f8eb65d..85ae9c0f4a 100644 --- a/editor/engine-features/render-config.json +++ b/editor/engine-features/render-config.json @@ -12,7 +12,7 @@ "label": "i18n:ENGINE.features.graphics.label", "multi": true, "description": "i18n:ENGINE.features.graphics.description", - "default": ["gfx-webgl", "gfx-webgl2"], + "default": ["gfx-webgl", "gfx-webgl2", "gfx-webgpu"], "options": { "gfx-webgl": { "required": true, diff --git a/editor/engine-features/schema.json b/editor/engine-features/schema.json index 060d10e5ac..8f79449fbc 100644 --- a/editor/engine-features/schema.json +++ b/editor/engine-features/schema.json @@ -76,6 +76,9 @@ "gfx-webgl2": { "$ref": "#/definitions/Item" }, + "gfx-webgpu": { + "$ref": "#/definitions/Item" + }, "graphcis": { "$ref": "#/definitions/Item" }, @@ -217,6 +220,9 @@ "gfx-webgl2": { "$ref": "#/definitions/BaseItem" }, + "gfx-webgpu": { + "$ref": "#/definitions/BaseItem" + }, "graphcis": { "$ref": "#/definitions/BaseItem" }, @@ -311,5 +317,4 @@ } }, "type": "object" -} - +} \ No newline at end of file diff --git a/editor/engine-features/types.ts b/editor/engine-features/types.ts index 467f787c0e..2ff6a5f7cd 100644 --- a/editor/engine-features/types.ts +++ b/editor/engine-features/types.ts @@ -3,6 +3,7 @@ export type EngineFeature = | 'gfx-webgl' | 'gfx-webgl2' + | 'gfx-webgpu' | 'base' | 'graphcis' | '3d' diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index b8baed93b1..3478a22375 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -174,9 +174,9 @@ module.exports = { atlas: 'Atlas that the image belongs to', type: 'Rendering mode:\n - Simple: Modifying the size will stretch the image as a whole, which is suitable for sequence frame animation and normal images. \n' + - '- Sliced: When changing the size, the four corners will not stretch, which is suitable for UI buttons and panel backgrounds. \n' + - '- Tiled : When changing the size, the original size image will continue to be tiled. \n' + - '- Filled : set a certain starting position and direction of filling, and the picture can be cropped and displayed at a certain ratio.', + '- Sliced: When changing the size, the four corners will not stretch, which is suitable for UI buttons and panel backgrounds. \n' + + '- Tiled : When changing the size, the original size image will continue to be tiled. \n' + + '- Filled : set a certain starting position and direction of filling, and the picture can be cropped and displayed at a certain ratio.', original_size: "Use the Image's original size as the Node size?", edit_button: 'Edit', select_button: 'Select In Atlas', @@ -544,7 +544,7 @@ module.exports = { vertical_align: 'Vertical alignment', font_size: 'Font size, in points', font: 'Custom TTF font of Rich Text', - font_family:'Custom System font of Rich Text', + font_family: 'Custom System font of Rich Text', use_system_font: 'Using system font', cache_mode: 'The cache mode of label. This mode only supports system fonts.', max_width: 'The maximize width of RichText, pass 0 means not limit the maximize width.', @@ -791,6 +791,10 @@ module.exports = { label: "WebGL 2.0", description: "Include support for WebGL 2.0 graphics API.\n If WebGL 2.0 is not available on target platform, the one will fallback as WebGL 1.0.", }, + gfx_webgpu: { + label: "WebGPU", + description: "Include support for WebGPU graphics API.", + }, ui: { label: "User Interface", description: "User interface support.", @@ -930,9 +934,9 @@ module.exports = { color: 'Main color for rendering, it normally multiplies with texture color.', }, ui_transform: { - content_size:'Size of the UI node.', - anchor_point:'Anchor point of the UI node.', - priority:'Priority of rendering ordering.', + content_size: 'Size of the UI node.', + anchor_point: 'Anchor point of the UI node.', + priority: 'Priority of rendering ordering.', }, graphics: { lineWidth: 'The width of edges', @@ -981,7 +985,7 @@ module.exports = { simplex_vertex2: 'Vertex 2 of the shape', simplex_vertex3: 'Vertex 3 of the shape', }, - constant_force:{ + constant_force: { force: 'The force apply on a rigid body in the world coordinate system', localForce: 'The force apply on a rigid body in the local coordinate system', torque: 'The torque applied to the rigid body in the world coordinate system', diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index 2c87782fa2..f5979671a0 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -772,6 +772,10 @@ module.exports = { label: "WebGL 2.0", description: "包含对 WebGL 2.0 图形 API 的支持。\n当 WebGL 2.0 在目标平台上不可用时会自动回退至 WebGL 1.0。", }, + gfx_webgpu: { + label: "WebGPU", + description: "包含对 WebGPU 图形 API 的支持。", + }, ui: { label: "用户界面", description: "用户界面支持。", @@ -911,9 +915,9 @@ module.exports = { color: '渲染颜色,一般情况下会和贴图颜色相乘', }, ui_transform: { - content_size:'内容尺寸', - anchor_point:'锚点位置', - priority:'渲染排序优先级', + content_size: '内容尺寸', + anchor_point: '锚点位置', + priority: '渲染排序优先级', }, graphics: { lineWidth: '线条宽度', @@ -962,7 +966,7 @@ module.exports = { simplex_vertex2: '形状的顶点 2', simplex_vertex3: '形状的顶点 3', }, - constant_force:{ + constant_force: { force: '在世界坐标系中,对刚体施加的力', localForce: '在本地坐标系中,对刚体施加的力', torque: '在世界坐标系中,对刚体施加的扭转力', diff --git a/gulp/util/api-docs-build.js b/gulp/util/api-docs-build.js index 28835bd83f..712893fc62 100644 --- a/gulp/util/api-docs-build.js +++ b/gulp/util/api-docs-build.js @@ -11,7 +11,7 @@ program const mode = 'commonjs'; const docsName = 'Cocos-Creator-API'; -const exclude = '"**/cocos/**/+(webgl|webgl2|utils|builtin|renderer|scene|models|misc|ammo|shapes|constraint|cannon|graphics|profiler|shader-sources|physx|spec|box2d)/*.ts"'; +const exclude = '"**/cocos/**/+(webgl|webgl2|webgpu|utils|builtin|renderer|scene|models|misc|ammo|shapes|constraint|cannon|graphics|profiler|shader-sources|physx|spec|box2d)/*.ts"'; const readme = 'none'; //const exclude = '"**/cocos/**/index.ts"'; @@ -108,7 +108,7 @@ exports.generateHTMLWithLocalization = function () { removeLanguage != "en" && this.generateAPIEN(index, jsonFiles, `${output}/en`); } -function checkJsonFileExists (jsonFils) { +function checkJsonFileExists(jsonFils) { let existsSync = fs.accessSync || fs.existsSync; try { existsSync(jsonFils) @@ -120,7 +120,7 @@ function checkJsonFileExists (jsonFils) { return true; } -function outputDebug (child) { +function outputDebug(child) { // spawnSync if (child.output && child.output.length > 0) { for (let i = 0; i < child.output.length; i++) { diff --git a/native/cmake/predefine.cmake b/native/cmake/predefine.cmake index a7241af001..d6b645fd47 100644 --- a/native/cmake/predefine.cmake +++ b/native/cmake/predefine.cmake @@ -263,6 +263,7 @@ elseif(ANDROID) elseif(OHOS) include(${CMAKE_CURRENT_LIST_DIR}/../../templates/cmake/ohos.cmake) elseif(QNX) +elseif(EMSCRIPTEN) else() message(FATAL_ERROR "Unhandled platform specified cmake utils!") endif() diff --git a/native/cocos/base/StringUtil.cpp b/native/cocos/base/StringUtil.cpp index 58168ed96b..fd324f9a44 100644 --- a/native/cocos/base/StringUtil.cpp +++ b/native/cocos/base/StringUtil.cpp @@ -28,7 +28,9 @@ #include #include #include -#include "base/ZipUtils.h" +#ifndef CC_WGPU_WASM + #include "base/ZipUtils.h" +#endif #include "base/base64.h" #include "base/std/container/string.h" #include "memory/Memory.h" @@ -163,6 +165,7 @@ ccstd::string &StringUtil::toupper(ccstd::string &str) { } ccstd::string GzipedString::value() const { // NOLINT(readability-convert-member-functions-to-static) +#ifndef CC_WGPU_WASM uint8_t *outGzip{nullptr}; uint8_t *outBase64{nullptr}; auto *input = reinterpret_cast(const_cast(_str.c_str())); @@ -172,6 +175,9 @@ ccstd::string GzipedString::value() const { // NOLINT(readability-convert-member free(outGzip); free(outBase64); return ret; +#else + return ""; +#endif } } // namespace cc diff --git a/native/cocos/base/TypeDef.h b/native/cocos/base/TypeDef.h index 7ac43b46c2..e1cd48eed1 100644 --- a/native/cocos/base/TypeDef.h +++ b/native/cocos/base/TypeDef.h @@ -32,7 +32,7 @@ using uint = std::uint32_t; using ushort = std::uint16_t; -#if (CC_PLATFORM != CC_PLATFORM_LINUX && CC_PLATFORM != CC_PLATFORM_QNX) // linux has typedef ulong +#if (CC_PLATFORM != CC_PLATFORM_LINUX && CC_PLATFORM != CC_PLATFORM_QNX && CC_PLATFORM != CC_PLATFORM_EMSCRIPTEN) // linux has typedef ulong using ulong = std::uint32_t; #endif using FlagBits = std::uint32_t; diff --git a/native/cocos/renderer/gfx-base/GFXDescriptorSet.h b/native/cocos/renderer/gfx-base/GFXDescriptorSet.h index 7d7f8be44f..15774c6109 100644 --- a/native/cocos/renderer/gfx-base/GFXDescriptorSet.h +++ b/native/cocos/renderer/gfx-base/GFXDescriptorSet.h @@ -55,7 +55,7 @@ public: Texture *getTexture(uint32_t binding, uint32_t index) const; Sampler *getSampler(uint32_t binding, uint32_t index) const; - inline DescriptorSetLayout *getLayout() { return _layout; } + inline DescriptorSetLayout *getLayout() const { return _layout; } inline void bindBuffer(uint32_t binding, Buffer *buffer) { bindBuffer(binding, buffer, 0U); } inline void bindTexture(uint32_t binding, Texture *texture) { bindTexture(binding, texture, 0U); } diff --git a/native/cocos/renderer/gfx-wgpu/CMakeLists.txt b/native/cocos/renderer/gfx-wgpu/CMakeLists.txt index 1f0b450045..8083028fb4 100644 --- a/native/cocos/renderer/gfx-wgpu/CMakeLists.txt +++ b/native/cocos/renderer/gfx-wgpu/CMakeLists.txt @@ -11,15 +11,25 @@ set(ENGINE_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/../../..) include(${ENGINE_ROOT_DIR}/cmake/predefine.cmake) -include (${ENGINE_ROOT_DIR}/external/CMakeLists.txt) +# include (${ENGINE_ROOT_DIR}/external/CMakeLists.txt) -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wno-nonportable-include-path -fno-exceptions -v") -set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g3 -D_DEBUG=1 -Wno-unused -O0") -set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -g0 -DNDEBUG=1 -O3") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -Wextra -Wno-nonportable-include-path -fno-exceptions -v") +set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall -g3 -D_DEBUG=1 -Wno-unused -O0 -std=c++17") +set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -w -DNDEBUG=1 -O3 -std=c++17") + +AUX_SOURCE_DIRECTORY( + ./states + WGPU_STATES_SRC +) AUX_SOURCE_DIRECTORY( . - WGPU_SRC + WGPU_IMPL_SRC +) + +set(WGPU_SRC + ${WGPU_STATES_SRC} + ${WGPU_IMPL_SRC} ) AUX_SOURCE_DIRECTORY( @@ -32,6 +42,7 @@ AUX_SOURCE_DIRECTORY( ../../../cocos/base COCOS_BASE ) +list(FILTER COCOS_BASE EXCLUDE REGEX "ZipUtils.*") AUX_SOURCE_DIRECTORY( ../../../cocos/renderer/gfx-base @@ -101,13 +112,14 @@ target_include_directories( ${CC_EXTERNAL_PRIVATE_INCLUDES} ) +# message(${WGPU_EMS_EXTERNAL_LIBS}) target_link_libraries( ${APP_NAME}_wasm PRIVATE PUBLIC - ${CC_EXTERNAL_LIBS} + # ${WGPU_EMS_EXTERNAL_LIBS} ) set(EMS_LINK_FLAGS -"--bind --no-entry -O3 -s USE_ES6_IMPORT_META=0 -s EXPORT_ES6=1 -s MODULARIZE=1 -s EXPORT_NAME='wasmDevice' -s ENVIRONMENT=web -s WASM=1 -s USE_WEBGPU=1 -s NO_EXIT_RUNTIME=1 -s LLD_REPORT_UNDEFINED -s ALLOW_MEMORY_GROWTH=1 -s ASSERTIONS=1 -s SAFE_HEAP -s WARN_UNALIGNED=1" +"-flto --bind --no-entry -O3 -s USE_ES6_IMPORT_META=0 -s EXPORT_ES6=1 -s MODULARIZE=1 -s EXPORT_NAME='wasmDevice' -s ENVIRONMENT=web -s WASM=1 -s USE_WEBGPU=1 -s NO_EXIT_RUNTIME=1 -s LLD_REPORT_UNDEFINED -s ALLOW_MEMORY_GROWTH=1" ) -set_target_properties(${APP_NAME}_wasm PROPERTIES LINK_FLAGS ${EMS_LINK_FLAGS}) \ No newline at end of file +set_target_properties(${APP_NAME}_wasm PROPERTIES CXX_STANDARD 17 LINK_FLAGS ${EMS_LINK_FLAGS}) diff --git a/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp b/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp index 4a7ec4c0cf..3f63837635 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp @@ -32,14 +32,18 @@ namespace cc { namespace gfx { -namespace anoymous { -CCWGPUBuffer *defaultUniformBuffer = nullptr; -CCWGPUBuffer *defaultStorageBuffer = nullptr; -} // namespace anoymous +namespace { +CCWGPUBuffer *dftUniformBuffer = nullptr; +CCWGPUBuffer *dftStorageBuffer = nullptr; +} // namespace using namespace emscripten; -CCWGPUBuffer::CCWGPUBuffer() : wrapper(val::object()) { +CCWGPUBuffer::CCWGPUBuffer() : Buffer() { +} + +CCWGPUBuffer::~CCWGPUBuffer() { + doDestroy(); } void CCWGPUBuffer::doInit(const BufferInfo &info) { @@ -58,7 +62,7 @@ void CCWGPUBuffer::doInit(const BufferInfo &info) { .label = nullptr, .usage = toWGPUBufferUsage(info.usage), .size = _size, - .mappedAtCreation = false, //hasFlag(info.memUsage, MemoryUsageBit::DEVICE), + .mappedAtCreation = false, // hasFlag(info.memUsage, MemoryUsageBit::DEVICE), }; _gpuBufferObject->mapped = descriptor.mappedAtCreation; @@ -72,6 +76,7 @@ void CCWGPUBuffer::doInit(const BufferInfo &info) { } _gpuBufferObject->wgpuBuffer = wgpuDeviceCreateBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + CCWGPUDevice::getInstance()->getMemoryStatus().bufferSize += _size; _internalChanged = true; } // namespace gfx @@ -83,10 +88,12 @@ void CCWGPUBuffer::doInit(const BufferViewInfo &info) { void CCWGPUBuffer::doDestroy() { if (_gpuBufferObject) { - if (_gpuBufferObject->wgpuBuffer) { - wgpuBufferDestroy(_gpuBufferObject->wgpuBuffer); + if (_gpuBufferObject->wgpuBuffer && !_isBufferView) { + CCWGPUDevice::getInstance()->moveToTrash(_gpuBufferObject->wgpuBuffer); + CCWGPUDevice::getInstance()->getMemoryStatus().bufferSize -= _size; } delete _gpuBufferObject; + _gpuBufferObject = nullptr; } _internalChanged = true; } @@ -97,8 +104,9 @@ void CCWGPUBuffer::doResize(uint32_t size, uint32_t count) { return; } if (_gpuBufferObject->wgpuBuffer) { - wgpuBufferDestroy(_gpuBufferObject->wgpuBuffer); + CCWGPUDevice::getInstance()->moveToTrash(_gpuBufferObject->wgpuBuffer); } + CCWGPUDevice::getInstance()->getMemoryStatus().bufferSize -= _size; if (hasFlag(_usage, BufferUsageBit::INDIRECT)) { const size_t drawInfoCount = _size / sizeof(DrawInfo); @@ -113,9 +121,10 @@ void CCWGPUBuffer::doResize(uint32_t size, uint32_t count) { .label = nullptr, .usage = toWGPUBufferUsage(_usage), .size = _size, - .mappedAtCreation = false, //hasFlag(_memUsage, MemoryUsageBit::DEVICE), + .mappedAtCreation = false, // hasFlag(_memUsage, MemoryUsageBit::DEVICE), }; _gpuBufferObject->wgpuBuffer = wgpuDeviceCreateBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + CCWGPUDevice::getInstance()->getMemoryStatus().bufferSize += _size; _internalChanged = true; } // namespace gfx @@ -161,7 +170,7 @@ void CCWGPUBuffer::update(const void *buffer, uint32_t size) { uint32_t alignedSize = ceil(size / 4.0) * 4; size_t buffSize = alignedSize; wgpuQueueWriteBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, _gpuBufferObject->wgpuBuffer, offset, buffer, buffSize); - //wgpuBufferUnmap(_gpuBufferObject->wgpuBuffer); + // wgpuBufferUnmap(_gpuBufferObject->wgpuBuffer); } void CCWGPUBuffer::update(const DrawInfoList &drawInfos) { @@ -170,7 +179,7 @@ void CCWGPUBuffer::update(const DrawInfoList &drawInfos) { void const *data = nullptr; size_t offset = _isBufferView ? _offset : 0; size_t buffSize = 0; - //if (hasFlag(_usage, BufferUsageBit::INDIRECT)) + // if (hasFlag(_usage, BufferUsageBit::INDIRECT)) if (drawInfos[0].indexCount) { auto &indexedIndirectObjs = _gpuBufferObject->indexedIndirectObjs; for (size_t i = 0; i < drawInfoCount; i++) { @@ -178,7 +187,7 @@ void CCWGPUBuffer::update(const DrawInfoList &drawInfos) { indexedIndirectObjs[i].instanceCount = drawInfos[i].instanceCount /* ? drawInfos[i]->instanceCoun : 1 */; indexedIndirectObjs[i].firstIndex = drawInfos[i].firstIndex; indexedIndirectObjs[i].baseVertex = drawInfos[i].vertexOffset; - indexedIndirectObjs[i].firstInstance = 0; //check definition of indexedIndirectObj; + indexedIndirectObjs[i].firstInstance = 0; // check definition of indexedIndirectObj; } data = indexedIndirectObjs.data(); buffSize = indexedIndirectObjs.size() * sizeof(CCWGPUDrawIndexedIndirectObject); @@ -209,31 +218,31 @@ void CCWGPUBuffer::stamp() { } CCWGPUBuffer *CCWGPUBuffer::defaultUniformBuffer() { - if (!anoymous::defaultUniformBuffer) { + if (!dftUniformBuffer) { BufferInfo info = { .usage = BufferUsageBit::UNIFORM, .memUsage = MemoryUsageBit::DEVICE, .size = 4, .flags = BufferFlagBit::NONE, }; - anoymous::defaultUniformBuffer = ccnew CCWGPUBuffer; - anoymous::defaultUniformBuffer->initialize(info); + dftUniformBuffer = ccnew CCWGPUBuffer; + dftUniformBuffer->initialize(info); } - return anoymous::defaultUniformBuffer; + return dftUniformBuffer; } CCWGPUBuffer *CCWGPUBuffer::defaultStorageBuffer() { - if (!anoymous::defaultStorageBuffer) { + if (!dftStorageBuffer) { BufferInfo info = { .usage = BufferUsageBit::STORAGE, .memUsage = MemoryUsageBit::DEVICE, .size = 4, .flags = BufferFlagBit::NONE, }; - anoymous::defaultStorageBuffer = ccnew CCWGPUBuffer; - anoymous::defaultStorageBuffer->initialize(info); + dftStorageBuffer = ccnew CCWGPUBuffer; + dftStorageBuffer->initialize(info); } - return anoymous::defaultStorageBuffer; + return dftStorageBuffer; } } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUBuffer.h b/native/cocos/renderer/gfx-wgpu/WGPUBuffer.h index fd18b64c0f..4cca467c19 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUBuffer.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUBuffer.h @@ -24,8 +24,9 @@ ****************************************************************************/ #pragma once -#include -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "base/std/container/vector.h" #include "gfx-base/GFXBuffer.h" @@ -34,37 +35,28 @@ namespace gfx { struct CCWGPUBufferObject; -class CCWGPUBuffer final : public emscripten::wrapper { +class CCWGPUBuffer final : public Buffer { public: - EMSCRIPTEN_WRAPPER(CCWGPUBuffer); CCWGPUBuffer(); - ~CCWGPUBuffer() = default; + ~CCWGPUBuffer(); + + inline CCWGPUBufferObject *gpuBufferObject() const { return _gpuBufferObject; } + inline uint32_t getOffset() const { return _offset; } + void update(const DrawInfoList &drawInfos); + // used before unmap? + void check(); + // stamp current resource handler + void stamp(); + // resource handler changed? + inline bool internalChanged() const { return _internalChanged; } + + static CCWGPUBuffer *defaultUniformBuffer(); + static CCWGPUBuffer *defaultStorageBuffer(); void update(const void *buffer, uint32_t size) override; - inline CCWGPUBufferObject *gpuBufferObject() const { return _gpuBufferObject; } - - static CCWGPUBuffer *defaultUniformBuffer(); - - static CCWGPUBuffer *defaultStorageBuffer(); - - inline uint32_t getOffset() const { return _offset; } - - void update(const emscripten::val &v, uint32_t size) { - ccstd::vector buffer = emscripten::convertJSArrayToNumberVector(v); - update(reinterpret_cast(buffer.data()), size); - } - - void update(const DrawInfoList &drawInfos); - - // used before unmap? - void check(); - - // stamp current resource handler - void stamp(); - - // resource handler changed? - inline bool internalChanged() const { return _internalChanged; } + EXPORT_EMS( + void update(const emscripten::val &v, uint32_t size);) protected: void doInit(const BufferInfo &info) override; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp index e5bc63475c..3c3f53fd34 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp @@ -36,6 +36,7 @@ #include "WGPUPipelineLayout.h" #include "WGPUPipelineState.h" #include "WGPUQueue.h" +#include "WGPUShader.h" #include "WGPUSwapchain.h" #include "WGPUTexture.h" #include "WGPUUtils.h" @@ -45,15 +46,22 @@ namespace gfx { namespace { uint32_t dynamicOffsetBuffer[256]; +uint32_t dynBufferStartIndex = 0; +} // namespace + +CCWGPUCommandBuffer::CCWGPUCommandBuffer() : CommandBuffer() { } -CCWGPUCommandBuffer::CCWGPUCommandBuffer() : wrapper(val::object()) { +CCWGPUCommandBuffer::~CCWGPUCommandBuffer() { + doDestroy(); } - void CCWGPUCommandBuffer::doInit(const CommandBufferInfo &info) { _gpuCommandBufferObj = ccnew CCWGPUCommandBufferObject; _gpuCommandBufferObj->type = info.type; _gpuCommandBufferObj->queue = static_cast(info.queue); + _gpuCommandBufferObj->stateCache.descriptorSets.resize(4); //(info.queue->getDevice()->getMaxDescriptorSetLayoutBindings()); + memset(dynamicOffsetBuffer, 0, sizeof(dynamicOffsetBuffer)); + dynBufferStartIndex = 0; } void CCWGPUCommandBuffer::doDestroy() { @@ -64,31 +72,35 @@ void CCWGPUCommandBuffer::doDestroy() { delete pair.second; } } - CC_SAFE_DELETE(_gpuCommandBufferObj); + delete _gpuCommandBufferObj; + _gpuCommandBufferObj = nullptr; } } void CCWGPUCommandBuffer::begin(RenderPass * /*renderPass*/, uint32_t /*subpass*/, Framebuffer * /*frameBuffer*/) { - //TODO_Zeqiang: subpass support - // printf("begin\n"); + // TODO_Zeqiang: subpass support + // printf("begin\n"); + reset(); + + _numTriangles = 0; + _numDrawCalls = 0; + _numInstances = 0; + _gpuCommandBufferObj->wgpuCommandEncoder = wgpuDeviceCreateCommandEncoder(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, nullptr); } void CCWGPUCommandBuffer::end() { - // printf("end\n"); auto *pipelineState = _gpuCommandBufferObj->stateCache.pipelineState; if (pipelineState) { if (pipelineState->getBindPoint() == PipelineBindPoint::GRAPHICS) { auto *queue = _gpuCommandBufferObj->queue; - auto wgpuCommandBuffer = wgpuCommandEncoderFinish(_gpuCommandBufferObj->wgpuCommandEncoder, nullptr); - wgpuQueueSubmit(queue->gpuQueueObject()->wgpuQueue, 1, &wgpuCommandBuffer); + _gpuCommandBufferObj->wgpuCommandBuffer = wgpuCommandEncoderFinish(_gpuCommandBufferObj->wgpuCommandEncoder, nullptr); wgpuCommandEncoderRelease(_gpuCommandBufferObj->wgpuCommandEncoder); _gpuCommandBufferObj->wgpuCommandEncoder = wgpuDefaultHandle; } else { - wgpuComputePassEncoderEndPass(_gpuCommandBufferObj->wgpuComputeEncoder); + wgpuComputePassEncoderEnd(_gpuCommandBufferObj->wgpuComputeEncoder); wgpuComputePassEncoderRelease(_gpuCommandBufferObj->wgpuComputeEncoder); - auto wgpuCommandBuffer = wgpuCommandEncoderFinish(_gpuCommandBufferObj->wgpuCommandEncoder, nullptr); - wgpuQueueSubmit(static_cast(_queue)->gpuQueueObject()->wgpuQueue, 1, &wgpuCommandBuffer); + _gpuCommandBufferObj->wgpuCommandBuffer = wgpuCommandEncoderFinish(_gpuCommandBufferObj->wgpuCommandEncoder, nullptr); wgpuCommandEncoderRelease(_gpuCommandBufferObj->wgpuCommandEncoder); _gpuCommandBufferObj->wgpuComputeEncoder = wgpuDefaultHandle; _gpuCommandBufferObj->wgpuCommandEncoder = wgpuDefaultHandle; @@ -115,10 +127,10 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f renderPassDesc.label = "swapchain"; WGPURenderPassColorAttachment color = { .view = swapchain->gpuSwapchainObject()->swapchainColor->gpuTextureObject()->selfView, - .resolveTarget = nullptr, //TODO_Zeqiang: wgpu offscr msaa - .loadOp = WGPULoadOp_Clear, //toWGPULoadOp(colorConfigs[0].loadOp), - .storeOp = WGPUStoreOp_Discard, //toWGPUStoreOp(colorConfigs[0].storeOp), - .clearColor = WGPUColor{0.2, 0.2, 0.2, 1.0}, + .resolveTarget = nullptr, // TODO_Zeqiang: wgpu offscr msaa + .loadOp = WGPULoadOp_Clear, // toWGPULoadOp(colorConfigs[0].loadOp), + .storeOp = WGPUStoreOp_Discard, // toWGPUStoreOp(colorConfigs[0].storeOp), + .clearValue = WGPUColor{0.2, 0.2, 0.2, 1.0}, }; colorAttachments.emplace_back(color); } else { @@ -129,10 +141,10 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f WGPURenderPassColorAttachment *colorAttchments = ccnew WGPURenderPassColorAttachment[colorConfigs.size()]; WGPURenderPassColorAttachment color = { .view = static_cast(textures[i])->gpuTextureObject()->selfView, - .resolveTarget = nullptr, //TODO_Zeqiang: wgpu offscr msaa + .resolveTarget = nullptr, // TODO_Zeqiang: wgpu offscr msaa .loadOp = toWGPULoadOp(colorConfigs[i].loadOp), .storeOp = toWGPUStoreOp(colorConfigs[i].storeOp), - .clearColor = toWGPUColor(colors[i]), + .clearValue = toWGPUColor(colors[i]), }; colorAttachments.emplace_back(color); } @@ -142,13 +154,13 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f if (dsTexture) { WGPURenderPassDepthStencilAttachment depthStencil = { .view = static_cast(dsTexture)->gpuTextureObject()->selfView, - .depthLoadOp = WGPULoadOp_Clear, //toWGPULoadOp(depthStencilConfig.depthLoadOp), + .depthLoadOp = WGPULoadOp_Clear, // toWGPULoadOp(depthStencilConfig.depthLoadOp), .depthStoreOp = toWGPUStoreOp(depthStencilConfig.depthStoreOp), - .clearDepth = depth, + .depthClearValue = depth, .depthReadOnly = false, .stencilLoadOp = toWGPULoadOp(depthStencilConfig.stencilLoadOp), .stencilStoreOp = toWGPUStoreOp(depthStencilConfig.stencilStoreOp), - .clearStencil = stencil, + .stencilClearValue = stencil, .stencilReadOnly = false, }; depthStencils.emplace_back(depthStencil); @@ -158,13 +170,13 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f } else { WGPURenderPassDepthStencilAttachment depthStencil = { .view = swapchain->gpuSwapchainObject()->swapchainDepthStencil->gpuTextureObject()->selfView, - .depthLoadOp = WGPULoadOp_Clear, //toWGPULoadOp(depthStencilConfig.depthLoadOp), + .depthLoadOp = WGPULoadOp_Clear, // toWGPULoadOp(depthStencilConfig.depthLoadOp), .depthStoreOp = toWGPUStoreOp(depthStencilConfig.depthStoreOp), - .clearDepth = depth, + .depthClearValue = depth, .depthReadOnly = false, .stencilLoadOp = toWGPULoadOp(depthStencilConfig.stencilLoadOp), .stencilStoreOp = toWGPUStoreOp(depthStencilConfig.stencilStoreOp), - .clearStencil = stencil, + .stencilClearValue = stencil, .stencilReadOnly = false, }; depthStencils.emplace_back(depthStencil); @@ -184,11 +196,16 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f void CCWGPUCommandBuffer::endRenderPass() { // printf("endr\n"); - wgpuRenderPassEncoderEndPass(_gpuCommandBufferObj->wgpuRenderPassEncoder); + wgpuRenderPassEncoderEnd(_gpuCommandBufferObj->wgpuRenderPassEncoder); wgpuRenderPassEncoderRelease(_gpuCommandBufferObj->wgpuRenderPassEncoder); _gpuCommandBufferObj->wgpuRenderPassEncoder = wgpuDefaultHandle; - _gpuCommandBufferObj->stateCache.descriptorSets.clear(); + for (auto &descObj : _gpuCommandBufferObj->stateCache.descriptorSets) { + descObj.descriptorSet = nullptr; + descObj.dynamicOffsetCount = 0; + descObj.dynamicOffsets = nullptr; + dynBufferStartIndex = 0; + } _gpuCommandBufferObj->renderPassBegan = false; } @@ -200,28 +217,23 @@ void CCWGPUCommandBuffer::bindDescriptorSet(uint32_t set, DescriptorSet *descrip uint32_t dynOffsetCount = dynamicOffsetCount; const uint32_t *dynOffsets = dynamicOffsets; auto &descriptorSets = _gpuCommandBufferObj->stateCache.descriptorSets; - auto iter = std::find_if(descriptorSets.begin(), descriptorSets.end(), [set](const CCWGPUDescriptorSetObject &descriptorSet) { - return descriptorSet.index == set; - }); auto *ccDescriptorSet = static_cast(descriptorSet); if (ccDescriptorSet->dynamicOffsetCount() == 0) { - dynOffsetCount = 0; dynOffsets = nullptr; + } else { + memcpy(dynamicOffsetBuffer + dynBufferStartIndex, dynamicOffsets, sizeof(uint32_t) * dynamicOffsetCount); + dynOffsets = dynamicOffsetBuffer + dynBufferStartIndex; + dynBufferStartIndex += dynamicOffsetCount; } CCWGPUDescriptorSetObject dsObj = { - .index = set, .descriptorSet = ccDescriptorSet, - .dynamicOffsetCount = dynOffsetCount, //dynamicOffsetCount, - .dynamicOffsets = dynOffsets, //dynamicOffsets, + .dynamicOffsetCount = dynOffsetCount, // dynamicOffsetCount, + .dynamicOffsets = dynOffsets, // dynamicOffsets, }; - if (iter != descriptorSets.end()) { - (*iter) = dsObj; - } else { - descriptorSets.push_back(dsObj); - } + descriptorSets[set] = dsObj; } void CCWGPUCommandBuffer::bindInputAssembler(InputAssembler *ia) { @@ -271,89 +283,86 @@ void CCWGPUCommandBuffer::bindStates() { } ccstd::set setInUse; - for (const auto &descriptorSet : _gpuCommandBufferObj->stateCache.descriptorSets) { - setInUse.insert(descriptorSet.index); - } - // printf("ppl binding %p\n", pipelineState); - - // ccstd::vector wgpuLayouts; + auto *pipelineLayout = static_cast(pipelineState->layout()); + const auto &setLayouts = pipelineLayout->getSetLayouts(); + bool pipelineLayoutChanged = false; if (pipelineState->getBindPoint() == PipelineBindPoint::GRAPHICS) { - //bindgroup & descriptorset + // bindgroup & descriptorset const auto &descriptorSets = _gpuCommandBufferObj->stateCache.descriptorSets; - for (size_t i = 0; i < descriptorSets.size(); i++) { - descriptorSets[i].descriptorSet->prepare(); + for (size_t i = 0; i < setLayouts.size(); i++) { + if (descriptorSets[i].descriptorSet) { + descriptorSets[i].descriptorSet->prepare(); - if (descriptorSets[i].descriptorSet->dynamicOffsetCount() != descriptorSets[i].dynamicOffsetCount) { - uint32_t *dynOffsets = dynamicOffsetBuffer; - const Pairs &dynamicOffsets = descriptorSets[i].descriptorSet->dynamicOffsets(); - uint32_t givenOffsetIndex = 0; - for (size_t j = 0; j < descriptorSets[i].descriptorSet->dynamicOffsetCount(); ++j) { - if (j >= descriptorSets[i].dynamicOffsetCount || dynamicOffsets[j].second == 0) { - dynOffsets[j] = 0; - } else { - dynOffsets[j] = descriptorSets[i].dynamicOffsets[givenOffsetIndex++]; + if (descriptorSets[i].descriptorSet->dynamicOffsetCount() != descriptorSets[i].dynamicOffsetCount) { + uint32_t *dynOffsets = dynamicOffsetBuffer; + const Pairs &dynamicOffsets = descriptorSets[i].descriptorSet->dynamicOffsets(); + uint32_t givenOffsetIndex = 0; + for (size_t j = 0; j < descriptorSets[i].descriptorSet->dynamicOffsetCount(); ++j) { + if (j >= descriptorSets[i].dynamicOffsetCount || dynamicOffsets[j].second == 0) { + dynOffsets[j] = 0; + } else { + dynOffsets[j] = descriptorSets[i].dynamicOffsets[givenOffsetIndex++]; + } } - } - // printf("set %d %p %p\n", descriptorSets[i].index, descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup, - // descriptorSets[i].descriptorSet->bgl()); - // wgpuLayouts.push_back(descriptorSets[i].descriptorSet->bgl()); - wgpuRenderPassEncoderSetBindGroup(_gpuCommandBufferObj->wgpuRenderPassEncoder, - descriptorSets[i].index, - descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup, - descriptorSets[i].descriptorSet->dynamicOffsetCount(), - dynOffsets); - - } else { - wgpuRenderPassEncoderSetBindGroup(_gpuCommandBufferObj->wgpuRenderPassEncoder, - descriptorSets[i].index, - descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup, - descriptorSets[i].dynamicOffsetCount, - descriptorSets[i].dynamicOffsets); - // printf("set %d %p %p\n", i, descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup, - // descriptorSets[i].descriptorSet->bgl()); - // wgpuLayouts.push_back(descriptorSets[i].descriptorSet->bgl()); - } - } - - // missing - if (setInUse.size() != pipelineState->getPipelineLayout()->getSetLayouts().size()) { - const auto &setLayouts = pipelineState->getPipelineLayout()->getSetLayouts(); - for (size_t i = 0; i < setLayouts.size(); i++) { - if (setInUse.find(i) == setInUse.end()) { wgpuRenderPassEncoderSetBindGroup(_gpuCommandBufferObj->wgpuRenderPassEncoder, i, - static_cast(CCWGPUDescriptorSet::defaultBindGroup()), - 0, - nullptr); - // printf("default %d %p\n", i, CCWGPUDescriptorSetLayout::defaultBindGroupLayout()); - // wgpuLayouts.push_back(CCWGPUDescriptorSetLayout::defaultBindGroupLayout()); + descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup, + descriptorSets[i].descriptorSet->dynamicOffsetCount(), + dynOffsets); + setInUse.insert(i); + if (setLayouts[i] != descriptorSets[i].descriptorSet->getLayout()) { + pipelineLayoutChanged = true; + } + } else { + wgpuRenderPassEncoderSetBindGroup(_gpuCommandBufferObj->wgpuRenderPassEncoder, + i, + descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup, + descriptorSets[i].dynamicOffsetCount, + descriptorSets[i].dynamicOffsets); } + setInUse.insert(i); + } else { + // missing + wgpuRenderPassEncoderSetBindGroup(_gpuCommandBufferObj->wgpuRenderPassEncoder, + i, + static_cast(CCWGPUDescriptorSet::defaultBindGroup()), + 0, + nullptr); } } - pipelineState->check(_renderPass); + + for (size_t i = 0; i < setLayouts.size(); i++) { + if (setInUse.find(i) == setInUse.end()) { + wgpuRenderPassEncoderSetBindGroup(_gpuCommandBufferObj->wgpuRenderPassEncoder, + i, + static_cast(CCWGPUDescriptorSet::defaultBindGroup()), + 0, + nullptr); + } + } + + if (1) { + ccstd::vector dsSets; + for (size_t i = 0; i < setLayouts.size(); i++) { + dsSets.push_back(descriptorSets[i].descriptorSet); + } + createPipelineLayoutFallback(dsSets, pipelineLayout); + } else { + pipelineLayout->prepare(setInUse); + } + + pipelineState->check(_renderPass, 1); pipelineState->prepare(setInUse); - // printf("ppshn: %s\n", static_cast(pipelineState->getShader())->gpuShaderObject()->name.c_str()); - const auto &pplLayout = static_cast(pipelineState->ppl()); - // for(size_t i = 0; i < pplLayout->layouts().size(); ++i) { - // // printf("bgl in ppl: %p\n", pplLayout->layouts()[i]); - // if(pplLayout->layouts()[i] != wgpuLayouts[i]) { - // printf("oooooooooooops %d %p %p\n", i, pplLayout->layouts()[i], wgpuLayouts[i]); - // static_cast(descriptorSets[i].descriptorSet->getLayout())->print(); - // static_cast(pplLayout->getSetLayouts()[i])->print(); - // } - // } - // if(pipelineState->ppl() != pipelineState->getPipelineLayout()){ - // printf("oooooooooooooooooooooooooooooooops\n"); - // } - //pipeline state + + // pipeline state wgpuRenderPassEncoderSetPipeline(_gpuCommandBufferObj->wgpuRenderPassEncoder, pipelineState->gpuPipelineStateObject()->wgpuRenderPipeline); - //input assembler + // input assembler const auto *ia = _gpuCommandBufferObj->stateCache.inputAssembler; const auto &vertexBufferList = ia->getVertexBuffers(); for (size_t i = 0; i < vertexBufferList.size(); i++) { @@ -364,9 +373,9 @@ void CCWGPUCommandBuffer::bindStates() { vertexBuffer->getOffset(), vertexBuffer->getSize()); } - +#if 1 { - //redundantVertexBufferMap + // redundantVertexBufferMap const uint32_t maxAttrLen = pipelineState->gpuPipelineStateObject()->maxAttrLength; if (maxAttrLen != 0) { CCWGPUBuffer *buffer = nullptr; @@ -382,6 +391,7 @@ void CCWGPUCommandBuffer::bindStates() { buffer = ccnew CCWGPUBuffer; buffer->initialize(info); _gpuCommandBufferObj->redundantVertexBufferMap.insert({maxAttrLen, buffer}); + printf("new vert buffer\n"); } wgpuRenderPassEncoderSetVertexBuffer(_gpuCommandBufferObj->wgpuRenderPassEncoder, vertexBufferList.size(), @@ -390,7 +400,7 @@ void CCWGPUCommandBuffer::bindStates() { maxAttrLen); } } - +#endif const auto *indexBuffer = static_cast(ia->getIndexBuffer()); if (indexBuffer) { wgpuRenderPassEncoderSetIndexBuffer(_gpuCommandBufferObj->wgpuRenderPassEncoder, @@ -411,11 +421,8 @@ void CCWGPUCommandBuffer::bindStates() { for (size_t i = 0; i < textures.size(); i++) { rtWidth = rtWidth > textures[i]->getWidth() ? textures[i]->getWidth() : rtWidth; rtHeight = rtHeight > textures[i]->getHeight() ? textures[i]->getHeight() : rtHeight; - // printf("w, h %d %d\n", textures[i]->getWidth(), textures[i]->getHeight()); } - // printf("minrt %u, %u\n", rtWidth, rtHeight); - const Viewport &vp = _gpuCommandBufferObj->stateCache.viewport; uint32_t left = vp.left > 0 ? vp.left : 0; uint32_t top = vp.top > 0 ? vp.top : 0; @@ -425,7 +432,6 @@ void CCWGPUCommandBuffer::bindStates() { uint32_t height = vp.top > 0 ? vp.height : vp.height + vp.top; height = top + height > rtHeight ? rtHeight - top : height; - // printf("vp %u, %u, %u, %u\n", left, top, width, height); wgpuRenderPassEncoderSetViewport(_gpuCommandBufferObj->wgpuRenderPassEncoder, left, top, width, height, vp.minDepth, vp.maxDepth); const Rect &rect = _gpuCommandBufferObj->stateCache.rect; @@ -435,19 +441,18 @@ void CCWGPUCommandBuffer::bindStates() { width = left + width > rtWidth ? rtWidth - left : width; height = rect.y > 0 ? rect.height : rect.height + rect.y; height = top + height > rtHeight ? rtHeight - top : height; - // printf("sc %u, %u, %u, %u\n", left, top, width, height); wgpuRenderPassEncoderSetScissorRect(_gpuCommandBufferObj->wgpuRenderPassEncoder, left, top, width, height); wgpuRenderPassEncoderSetStencilReference(_gpuCommandBufferObj->wgpuRenderPassEncoder, pipelineState->getDepthStencilState().stencilRefFront); } else if (pipelineState->getBindPoint() == PipelineBindPoint::COMPUTE) { auto *pipelineState = _gpuCommandBufferObj->stateCache.pipelineState; - //bindgroup & descriptorset + // bindgroup & descriptorset const auto &descriptorSets = _gpuCommandBufferObj->stateCache.descriptorSets; for (size_t i = 0; i < descriptorSets.size(); i++) { if (descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup) { wgpuComputePassEncoderSetBindGroup(_gpuCommandBufferObj->wgpuComputeEncoder, - descriptorSets[i].index, + i, descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup, descriptorSets[i].dynamicOffsetCount, descriptorSets[i].dynamicOffsets); @@ -481,7 +486,7 @@ void CCWGPUCommandBuffer::draw(const DrawInfo &info) { // todo } else { if (info.indexCount) { - //indexedIndirect not supported, emsdk 2.0.26 + // indexedIndirect not supported, emsdk 2.0.26 uint32_t drawInfoCount = indirectBuffer->getCount(); // for (size_t i = 0; i < drawInfoCount; i++) { // wgpuRenderPassEncoderDrawIndexedIndirect(_gpuCommandBufferObj->wgpuRenderPassEncoder, @@ -507,21 +512,38 @@ void CCWGPUCommandBuffer::draw(const DrawInfo &info) { } else { auto *indexBuffer = static_cast(ia->getIndexBuffer()); bool drawIndexed = indexBuffer && info.indexCount; + uint32_t instanceCount = std::max(info.instanceCount, 1U); if (drawIndexed) { wgpuRenderPassEncoderDrawIndexed(_gpuCommandBufferObj->wgpuRenderPassEncoder, info.indexCount, - info.instanceCount > 1 ? info.instanceCount : 1, + instanceCount, info.firstIndex, info.vertexOffset, info.firstInstance); } else { wgpuRenderPassEncoderDraw(_gpuCommandBufferObj->wgpuRenderPassEncoder, info.vertexCount, - info.instanceCount > 1 ? info.instanceCount : 1, + instanceCount, info.firstVertex, info.firstInstance); } + + ++_numDrawCalls; + _numInstances += info.instanceCount; + if (_gpuCommandBufferObj->stateCache.pipelineState) { + uint32_t indexCount = drawIndexed ? info.indexCount : info.vertexCount; + switch (_gpuCommandBufferObj->stateCache.pipelineState->getPrimitive()) { + case PrimitiveMode::TRIANGLE_LIST: + _numTriangles += indexCount / 3 * instanceCount; + break; + case PrimitiveMode::TRIANGLE_STRIP: + case PrimitiveMode::TRIANGLE_FAN: + _numTriangles += (indexCount - 2) * instanceCount; + break; + default: break; + } + } } } @@ -554,47 +576,131 @@ void CCWGPUCommandBuffer::updateBuffer(Buffer *buff, const void *data, uint32_t wgpuCommandEncoderCopyBufferToBuffer(cmdEncoder, stagingBuffer, 0, bufferObj->wgpuBuffer, offset, alignedSize); WGPUCommandBuffer commandBuffer = wgpuCommandEncoderFinish(cmdEncoder, nullptr); wgpuQueueSubmit(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, &commandBuffer); - wgpuBufferRelease(stagingBuffer); wgpuCommandEncoderRelease(cmdEncoder); wgpuCommandBufferRelease(commandBuffer); } + CCWGPUDevice::getInstance()->moveToTrash(stagingBuffer); } - +// WGPU_EXPORT void wgpuCommandEncoderCopyBufferToTexture(WGPUCommandEncoder commandEncoder, WGPUImageCopyBuffer const * source, WGPUImageCopyTexture const * destination, WGPUExtent3D const * copySize); void CCWGPUCommandBuffer::copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) { + auto encoder = _gpuCommandBufferObj->wgpuCommandEncoder; + if (!encoder) { + WGPUCommandEncoder cmdEncoder = wgpuDeviceCreateCommandEncoder(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, nullptr); + } + + Format dstFormat = texture->getFormat(); + auto wgpuDevice = CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice; + auto *ccTexture = static_cast(texture); + auto blockSize = formatAlignment(dstFormat); + + if (ccTexture->isTextureView()) { + ccTexture = static_cast(ccTexture->getViewInfo().texture); + } + for (size_t i = 0; i < count; i++) { - WGPUOrigin3D origin = { - .x = static_cast(regions[i].texOffset.x), - .y = static_cast(regions[i].texOffset.y), - .z = static_cast(regions[i].texOffset.z), + const auto ®ion = regions[i]; + auto bufferPixelWidth = region.buffStride > 0 ? region.buffStride : region.texExtent.width; + auto bufferPixelHeight = region.buffTexHeight > 0 ? region.buffTexHeight : region.texExtent.height; + auto bytesPerRow = formatSize(dstFormat, region.texExtent.width, 1, 1); + auto bufferBytesPerRow = formatSize(dstFormat, bufferPixelWidth, 1, 1); + auto bufferBytesPerImageSlice = formatSize(dstFormat, bufferPixelWidth, bufferPixelHeight, 1); + auto bufferBytesPerImageLayer = formatSize(dstFormat, bufferPixelWidth, bufferPixelHeight, region.texExtent.depth); + auto targetWidth = region.texExtent.width == 0 ? 0 : utils::alignTo(region.texExtent.width, blockSize.first); + auto targetHeight = region.texExtent.height == 0 ? 0 : utils::alignTo(region.texExtent.height, blockSize.second); + + // it's buffer data layout + WGPUTextureDataLayout texDataLayout = { + .offset = 0, // we always create a non-offset staging buffer or give interface a non-offset buffer address + .bytesPerRow = bufferBytesPerRow, + .rowsPerImage = bufferPixelHeight, }; - WGPUImageCopyTexture imageCopyTexture = { - .texture = static_cast(texture)->gpuTextureObject()->wgpuTexture, - .mipLevel = 0, - .origin = origin, - .aspect = WGPUTextureAspect_All, - }; + bool compactInWidth = bufferPixelWidth == region.texExtent.width; + for (size_t l = region.texSubres.baseArrayLayer; l < region.texSubres.layerCount + region.texSubres.baseArrayLayer; ++l) { + for (size_t d = region.texOffset.z; d < region.texExtent.depth + region.texOffset.z; ++d) { + if (compactInWidth) { + auto *srcData = buffers[i] + region.buffOffset + (l - region.texSubres.baseArrayLayer) * bufferBytesPerImageLayer + (d - region.texOffset.z) * bufferBytesPerImageSlice; + WGPUImageCopyTexture imageCopyTexture = { + .texture = ccTexture->gpuTextureObject()->wgpuTexture, + .mipLevel = region.texSubres.mipLevel, + .origin = WGPUOrigin3D{ + static_cast(region.texOffset.x), + static_cast(region.texOffset.y), + static_cast(d)}, + .aspect = WGPUTextureAspect_All, + }; - auto *ccTex = static_cast(texture); - uint32_t width = regions[i].texExtent.width; - uint32_t height = regions[i].texExtent.height; - uint32_t depth = regions[i].texExtent.depth; - uint32_t bytesPerRow = GFX_FORMAT_INFOS[static_cast(ccTex->getFormat())].size * width; - uint32_t dataSize = bytesPerRow * height * depth; + WGPUExtent3D extent = { + .width = targetWidth, + .height = targetHeight, + .depthOrArrayLayers = 1, + }; - WGPUTextureDataLayout texLayout = { - .offset = 0, - .bytesPerRow = bytesPerRow, - .rowsPerImage = height, - }; + WGPUBufferDescriptor bufferDesc = { + .usage = WGPUBufferUsage_CopySrc, + .size = bufferBytesPerImageSlice, + .mappedAtCreation = true, + }; - WGPUExtent3D extent = { - .width = width, - .height = height, - .depthOrArrayLayers = depth, - }; + auto stagingBuffer = wgpuDeviceCreateBuffer(wgpuDevice, &bufferDesc); + auto *mappedBuffer = wgpuBufferGetMappedRange(stagingBuffer, 0, bufferBytesPerImageSlice); + memcpy(mappedBuffer, buffers[i], bufferBytesPerImageSlice); + wgpuBufferUnmap(static_cast(stagingBuffer)); - wgpuQueueWriteTexture(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, &imageCopyTexture, buffers[i], dataSize, &texLayout, &extent); + WGPUImageCopyBuffer imageCopyBuffer = { + .layout = texDataLayout, + .buffer = stagingBuffer, + }; + wgpuCommandEncoderCopyBufferToTexture(encoder, &imageCopyBuffer, &imageCopyTexture, &extent); + CCWGPUDevice::getInstance()->moveToTrash(stagingBuffer); + } else { + for (size_t h = region.texOffset.y; h < region.texExtent.height + region.texOffset.y; h += blockSize.second) { + auto *srcData = buffers[i] + region.buffOffset + (l - region.texSubres.baseArrayLayer) * bufferBytesPerImageLayer + (d - region.texOffset.z) * bufferBytesPerImageSlice + + (h - region.texOffset.y) / blockSize.second * bufferBytesPerRow; + WGPUImageCopyTexture imageCopyTexture = { + .texture = ccTexture->gpuTextureObject()->wgpuTexture, + .mipLevel = region.texSubres.mipLevel, + .origin = WGPUOrigin3D{ + static_cast(region.texOffset.x), + static_cast(h), + static_cast(d)}, + .aspect = WGPUTextureAspect_All, + }; + + WGPUExtent3D extent = { + .width = targetWidth, + .height = blockSize.second, + .depthOrArrayLayers = 1, + }; + + WGPUBufferDescriptor bufferDesc = { + .usage = WGPUBufferUsage_CopySrc, + .size = bytesPerRow, + .mappedAtCreation = true, + }; + + auto stagingBuffer = wgpuDeviceCreateBuffer(wgpuDevice, &bufferDesc); + auto *mappedBuffer = wgpuBufferGetMappedRange(stagingBuffer, 0, bytesPerRow); + memcpy(mappedBuffer, buffers[i], bytesPerRow); + wgpuBufferUnmap(static_cast(stagingBuffer)); + + WGPUImageCopyBuffer imageCopyBuffer = { + .layout = texDataLayout, + .buffer = stagingBuffer, + }; + wgpuCommandEncoderCopyBufferToTexture(encoder, &imageCopyBuffer, &imageCopyTexture, &extent); + CCWGPUDevice::getInstance()->moveToTrash(stagingBuffer); + } + } + } + } + } + + if (!_gpuCommandBufferObj->wgpuCommandEncoder) { + WGPUCommandBuffer commandBuffer = wgpuCommandEncoderFinish(encoder, nullptr); + wgpuQueueSubmit(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, &commandBuffer); + wgpuCommandEncoderRelease(encoder); + wgpuCommandBufferRelease(commandBuffer); } } @@ -640,7 +746,7 @@ void CCWGPUCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, } void CCWGPUCommandBuffer::execute(CommandBuffer *const * /*cmdBuffs*/, uint32_t /*count*/) { - printf("....."); + printf(".....\n"); } void CCWGPUCommandBuffer::dispatch(const DispatchInfo &info) { @@ -651,24 +757,35 @@ void CCWGPUCommandBuffer::dispatch(const DispatchInfo &info) { if (info.indirectBuffer) { auto *indirectBuffer = static_cast(info.indirectBuffer); - wgpuComputePassEncoderDispatchIndirect(_gpuCommandBufferObj->wgpuComputeEncoder, - indirectBuffer->gpuBufferObject()->wgpuBuffer, - info.indirectOffset); + wgpuComputePassEncoderDispatchWorkgroupsIndirect(_gpuCommandBufferObj->wgpuComputeEncoder, + indirectBuffer->gpuBufferObject()->wgpuBuffer, + info.indirectOffset); } else { - wgpuComputePassEncoderDispatch(_gpuCommandBufferObj->wgpuComputeEncoder, - info.groupCountX, - info.groupCountY, - info.groupCountZ); + wgpuComputePassEncoderDispatchWorkgroups(_gpuCommandBufferObj->wgpuComputeEncoder, + info.groupCountX, + info.groupCountY, + info.groupCountZ); } } -void CCWGPUCommandBuffer::pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) { +void CCWGPUCommandBuffer::pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const *buffers, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) { } void CCWGPUCommandBuffer::updateIndirectBuffer(Buffer *buffer, const DrawInfoList &list) { buffer->update(list.data(), 0); // indirectBuffer calc size inside. } +void CCWGPUCommandBuffer::reset() { + _gpuCommandBufferObj->renderPassBegan = false; + + _gpuCommandBufferObj->wgpuCommandBuffer = wgpuDefaultHandle; + _gpuCommandBufferObj->wgpuCommandEncoder = wgpuDefaultHandle; + _gpuCommandBufferObj->wgpuRenderPassEncoder = wgpuDefaultHandle; + _gpuCommandBufferObj->wgpuComputeEncoder = wgpuDefaultHandle; + + CCWGPUStateCache stateCache = {}; +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h index c12794a271..01e7dcff64 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h @@ -24,8 +24,9 @@ ****************************************************************************/ #pragma once -#include -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include #include "base/std/container/vector.h" #include "gfx-base/GFXCommandBuffer.h" @@ -37,11 +38,10 @@ struct CCWGPUCommandBufferObject; typedef std::function EncodeFunc; -class CCWGPUCommandBuffer final : public emscripten::wrapper { +class CCWGPUCommandBuffer final : public CommandBuffer { public: - EMSCRIPTEN_WRAPPER(CCWGPUCommandBuffer); CCWGPUCommandBuffer(); - ~CCWGPUCommandBuffer() = default; + ~CCWGPUCommandBuffer(); void begin(RenderPass *renderPass, uint32_t subpass, Framebuffer *frameBuffer) override; void end() override; @@ -65,27 +65,32 @@ public: void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; - void pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; + void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const *buffers, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; - //TODO_Zeqiang: wgpu query pool + // TODO_Zeqiang: wgpu query pool void beginQuery(QueryPool *queryPool, uint32_t id) override{}; void endQuery(QueryPool *queryPool, uint32_t id) override{}; void resetQueryPool(QueryPool *queryPool) override{}; void completeQueryPool(QueryPool *queryPool) override{}; - inline CCWGPUCommandBufferObject *gpuCommandBufferObject() { return _gpuCommandBufferObj; } + inline CCWGPUCommandBufferObject *gpuCommandBufferObject() const { return _gpuCommandBufferObj; } void updateIndirectBuffer(Buffer *buffer, const DrawInfoList &list); - void updateBuffer(Buffer *buff, const emscripten::val &v, uint32_t size) { - ccstd::vector buffer = emscripten::convertJSArrayToNumberVector(v); - updateBuffer(buff, reinterpret_cast(buffer.data()), size); - } - void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const ColorList &colors, float depth, uint32_t stencil) { this->CommandBuffer::beginRenderPass(renderPass, fbo, renderArea, colors.data(), depth, stencil); } + void reset(); + + void bindDescriptorSet(uint32_t set, DescriptorSet *descriptorSet, const std::vector &dynamicOffsets) { + bindDescriptorSet(set, descriptorSet, dynamicOffsets.size(), dynamicOffsets.data()); + } + + // emscripten export + EXPORT_EMS( + void updateBuffer(Buffer *buff, const emscripten::val &v, uint32_t size);) + protected: virtual void doInit(const CommandBufferInfo &info); virtual void doDestroy(); @@ -99,8 +104,8 @@ protected: Framebuffer *_frameBuffer = nullptr; // command buffer inner impl - //std::queue _renderPassFuncQ; - //std::queue _computeFuncQ; + // std::queue _renderPassFuncQ; + // std::queue _computeFuncQ; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDef.h b/native/cocos/renderer/gfx-wgpu/WGPUDef.h index 775756a8b7..a04a735396 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDef.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUDef.h @@ -1,321 +1,219 @@ #pragma once +#include #include +#include +#include +#include +#include +#include #include "../gfx-base/GFXDef-common.h" -#include "base/std/container/vector.h" +#include "../gfx-base/GFXDef.h" -namespace cc { -namespace gfx { +#ifdef CC_WGPU_WASM + #define EXPORT_EMS(expr) expr +#else + #define EXPORT_EMS(expr) +#endif -//emscripten export struct with pointers. -class TextureInfoInstance { -public: - TextureInfoInstance() = default; +#ifdef CC_WGPU_DAWN + #define EXPORT_DAWN(expr) expr +#else + #define EXPORT_DAWN(expr) +#endif - inline void setType(TextureType type) { info.type = type; } - inline void setUsage(uint32_t usageIn) { - TextureUsage usage = TextureUsageBit::NONE; - if (hasFlag(static_cast(usageIn), TextureUsageBit::TRANSFER_SRC)) { - usage |= TextureUsageBit::TRANSFER_SRC; - } - if (hasFlag(static_cast(usageIn), TextureUsageBit::TRANSFER_DST)) { - usage |= TextureUsageBit::TRANSFER_DST; - } - if (hasFlag(static_cast(usageIn), TextureUsageBit::SAMPLED)) { - usage |= TextureUsageBit::SAMPLED; - } - if (hasFlag(static_cast(usageIn), TextureUsageBit::STORAGE)) { - usage |= TextureUsageBit::STORAGE; - } - if (hasFlag(static_cast(usageIn), TextureUsageBit::COLOR_ATTACHMENT)) { - usage |= TextureUsageBit::COLOR_ATTACHMENT; - } - if (hasFlag(static_cast(usageIn), TextureUsageBit::DEPTH_STENCIL_ATTACHMENT)) { - usage |= TextureUsageBit::DEPTH_STENCIL_ATTACHMENT; - } - if (hasFlag(static_cast(usageIn), TextureUsageBit::INPUT_ATTACHMENT)) { - usage |= TextureUsageBit::INPUT_ATTACHMENT; - } - info.usage = usage; +#ifdef CC_WGPU_RS + #define EXPORT_RS(expr) expr +#else + #define EXPORT_RS(expr) +#endif + +// https://github.com/emscripten-core/emscripten/issues/11070#issuecomment-717675128 +namespace emscripten { + +template +std::vector vecFromEMS(const val &vals) { + uint32_t len = vals["length"].as(); + std::vector res(len); + const std::vector Ts = vecFromJSArray(vals); + for (size_t i = 0; i < len; ++i) { + const val &t = Ts[i]; + res[i] = static_cast(t.as(allow_raw_pointers())); } - inline void setFormat(Format format) { info.format = format; } - inline void setWidth(uint32_t width) { info.width = width; } - inline void setHeight(uint32_t height) { info.height = height; } - inline void setFlags(uint32_t flagsIn) { - TextureFlags flags = TextureFlagBit::NONE; + return res; +} - if (hasFlag(static_cast(flagsIn), TextureFlagBit::GEN_MIPMAP)) { - flags |= TextureFlagBit::GEN_MIPMAP; - } - if (hasFlag(static_cast(flagsIn), TextureFlagBit::GENERAL_LAYOUT)) { - flags |= TextureFlagBit::GENERAL_LAYOUT; - } - - info.flags = flags; +template +val vecToEMS(const std::vector &Ts) { + auto arr = val::array(); + for (size_t i = 0; i < Ts.size(); ++i) { + arr.set(i, TWrapper(Ts[i])); } - inline void setLevelCount(uint32_t levelCount) { info.levelCount = levelCount; } - inline void setLayerCount(uint32_t layerCount) { info.layerCount = layerCount; } - inline void setSamples(SampleCount sample) { info.samples = sample; } - inline void setDepth(uint32_t depth) { info.depth = depth; } - inline void setImageBuffer(intptr_t imgBuff) { info.externalRes = reinterpret_cast(imgBuff); } + return arr; +} - explicit operator const TextureInfo() const { return info; } +// template ::value, bool>::type = true> +// std::vector ptrVecFromEMS(const val& vals) { +// uint32_t len = vals["length"].as(); +// std::vector res(len); +// const std::vector Ts = vecFromJSArray(vals); +// for (size_t i = 0; i < len; ++i) { +// const val& t = Ts[i]; +// t.as(emscripten::allow_raw_pointers()); +// res[i] = reinterpret_cast(t.as()); +// } +// return res; +// } -private: - TextureInfo info; -}; - -class TextureViewInfoInstance { -public: - TextureViewInfoInstance() = default; - - inline void setTexture(Texture *tex) { info.texture = tex; } - inline void setType(TextureType type) { info.type = type; } - inline void setFormat(Format format) { info.format = format; } - inline void setBaseLevel(uint32_t baseLevel) { info.baseLevel = baseLevel; } - inline void setLevelCount(uint32_t levelCount) { info.levelCount = levelCount; } - inline void setBaseLayer(uint32_t baseLayer) { info.baseLayer = baseLayer; } - inline void setLayerCount(uint32_t layerCount) { info.layerCount = layerCount; } - - explicit operator const TextureViewInfo() const { return info; } - -private: - TextureViewInfo info; -}; - -class SwapchainInfoInstance { -public: - SwapchainInfoInstance() = default; - - inline void setWindowHandle(uintptr_t hwnd) { info.windowHandle = reinterpret_cast(hwnd); } - inline void setVsyncMode(VsyncMode mode) { info.vsyncMode = mode; } - inline void setWidth(uint32_t width) { info.width = width; } - inline void setHeight(uint32_t height) { info.height = height; } - - explicit operator const SwapchainInfo() const { return info; } - -private: - SwapchainInfo info; -}; - -class FramebufferInfoInstance { -public: - FramebufferInfoInstance() = default; - - inline void setRenderPass(RenderPass *renderPass) { info.renderPass = renderPass; } - inline void setColorTextures(TextureList colors) { info.colorTextures = colors; } - inline void setDepthStencilTexture(Texture *tex) { info.depthStencilTexture = tex; } - - explicit operator const FramebufferInfo() const { return info; } - -private: - FramebufferInfo info; -}; - -class BufferViewInfoInstance { -public: - BufferViewInfoInstance() = default; - - inline void setBuffer(Buffer *buffer) { info.buffer = buffer; } - inline void setOffset(uint32_t offset) { info.offset = offset; } - inline void setRange(uint32_t range) { info.range = range; } - - explicit operator const BufferViewInfo() const { return info; } - -private: - BufferViewInfo info; -}; - -class DescriptorSetInfoInstance { -public: - DescriptorSetInfoInstance() = default; - inline void setDescriptorSetLayout(DescriptorSetLayout *layout) { info.layout = layout; } - - explicit operator const DescriptorSetInfo() const { return info; } - -private: - DescriptorSetInfo info; -}; - -class PipelineStateInfoInstance { -public: - inline void setShader(Shader *shader) { info.shader = shader; } - inline void setPipelineLayout(PipelineLayout *pipelineLayout) { info.pipelineLayout = pipelineLayout; } - inline void setRenderPass(RenderPass *renderPass) { info.renderPass = renderPass; } - inline void setInputState(InputState inputState) { info.inputState = inputState; } - inline void setRasterizerState(RasterizerState rasterizerState) { info.rasterizerState = rasterizerState; } - inline void setDepthStencilState(DepthStencilState depthStencilState) { info.depthStencilState = depthStencilState; } - inline void setBlendState(BlendState blendState) { info.blendState = blendState; } - inline void setPrimitiveMode(PrimitiveMode primitive) { info.primitive = primitive; } - inline void setDynamicStateFlags(DynamicStateFlagBit dynamicStates) { info.dynamicStates = dynamicStates; } - inline void setPipelineBindPoint(PipelineBindPoint bindPoint) { info.bindPoint = bindPoint; } - inline void setSubpass(uint32_t subpass) { info.subpass = subpass; } - - explicit operator const PipelineStateInfo() const { return info; } - -private: - PipelineStateInfo info; -}; - -class InputAssemblerInfoInstance { -public: - inline void setAttributes(AttributeList attributes) { info.attributes = attributes; } - inline void setBuffers(BufferList buffers) { info.vertexBuffers = buffers; } - inline void setIndexBuffer(Buffer *buffer) { info.indexBuffer = buffer; } - inline void setIndirectBuffer(Buffer *buffer) { info.indirectBuffer = buffer; } - - explicit operator const InputAssemblerInfo() const { return info; } - -private: - InputAssemblerInfo info; -}; - -class CommandBufferInfoInstance { -public: - inline void setQueue(Queue *q) { info.queue = q; } - inline void setType(CommandBufferType type) { info.type = type; } - - explicit operator const CommandBufferInfo() const { return info; } - -private: - CommandBufferInfo info; -}; - -class DispatchInfoInstance { -public: - inline void setGroupCountX(uint32_t groupCountX) { info.groupCountX = groupCountX; } - inline void setGroupCountY(uint32_t groupCountY) { info.groupCountY = groupCountY; } - inline void setGroupCountZ(uint32_t groupCountZ) { info.groupCountZ = groupCountZ; } - inline void setIndirectBuffer(Buffer *indirectBuffer) { info.indirectBuffer = indirectBuffer; } - inline void setIndirectOffset(uint32_t offset) { info.indirectOffset = offset; } - - explicit operator const DispatchInfo() const { return info; } - -private: - DispatchInfo info; -}; - -class SPVShaderStageInstance { -public: - ShaderStageFlagBit stage{ShaderStageFlagBit::NONE}; - ccstd::vector spv; - - inline void setStage(ShaderStageFlagBit stageIn) { stage = stageIn; } - inline void setSPVData(const emscripten::val &v) { spv = emscripten::convertJSArrayToNumberVector(v); } -}; - -class SPVShaderInfoInstance { -public: - inline void setName(ccstd::string name) { info.name = name; } - inline void setAttributes(AttributeList attrs) { info.attributes = attrs; } - inline void setStages(ccstd::vector spvStages) { stages = spvStages; } - inline void setBlocks(UniformBlockList blocks) { info.blocks = blocks; } - inline void setBuffers(UniformStorageBufferList buffers) { info.buffers = buffers; } - inline void setSamplerTextures(UniformSamplerTextureList list) { info.samplerTextures = list; } - inline void setTextures(UniformTextureList textures) { info.textures = textures; } - inline void setSamplers(UniformSamplerList samplers) { info.samplers = samplers; } - inline void setImages(UniformStorageImageList images) { info.images = images; } - inline void setSubpasses(UniformInputAttachmentList subpassInputs) { info.subpassInputs = subpassInputs; } - - ShaderInfo info; - ccstd::vector stages; -}; - -class DescriptorSetLayoutBindingInstance { -public: - inline void setBinding(uint32_t binding) { info.binding = binding; } - inline void setDescriptorType(DescriptorType descriptorType) { info.descriptorType = descriptorType; } - inline void setCount(uint32_t count) { info.count = count; } - inline void setStageFlags(uint32_t stageFlags) { - ShaderStageFlags flag = ShaderStageFlagBit::NONE; - if (hasFlag(static_cast(stageFlags), ShaderStageFlagBit::VERTEX)) { - flag |= ShaderStageFlagBit::VERTEX; - } - if (hasFlag(static_cast(stageFlags), ShaderStageFlagBit::CONTROL)) { - flag |= ShaderStageFlagBit::CONTROL; - } - if (hasFlag(static_cast(stageFlags), ShaderStageFlagBit::EVALUATION)) { - flag |= ShaderStageFlagBit::EVALUATION; - } - if (hasFlag(static_cast(stageFlags), ShaderStageFlagBit::GEOMETRY)) { - flag |= ShaderStageFlagBit::GEOMETRY; - } - if (hasFlag(static_cast(stageFlags), ShaderStageFlagBit::FRAGMENT)) { - flag |= ShaderStageFlagBit::FRAGMENT; - } - if (hasFlag(static_cast(stageFlags), ShaderStageFlagBit::COMPUTE)) { - flag |= ShaderStageFlagBit::COMPUTE; - } - info.stageFlags = flag; +template ::value, bool>::type = true> +val ptrVecToEMS(const std::vector &Ts) { + auto arr = val::array(); + for (size_t i = 0; i < Ts.size(); ++i) { + arr.set(i, Ts[i]); } - inline void setImmutableSamplers(SamplerList immutableSamplers) { info.immutableSamplers = immutableSamplers; } + return arr; +} - explicit operator const DescriptorSetLayoutBinding() const { return info; } +namespace internal { -private: - DescriptorSetLayoutBinding info; -}; +// vector -> [] & [] ->vector +template +struct BindingType> { + using ValBinding = BindingType; + using WireType = ValBinding::WireType; -class DescriptorSetLayoutInfoInstance { -public: - inline void setBindings(ccstd::vector bindings) { info.bindings = ccstd::vector(bindings.begin(), bindings.end()); } - - explicit operator const DescriptorSetLayoutInfo() const { return info; } - -private: - DescriptorSetLayoutInfo info; -}; - -class BufferInfoInstance { -public: - inline void setUsage(uint32_t usageIn) { - BufferUsage usage = BufferUsageBit::NONE; - if (hasFlag(static_cast(usageIn), BufferUsageBit::TRANSFER_SRC)) { - usage |= BufferUsageBit::TRANSFER_SRC; - } - if (hasFlag(static_cast(usageIn), BufferUsageBit::TRANSFER_DST)) { - usage |= BufferUsageBit::TRANSFER_DST; - } - if (hasFlag(static_cast(usageIn), BufferUsageBit::INDEX)) { - usage |= BufferUsageBit::INDEX; - } - if (hasFlag(static_cast(usageIn), BufferUsageBit::VERTEX)) { - usage |= BufferUsageBit::VERTEX; - } - if (hasFlag(static_cast(usageIn), BufferUsageBit::UNIFORM)) { - usage |= BufferUsageBit::UNIFORM; - } - if (hasFlag(static_cast(usageIn), BufferUsageBit::STORAGE)) { - usage |= BufferUsageBit::STORAGE; - } - if (hasFlag(static_cast(usageIn), BufferUsageBit::INDIRECT)) { - usage |= BufferUsageBit::INDIRECT; - } - - info.usage = usage; - } - inline void setMemUsage(uint32_t memUsageIn) { - MemoryUsage memUsage = MemoryUsageBit::NONE; - if (hasFlag(static_cast(memUsageIn), MemoryUsageBit::DEVICE)) { - memUsage |= MemoryUsageBit::DEVICE; - } - if (hasFlag(static_cast(memUsageIn), MemoryUsageBit::HOST)) { - memUsage |= MemoryUsageBit::HOST; - } - info.memUsage = memUsage; - } - inline void setSize(uint32_t size) { info.size = size; } - inline void setStride(uint32_t stride) { info.stride = stride; } - inline void setFlags(uint32_t flagsIn) { - BufferFlags flags = BufferFlagBit::NONE; - - info.flags = static_cast(flagsIn); + static WireType toWireType(const std::vector &vec) { + return ValBinding::toWireType(vecToEMS(vec)); } - explicit operator const BufferInfo() const { return info; } - -private: - BufferInfo info; + static std::vector fromWireType(WireType value) { + return vecFromJSArray(ValBinding::fromWireType(value), allow_raw_pointers()); + } }; -} // namespace gfx -} // namespace cc +template +struct TypeID::type, + std::vector::type::value_type, + typename Canonicalized::type::allocator_type>>::value>> { + static constexpr TYPEID get() { return TypeID::get(); } +}; + +} // namespace internal +} // namespace emscripten + +template +struct GenInstance { + static T instance() { + return T(); + } +}; + +template +R getMemberType(R T::*); + +#define MEMBER_TYPE(prop) decltype(getMemberType(prop)) + +template +struct Exporter { + Exporter(T &t, const char *propName, U V::*field, bool ignorePtrAssert = false) { + t.field(propName, field); + } +}; + +template +struct Exporter::value>::type> { + Exporter(T &t, const char *propName, U V::*field, bool ignorePtrAssert = false) { + std::function u)> set = [field](V &v, std::underlying_type_t u) { + v.*field = U{u}; + }; + std::function(const V &v)> get = [field](const V &v) { + return static_cast>(v.*field); + }; + t.field(propName, get, set); + } +}; + +template +struct Exporter::value>::type> { + Exporter(T &t, const char *propName, U V::*field) { + static_assert(!std::is_pointer::value, "Export pointer with struct, try EXPORT_STRUCT_NPOD!"); + } + + Exporter(T &t, const char *propName, U V::*field, bool ignorePtrAssert) { + t.field(propName, field); + } +}; + +#define PROCESS_STRUCT_MEMBERS(r, struct_name, property) \ + { Exporter exporter(obj, BOOST_PP_STRINGIZE(property), &struct_name::property); } + +#define EXPORT_STRUCT_POD(struct_name, ...) \ + { \ + auto obj = value_object(#struct_name); \ + BOOST_PP_SEQ_FOR_EACH(PROCESS_STRUCT_MEMBERS, struct_name, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); \ + } + +#define PROCESS_STRUCT_MEMBERS_MAY_BE_PTR(r, struct_name, property) \ + { Exporter exporter(obj, BOOST_PP_STRINGIZE(property), &struct_name::property, true); } + +#define EXPORT_STRUCT_NPOD(struct_name, ...) \ + { \ + auto obj = value_object(#struct_name); \ + BOOST_PP_SEQ_FOR_EACH(PROCESS_STRUCT_MEMBERS_MAY_BE_PTR, struct_name, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); \ + } + +#define SPECIALIZE_PTR_FOR_STRUCT(r, _, TYPE) \ + template <> \ + struct emscripten::internal::TypeID::type *, void> { \ + static constexpr emscripten::internal::TYPEID get() { return emscripten::internal::TypeID>::get(); } \ + }; \ + template <> \ + struct emscripten::internal::TypeID::type *, void> { \ + static constexpr emscripten::internal::TYPEID get() { return emscripten::internal::TypeID>::get(); } \ + }; + +#define REGISTER_GFX_PTRS_FOR_STRUCT(...) \ + BOOST_PP_SEQ_FOR_EACH(SPECIALIZE_PTR_FOR_STRUCT, _, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); + +// specialize for void* +template <> +struct emscripten::internal::TypeID { + static constexpr emscripten::internal::TYPEID get() { return emscripten::internal::TypeID::get(); } +}; + +template +struct emscripten::internal::TypeID::value>::type> { + static constexpr emscripten::internal::TYPEID get() { return emscripten::internal::TypeID::type>::get(); } +}; + +namespace cc::gfx { + +using ::emscripten::allow_raw_pointers; +using ::emscripten::convertJSArrayToNumberVector; +using ::emscripten::val; + +// template ::value, bool>::type = true> +// std::vector ptrVecFromEMS(const val& vals) { +// uint32_t len = vals["length"].as(); +// std::vector res(len); +// const std::vector Ts = vecFromJSArray(vals); +// for (size_t i = 0; i < len; ++i) { +// const val& t = Ts[i]; +// t.as(emscripten::allow_raw_pointers()); +// res[i] = reinterpret_cast(t.as()); +// } +// return res; +// } + +template +struct GetType { + using type = T; +}; + +template +struct GetType::value>::type> { + using type = typename std::underlying_type::type; +}; + +} // namespace cc::gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.cpp b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.cpp index a64723bf58..2da1a08a3c 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.cpp @@ -36,13 +36,33 @@ namespace cc { namespace gfx { -namespace anoymous { -WGPUBindGroup defaultBindGroup = wgpuDefaultHandle; +namespace { +WGPUBindGroup dftBindGroup = wgpuDefaultHandle; + +struct BindGroupCache { + CCWGPUDescriptorSet *descriptorSet{nullptr}; + WGPUBindGroup bindGroup{wgpuDefaultHandle}; + ccstd::hash_t bornHash{0}; +}; + +thread_local ccstd::unordered_map bindGroupMap; +} // namespace + +CCWGPUDescriptorSet::CCWGPUDescriptorSet() : DescriptorSet() { } -using namespace emscripten; +CCWGPUDescriptorSet::~CCWGPUDescriptorSet() { + doDestroy(); +} -CCWGPUDescriptorSet::CCWGPUDescriptorSet() : wrapper(val::object()) { +void CCWGPUDescriptorSet::clearCache() { + if (!bindGroupMap.empty()) { + for (auto &it : bindGroupMap) { + wgpuBindGroupRelease(static_cast(it.second.bindGroup)); + it.second.descriptorSet->_isDirty = true; + } + bindGroupMap.clear(); + } } void CCWGPUDescriptorSet::doInit(const DescriptorSetInfo &info) { @@ -55,7 +75,7 @@ void CCWGPUDescriptorSet::doInit(const DescriptorSetInfo &info) { for (size_t i = 0; i < bindings.size(); i++) { // effect.ts: INPUT_ATTACHMENT as combined texture but no sampler_texture desc type. if (hasFlag(COMBINED_ST_IN_USE, bindings[i].descriptorType)) { - //1. texture + // 1. texture CCWGPUTexture *texture = deviceObj->defaultResources.commonTexture; WGPUBindGroupEntry texEntry = { .binding = bindings[i].binding, @@ -63,17 +83,17 @@ void CCWGPUDescriptorSet::doInit(const DescriptorSetInfo &info) { }; _gpuBindGroupObj->bindGroupEntries.push_back(texEntry); _textureIdxMap.insert(std::make_pair(bindings[i].binding, _gpuBindGroupObj->bindGroupEntries.size() - 1)); - dsLayout->updateLayout(texEntry.binding, nullptr, texture); + dsLayout->updateTextureLayout(texEntry.binding, texture); // 2. sampler - CCWGPUSampler *sampler = deviceObj->defaultResources.sampler; + CCWGPUSampler *sampler = deviceObj->defaultResources.unfilterableSampler; WGPUBindGroupEntry smpEntry = { .binding = bindings[i].binding + CC_WGPU_MAX_ATTACHMENTS, .sampler = sampler->gpuSampler(), }; _gpuBindGroupObj->bindGroupEntries.push_back(smpEntry); _samplerIdxMap.insert(std::make_pair(bindings[i].binding, _gpuBindGroupObj->bindGroupEntries.size() - 1)); - dsLayout->updateLayout(smpEntry.binding, nullptr, nullptr, sampler); + dsLayout->updateSamplerLayout(smpEntry.binding, sampler); } else if (hasFlag(DESCRIPTOR_BUFFER_TYPE, bindings[i].descriptorType)) { CCWGPUBuffer *buffer = hasFlag(DescriptorType::DYNAMIC_STORAGE_BUFFER | DescriptorType::STORAGE_BUFFER, bindings[i].descriptorType) ? deviceObj->defaultResources.storageBuffer @@ -96,7 +116,23 @@ void CCWGPUDescriptorSet::doInit(const DescriptorSetInfo &info) { .textureView = texture->gpuTextureObject()->selfView, }; _gpuBindGroupObj->bindGroupEntries.push_back(texEntry); - dsLayout->updateLayout(texEntry.binding, nullptr, texture); + dsLayout->updateTextureLayout(texEntry.binding, texture); + } else if (bindings[i].descriptorType == DescriptorType::TEXTURE) { + CCWGPUTexture *texture = deviceObj->defaultResources.commonTexture; + WGPUBindGroupEntry texEntry = { + .binding = bindings[i].binding, + .textureView = texture->gpuTextureObject()->selfView, + }; + _gpuBindGroupObj->bindGroupEntries.push_back(texEntry); + dsLayout->updateTextureLayout(texEntry.binding, texture); + } else if (bindings[i].descriptorType == DescriptorType::SAMPLER) { + CCWGPUSampler *sampler = deviceObj->defaultResources.unfilterableSampler; + WGPUBindGroupEntry smpEntry = { + .binding = bindings[i].binding, + .sampler = sampler->gpuSampler(), + }; + _gpuBindGroupObj->bindGroupEntries.push_back(smpEntry); + dsLayout->updateSamplerLayout(smpEntry.binding, sampler); } else { WGPUBindGroupEntry texEntry = { .binding = bindings[i].binding, @@ -106,10 +142,36 @@ void CCWGPUDescriptorSet::doInit(const DescriptorSetInfo &info) { } (void)defaultBindGroup(); -} // namespace gfx +} + +ccstd::hash_t CCWGPUDescriptorSet::hash() const { + ccstd::hash_t hash = 9527; + for (const auto &buffer : _buffers) { + if (buffer) { + auto *wgpuBuffer = static_cast(buffer)->gpuBufferObject()->wgpuBuffer; + ccstd::hash_combine(hash, wgpuBuffer); + } + } + for (const auto &texture : _textures) { + if (texture) { + auto *wgpuTextureView = static_cast(texture)->gpuTextureObject()->selfView; + ccstd::hash_combine(hash, wgpuTextureView); + } + } + for (const auto &sampler : _samplers) { + if (sampler) { + auto *wgpuSampler = static_cast(sampler)->gpuSampler(); + ccstd::hash_combine(hash, wgpuSampler); + } + } + return hash; +} void CCWGPUDescriptorSet::doDestroy() { - delete _gpuBindGroupObj; + if (_gpuBindGroupObj) { + delete _gpuBindGroupObj; + _gpuBindGroupObj = nullptr; + } } void CCWGPUDescriptorSet::update() { @@ -131,28 +193,29 @@ void CCWGPUDescriptorSet::update() { bindGroupEntry.buffer = buffer->gpuBufferObject()->wgpuBuffer; bindGroupEntry.offset = buffer->getOffset(); bindGroupEntry.size = buffer->getSize(); - dsLayout->updateLayout(bindGroupEntry.binding, buffer); + dsLayout->updateBufferLayout(bindGroupEntry.binding, buffer); uint8_t bindIndex = binding.binding; if (hasAnyFlags(binding.descriptorType, DescriptorType::DYNAMIC_STORAGE_BUFFER | DescriptorType::DYNAMIC_UNIFORM_BUFFER)) { auto iter = std::find_if(_dynamicOffsets.begin(), _dynamicOffsets.end(), [bindIndex](const std::pair dynIndex) { return dynIndex.first == bindIndex; }); - //assert(iter != _dynamicOffsets.end()); //can't happen + // assert(iter != _dynamicOffsets.end()); //can't happen (*iter).second = 1; } } } else if (hasFlag(COMBINED_ST_IN_USE, bindings[i].descriptorType)) { auto texIter = _textureIdxMap.find(binding.binding); auto smpIter = _samplerIdxMap.find(binding.binding); - //assert((texIter != _textureIdxMap.end()) + (smpIter != _samplerIdxMap.end()) == 1); + // assert((texIter != _textureIdxMap.end()) + (smpIter != _samplerIdxMap.end()) == 1); uint8_t textureIdx = texIter != _textureIdxMap.end() ? texIter->second : 255; uint8_t samplerIdx = smpIter != _samplerIdxMap.end() ? smpIter->second : 255; + if (textureIdx != 255 && _textures[resourceIndex]) { auto &bindGroupEntry = _gpuBindGroupObj->bindGroupEntries[textureIdx]; auto *texture = static_cast(_textures[resourceIndex]); bindGroupEntry.binding = binding.binding; bindGroupEntry.textureView = texture->gpuTextureObject()->selfView; - dsLayout->updateLayout(bindGroupEntry.binding, nullptr, texture); + dsLayout->updateTextureLayout(bindGroupEntry.binding, texture); _gpuBindGroupObj->bindingSet.insert(binding.binding); } if (samplerIdx != 255 && _samplers[resourceIndex]) { @@ -160,87 +223,102 @@ void CCWGPUDescriptorSet::update() { auto *sampler = static_cast(_samplers[resourceIndex]); bindGroupEntry.binding = binding.binding + CC_WGPU_MAX_ATTACHMENTS; bindGroupEntry.sampler = sampler->gpuSampler(); - dsLayout->updateLayout(bindGroupEntry.binding, nullptr, nullptr, sampler); + dsLayout->updateSamplerLayout(bindGroupEntry.binding, sampler); _gpuBindGroupObj->bindingSet.insert(binding.binding + CC_WGPU_MAX_ATTACHMENTS); } - } else if (DescriptorType::STORAGE_IMAGE == bindings[i].descriptorType) { + } else if (DescriptorType::STORAGE_IMAGE == bindings[i].descriptorType || DescriptorType::TEXTURE == bindings[i].descriptorType) { if (_textures[resourceIndex]) { auto &bindGroupEntry = _gpuBindGroupObj->bindGroupEntries[resourceIndex]; auto *texture = static_cast(_textures[resourceIndex]); bindGroupEntry.binding = binding.binding; bindGroupEntry.textureView = texture->gpuTextureObject()->selfView; - dsLayout->updateLayout(bindGroupEntry.binding, nullptr, texture); + dsLayout->updateTextureLayout(bindGroupEntry.binding, texture); } + } else if (DescriptorType::SAMPLER == bindings[i].descriptorType) { + auto &bindGroupEntry = _gpuBindGroupObj->bindGroupEntries[resourceIndex]; + auto *sampler = static_cast(_samplers[resourceIndex]); + bindGroupEntry.binding = binding.binding; + bindGroupEntry.sampler = sampler->gpuSampler(); + dsLayout->updateSamplerLayout(bindGroupEntry.binding, sampler); + } else { + printf("*******unexpected binding type detected!\n"); } } } void CCWGPUDescriptorSet::prepare() { auto buffIter = std::find_if(_buffers.begin(), _buffers.end(), [](const Buffer *buffer) { - return buffer ? static_cast(buffer)->internalChanged() : false; + return buffer && static_cast(buffer)->internalChanged(); }); auto texIter = std::find_if(_textures.begin(), _textures.end(), [](const Texture *texture) { - return texture ? static_cast(texture)->internalChanged() : false; + return texture && static_cast(texture)->internalChanged(); }); bool forceUpdate = buffIter != _buffers.end() || texIter != _textures.end(); - if (forceUpdate) { - _isDirty = true; + + _isDirty |= forceUpdate; + if (_isDirty) { update(); } + const auto &entries = _gpuBindGroupObj->bindGroupEntries; + if (_isDirty || forceUpdate || !_gpuBindGroupObj->bindgroup) { auto *dsLayout = static_cast(_layout); - dsLayout->prepare(forceUpdate); - // ccstd::vector - // bindGroupEntries; + dsLayout->prepare(_gpuBindGroupObj->bindingSet, forceUpdate); + + // ccstd::vector bindGroupEntries; // bindGroupEntries.assign(_gpuBindGroupObj->bindGroupEntries.begin(), _gpuBindGroupObj->bindGroupEntries.end()); // bindGroupEntries.erase(std::remove_if( - // bindGroupEntries.begin(), bindGroupEntries.end(), [this, &bindGroupEntries](const WGPUBindGroupEntry& entry) { + // bindGroupEntries.begin(), bindGroupEntries.end(), [this, &bindGroupEntries](const WGPUBindGroupEntry &entry) { // return _gpuBindGroupObj->bindingSet.find(entry.binding) == _gpuBindGroupObj->bindingSet.end(); // }), // bindGroupEntries.end()); - - const auto &entries = _gpuBindGroupObj->bindGroupEntries; - - // for (size_t j = 0; j < entries.size(); j++) { - // const auto& entry = entries[j]; - // if ((entry.buffer != 0) + (entry.textureView != 0) + (entry.sampler != 0) != 1) { - // printf("***************missing binding, b, t, s %d, %p, %p, %p\n", entry.binding, entry.buffer, entry.textureView, entry.sampler); - // } - // } - - CCWGPUDeviceObject *deviceObj = CCWGPUDevice::getInstance()->gpuDeviceObject(); - if (_gpuBindGroupObj->bindgroup && _gpuBindGroupObj->bindgroup != anoymous::defaultBindGroup) { - wgpuBindGroupRelease(_gpuBindGroupObj->bindgroup); - } - if (entries.empty()) { - _gpuBindGroupObj->bindgroup = anoymous::defaultBindGroup; - // _bgl = CCWGPUDescriptorSetLayout::defaultBindGroupLayout(); + _gpuBindGroupObj->bindgroup = dftBindGroup; + _bornHash = 0; } else { - WGPUBindGroupDescriptor bindGroupDesc = { - .nextInChain = nullptr, - .label = nullptr, - .layout = dsLayout->gpuLayoutEntryObject()->bindGroupLayout, - .entryCount = entries.size(), - .entries = entries.data(), - }; - _gpuBindGroupObj->bindgroup = wgpuDeviceCreateBindGroup(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &bindGroupDesc); - // _bgl = dsLayout->gpuLayoutEntryObject()->bindGroupLayout; - // _local = dsLayout; + _hash = hash(); + auto iter = bindGroupMap.find(_hash); + if (iter == bindGroupMap.end()) { + // layout might be changed later. + _bornHash = dsLayout->getHash(); + CCWGPUDeviceObject *deviceObj = CCWGPUDevice::getInstance()->gpuDeviceObject(); + // if (_gpuBindGroupObj->bindgroup && _gpuBindGroupObj->bindgroup != dftBindGroup) { + // wgpuBindGroupRelease(_gpuBindGroupObj->bindgroup); + // } + label = std::to_string(_bornHash); + WGPUBindGroupDescriptor bindGroupDesc = { + .nextInChain = nullptr, + .label = label.c_str(), + .layout = dsLayout->gpuLayoutEntryObject()->bindGroupLayout, + .entryCount = entries.size(), + .entries = entries.data(), + }; + + _gpuBindGroupObj->bindgroup = wgpuDeviceCreateBindGroup(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &bindGroupDesc); + // printf("create new bg\n"); + + _isDirty = false; + if (buffIter != _buffers.end()) + std::for_each(_buffers.begin(), _buffers.end(), [](Buffer *buffer) { + if (buffer) + static_cast(buffer)->stamp(); + }); + if (texIter != _textures.end()) + std::for_each(_textures.begin(), _textures.end(), [](Texture *texture) { + if (texture) + static_cast(texture)->stamp(); + }); + + bindGroupMap.insert(std::make_pair(_hash, BindGroupCache{this, _gpuBindGroupObj->bindgroup, _bornHash})); + // CCWGPUDevice::getInstance()->destroyLater(_gpuBindGroupObj->bindgroup); + } else { + _gpuBindGroupObj->bindgroup = static_cast(iter->second.bindGroup); + _bornHash = iter->second.bornHash; + // printf("reuse bg\n"); + } } - _isDirty = false; - if (buffIter != _buffers.end()) - std::for_each(_buffers.begin(), _buffers.end(), [](Buffer *buffer) { - if (buffer) - static_cast(buffer)->stamp(); - }); - if (texIter != _textures.end()) - std::for_each(_textures.begin(), _textures.end(), [](Texture *texture) { - if (texture) - static_cast(texture)->stamp(); - }); } } @@ -251,7 +329,7 @@ uint8_t CCWGPUDescriptorSet::dynamicOffsetCount() const { void *CCWGPUDescriptorSet::defaultBindGroup() { CCWGPUDeviceObject *deviceObj = CCWGPUDevice::getInstance()->gpuDeviceObject(); - if (!anoymous::defaultBindGroup) { + if (!dftBindGroup) { CCWGPUBuffer *buffer = deviceObj->defaultResources.uniformBuffer; WGPUBindGroupEntry bufferEntry = { .binding = 0, @@ -262,15 +340,15 @@ void *CCWGPUDescriptorSet::defaultBindGroup() { WGPUBindGroupDescriptor bindGroupDesc = { .nextInChain = nullptr, - .label = nullptr, + .label = "defaultBindGroup", .layout = static_cast(CCWGPUDescriptorSetLayout::defaultBindGroupLayout()), .entryCount = 1, .entries = &bufferEntry, }; - anoymous::defaultBindGroup = wgpuDeviceCreateBindGroup(deviceObj->wgpuDevice, &bindGroupDesc); + dftBindGroup = wgpuDeviceCreateBindGroup(deviceObj->wgpuDevice, &bindGroupDesc); } - return anoymous::defaultBindGroup; + return dftBindGroup; } } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.h b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.h index 743ef42faa..259bf4010b 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.h @@ -24,8 +24,9 @@ ****************************************************************************/ #pragma once - -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "base/std/container/unordered_map.h" #include "base/std/container/vector.h" #include "gfx-base/GFXDescriptorSet.h" @@ -36,31 +37,29 @@ struct CCWGPUBindGroupObject; using Pairs = ccstd::vector>; -class CCWGPUDescriptorSet final : public emscripten::wrapper { +class CCWGPUDescriptorSet final : public DescriptorSet { public: - EMSCRIPTEN_WRAPPER(CCWGPUDescriptorSet); CCWGPUDescriptorSet(); - ~CCWGPUDescriptorSet() = default; + ~CCWGPUDescriptorSet(); inline CCWGPUBindGroupObject *gpuBindGroupObject() { return _gpuBindGroupObj; } - - void update() override; - - uint8_t dynamicOffsetCount() const; - - void prepare(); - - static void *defaultBindGroup(); - inline Pairs &dynamicOffsets() { return _dynamicOffsets; } - // void* bgl() const{return _bgl;} + void update() override; + void forceUpdate() override{}; + uint8_t dynamicOffsetCount() const; + void prepare(); + ccstd::hash_t getHash() { return _bornHash; }; - // DescriptorSetLayout* local()const {return _local;} + static void *defaultBindGroup(); + static void clearCache(); + + std::string label; protected: void doInit(const DescriptorSetInfo &info) override; void doDestroy() override; + ccstd::hash_t hash() const; CCWGPUBindGroupObject *_gpuBindGroupObj = nullptr; @@ -70,10 +69,8 @@ protected: // dynamic offsets, inuse ? 1 : 0; Pairs _dynamicOffsets; - - // void* _bgl = nullptr; - - // DescriptorSetLayout* _local = nullptr; + ccstd::hash_t _hash{0}; + ccstd::hash_t _bornHash{0}; // hash when created, this relate to reuse bindgroup layout }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp index f26243b36a..e055cfad39 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp @@ -37,16 +37,19 @@ namespace cc { namespace gfx { -namespace anoymous { -WGPUBindGroupLayout defaultBindgroupLayout = wgpuDefaultHandle; +namespace { +WGPUBindGroupLayout dftBindgroupLayout = wgpuDefaultHandle; -ccstd::unordered_map layoutPool; -} // namespace anoymous +ccstd::unordered_map layoutPool; +} // namespace using namespace emscripten; -using namespace anoymous; -CCWGPUDescriptorSetLayout::CCWGPUDescriptorSetLayout() : wrapper(val::object()) { +CCWGPUDescriptorSetLayout::CCWGPUDescriptorSetLayout() : DescriptorSetLayout() { +} + +CCWGPUDescriptorSetLayout::~CCWGPUDescriptorSetLayout() { + doDestroy(); } void CCWGPUDescriptorSetLayout::doInit(const DescriptorSetLayoutInfo &info) { @@ -70,7 +73,7 @@ void CCWGPUDescriptorSetLayout::doInit(const DescriptorSetLayoutInfo &info) { .nextInChain = nullptr, .binding = _bindings[i].binding + CC_WGPU_MAX_ATTACHMENTS, .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), - .sampler.type = WGPUSamplerBindingType_Filtering, + .sampler.type = WGPUSamplerBindingType_NonFiltering, }; _gpuLayoutEntryObj->bindGroupLayoutEntries.push_back(samplerLayout); } else if (hasFlag(DESCRIPTOR_BUFFER_TYPE, _bindings[i].descriptorType)) { @@ -100,7 +103,7 @@ void CCWGPUDescriptorSetLayout::doInit(const DescriptorSetLayoutInfo &info) { .nextInChain = nullptr, .binding = _bindings[i].binding, .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), - .sampler = {nullptr, WGPUSamplerBindingType::WGPUSamplerBindingType_Comparison}, + .sampler = {nullptr, WGPUSamplerBindingType::WGPUSamplerBindingType_NonFiltering}, }; _gpuLayoutEntryObj->bindGroupLayoutEntries.push_back(layout); } else if (_bindings[i].descriptorType == DescriptorType::STORAGE_IMAGE) { @@ -125,90 +128,118 @@ void CCWGPUDescriptorSetLayout::doInit(const DescriptorSetLayoutInfo &info) { _gpuLayoutEntryObj->bindGroupLayoutEntries.push_back(layout); } } + (void)defaultBindGroupLayout(); + + _hash = hash(); } -void CCWGPUDescriptorSetLayout::updateLayout(uint8_t binding, const CCWGPUBuffer *buffer, const CCWGPUTexture *tex, const CCWGPUSampler *sampler) { +void CCWGPUDescriptorSetLayout::updateBufferLayout(uint8_t binding, const CCWGPUBuffer *buffer) { + // auto iter = std::find_if(_gpuLayoutEntryObj->bindGroupLayoutEntries.begin(), _gpuLayoutEntryObj->bindGroupLayoutEntries.end(), [binding](const WGPUBindGroupLayoutEntry &entry) { + // return entry.binding == binding; + // }); + + // if (iter != _gpuLayoutEntryObj->bindGroupLayoutEntries.end()) { + // auto bindingIter = std::find_if(_bindings.begin(), _bindings.end(), [binding](const auto &binding) { + // return binding.binding == binding; + // }); + // } + + // _internalChanged = true; +} + +void CCWGPUDescriptorSetLayout::updateTextureLayout(uint8_t binding, const CCWGPUTexture *texture) { auto iter = std::find_if(_gpuLayoutEntryObj->bindGroupLayoutEntries.begin(), _gpuLayoutEntryObj->bindGroupLayoutEntries.end(), [binding](const WGPUBindGroupLayoutEntry &entry) { return entry.binding == binding; }); if (iter != _gpuLayoutEntryObj->bindGroupLayoutEntries.end()) { - if (buffer) { - // - } - if (sampler) { - const SamplerInfo &info = sampler->getInfo(); - if (info.minFilter == Filter::POINT && info.magFilter == Filter::POINT && info.mipFilter == Filter::POINT) - (*iter).sampler.type = WGPUSamplerBindingType::WGPUSamplerBindingType_NonFiltering; - else - (*iter).sampler.type = WGPUSamplerBindingType::WGPUSamplerBindingType_Filtering; - } - if (tex) { - if (tex->getInfo().usage == TextureUsageBit::STORAGE) { + auto bindingIter = std::find_if(_bindings.begin(), _bindings.end(), [binding](const auto &bindingElem) { + return bindingElem.binding == binding; + }); + if (texture) { + if (texture->getInfo().usage == TextureUsageBit::STORAGE) { (*iter).storageTexture.nextInChain = nullptr; (*iter).storageTexture.access = WGPUStorageTextureAccess::WGPUStorageTextureAccess_WriteOnly; - (*iter).storageTexture.format = toWGPUTextureFormat(tex->getFormat()); - TextureType type = tex->isTextureView() ? tex->getViewInfo().type : tex->getInfo().type; + (*iter).storageTexture.format = toWGPUTextureFormat(texture->getFormat()); + TextureType type = texture->isTextureView() ? texture->getViewInfo().type : texture->getInfo().type; (*iter).storageTexture.viewDimension = toWGPUTextureViewDimension(type); } else { (*iter).texture.nextInChain = nullptr; - (*iter).texture.sampleType = textureSampleTypeTrait(tex->getFormat()); - const CCWGPUTexture *ccTex = static_cast(tex->isTextureView() ? tex->getViewInfo().texture : tex); + (*iter).texture.sampleType = textureSampleTypeTrait(texture->getFormat()); + const CCWGPUTexture *ccTex = static_cast(texture->isTextureView() ? texture->getViewInfo().texture : texture); TextureType type = ccTex->getViewInfo().type; (*iter).texture.viewDimension = toWGPUTextureViewDimension(type); (*iter).texture.multisampled = ccTex->getInfo().samples != SampleCount::ONE; } + } else { + (*iter).texture.nextInChain = nullptr; + (*iter).texture.sampleType = WGPUTextureSampleType::WGPUTextureSampleType_Float; + (*iter).texture.viewDimension = WGPUTextureViewDimension::WGPUTextureViewDimension_2D; + (*iter).texture.multisampled = false; } + _internalChanged = true; } } -size_t CCWGPUDescriptorSetLayout::hash() const { +void CCWGPUDescriptorSetLayout::updateSamplerLayout(uint8_t binding, const CCWGPUSampler *sampler) { + auto iter = std::find_if(_gpuLayoutEntryObj->bindGroupLayoutEntries.begin(), _gpuLayoutEntryObj->bindGroupLayoutEntries.end(), [binding](const WGPUBindGroupLayoutEntry &entry) { + return entry.binding == binding; + }); + + if (iter != _gpuLayoutEntryObj->bindGroupLayoutEntries.end()) { + auto bindingIter = std::find_if(_bindings.begin(), _bindings.end(), [binding](const auto &bindingElem) { + return bindingElem.binding == binding; + }); + if (sampler) { + const SamplerInfo &info = sampler->getInfo(); + if ((info.minFilter == Filter::POINT || info.minFilter == Filter::NONE) && + (info.magFilter == Filter::POINT || info.magFilter == Filter::NONE) && + (info.mipFilter == Filter::POINT || info.mipFilter == Filter::NONE)) { + (*iter).sampler.type = WGPUSamplerBindingType::WGPUSamplerBindingType_NonFiltering; + } else { + (*iter).sampler.type = WGPUSamplerBindingType::WGPUSamplerBindingType_Filtering; + } + } else { + (*iter).sampler.type = WGPUSamplerBindingType::WGPUSamplerBindingType_NonFiltering; + } + _internalChanged = true; + } +} + +ccstd::hash_t CCWGPUDescriptorSetLayout::hash() const { const auto &entries = _gpuLayoutEntryObj->bindGroupLayoutEntries; - // size_t seed = 129; - // boost::hash_combine(seed, entries.size()); - // for(size_t i = 0; i < entries.size(); i++) { - // boost::hash_combine(seed, i); - // boost::hash_combine(seed, entries[i].binding); - // boost::hash_combine(seed, entries[i].buffer.type); - // boost::hash_combine(seed, entries[i].sampler.type); - // boost::hash_combine(seed, entries[i].texture.sampleType); - // boost::hash_combine(seed, entries[i].storageTexture.access); - // } - - ccstd::string hashStr = ""; - - std::size_t seed = entries.size(); + ccstd::hash_t hash = 9527; + ccstd::hash_combine(hash, entries.size()); for (size_t i = 0; i < entries.size(); i++) { - const auto &entry = entries[i]; - hashStr += std::to_string(entry.binding); - hashStr += std::to_string(entry.visibility); - if (entry.buffer.type != WGPUBufferBindingType_Undefined) { - hashStr += std::to_string(entry.buffer.type); - hashStr += std::to_string(entry.buffer.hasDynamicOffset ? 1 : 0); - hashStr += std::to_string(entry.buffer.minBindingSize); + ccstd::hash_combine(hash, i); + ccstd::hash_combine(hash, entries[i].binding); + ccstd::hash_combine(hash, entries[i].visibility); + if (entries[i].buffer.type != WGPUBufferBindingType_Undefined) { + ccstd::hash_combine(hash, entries[i].buffer.type); + ccstd::hash_combine(hash, entries[i].buffer.hasDynamicOffset); + ccstd::hash_combine(hash, entries[i].buffer.minBindingSize); } - if (entry.sampler.type == WGPUSamplerBindingType_Undefined) { - hashStr += std::to_string(entry.sampler.type); + if (entries[i].sampler.type != WGPUSamplerBindingType_Undefined) { + ccstd::hash_combine(hash, entries[i].sampler.type); } - if (entry.texture.sampleType != WGPUTextureSampleType_Undefined) { - hashStr += std::to_string(entry.texture.sampleType); - hashStr += std::to_string(entry.texture.viewDimension); - hashStr += std::to_string(entry.texture.multisampled ? 1 : 0); + if (entries[i].texture.sampleType != WGPUTextureSampleType_Undefined) { + ccstd::hash_combine(hash, entries[i].texture.sampleType); + ccstd::hash_combine(hash, entries[i].texture.viewDimension); + ccstd::hash_combine(hash, entries[i].texture.multisampled); } - if (entry.storageTexture.access != WGPUStorageTextureAccess_Undefined) { - hashStr += std::to_string(entry.storageTexture.access); - hashStr += std::to_string(entry.storageTexture.format); - hashStr += std::to_string(entry.storageTexture.viewDimension); + if (entries[i].storageTexture.access != WGPUStorageTextureAccess_Undefined) { + ccstd::hash_combine(hash, entries[i].storageTexture.access); + ccstd::hash_combine(hash, entries[i].storageTexture.format); + ccstd::hash_combine(hash, entries[i].storageTexture.viewDimension); } } - - return std::hash{}(hashStr); + return hash; } void CCWGPUDescriptorSetLayout::print() const { - size_t hashVal = this->hash(); - printf("pr this %p %p %zu\n", _gpuLayoutEntryObj, this, hashVal); + size_t hashVal = _hash; + printf("\npr this %p %p %zu\n", _gpuLayoutEntryObj, this, hashVal); const auto &entries = _gpuLayoutEntryObj->bindGroupLayoutEntries; for (size_t j = 0; j < entries.size(); j++) { const auto &entry = entries[j]; @@ -235,20 +266,21 @@ void CCWGPUDescriptorSetLayout::print() const { } } -void CCWGPUDescriptorSetLayout::prepare(bool forceUpdate) { - if (_gpuLayoutEntryObj->bindGroupLayout && !forceUpdate) { - return; - } +void CCWGPUDescriptorSetLayout::prepare(ccstd::set &bindingInUse, bool forceUpdate) { + // if (_gpuLayoutEntryObj->bindGroupLayout && !forceUpdate) { + // return; + // } // ccstd::vector bindGroupLayoutEntries; // bindGroupLayoutEntries.assign(_gpuLayoutEntryObj->bindGroupLayoutEntries.begin(), _gpuLayoutEntryObj->bindGroupLayoutEntries.end()); // bindGroupLayoutEntries.erase(std::remove_if( - // bindGroupLayoutEntries.begin(), bindGroupLayoutEntries.end(), [&bindingInUse, &bindGroupLayoutEntries](const WGPUBindGroupLayoutEntry& entry) { + // bindGroupLayoutEntries.begin(), bindGroupLayoutEntries.end(), [&bindingInUse, &bindGroupLayoutEntries](const WGPUBindGroupLayoutEntry &entry) { // return bindingInUse.find(entry.binding) == bindingInUse.end(); // }), // bindGroupLayoutEntries.end()); - size_t hashVal = hash(); - auto iter = layoutPool.find(hashVal); + _hash = hash(); + auto iter = layoutPool.find(_hash); + // printf("dsl upd %zu\n", _hash); if (iter != layoutPool.end()) { _gpuLayoutEntryObj->bindGroupLayout = iter->second; return; @@ -268,22 +300,31 @@ void CCWGPUDescriptorSetLayout::prepare(bool forceUpdate) { // } if (entries.empty()) { - _gpuLayoutEntryObj->bindGroupLayout = anoymous::defaultBindgroupLayout; + _gpuLayoutEntryObj->bindGroupLayout = dftBindgroupLayout; } else { WGPUBindGroupLayoutDescriptor descriptor = { .nextInChain = nullptr, - .label = nullptr, + .label = std::to_string(_hash).c_str(), .entryCount = entries.size(), .entries = entries.data(), }; _gpuLayoutEntryObj->bindGroupLayout = wgpuDeviceCreateBindGroupLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + printf("create new bglayout\n"); } - // printf("bgl %p\n", _gpuLayoutEntryObj->bindGroupLayout); - layoutPool.insert({hashVal, _gpuLayoutEntryObj->bindGroupLayout}); + layoutPool.insert({_hash, _gpuLayoutEntryObj->bindGroupLayout}); +} + +void *CCWGPUDescriptorSetLayout::getBindGroupLayoutByHash(ccstd::hash_t hash) { + void *ret = nullptr; + auto iter = layoutPool.find(hash); + if (iter != layoutPool.end()) { + ret = iter->second; + } + return ret; } void *CCWGPUDescriptorSetLayout::defaultBindGroupLayout() { - if (!anoymous::defaultBindgroupLayout) { + if (!dftBindgroupLayout) { // default bindgroupLayout: for empty set WGPUBindGroupLayoutEntry layout = { .nextInChain = nullptr, @@ -294,18 +335,21 @@ void *CCWGPUDescriptorSetLayout::defaultBindGroupLayout() { WGPUBindGroupLayoutDescriptor descriptor = { .nextInChain = nullptr, - .label = nullptr, + .label = "defaultBindgroupLayout", .entryCount = 1, .entries = &layout, }; - anoymous::defaultBindgroupLayout = wgpuDeviceCreateBindGroupLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + dftBindgroupLayout = wgpuDeviceCreateBindGroupLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); } - return anoymous::defaultBindgroupLayout; + return dftBindgroupLayout; } void CCWGPUDescriptorSetLayout::doDestroy() { - delete _gpuLayoutEntryObj; + if (_gpuLayoutEntryObj) { + delete _gpuLayoutEntryObj; + _gpuLayoutEntryObj = nullptr; + } } } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.h b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.h index dc148f3e9d..713944e2b4 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.h @@ -24,9 +24,10 @@ ****************************************************************************/ #pragma once - -#include -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif +#include "base/std/container/set.h" #include "gfx-base/GFXDescriptorSetLayout.h" namespace cc { @@ -37,29 +38,37 @@ class CCWGPUTexture; class CCWGPUBuffer; class CCWGPUSampler; -class CCWGPUDescriptorSetLayout final : public emscripten::wrapper { +class CCWGPUDescriptorSetLayout final : public DescriptorSetLayout { public: - EMSCRIPTEN_WRAPPER(CCWGPUDescriptorSetLayout); CCWGPUDescriptorSetLayout(); - ~CCWGPUDescriptorSetLayout() = default; + ~CCWGPUDescriptorSetLayout(); inline CCWGPUBindGroupLayoutObject *gpuLayoutEntryObject() { return _gpuLayoutEntryObj; } - void updateLayout(uint8_t binding, const CCWGPUBuffer *buffer = nullptr, const CCWGPUTexture *tex = nullptr, const CCWGPUSampler *sampler = nullptr); + void updateBufferLayout(uint8_t binding, const CCWGPUBuffer *buffer); + void updateTextureLayout(uint8_t binding, const CCWGPUTexture *texture); + void updateSamplerLayout(uint8_t binding, const CCWGPUSampler *sampler); - void prepare(bool forceUpdate = false); + void prepare(ccstd::set &bindingInUse, bool forceUpdate = false); inline uint8_t dynamicOffsetCount() { return _dynamicOffsetCount; } static void *defaultBindGroupLayout(); + static void *getBindGroupLayoutByHash(ccstd::hash_t hash); void print() const; + ccstd::hash_t getHash() { + return _hash; + } + protected: void doInit(const DescriptorSetLayoutInfo &info) override; void doDestroy() override; - size_t hash() const; + ccstd::hash_t hash() const; + ccstd::hash_t _hash{0}; + bool _internalChanged{false}; CCWGPUBindGroupLayoutObject *_gpuLayoutEntryObj = nullptr; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDevice.cpp b/native/cocos/renderer/gfx-wgpu/WGPUDevice.cpp index 2c35ef6355..016d3edacc 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDevice.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUDevice.cpp @@ -49,6 +49,7 @@ namespace cc { namespace gfx { +namespace { struct BufferMapData { Semaphore *semaphore = nullptr; WGPUBuffer buffer = wgpuDefaultHandle; @@ -57,6 +58,22 @@ struct BufferMapData { bool finished = false; }; +} // namespace + +void onAdapterGot(WGPURequestAdapterStatus status, WGPUAdapter adapter, char const *message, void *userdata) { + if (message) { + printf("onAdapterGot: %s\n", message); + } + if (status == WGPURequestAdapterStatus_Success) { + auto *device = static_cast(userdata); + device->gpuDeviceObject()->instance.wgpuAdapter = adapter; + device->initConfigs(); + device->initLimits(); + } else { + printf("onAdapterGot: failed to get adapter\n"); + } +} + CCWGPUDevice *CCWGPUDevice::instance = nullptr; CCWGPUDevice *CCWGPUDevice::getInstance() { @@ -68,19 +85,30 @@ CCWGPUDevice *CCWGPUDevice::getInstance() { return instance; } -CCWGPUDevice::CCWGPUDevice() : wrapper(val::object()) { +CCWGPUDevice::CCWGPUDevice() : Device() { _api = API::WEBGPU; _deviceName = "WebGPU"; _caps.clipSpaceMinZ = 0.0F; _caps.screenSpaceSignY = -1.0F; - _caps.clipSpaceSignY = -1.0F; + _caps.clipSpaceSignY = 1.0F; + + // Sept 6th 2022: ems getLimits not implemented + _caps.uboOffsetAlignment = 256; + _caps.uboOffsetAlignment = 256; + _caps.maxVertexUniformVectors = 256; + _caps.maxFragmentUniformVectors = 256; + + _caps.maxComputeSharedMemorySize = 32768; + _caps.maxComputeWorkGroupInvocations = 256; + _caps.maxComputeWorkGroupSize = {65535, 65535, 65535}; + _caps.maxComputeWorkGroupCount = {256, 256, 64}; + instance = this; } CCWGPUDevice::~CCWGPUDevice() { + doDestroy(); instance = nullptr; - delete _gpuDeviceObj; - delete this; } bool CCWGPUDevice::doInit(const DeviceInfo &info) { @@ -92,7 +120,8 @@ bool CCWGPUDevice::doInit(const DeviceInfo &info) { _gpuDeviceObj->defaultResources.storageBuffer = CCWGPUBuffer::defaultStorageBuffer(); _gpuDeviceObj->defaultResources.commonTexture = CCWGPUTexture::defaultCommonTexture(); _gpuDeviceObj->defaultResources.storageTexture = CCWGPUTexture::defaultStorageTexture(); - _gpuDeviceObj->defaultResources.sampler = CCWGPUSampler::defaultSampler(); + _gpuDeviceObj->defaultResources.filterableSampler = CCWGPUSampler::defaultFilterableSampler(); + _gpuDeviceObj->defaultResources.unfilterableSampler = CCWGPUSampler::defaultUnfilterableSampler(); QueueInfo queueInfo = { .type = QueueType::GRAPHICS, @@ -104,10 +133,90 @@ bool CCWGPUDevice::doInit(const DeviceInfo &info) { .type = CommandBufferType::PRIMARY, }; _cmdBuff = this->Device::createCommandBuffer(cmdInfo); + // Sept 6th 2022: not implemented by emscripten + // _gpuDeviceObj->instance.wgpuInstance = wgpuCreateInstance({}); + +#ifdef CC_WGPU_WASM + WGPUSurfaceDescriptorFromCanvasHTMLSelector canvDesc = {}; + canvDesc.chain.sType = WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector; + canvDesc.selector = "canvas"; + + WGPUSurfaceDescriptor surfDesc = {}; + surfDesc.nextInChain = reinterpret_cast(&canvDesc); + _gpuDeviceObj->instance.wgpuSurface = wgpuInstanceCreateSurface(nullptr, &surfDesc); + +#elif defined(CC_WGPU_DAWN) + _gpuDeviceObj->instance.wgpuInstance = wgpuCreateInstance({}); + WGPUSurfaceDescriptor sufaceDesc = { + .label = "DAWNSurface", + }; + _gpuDeviceObj->instance.wgpuSurface = wgpuInstanceCreateSurface(_gpuDeviceObj->instance.wgpuInstance, &sufaceDesc); + +#endif + WGPURequestAdapterOptions options = { + .compatibleSurface = _gpuDeviceObj->instance.wgpuSurface, + .powerPreference = WGPUPowerPreference_LowPower, + }; + + wgpuInstanceRequestAdapter(_gpuDeviceObj->instance.wgpuInstance, &options, onAdapterGot, this); + + // auto bufferRecycleFunc = [this](WGPUBuffer buffer) { + // _recycleBin[getCurrentFrameIndex()].bufferBin.collect(buffer); + // }; + // for (size_t i = 0; i < CC_WGPU_MAX_FRAME_COUNT; ++i) { + // _stagingBuffers[i] = new CCWGPUStagingBuffer(_gpuDeviceObj->wgpuDevice, bufferRecycleFunc); + // } + + initFeatures(); return true; } void CCWGPUDevice::doDestroy() { + if (_gpuDeviceObj) { + if (_gpuDeviceObj->defaultResources.uniformBuffer) { + delete _gpuDeviceObj->defaultResources.uniformBuffer; + } + if (_gpuDeviceObj->defaultResources.storageBuffer) { + delete _gpuDeviceObj->defaultResources.storageBuffer; + } + if (_gpuDeviceObj->defaultResources.commonTexture) { + delete _gpuDeviceObj->defaultResources.commonTexture; + } + if (_gpuDeviceObj->defaultResources.storageTexture) { + delete _gpuDeviceObj->defaultResources.storageTexture; + } + if (_gpuDeviceObj->defaultResources.filterableSampler) { + delete _gpuDeviceObj->defaultResources.filterableSampler; + } + if (_gpuDeviceObj->defaultResources.unfilterableSampler) { + delete _gpuDeviceObj->defaultResources.unfilterableSampler; + } + + for (size_t i = 0; i < CC_WGPU_MAX_FRAME_COUNT; ++i) { + _recycleBin[i].bufferBin.purge(); + _recycleBin[i].textureBin.purge(); + _recycleBin[i].queryBin.purge(); + } + + if (_gpuDeviceObj->wgpuQueue) { + wgpuQueueRelease(_gpuDeviceObj->wgpuQueue); + } + if (_gpuDeviceObj->instance.wgpuSurface) { + wgpuSurfaceRelease(_gpuDeviceObj->instance.wgpuSurface); + } + if (_gpuDeviceObj->instance.wgpuInstance) { + wgpuInstanceRelease(_gpuDeviceObj->instance.wgpuInstance); + } + if (_gpuDeviceObj->instance.wgpuAdapter) { + wgpuAdapterRelease(_gpuDeviceObj->instance.wgpuAdapter); + } + if (_gpuDeviceObj->wgpuDevice) { + wgpuDeviceRelease(_gpuDeviceObj->wgpuDevice); + } + + delete _gpuDeviceObj; + _gpuDeviceObj = nullptr; + } } Swapchain *CCWGPUDevice::createSwapchain() { @@ -162,147 +271,177 @@ CommandBuffer *CCWGPUDevice::createCommandBuffer(const CommandBufferInfo &info, return ccnew CCWGPUCommandBuffer; } -void CCWGPUDevice::copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) { +Shader *CCWGPUDevice::createShader(const ShaderInfo &info, const std::vector> &spvData) { + auto *shader = ccnew CCWGPUShader; + shader->initialize(info, spvData); + return shader; +} + +void CCWGPUDevice::copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) { Format dstFormat = dst->getFormat(); - uint32_t pxSize = GFX_FORMAT_INFOS[static_cast(dstFormat)].size; + uint32_t pxSize = GFX_FORMAT_INFOS[static_cast(dstFormat)].size; auto *texture = static_cast(dst); + auto blockSize = formatAlignment(dstFormat); + + auto *ccTexture = static_cast(texture); + if (ccTexture->isTextureView()) { + ccTexture = static_cast(ccTexture->getViewInfo().texture); + } for (size_t i = 0; i < count; i++) { - uint32_t bufferSize = pxSize * regions[i].texExtent.width * regions[i].texExtent.height; + const auto ®ion = regions[i]; + auto bufferPixelWidth = region.buffStride > 0 ? region.buffStride : region.texExtent.width; + auto bufferPixelHeight = region.buffTexHeight > 0 ? region.buffTexHeight : region.texExtent.height; + auto bytesPerRow = formatSize(dstFormat, region.texExtent.width, 1, 1); + auto bufferBytesPerRow = formatSize(dstFormat, bufferPixelWidth, 1, 1); + auto bufferBytesPerImageSlice = formatSize(dstFormat, bufferPixelWidth, bufferPixelHeight, 1); + auto bufferBytesPerImageLayer = formatSize(dstFormat, bufferPixelWidth, bufferPixelHeight, region.texExtent.depth); + auto targetWidth = region.texExtent.width == 0 ? 0 : utils::alignTo(region.texExtent.width, blockSize.first); + auto targetHeight = region.texExtent.height == 0 ? 0 : utils::alignTo(region.texExtent.height, blockSize.second); - uint32_t bytesPerRow = pxSize * regions[i].texExtent.width; - //it's buffer data layout + // it's buffer data layout WGPUTextureDataLayout texDataLayout = { - .offset = 0, - .bytesPerRow = bytesPerRow, - .rowsPerImage = regions[i].texExtent.height, + .offset = 0, // we always create a non-offset staging buffer or give interface a non-offset buffer address + .bytesPerRow = bufferBytesPerRow, + .rowsPerImage = bufferPixelHeight, }; - WGPUExtent3D extent = { - .width = regions[i].texExtent.width, - .height = regions[i].texExtent.height, - .depthOrArrayLayers = regions[i].texExtent.depth, - }; + bool compactInWidth = bufferPixelWidth == region.texExtent.width; + for (size_t l = region.texSubres.baseArrayLayer; l < region.texSubres.layerCount + region.texSubres.baseArrayLayer; ++l) { + for (size_t d = region.texOffset.z; d < region.texExtent.depth + region.texOffset.z; ++d) { + if (compactInWidth) { + auto *srcData = buffers[i] + region.buffOffset + (l - region.texSubres.baseArrayLayer) * bufferBytesPerImageLayer + (d - region.texOffset.z) * bufferBytesPerImageSlice; + WGPUImageCopyTexture imageCopyTexture = { + .texture = ccTexture->gpuTextureObject()->wgpuTexture, + .mipLevel = region.texSubres.mipLevel, + .origin = WGPUOrigin3D{ + static_cast(region.texOffset.x), + static_cast(region.texOffset.y), + static_cast(d)}, + .aspect = WGPUTextureAspect_All, + }; - WGPUImageCopyTexture imageCopyTexture = { - .texture = texture->gpuTextureObject()->wgpuTexture, - .mipLevel = regions[i].texSubres.mipLevel, - .origin = WGPUOrigin3D{ - static_cast(regions[i].texOffset.x), - static_cast(regions[i].texOffset.y), - static_cast(regions[i].texSubres.baseArrayLayer)}, - .aspect = WGPUTextureAspect_All, - }; - wgpuQueueWriteTexture(_gpuDeviceObj->wgpuQueue, &imageCopyTexture, buffers[i], bufferSize, &texDataLayout, &extent); + WGPUExtent3D extent = { + .width = targetWidth, + .height = targetHeight, + .depthOrArrayLayers = 1, + }; - // //genMipmap manually when level 0 updated. - // const TextureInfo& texInfo = dst->getInfo(); - // if (hasFlag(texInfo.flags, TextureFlagBit::GEN_MIPMAP) && regions[i].texSubres.mipLevel == 0) { - // for(size_t j = 1; j < texInfo.levelCount; j++) { - // imageCopyTexture.mipLevel = j; - // extent = { - // .width = (uint32_t)(regions[i].texExtent.width / float(std::pow(2, j))), - // .height = (uint32_t)(regions[i].texExtent.height / float(std::pow(2, j))), - // .depthOrArrayLayers = regions[i].texExtent.depth, - // }; + wgpuQueueWriteTexture(_gpuDeviceObj->wgpuQueue, &imageCopyTexture, srcData, bufferBytesPerImageSlice, &texDataLayout, &extent); + } else { + for (size_t h = region.texOffset.y; h < region.texExtent.height + region.texOffset.y; h += blockSize.second) { + auto *srcData = buffers[i] + region.buffOffset + (l - region.texSubres.baseArrayLayer) * bufferBytesPerImageLayer + (d - region.texOffset.z) * bufferBytesPerImageSlice + + (h - region.texOffset.y) / blockSize.second * bufferBytesPerRow; + WGPUImageCopyTexture imageCopyTexture = { + .texture = ccTexture->gpuTextureObject()->wgpuTexture, + .mipLevel = region.texSubres.mipLevel, + .origin = WGPUOrigin3D{ + static_cast(region.texOffset.x), + static_cast(h), + static_cast(d)}, + .aspect = WGPUTextureAspect_All, + }; - // wgpuQueueWriteTexture(_gpuDeviceObj->wgpuQueue, &imageCopyTexture, buffers[i], bufferSize, &texDataLayout, &extent); - // } - // } + WGPUExtent3D extent = { + .width = targetWidth, + .height = blockSize.second, + .depthOrArrayLayers = 1, + }; + + wgpuQueueWriteTexture(_gpuDeviceObj->wgpuQueue, &imageCopyTexture, srcData, bytesPerRow, &texDataLayout, &extent); + } + } + } + } } } void onQueueDone(WGPUQueueWorkDoneStatus status, void *userdata) { - printf("Q done beg\n"); if (status == WGPUQueueWorkDoneStatus_Success) { - printf("Q done beg0\n"); auto *bufferMapData = static_cast(userdata); - printf("Q done beg1\n"); // auto* mappedBuffer = wgpuBufferGetMappedRange(bufferMapData->buffer, 0, bufferMapData->size); auto *mappedBuffer = (uint8_t *)malloc(static_cast(bufferMapData->size)); - printf("Q done beg2\n"); *bufferMapData->retBuffer = emscripten::val(emscripten::typed_memory_view(bufferMapData->size, static_cast(mappedBuffer))); - printf("Q suc %d\n", bufferMapData->size); bufferMapData->finished = true; // memcpy(bufferMapData->dst, mappedBuffer, bufferMapData->size); } - printf("Q done\n"); } emscripten::val CCWGPUDevice::copyTextureToBuffers(Texture *src, const BufferTextureCopyList ®ions) { - auto *texture = static_cast(src); - Format dstFormat = src->getFormat(); - uint32_t pxSize = GFX_FORMAT_INFOS[static_cast(dstFormat)].size; - auto wgpuCommandEncoder = wgpuDeviceCreateCommandEncoder(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, nullptr); + // auto *texture = static_cast(src); + // Format dstFormat = src->getFormat(); + // uint32_t pxSize = GFX_FORMAT_INFOS[static_cast(dstFormat)].size; + // auto wgpuCommandEncoder = wgpuDeviceCreateCommandEncoder(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, nullptr); - uint64_t size = std::accumulate(regions.begin(), regions.end(), 0, [pxSize](uint64_t initVal, const BufferTextureCopy &in) { - uint32_t bytesPerRow = (pxSize * in.texExtent.width + 255) / 256 * 256; - uint32_t bufferSize = bytesPerRow * in.texExtent.height * in.texExtent.depth; - return initVal + bufferSize; - }); + // uint64_t size = std::accumulate(regions.begin(), regions.end(), 0, [pxSize](uint64_t initVal, const BufferTextureCopy &in) { + // uint32_t bytesPerRow = (pxSize * in.texExtent.width + 255) / 256 * 256; + // uint32_t bufferSize = bytesPerRow * in.texExtent.height * in.texExtent.depth; + // return initVal + bufferSize; + // }); - WGPUBufferDescriptor descriptor = { - .nextInChain = nullptr, - .label = nullptr, - .usage = WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst, - .size = size, - .mappedAtCreation = false, - }; + // WGPUBufferDescriptor descriptor = { + // .nextInChain = nullptr, + // .label = nullptr, + // .usage = WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst, + // .size = size, + // .mappedAtCreation = false, + // }; - WGPUBuffer buffer = wgpuDeviceCreateBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); - uint64_t offset = 0; - for (size_t i = 0; i < regions.size(); i++) { - uint32_t bytesPerRow = (pxSize * regions[i].texExtent.width + 255) / 256 * 256; - WGPUImageCopyTexture imageCopyTexture = { - .texture = texture->gpuTextureObject()->wgpuTexture, - .mipLevel = regions[i].texSubres.mipLevel, - .origin = WGPUOrigin3D{ - static_cast(regions[i].texOffset.x), - static_cast(regions[i].texOffset.y), - static_cast(regions[i].texOffset.z)}, - .aspect = WGPUTextureAspect_All, - }; + // WGPUBuffer buffer = wgpuDeviceCreateBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + // uint64_t offset = 0; + // for (size_t i = 0; i < regions.size(); i++) { + // uint32_t bytesPerRow = (pxSize * regions[i].texExtent.width + 255) / 256 * 256; + // WGPUImageCopyTexture imageCopyTexture = { + // .texture = texture->gpuTextureObject()->wgpuTexture, + // .mipLevel = regions[i].texSubres.mipLevel, + // .origin = WGPUOrigin3D{ + // static_cast(regions[i].texOffset.x), + // static_cast(regions[i].texOffset.y), + // static_cast(regions[i].texOffset.z)}, + // .aspect = WGPUTextureAspect_All, + // }; - WGPUTextureDataLayout texDataLayout = { - .offset = offset, - .bytesPerRow = bytesPerRow, - .rowsPerImage = regions[i].texExtent.height, - }; - uint32_t bufferSize = pxSize * regions[i].texExtent.width * regions[i].texExtent.depth; - offset += bufferSize; + // WGPUTextureDataLayout texDataLayout = { + // .offset = offset, + // .bytesPerRow = bytesPerRow, + // .rowsPerImage = regions[i].texExtent.height, + // }; + // uint32_t bufferSize = pxSize * regions[i].texExtent.width * regions[i].texExtent.depth; + // offset += bufferSize; - WGPUImageCopyBuffer imageCopyBuffer = { - .layout = texDataLayout, - .buffer = buffer, - }; + // WGPUImageCopyBuffer imageCopyBuffer = { + // .layout = texDataLayout, + // .buffer = buffer, + // }; - WGPUExtent3D extent = { - .width = regions[i].texExtent.width, - .height = regions[i].texExtent.height, - .depthOrArrayLayers = regions[i].texExtent.depth, - }; + // WGPUExtent3D extent = { + // .width = regions[i].texExtent.width, + // .height = regions[i].texExtent.height, + // .depthOrArrayLayers = regions[i].texExtent.depth, + // }; - wgpuCommandEncoderCopyTextureToBuffer(wgpuCommandEncoder, &imageCopyTexture, &imageCopyBuffer, &extent); - } - auto wgpuCommandBuffer = wgpuCommandEncoderFinish(wgpuCommandEncoder, nullptr); - wgpuQueueSubmit(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, &wgpuCommandBuffer); - printf("Q submit\n"); - Semaphore sem{0}; - BufferMapData *bufferMapData = ccnew BufferMapData{ - &sem, - buffer, - nullptr, - size, - false, - }; + // wgpuCommandEncoderCopyTextureToBuffer(wgpuCommandEncoder, &imageCopyTexture, &imageCopyBuffer, &extent); + // } - wgpuQueueOnSubmittedWorkDone(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, onQueueDone, bufferMapData); + // auto wgpuCommandBuffer = wgpuCommandEncoderFinish(wgpuCommandEncoder, nullptr); + // wgpuQueueSubmit(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, &wgpuCommandBuffer); + // printf("Q submit\n"); + // Semaphore sem{0}; + // BufferMapData *bufferMapData = ccnew BufferMapData{ + // &sem, + // buffer, + // nullptr, + // size, + // false, + // }; - while (!bufferMapData->finished) { - ; - } - // wgpuBufferRelease(buffer); - return *bufferMapData->retBuffer; + // wgpuQueueOnSubmittedWorkDone(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, onQueueDone, bufferMapData); + + // while (!bufferMapData->finished) { + // ; + // } + // // wgpuBufferRelease(buffer); + // return *bufferMapData->retBuffer; } void CCWGPUDevice::copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) { @@ -314,12 +453,6 @@ void CCWGPUDevice::acquire(Swapchain *const *swapchains, uint32_t count) { } } -Shader *CCWGPUDevice::createShader(const SPVShaderInfoInstance &info) { - CCWGPUShader *shader = ccnew CCWGPUShader; - shader->initialize(info); - return shader; -} - QueryPool *CCWGPUDevice::createQueryPool() { return ccnew CCWGPUQueryPool; } @@ -329,6 +462,15 @@ Sampler *CCWGPUDevice::createSampler(const SamplerInfo &info) { } void CCWGPUDevice::present() { + auto *queue = static_cast(_queue); + _numDrawCalls = queue->getNumDrawCalls(); + _numInstances = queue->getNumInstances(); + _numTriangles = queue->getNumTris(); + queue->resetStatus(); + + CCWGPUDescriptorSet::clearCache(); + + _currentFrameIndex = (++_currentFrameIndex) % CC_WGPU_MAX_FRAME_COUNT; } void CCWGPUDevice::getQueryPoolResults(QueryPool *queryPool) { @@ -341,6 +483,266 @@ void CCWGPUDevice::debug() { wgpuQueueSubmit(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, &wgpuCommandBuffer); } +void CCWGPUDevice::initConfigs() { + WGPUAdapterProperties props; + wgpuAdapterGetProperties(_gpuDeviceObj->instance.wgpuAdapter, &props); + // _deviceName = props.name; + // _vendor = props.driverDescription; + + const auto &adapterName = getAdapterTypeName(props.adapterType); + const auto &backendName = getBackendTypeName(props.backendType); + + printf("WebGPU:%s enabled with: %s , adapter:%s, backend: %s, vendorID: %u, deviceID:%u\n", + _deviceName.c_str(), _vendor.c_str(), adapterName.c_str(), backendName.c_str(), props.vendorID, props.deviceID); + + if (wgpuAdapterHasFeature(_gpuDeviceObj->instance.wgpuAdapter, WGPUFeatureName_TextureCompressionBC)) { + _formatFeatures[toNumber(Format::BC1_ALPHA)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC1_SRGB_ALPHA)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC2)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC2_SRGB)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC3)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC3_SRGB)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC4)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC4_SNORM)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC5_SNORM)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC6H_SF16)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC6H_UF16)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC7)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC7_SRGB)] = FormatFeature::SAMPLED_TEXTURE; + } + + if (wgpuAdapterHasFeature(_gpuDeviceObj->instance.wgpuAdapter, WGPUFeatureName_TextureCompressionETC2)) { + _formatFeatures[toNumber(Format::ETC2_RGBA8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ETC2_SRGB8_A8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ETC2_RGB8_A1)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ETC2_SRGB8_A1)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ETC2_RGB8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ETC2_SRGB8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::EAC_R11)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::EAC_R11SN)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::EAC_RG11)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::EAC_RG11SN)] = FormatFeature::SAMPLED_TEXTURE; + } + + if (wgpuAdapterHasFeature(_gpuDeviceObj->instance.wgpuAdapter, WGPUFeatureName_TextureCompressionASTC)) { + _formatFeatures[toNumber(Format::ASTC_RGBA_4X4)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_4X4)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_5X4)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_5X4)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_5X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_5X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_6X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_6X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_6X6)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_6X6)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_8X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_8X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_8X6)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_8X6)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_8X8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_8X8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_10X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_10X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_10X6)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_10X6)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_10X8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_10X8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_10X10)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_10X10)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_12X10)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_12X10)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_12X12)] = FormatFeature::SAMPLED_TEXTURE; + } +} + +void CCWGPUDevice::initLimits() { + WGPUSupportedLimits supportLimits; + + // Aug-19th 2022: getlimits not impled. + +#if 0 + wgpuAdapterGetLimits(_gpuDeviceObj->instance.wgpuAdapter, &supportLimits); + + const auto &limits = supportLimits.limits; + _caps.maxVertexAttributes = limits.maxVertexAttributes; + _caps.maxVertexUniformVectors = 256; + _caps.maxFragmentUniformVectors = 256; + _caps.maxTextureUnits = limits.maxSamplersPerShaderStage; + _caps.maxImageUnits = limits.maxSampledTexturesPerShaderStage; + _caps.maxVertexTextureUnits = limits.maxSampledTexturesPerShaderStage; + _caps.maxShaderStorageBufferBindings = limits.maxStorageBuffersPerShaderStage; + _caps.maxUniformBlockSize = limits.maxUniformBufferBindingSize; + _caps.maxShaderStorageBlockSize = limits.maxStorageBufferBindingSize; + _caps.maxShaderStorageBufferBindings = limits.maxStorageBuffersPerShaderStage; + _caps.maxTextureSize = limits.maxTextureDimension2D; + _caps.uboOffsetAlignment = limits.minUniformBufferOffsetAlignment; + + _caps.maxComputeSharedMemorySize = limits.maxComputeWorkgroupStorageSize; + _caps.maxComputeWorkGroupInvocations = limits.maxComputeInvocationsPerWorkgroup; + _caps.maxComputeWorkGroupSize = {limits.maxComputeWorkgroupsPerDimension, limits.maxComputeWorkgroupsPerDimension, limits.maxComputeWorkgroupsPerDimension}; + _caps.maxComputeWorkGroupCount = {limits.maxComputeWorkgroupSizeX, limits.maxComputeWorkgroupSizeY, limits.maxComputeWorkgroupSizeZ}; + +#endif +} + +void CCWGPUDevice::initFeatures() { + const FormatFeature completeFeature = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE | FormatFeature::LINEAR_FILTER | FormatFeature::STORAGE_TEXTURE; + + FormatFeature tempFeature = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE | FormatFeature::STORAGE_TEXTURE; + + // render target + _formatFeatures[toNumber(Format::R8)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R8UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R8I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RG8)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RG8UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RG8I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA8)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::SRGB8_A8)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA8UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA8I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::BGRA8)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R16UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R16I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R16F)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RG16UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RG16I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RG16F)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA16UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA16I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA16F)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R32UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R32I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R32F)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R32UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R32I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RG32F)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA32UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA32I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA32F)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGB10A2)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::DEPTH)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::DEPTH_STENCIL)] |= FormatFeature::RENDER_TARGET; + + // storage + _formatFeatures[toNumber(Format::RGBA8)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA8SN)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA8UI)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA8I)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA16UI)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA16I)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA16F)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::R32UI)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::R32I)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::R32F)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::R32UI)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::R32I)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RG32F)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA32UI)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA32I)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA32F)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGB10A2)] |= FormatFeature::STORAGE_TEXTURE; + + // sampled + _formatFeatures[toNumber(Format::R8)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R8SN)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R8UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R8I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG8)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG8SN)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG8UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG8I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA8)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::SRGB8_A8)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA8SN)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA8UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA8I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BGRA8)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R16UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R16I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R16F)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG16UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG16I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG16F)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA16UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA16I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA16F)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R32UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R32I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R32F)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R32UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R32I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG32F)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA32UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA32I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA32F)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGB10A2)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R11G11B10F)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::DEPTH)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::DEPTH_STENCIL)] |= FormatFeature::SAMPLED_TEXTURE; + + _formatFeatures[toNumber(Format::RGB9E5)] |= FormatFeature::SAMPLED_TEXTURE; + + _formatFeatures[toNumber(Format::R8)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG8)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB8)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA8)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R8SN)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG8SN)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB8SN)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA8SN)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R8I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG8I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB8I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA8I)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R8UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG8UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB8UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA8UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R16I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG16I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB16I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA16I)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R16UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG16UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB16UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA16UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R16F)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG16F)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB16F)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA16F)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R32UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG32UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB32UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA32UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R32I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG32I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB32I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA32I)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R32F)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG32F)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB32F)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA32F)] |= FormatFeature::VERTEX_ATTRIBUTE; + + // + _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; + _features[toNumber(Feature::INSTANCED_ARRAYS)] = true; + _features[toNumber(Feature::MULTIPLE_RENDER_TARGETS)] = true; + _features[toNumber(Feature::BLEND_MINMAX)] = true; + _features[toNumber(Feature::COMPUTE_SHADER)] = true; + _features[toNumber(Feature::INPUT_ATTACHMENT_BENEFIT)] = true; +} + } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDevice.h b/native/cocos/renderer/gfx-wgpu/WGPUDevice.h index a0972fb007..b9dc6bba7c 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDevice.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUDevice.h @@ -28,14 +28,13 @@ #if (CC_PLATFORM == CC_PLATFORM_WINDOWS) #include #endif - -#include -#include -#include "WGPUDef.h" +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif +#include "WGPUObject.h" #include "base/std/container/vector.h" #include "gfx-base/GFXDevice.h" -#define EMSArraysToU8Vec(v, i) (emscripten::convertJSArrayToNumberVector(v[i])) namespace cc { namespace gfx { @@ -43,22 +42,24 @@ struct CCWGPUDeviceObject; class CCWGPUSwapchain; class CCWGPUTexture; +class WGPUGeneralBarrier; -using namespace emscripten; - -class CCWGPUDevice final : public wrapper { +class CCWGPUDevice final : public Device { public: - EMSCRIPTEN_WRAPPER(CCWGPUDevice); - static CCWGPUDevice *getInstance(); + CCWGPUDevice(); ~CCWGPUDevice(); + void acquire(const std::vector &swapchains) { + return acquire(swapchains.data(), swapchains.size()); + } void acquire(Swapchain *const *swapchains, uint32_t count) override; void present() override; inline CCWGPUDeviceObject *gpuDeviceObject() { return _gpuDeviceObj; } - + inline uint8_t getCurrentFrameIndex() const { return _currentFrameIndex; } + inline CCWGPURecycleBin *recycleBin() { return &_recycleBin[_currentFrameIndex]; } inline void registerSwapchain(CCWGPUSwapchain *swapchain) { _swapchains.push_back(swapchain); } inline void unRegisterSwapchain(CCWGPUSwapchain *swapchain) { auto iter = std::find(_swapchains.begin(), _swapchains.end(), swapchain); @@ -67,74 +68,66 @@ public: } } - // ems export override - Swapchain *createSwapchain(const SwapchainInfoInstance &info) { - return Device::createSwapchain(static_cast(info)); - } + template + void moveToTrash(T t); - Framebuffer *createFramebuffer(const FramebufferInfoInstance &info) { - return Device::createFramebuffer(static_cast(info)); - } - - Texture *createTexture(const TextureInfoInstance &info) { - return Device::createTexture(static_cast(info)); - } - - Texture *createTexture(const TextureViewInfoInstance &info) { - return Device::createTexture(static_cast(info)); - } - - Buffer *createBuffer(const BufferInfoInstance &info) { - return Device::createBuffer(static_cast(info)); - } - - Buffer *createBuffer(const BufferViewInfoInstance &info) { - return Device::createBuffer(static_cast(info)); - } - - DescriptorSet *createDescriptorSet(const DescriptorSetInfoInstance &info) { - return Device::createDescriptorSet(static_cast(info)); - } - - DescriptorSetLayout *createDescriptorSetLayout(const DescriptorSetLayoutInfoInstance &info) { - return Device::createDescriptorSetLayout(static_cast(info)); - } - - InputAssembler *createInputAssembler(const InputAssemblerInfoInstance &info) { - return Device::createInputAssembler(static_cast(info)); - } - - PipelineState *createPipelineState(const PipelineStateInfoInstance &info) { - return Device::createPipelineState(static_cast(info)); - } - - CommandBuffer *createCommandBuffer(const CommandBufferInfoInstance &info) { - return Device::createCommandBuffer(static_cast(info)); - } - - emscripten::val copyTextureToBuffers(Texture *src, const BufferTextureCopyList ®ions); - - Shader *createShader(const SPVShaderInfoInstance &spvInfo); - - void copyBuffersToTexture(const emscripten::val &v, Texture *dst, const BufferTextureCopyList ®ions) { - uint32_t len = v["length"].as(); - ccstd::vector> lifeProlonger(len); - ccstd::vector buffers; - for (size_t i = 0; i < len; i++) { - lifeProlonger[i] = EMSArraysToU8Vec(v, i); - buffers.push_back(lifeProlonger[i].data()); - } - - return copyBuffersToTexture(buffers.data(), dst, regions.data(), regions.size()); - } + // CCWGPUStagingBuffer *stagingBuffer() { + // return _stagingBuffers[_currentFrameIndex]; + // } void debug(); + using Device::createBuffer; + using Device::createDescriptorSet; + using Device::createDescriptorSetLayout; + using Device::createFramebuffer; + using Device::createInputAssembler; + using Device::createPipelineLayout; + using Device::createPipelineState; + using Device::createRenderPass; + using Device::createShader; + using Device::createSwapchain; + using Device::createTexture; + using Device::getGeneralBarrier; + using Device::getSampler; + using Device::initialize; + + Shader *createShader(const ShaderInfo &, const std::vector> &); + + void copyBuffersToTexture(const std::vector> &buffers, Texture *dst, const std::vector ®ions) { + std::vector datas(buffers.size()); + for (size_t i = 0; i < buffers.size(); ++i) { + datas[i] = buffers[i].data(); + } + return copyBuffersToTexture(datas.data(), dst, regions.data(), regions.size()); + } + uint32_t getGFXAPI() const { + return static_cast(Device::getGfxAPI()); + }; + uint32_t hasFeature(uint32_t feature) { + return static_cast(Device::hasFeature(Feature{feature})); + }; + inline MemoryStatus getMemStatus() const { + return _memoryStatus; + } + uint32_t getFormatFeatures(uint32_t format) { + return static_cast(Device::getFormatFeatures(Format{format})); + }; + + // ems export override + EXPORT_EMS( + void copyTextureToBuffers(Texture *src, const emscripten::val &buffers, const emscripten::val ®ions); + emscripten::val copyTextureToBuffers(Texture * src, const BufferTextureCopyList ®ions); + Shader * createShader(const ShaderInfo &info, const emscripten::val &spirvVal); + void copyBuffersToTexture(const emscripten::val &v, Texture *dst, const std::vector ®ions);) + + void initFeatures(); + void initLimits(); + void initConfigs(); + protected: static CCWGPUDevice *instance; - CCWGPUDevice(); - bool doInit(const DeviceInfo &info) override; void doDestroy() override; CommandBuffer *createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; @@ -157,10 +150,28 @@ protected: void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) override; void getQueryPoolResults(QueryPool *queryPool) override; + uint8_t _currentFrameIndex{0}; CCWGPUDeviceObject *_gpuDeviceObj = nullptr; ccstd::vector _swapchains; + + CCWGPURecycleBin _recycleBin[CC_WGPU_MAX_FRAME_COUNT]; }; +template <> +inline void CCWGPUDevice::moveToTrash(WGPUBuffer t) { + _recycleBin[_currentFrameIndex].bufferBin.collect(t); +} + +template <> +inline void CCWGPUDevice::moveToTrash(WGPUTexture t) { + _recycleBin[_currentFrameIndex].textureBin.collect(t); +} + +template <> +inline void CCWGPUDevice::moveToTrash(WGPUQuerySet t) { + _recycleBin[_currentFrameIndex].queryBin.collect(t); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUEMSImpl.cpp b/native/cocos/renderer/gfx-wgpu/WGPUEMSImpl.cpp new file mode 100644 index 0000000000..fbe6da4a0e --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/WGPUEMSImpl.cpp @@ -0,0 +1,161 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include "WGPUBuffer.h" +#include "WGPUCommandBuffer.h" +#include "WGPUDef.h" +#include "WGPUDescriptorSet.h" +#include "WGPUDescriptorSetLayout.h" +#include "WGPUDevice.h" +#include "WGPUFrameBuffer.h" +#include "WGPUInputAssembler.h" +#include "WGPUQueue.h" +#include "WGPURenderPass.h" +#include "WGPUSampler.h" +#include "WGPUShader.h" +#include "WGPUSwapchain.h" +#include "WGPUTexture.h" +#include "gfx-base/GFXDef-common.h" +#include "states/WGPUBufferBarrier.h" +#include "states/WGPUGeneralBarrier.h" +#include "states/WGPUTextureBarrier.h" +namespace cc::gfx { + +using ::emscripten::allow_raw_pointers; +// using ::emscripten::convertJSArrayToNumberVector_local; +using ::emscripten::val; + +#define CACHE_NAME(r, _, property) \ + const val BOOST_PP_CAT(property, _val){BOOST_PP_STRINGIZE(property)}; + +#define CACHE_EMS_VAL(...) \ + BOOST_PP_SEQ_FOR_EACH(CACHE_NAME, _, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); + +CACHE_EMS_VAL(length) + +template +std::vector convertJSArrayToNumberVector_local(const val& v) { + const size_t l = v[length_val].as(); + + std::vector rv; + rv.resize(l); + + // Copy the array into our vector through the use of typed arrays. + // It will try to convert each element through Number(). + // See https://www.ecma-international.org/ecma-262/6.0/#sec-%typedarray%.prototype.set-array-offset + // and https://www.ecma-international.org/ecma-262/6.0/#sec-tonumber + val memoryView{emscripten::typed_memory_view(l, rv.data())}; + memoryView.call("set", v); + + return rv; +} + +template +std::vector vecFromJSArray_local(const val& v) { + const size_t l = v[length_val].as(); + + std::vector rv; + rv.reserve(l); + for (size_t i = 0; i < l; ++i) { + rv.push_back(v[i].as()); + } + + return rv; +} + +#define UNREACHABLE_CONDITION CC_ASSERT(false); + +#define NUMARGS(...) (sizeof((int[]){__VA_ARGS__}) / sizeof(int)) + +#define ASSIGN_PROERTY_BY_SEQ(r, obj, property) \ + if (!ems_##obj[BOOST_PP_CAT(property, _val)].isUndefined() && !ems_##obj[BOOST_PP_CAT(property, _val)].isNull()) { \ + obj.property = decltype(obj.property){ems_##obj[BOOST_PP_CAT(property, _val)].as::type>(allow_raw_pointers())}; \ + } + +#define ASSIGN_FROM_EMS(obj, ...) \ + { \ + BOOST_PP_SEQ_FOR_EACH(ASSIGN_PROERTY_BY_SEQ, obj, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); \ + } + +#define SET_PROERTY_BY_SEQ(r, obj, property) \ + ems_##obj.set(BOOST_STRINGIZE(property), static_cast::type>(obj.property)); + +#define SET_TO_EMS(obj, ...) \ + { \ + BOOST_PP_SEQ_FOR_EACH(SET_PROERTY_BY_SEQ, obj, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); \ + } + +#define ASSIGN_VEC_BY_SEQ(r, obj, property) \ + obj.property = std::move(convertJSArrayToNumberVector_local(ems_##obj[#property])); + +#define ASSIGN_FROM_EMSARRAY(obj, ...) \ + { \ + BOOST_PP_SEQ_FOR_EACH(ASSIGN_VEC_BY_SEQ, obj, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); \ + } + +#ifdef CC_DEBUG + #define CHECK_VOID(v) \ + if (v.isUndefined() || v.isNull()) { \ + return; \ + } + + #define CHECK_PTR(v) \ + if (v.isUndefined() || v.isNull()) { \ + return nullptr; \ + } +#else + #define CHECK_VOID(v) + #define CHECK_PTR(v) +#endif + +#define EMSArraysToU8Vec(v, i) (convertJSArrayToNumberVector_local(v[i])) + +void CCWGPUCommandBuffer::updateBuffer(Buffer* buff, const emscripten::val& v, uint32_t size) { + ccstd::vector buffer = convertJSArrayToNumberVector_local(v); + updateBuffer(buff, reinterpret_cast(buffer.data()), size); +} + +void CCWGPUBuffer::update(const val& v, uint32_t size) { + // this is the most fastest way from js array to vector now + ccstd::vector buffer = convertJSArrayToNumberVector_local(v); + update(reinterpret_cast(buffer.data()), size); +} + +void CCWGPUDevice::copyTextureToBuffers(Texture* src, const emscripten::val& buffers, const emscripten::val& regions) { + // @hana-alice +} + +Shader* CCWGPUDevice::createShader(const ShaderInfo& info, const emscripten::val& spirvVal) { + CHECK_PTR(spirvVal); + + auto len = spirvVal[length_val].as(); + std::vector> spvData; + for (size_t i = 0; i < len; ++i) { + spvData.emplace_back(std::move(convertJSArrayToNumberVector_local(spirvVal[i]))); + } + + auto* shader = new CCWGPUShader(); + // shader->initialize(shaderInfo); + shader->initialize(info, spvData); + return shader; +} + +void CCWGPUDevice::copyBuffersToTexture(const emscripten::val& v, Texture* dst, const std::vector& regions) { + CHECK_VOID(v); + auto len = v[length_val].as(); + len = v[length_val].as(); + std::vector> lifeProlonger(len); + std::vector buffers; + for (size_t i = 0; i < len; i++) { + lifeProlonger[i] = EMSArraysToU8Vec(v, i); + buffers.push_back(lifeProlonger[i].data()); + } + + return copyBuffersToTexture(buffers.data(), dst, regions.data(), regions.size()); +} + +} // namespace cc::gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUExports.h b/native/cocos/renderer/gfx-wgpu/WGPUExports.h index b02a3dea3d..e0f54bfb25 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUExports.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUExports.h @@ -15,970 +15,245 @@ #include "WGPUShader.h" #include "WGPUSwapchain.h" #include "WGPUTexture.h" +#include "boost/pfr.hpp" +#include "boost/type_index.hpp" +#include "states/WGPUBufferBarrier.h" +#include "states/WGPUGeneralBarrier.h" +#include "states/WGPUTextureBarrier.h" + +REGISTER_GFX_PTRS_FOR_STRUCT(Device, Buffer, Texture, GeneralBarrier, Queue, RenderPass, Shader, PipelineLayout, DescriptorSetLayout, CommandBuffer, DescriptorSet); -// #define OBJECT_EXPORT(c) \ -// static c c##Instance() { return c(); } namespace cc::gfx { -template -struct GenInstance { - static T instance() { - return T(); - } -}; +using ::emscripten::allow_raw_pointer; +using ::emscripten::allow_raw_pointers; +using ::emscripten::arg; +using ::emscripten::base; +using ::emscripten::class_; +using ::emscripten::constant; +using ::emscripten::enum_; +using ::emscripten::function; +using ::emscripten::pure_virtual; +using ::emscripten::register_vector; +using ::emscripten::select_overload; +using ::emscripten::val; +using ::emscripten::value_object; -// template -// struct GenInstances { -// OBJECT_EXPORT(T); -// GenInstance; -// }; - -// template -// struct GenInstances { -// OBJECT_EXPORT(T); -// }; - -// GenInstances; +using String = ccstd::string; +using ccstd::vector; EMSCRIPTEN_BINDINGS(WEBGPU_DEVICE_WASM_EXPORT) { - // TODO_Zeqiang: compile time traverse enum - - //------------------------------------------------ENUM------------------------------------------------------------ - enum_("Format") - .value("UNKNOWN", Format::UNKNOWN) - .value("A8", Format::A8) - .value("L8", Format::L8) - .value("LA8", Format::LA8) - .value("R8", Format::R8) - .value("R8SN", Format::R8SN) - .value("R8UI", Format::R8UI) - .value("R8I", Format::R8I) - .value("R16F", Format::R16F) - .value("R16UI", Format::R16UI) - .value("R16I", Format::R16I) - .value("R32F", Format::R32F) - .value("R32UI", Format::R32UI) - .value("R32I", Format::R32I) - .value("RG8", Format::RG8) - .value("RG8SN", Format::RG8SN) - .value("RG8UI", Format::RG8UI) - .value("RG8I", Format::RG8I) - .value("RG16F", Format::RG16F) - .value("RG16UI", Format::RG16UI) - .value("RG16I", Format::RG16I) - .value("RG32F", Format::RG32F) - .value("RG32UI", Format::RG32UI) - .value("RG32I", Format::RG32I) - .value("RGB8", Format::RGB8) - .value("SRGB8", Format::SRGB8) - .value("RGB8SN", Format::RGB8SN) - .value("RGB8UI", Format::RGB8UI) - .value("RGB8I", Format::RGB8I) - .value("RGB16F", Format::RGB16F) - .value("RGB16UI", Format::RGB16UI) - .value("RGB16I", Format::RGB16I) - .value("RGB32F", Format::RGB32F) - .value("RGB32UI", Format::RGB32UI) - .value("RGB32I", Format::RGB32I) - .value("RGBA8", Format::RGBA8) - .value("BGRA8", Format::BGRA8) - .value("SRGB8_A8", Format::SRGB8_A8) - .value("RGBA8SN", Format::RGBA8SN) - .value("RGBA8UI", Format::RGBA8UI) - .value("RGBA8I", Format::RGBA8I) - .value("RGBA16F", Format::RGBA16F) - .value("RGBA16UI", Format::RGBA16UI) - .value("RGBA16I", Format::RGBA16I) - .value("RGBA32F", Format::RGBA32F) - .value("RGBA32UI", Format::RGBA32UI) - .value("RGBA32I", Format::RGBA32I) - .value("R5G6B5", Format::R5G6B5) - .value("R11G11B10F", Format::R11G11B10F) - .value("RGB5A1", Format::RGB5A1) - .value("RGBA4", Format::RGBA4) - .value("RGB10A2", Format::RGB10A2) - .value("RGB10A2UI", Format::RGB10A2UI) - .value("RGB9E5", Format::RGB9E5) - .value("DEPTH", Format::DEPTH) - .value("DEPTH_STENCIL", Format::DEPTH_STENCIL) - .value("BC1", Format::BC1) - .value("BC1_ALPHA", Format::BC1_ALPHA) - .value("BC1_SRGB", Format::BC1_SRGB) - .value("BC1_SRGB_ALPHA", Format::BC1_SRGB_ALPHA) - .value("BC2", Format::BC2) - .value("BC2_SRGB", Format::BC2_SRGB) - .value("BC3", Format::BC3) - .value("BC3_SRGB", Format::BC3_SRGB) - .value("BC4", Format::BC4) - .value("BC4_SNORM", Format::BC4_SNORM) - .value("BC5", Format::BC5) - .value("BC5_SNORM", Format::BC5_SNORM) - .value("BC6H_UF16", Format::BC6H_UF16) - .value("BC6H_SF16", Format::BC6H_SF16) - .value("BC7", Format::BC7) - .value("BC7_SRGB", Format::BC7_SRGB) - .value("ETC_RGB8", Format::ETC_RGB8) - .value("ETC2_RGB8", Format::ETC2_RGB8) - .value("ETC2_SRGB8", Format::ETC2_SRGB8) - .value("ETC2_RGB8_A1", Format::ETC2_RGB8_A1) - .value("ETC2_SRGB8_A1", Format::ETC2_SRGB8_A1) - .value("ETC2_RGBA8", Format::ETC2_RGBA8) - .value("ETC2_SRGB8_A8", Format::ETC2_SRGB8_A8) - .value("EAC_R11", Format::EAC_R11) - .value("EAC_R11SN", Format::EAC_R11SN) - .value("EAC_RG11", Format::EAC_RG11) - .value("EAC_RG11SN", Format::EAC_RG11SN) - .value("PVRTC_RGB2", Format::PVRTC_RGB2) - .value("PVRTC_RGBA2", Format::PVRTC_RGBA2) - .value("PVRTC_RGB4", Format::PVRTC_RGB4) - .value("PVRTC_RGBA4", Format::PVRTC_RGBA4) - .value("PVRTC2_2BPP", Format::PVRTC2_2BPP) - .value("PVRTC2_4BPP", Format::PVRTC2_4BPP) - .value("ASTC_RGBA_4X4", Format::ASTC_RGBA_4X4) - .value("ASTC_RGBA_5X4", Format::ASTC_RGBA_5X4) - .value("ASTC_RGBA_5X5", Format::ASTC_RGBA_5X5) - .value("ASTC_RGBA_6X5", Format::ASTC_RGBA_6X5) - .value("ASTC_RGBA_6X6", Format::ASTC_RGBA_6X6) - .value("ASTC_RGBA_8X5", Format::ASTC_RGBA_8X5) - .value("ASTC_RGBA_8X6", Format::ASTC_RGBA_8X6) - .value("ASTC_RGBA_8X8", Format::ASTC_RGBA_8X8) - .value("ASTC_RGBA_10X5", Format::ASTC_RGBA_10X5) - .value("ASTC_RGBA_10X6", Format::ASTC_RGBA_10X6) - .value("ASTC_RGBA_10X8", Format::ASTC_RGBA_10X8) - .value("ASTC_RGBA_10X10", Format::ASTC_RGBA_10X10) - .value("ASTC_RGBA_12X10", Format::ASTC_RGBA_12X10) - .value("ASTC_RGBA_12X12", Format::ASTC_RGBA_12X12) - .value("ASTC_SRGBA_4X4", Format::ASTC_SRGBA_4X4) - .value("ASTC_SRGBA_5X4", Format::ASTC_SRGBA_5X4) - .value("ASTC_SRGBA_5X5", Format::ASTC_SRGBA_5X5) - .value("ASTC_SRGBA_6X5", Format::ASTC_SRGBA_6X5) - .value("ASTC_SRGBA_6X6", Format::ASTC_SRGBA_6X6) - .value("ASTC_SRGBA_8X5", Format::ASTC_SRGBA_8X5) - .value("ASTC_SRGBA_8X6", Format::ASTC_SRGBA_8X6) - .value("ASTC_SRGBA_8X8", Format::ASTC_SRGBA_8X8) - .value("ASTC_SRGBA_10X5", Format::ASTC_SRGBA_10X5) - .value("ASTC_SRGBA_10X6", Format::ASTC_SRGBA_10X6) - .value("ASTC_SRGBA_10X8", Format::ASTC_SRGBA_10X8) - .value("ASTC_SRGBA_10X10", Format::ASTC_SRGBA_10X10) - .value("ASTC_SRGBA_12X10", Format::ASTC_SRGBA_12X10) - .value("ASTC_SRGBA_12X12", Format::ASTC_SRGBA_12X12) - .value("COUNT", Format::COUNT); - - enum_("VsyncMode") - .value("OFF", VsyncMode::OFF) - .value("ON", VsyncMode::ON) - .value("RELAXED", VsyncMode::RELAXED) - .value("MAILBOX", VsyncMode::MAILBOX) - .value("HALF", VsyncMode::HALF); - - enum_("SampleCount") - .value("ONE", SampleCount::ONE) - .value("MULTIPLE_PERFORMANCE", SampleCount::MULTIPLE_PERFORMANCE) - .value("MULTIPLE_BALANCE", SampleCount::MULTIPLE_BALANCE) - .value("MULTIPLE_QUALITY", SampleCount::MULTIPLE_QUALITY); - - enum_("LoadOp") - .value("LOAD", LoadOp::LOAD) - .value("CLEAR", LoadOp::CLEAR) - .value("DISCARD", LoadOp::DISCARD); - - enum_("StoreOp") - .value("STORE", StoreOp::STORE) - .value("DISCARD", StoreOp::DISCARD); - - enum_("AccessType") - .value("NONE", AccessType::NONE) - .value("INDIRECT_BUFFER", AccessType::INDIRECT_BUFFER) - .value("INDEX_BUFFER", AccessType::INDEX_BUFFER) - .value("VERTEX_BUFFER", AccessType::VERTEX_BUFFER) - .value("VERTEX_SHADER_READ_UNIFORM_BUFFER", AccessType::VERTEX_SHADER_READ_UNIFORM_BUFFER) - .value("VERTEX_SHADER_READ_TEXTURE", AccessType::VERTEX_SHADER_READ_TEXTURE) - .value("VERTEX_SHADER_READ_OTHER", AccessType::VERTEX_SHADER_READ_OTHER); - - enum_("ResolveMode") - .value("NONE", ResolveMode::NONE) - .value("SAMPLE_ZERO", ResolveMode::SAMPLE_ZERO) - .value("AVERAGE", ResolveMode::AVERAGE) - .value("MIN", ResolveMode::MIN) - .value("MAX", ResolveMode::MAX); - - enum_("TextureType") - .value("TEX1D", TextureType::TEX1D) - .value("TEX2D", TextureType::TEX2D) - .value("TEX3D", TextureType::TEX3D) - .value("CUBE", TextureType::CUBE) - .value("TEX1D_ARRAY", TextureType::TEX1D_ARRAY) - .value("TEX2D_ARRAY", TextureType::TEX2D_ARRAY); - - enum_("TextureUsage") - .value("NONE", TextureUsageBit::NONE) - .value("TRANSFER_SRC", TextureUsageBit::TRANSFER_SRC) - .value("TRANSFER_DST", TextureUsageBit::TRANSFER_DST) - .value("SAMPLED", TextureUsageBit::SAMPLED) - .value("STORAGE", TextureUsageBit::STORAGE) - .value("COLOR_ATTACHMENT", TextureUsageBit::COLOR_ATTACHMENT) - .value("DEPTH_STENCIL_ATTACHMENT", TextureUsageBit::DEPTH_STENCIL_ATTACHMENT) - .value("INPUT_ATTACHMENT", TextureUsageBit::INPUT_ATTACHMENT); - - enum_("TextureFlags") - .value("NONE", TextureFlagBit::NONE) - .value("GEN_MIPMAP", TextureFlagBit::GEN_MIPMAP) - .value("GENERAL_LAYOUT", TextureFlagBit::GENERAL_LAYOUT); - - enum_("SurfaceTransform") - .value("IDENTITY", SurfaceTransform::IDENTITY) - .value("ROTATE_90", SurfaceTransform::ROTATE_90) - .value("ROTATE_180", SurfaceTransform::ROTATE_180) - .value("ROTATE_270", SurfaceTransform::ROTATE_270); - - enum_("Filter") - .value("NONE", Filter::NONE) - .value("POINT", Filter::POINT) - .value("LINEAR", Filter::LINEAR) - .value("ANISOTROPIC", Filter::ANISOTROPIC); - - enum_
("Address") - .value("WRAP", Address::WRAP) - .value("MIRROR", Address::MIRROR) - .value("CLAMP", Address::CLAMP) - .value("BORDER", Address::BORDER); - - enum_("ComparisonFunc") - .value("NEVER", ComparisonFunc::NEVER) - .value("LESS", ComparisonFunc::LESS) - .value("EQUAL", ComparisonFunc::EQUAL) - .value("LESS_EQUAL", ComparisonFunc::LESS_EQUAL) - .value("GREATER", ComparisonFunc::GREATER) - .value("NOT_EQUAL", ComparisonFunc::NOT_EQUAL) - .value("GREATER_EQUAL", ComparisonFunc::GREATER_EQUAL) - .value("ALWAYS", ComparisonFunc::ALWAYS); - - enum_("BufferUsage") - .value("NONE", BufferUsageBit::NONE) - .value("TRANSFER_SRC", BufferUsageBit::TRANSFER_SRC) - .value("TRANSFER_DST", BufferUsageBit::TRANSFER_DST) - .value("INDEX", BufferUsageBit::INDEX) - .value("VERTEX", BufferUsageBit::VERTEX) - .value("UNIFORM", BufferUsageBit::UNIFORM) - .value("STORAGE", BufferUsageBit::STORAGE) - .value("INDIRECT", BufferUsageBit::INDIRECT); - - enum_("MemoryUsage") - .value("NONE", MemoryUsageBit::NONE) - .value("DEVICE", MemoryUsageBit::DEVICE) - .value("HOST", MemoryUsageBit::HOST); - - enum_("BufferFlags") - .value("NONE", BufferFlagBit::NONE); - - enum_("DescriptorType") - .value("UNKNOWN", DescriptorType::UNKNOWN) - .value("UNIFORM_BUFFER", DescriptorType::UNIFORM_BUFFER) - .value("DYNAMIC_UNIFORM_BUFFER", DescriptorType::DYNAMIC_UNIFORM_BUFFER) - .value("STORAGE_BUFFER", DescriptorType::STORAGE_BUFFER) - .value("DYNAMIC_STORAGE_BUFFER", DescriptorType::DYNAMIC_STORAGE_BUFFER) - .value("SAMPLER_TEXTURE", DescriptorType::SAMPLER_TEXTURE) - .value("SAMPLER", DescriptorType::SAMPLER) - .value("TEXTURE", DescriptorType::TEXTURE) - .value("STORAGE_IMAGE", DescriptorType::STORAGE_IMAGE) - .value("INPUT_ATTACHMENT", DescriptorType::INPUT_ATTACHMENT); - - enum_("ShaderStageFlags") - .value("NONE", ShaderStageFlagBit::NONE) - .value("VERTEX", ShaderStageFlagBit::VERTEX) - .value("CONTROL", ShaderStageFlagBit::CONTROL) - .value("EVALUATION", ShaderStageFlagBit::EVALUATION) - .value("GEOMETRY", ShaderStageFlagBit::GEOMETRY) - .value("FRAGMENT", ShaderStageFlagBit::FRAGMENT) - .value("COMPUTE", ShaderStageFlagBit::COMPUTE) - .value("ALL", ShaderStageFlagBit::ALL); - - enum_("MemoryAccess") - .value("NONE", MemoryAccessBit::NONE) - .value("READ_ONLY", MemoryAccessBit::READ_ONLY) - .value("WRITE_ONLY", MemoryAccessBit::WRITE_ONLY) - .value("READ_WRITE", MemoryAccessBit::READ_WRITE); - - enum_("Type") - .value("UNKNOWN", Type::UNKNOWN) - .value("BOOL", Type::BOOL) - .value("BOOL2", Type::BOOL2) - .value("BOOL3", Type::BOOL3) - .value("BOOL4", Type::BOOL4) - .value("INT", Type::INT) - .value("INT2", Type::INT2) - .value("INT3", Type::INT3) - .value("INT4", Type::INT4) - .value("UINT", Type::UINT) - .value("UINT2", Type::UINT2) - .value("UINT3", Type::UINT3) - .value("UINT4", Type::UINT4) - .value("FLOAT", Type::FLOAT) - .value("FLOAT2", Type::FLOAT2) - .value("FLOAT3", Type::FLOAT3) - .value("FLOAT4", Type::FLOAT4) - .value("MAT2", Type::MAT2) - .value("MAT2X3", Type::MAT2X3) - .value("MAT2X4", Type::MAT2X4) - .value("MAT3X2", Type::MAT3X2) - .value("MAT3X4", Type::MAT3X4) - .value("MAT4X2", Type::MAT4X2) - .value("MAT4X3", Type::MAT4X3) - .value("MAT4", Type::MAT4) - .value("SAMPLER1D", Type::SAMPLER1D) - .value("SAMPLER1D_ARRAY", Type::SAMPLER1D_ARRAY) - .value("SAMPLER2D", Type::SAMPLER2D) - .value("SAMPLER2D_ARRAY", Type::SAMPLER2D_ARRAY) - .value("SAMPLER3D", Type::SAMPLER3D) - .value("SAMPLER_CUBE", Type::SAMPLER_CUBE) - .value("SAMPLER", Type::SAMPLER) - .value("TEXTURE1D", Type::TEXTURE1D) - .value("TEXTURE1D_ARRAY", Type::TEXTURE1D_ARRAY) - .value("TEXTURE2D", Type::TEXTURE2D) - .value("TEXTURE2D_ARRAY", Type::TEXTURE2D_ARRAY) - .value("TEXTURE3D", Type::TEXTURE3D) - .value("TEXTURE_CUBE", Type::TEXTURE_CUBE) - .value("IMAGE1D", Type::IMAGE1D) - .value("IMAGE1D_ARRAY", Type::IMAGE1D_ARRAY) - .value("IMAGE2D", Type::IMAGE2D) - .value("IMAGE2D_ARRAY", Type::IMAGE2D_ARRAY) - .value("IMAGE3D", Type::IMAGE3D) - .value("IMAGE_CUBE", Type::IMAGE_CUBE) - .value("IMAGE3D", Type::IMAGE3D) - .value("SUBPASS_INPUT", Type::SUBPASS_INPUT) - .value("COUNT", Type::COUNT); - - enum_("PolygonMode") - .value("FILL", PolygonMode::FILL) - .value("POINT", PolygonMode::POINT) - .value("LINE", PolygonMode::LINE); - - enum_("ShadeModel") - .value("GOURAND", ShadeModel::GOURAND) - .value("FLAT", ShadeModel::FLAT); - - enum_("CullMode") - .value("NONE", CullMode::NONE) - .value("FRONT", CullMode::FRONT) - .value("BACK", CullMode::BACK); - - enum_("StencilOp") - .value("ZERO", StencilOp::ZERO) - .value("KEEP", StencilOp::KEEP) - .value("REPLACE", StencilOp::REPLACE) - .value("INCR", StencilOp::INCR) - .value("DECR", StencilOp::DECR) - .value("INVERT", StencilOp::INVERT) - .value("INCR_WRAP", StencilOp::INCR_WRAP) - .value("DECR_WRAP", StencilOp::DECR_WRAP); - - enum_("BlendFactor") - .value("ZERO", BlendFactor::ZERO) - .value("ONE", BlendFactor::ONE) - .value("SRC_ALPHA", BlendFactor::SRC_ALPHA) - .value("DST_ALPHA", BlendFactor::DST_ALPHA) - .value("ONE_MINUS_SRC_ALPHA", BlendFactor::ONE_MINUS_SRC_ALPHA) - .value("ONE_MINUS_DST_ALPHA", BlendFactor::ONE_MINUS_DST_ALPHA) - .value("SRC_COLOR", BlendFactor::SRC_COLOR) - .value("DST_COLOR", BlendFactor::DST_COLOR) - .value("ONE_MINUS_SRC_COLOR", BlendFactor::ONE_MINUS_SRC_COLOR) - .value("ONE_MINUS_DST_COLOR", BlendFactor::ONE_MINUS_DST_COLOR) - .value("SRC_ALPHA_SATURATE", BlendFactor::SRC_ALPHA_SATURATE) - .value("CONSTANT_COLOR", BlendFactor::CONSTANT_COLOR) - .value("ONE_MINUS_CONSTANT_COLOR", BlendFactor::ONE_MINUS_CONSTANT_COLOR) - .value("CONSTANT_ALPHA", BlendFactor::CONSTANT_ALPHA) - .value("ONE_MINUS_CONSTANT_ALPHA", BlendFactor::ONE_MINUS_CONSTANT_ALPHA); - - enum_("BlendOp") - .value("ADD", BlendOp::ADD) - .value("SUB", BlendOp::SUB) - .value("REV_SUB", BlendOp::REV_SUB) - .value("MIN", BlendOp::MIN) - .value("MAX", BlendOp::MAX); - - enum_("ColorMask") - .value("NONE", ColorMask::NONE) - .value("R", ColorMask::R) - .value("G", ColorMask::G) - .value("B", ColorMask::B) - .value("A", ColorMask::A) - .value("ALL", ColorMask::ALL); - - enum_("PrimitiveMode") - .value("POINT_LIST", PrimitiveMode::POINT_LIST) - .value("LINE_LIST", PrimitiveMode::LINE_LIST) - .value("LINE_STRIP", PrimitiveMode::LINE_STRIP) - .value("LINE_LOOP", PrimitiveMode::LINE_LOOP) - .value("LINE_LIST_ADJACENCY", PrimitiveMode::LINE_LIST_ADJACENCY) - .value("LINE_STRIP_ADJACENCY", PrimitiveMode::LINE_STRIP_ADJACENCY) - .value("ISO_LINE_LIST", PrimitiveMode::ISO_LINE_LIST) - .value("TRIANGLE_LIST", PrimitiveMode::TRIANGLE_LIST) - .value("TRIANGLE_STRIP", PrimitiveMode::TRIANGLE_STRIP) - .value("TRIANGLE_FAN", PrimitiveMode::TRIANGLE_FAN) - .value("TRIANGLE_LIST_ADJACENCY", PrimitiveMode::TRIANGLE_LIST_ADJACENCY) - .value("TRIANGLE_STRIP_ADJACENCY", PrimitiveMode::TRIANGLE_STRIP_ADJACENCY) - .value("TRIANGLE_PATCH_ADJACENCY", PrimitiveMode::TRIANGLE_PATCH_ADJACENCY) - .value("QUAD_PATCH_LIST", PrimitiveMode::QUAD_PATCH_LIST); - - enum_("DynamicStateFlagBit") - .value("NONE", DynamicStateFlagBit::NONE) - .value("LINE_WIDTH", DynamicStateFlagBit::LINE_WIDTH) - .value("DEPTH_BIAS", DynamicStateFlagBit::DEPTH_BIAS) - .value("BLEND_CONSTANTS", DynamicStateFlagBit::BLEND_CONSTANTS) - .value("DEPTH_BOUNDS", DynamicStateFlagBit::DEPTH_BOUNDS) - .value("STENCIL_WRITE_MASK", DynamicStateFlagBit::STENCIL_WRITE_MASK) - .value("STENCIL_COMPARE_MASK", DynamicStateFlagBit::STENCIL_COMPARE_MASK); - - enum_("PipelineBindPoint") - .value("GRAPHICS", PipelineBindPoint::GRAPHICS) - .value("COMPUTE", PipelineBindPoint::COMPUTE) - .value("RAY_TRACING", PipelineBindPoint::RAY_TRACING); - - enum_("QueueType") - .value("GRAPHICS", QueueType::GRAPHICS) - .value("COMPUTE", QueueType::COMPUTE) - .value("TRANSFER", QueueType::TRANSFER); - - //-----------------------------------------------STRUCT------------------------------------------------------------------- - value_object("ColorAttachment") - .field("format", &ColorAttachment::format) - .field("sampleCount", &ColorAttachment::sampleCount) - .field("loadOp", &ColorAttachment::loadOp) - .field("storeOp", &ColorAttachment::storeOp) - .field("beginAccesses", &ColorAttachment::beginAccesses) - .field("endAccesses", &ColorAttachment::endAccesses) - .field("isGeneralLayout", &ColorAttachment::isGeneralLayout); - function("ColorAttachmentInstance", &GenInstance::instance); - - value_object("DepthStencilAttachment") - .field("format", &DepthStencilAttachment::format) - .field("sampleCount", &DepthStencilAttachment::sampleCount) - .field("depthLoadOp", &DepthStencilAttachment::depthLoadOp) - .field("depthStoreOp", &DepthStencilAttachment::depthStoreOp) - .field("stencilLoadOp", &DepthStencilAttachment::stencilLoadOp) - .field("stencilStoreOp", &DepthStencilAttachment::stencilStoreOp) - .field("beginAccesses", &DepthStencilAttachment::beginAccesses) - .field("endAccesses", &DepthStencilAttachment::endAccesses) - .field("isGeneralLayout", &DepthStencilAttachment::isGeneralLayout); - function("DepthStencilAttachmentInstance", &GenInstance::instance); - - value_object("SubpassInfo") - .field("inputs", &SubpassInfo::inputs) - .field("colors", &SubpassInfo::colors) - .field("resolves", &SubpassInfo::resolves) - .field("preserves", &SubpassInfo::preserves) - .field("depthStencil", &SubpassInfo::depthStencil) - .field("depthStencilResolve", &SubpassInfo::depthStencilResolve) - .field("depthResolveMode", &SubpassInfo::depthResolveMode) - .field("stencilResolveMode", &SubpassInfo::stencilResolveMode); - function("SubpassInfoInstance", &GenInstance::instance); - - value_object("SubpassDependency") - .field("srcSubpass", &SubpassDependency::srcSubpass) - .field("dstSubpass", &SubpassDependency::dstSubpass) - .field("srcAccesses", &SubpassDependency::srcAccesses) - .field("dstAccesses", &SubpassDependency::dstAccesses); - function("SubpassDependencyInstance", &GenInstance::instance); - - value_object("RenderPassInfo") - .field("colorAttachments", &RenderPassInfo::colorAttachments) - .field("depthStencilAttachment", &RenderPassInfo::depthStencilAttachment) - .field("subpasses", &RenderPassInfo::subpasses) - .field("dependencies", &RenderPassInfo::dependencies); - function("RenderPassInfoInstance", &GenInstance::instance); - - value_object("BindingMappingInfo") - .field("bufferOffsets", &BindingMappingInfo::bufferOffsets) - .field("samplerOffsets", &BindingMappingInfo::samplerOffsets) - .field("flexibleSet", &BindingMappingInfo::flexibleSet); - function("BindingMappingInfoInstance", &GenInstance::instance); - - value_object("DeviceInfo") - .field("bindingMappingInfo", &DeviceInfo::bindingMappingInfo); - function("DeviceInfoInstance", &GenInstance::instance); - - value_object("Offset") - .field("x", &Offset::x) - .field("y", &Offset::y) - .field("z", &Offset::z); - function("OffsetInstance", &GenInstance::instance); - - value_object("Extent") - .field("width", &Extent::width) - .field("height", &Extent::height) - .field("depth", &Extent::depth); - function("ExtentInstance", &GenInstance::instance); - - value_object("TextureSubresLayers") - .field("mipLevel", &TextureSubresLayers::mipLevel) - .field("baseArrayLayer", &TextureSubresLayers::baseArrayLayer) - .field("layerCount", &TextureSubresLayers::layerCount); - function("TextureSubresLayersInstance", &GenInstance::instance); - - value_object("BufferTextureCopy") - .field("buffStride", &BufferTextureCopy::buffStride) - .field("buffTexHeight", &BufferTextureCopy::buffTexHeight) - .field("texOffset", &BufferTextureCopy::texOffset) - .field("texExtent", &BufferTextureCopy::texExtent) - .field("texSubres", &BufferTextureCopy::texSubres); - function("BufferTextureCopyInstance", &GenInstance::instance); - - value_object("SamplerInfo") - .field("minFilter", &SamplerInfo::minFilter) - .field("magFilter", &SamplerInfo::magFilter) - .field("mipFilter", &SamplerInfo::mipFilter) - .field("addressU", &SamplerInfo::addressU) - .field("addressV", &SamplerInfo::addressV) - .field("addressW", &SamplerInfo::addressW) - .field("maxAnisotropy", &SamplerInfo::maxAnisotropy) - .field("cmpFunc", &SamplerInfo::cmpFunc); - function("SamplerInfoInstance", &GenInstance::instance); - - // value_object("BufferInfo") - // .field("usage", &BufferInfo::usage) - // .field("memUsage", &BufferInfo::memUsage) - // .field("size", &BufferInfo::size) - // .field("stride", &BufferInfo::stride) - // .field("flags", &BufferInfo::flags); - // function("BufferInfoInstance", &GenInstance::instance); - - // value_object("DescriptorSetLayoutInfo") - // .field("bindings", &DescriptorSetLayoutInfo::bindings); - // function("DescriptorSetLayoutInfoInstance", &GenInstance::instance); - - // value_object("DescriptorSetLayoutBinding") - // .field("binding", &DescriptorSetLayoutBinding::binding) - // .field("descriptorType", &DescriptorSetLayoutBinding::descriptorType) - // .field("count", &DescriptorSetLayoutBinding::count) - // .field("stageFlags", &DescriptorSetLayoutBinding::stageFlags) - // .field("immutableSamplers", &DescriptorSetLayoutBinding::immutableSamplers); - // function("DescriptorSetLayoutBindingInstance", &GenInstance::instance); - - value_object("PipelineLayoutInfo") - .field("setLayouts", &PipelineLayoutInfo::setLayouts); - function("PipelineLayoutInfoInstance", &GenInstance::instance); - - value_object("UniformStorageImage") - .field("set", &UniformStorageImage::set) - .field("binding", &UniformStorageImage::binding) - .field("name", &UniformStorageImage::name) - .field("type", &UniformStorageImage::type) - .field("count", &UniformStorageImage::count) - .field("memoryAccess", &UniformStorageImage::memoryAccess); - function("UniformStorageImageInstance", &GenInstance::instance); - - value_object("ShaderStage") - .field("stage", &ShaderStage::stage) - .field("source", &ShaderStage::source); - function("ShaderStageInstance", &GenInstance::instance); - - value_object("Attribute") - .field("name", &Attribute::name) - .field("format", &Attribute::format) - .field("isNormalized", &Attribute::isNormalized) - .field("stream", &Attribute::stream) - .field("isInstanced", &Attribute::isInstanced) - .field("location", &Attribute::location); - function("AttributeInstance", &GenInstance::instance); - - value_object("Uniform") - .field("name", &Uniform::name) - .field("type", &Uniform::type) - .field("count", &Uniform::count); - function("UniformInstance", &GenInstance::instance); - - value_object("UniformBlock") - .field("set", &UniformBlock::set) - .field("binding", &UniformBlock::binding) - .field("name", &UniformBlock::name) - .field("members", &UniformBlock::members) - .field("count", &UniformBlock::count); - function("UniformBlockInstance", &GenInstance::instance); - - value_object("UniformStorageBuffer") - .field("set", &UniformStorageBuffer::set) - .field("binding", &UniformStorageBuffer::binding) - .field("name", &UniformStorageBuffer::name) - .field("count", &UniformStorageBuffer::count) - .field("memoryAccess", &UniformStorageBuffer::memoryAccess); - function("UniformStorageBufferInstance", &GenInstance::instance); - - value_object("UniformSamplerTexture") - .field("set", &UniformSamplerTexture::set) - .field("binding", &UniformSamplerTexture::binding) - .field("name", &UniformSamplerTexture::name) - .field("type", &UniformSamplerTexture::type) - .field("count", &UniformSamplerTexture::count); - function("UniformSamplerTextureInstance", &GenInstance::instance); - - value_object("UniformSampler") - .field("set", &UniformSampler::set) - .field("binding", &UniformSampler::binding) - .field("name", &UniformSampler::name) - .field("count", &UniformSampler::count); - function("UniformSamplerInstance", &GenInstance::instance); - - value_object("UniformTexture") - .field("set", &UniformTexture::set) - .field("binding", &UniformTexture::binding) - .field("name", &UniformTexture::name) - .field("type", &UniformTexture::type) - .field("count", &UniformTexture::count); - function("UniformTextureInstance", &GenInstance::instance); - - value_object("UniformInputAttachment") - .field("set", &UniformInputAttachment::set) - .field("binding", &UniformInputAttachment::binding) - .field("name", &UniformInputAttachment::name) - .field("count", &UniformInputAttachment::count); - function("UniformInputAttachmentInstance", &GenInstance::instance); - - value_object("ShaderInfo") - .field("name", &ShaderInfo::name) - .field("stages", &ShaderInfo::stages) - .field("attributes", &ShaderInfo::attributes) - .field("blocks", &ShaderInfo::blocks) - .field("buffers", &ShaderInfo::buffers) - .field("samplerTextures", &ShaderInfo::samplerTextures) - .field("samplers", &ShaderInfo::samplers) - .field("textures", &ShaderInfo::textures) - .field("images", &ShaderInfo::images) - .field("subpassInputs", &ShaderInfo::subpassInputs); - function("ShaderInfoInstance", &GenInstance::instance); - - value_object("InputState") - .field("attributes", &InputState::attributes); - function("InputStateInstance", &GenInstance::instance); - - value_object("RasterizerState") - .field("isDiscard", &RasterizerState::isDiscard) - .field("polygonMode", &RasterizerState::polygonMode) - .field("shadeModel", &RasterizerState::shadeModel) - .field("cullMode", &RasterizerState::cullMode) - .field("isFrontFaceCCW", &RasterizerState::isFrontFaceCCW) - .field("depthBiasEnabled", &RasterizerState::depthBiasEnabled) - .field("depthBias", &RasterizerState::depthBias) - .field("depthBiasClamp", &RasterizerState::depthBiasClamp) - .field("depthBiasSlop", &RasterizerState::depthBiasSlop) - .field("isDepthClip", &RasterizerState::isDepthClip) - .field("isMultisample", &RasterizerState::isMultisample) - .field("lineWidth", &RasterizerState::lineWidth); - function("RasterizerStateInstance", &GenInstance::instance); - - value_object("DepthStencilState") - .field("depthTest", &DepthStencilState::depthTest) - .field("depthWrite", &DepthStencilState::depthWrite) - .field("depthFunc", &DepthStencilState::depthFunc) - .field("stencilTestFront", &DepthStencilState::stencilTestFront) - .field("stencilFuncFront", &DepthStencilState::stencilFuncFront) - .field("stencilReadMaskFront", &DepthStencilState::stencilReadMaskFront) - .field("stencilWriteMaskFront", &DepthStencilState::stencilWriteMaskFront) - .field("stencilFailOpFront", &DepthStencilState::stencilFailOpFront) - .field("stencilZFailOpFront", &DepthStencilState::stencilZFailOpFront) - .field("stencilPassOpFront", &DepthStencilState::stencilPassOpFront) - .field("stencilRefFront", &DepthStencilState::stencilRefFront) - .field("stencilFuncBack", &DepthStencilState::stencilFuncBack) - .field("stencilReadMaskBack", &DepthStencilState::stencilReadMaskBack) - .field("stencilWriteMaskBack", &DepthStencilState::stencilWriteMaskBack) - .field("stencilFailOpBack", &DepthStencilState::stencilFailOpBack) - .field("stencilZFailOpBack", &DepthStencilState::stencilZFailOpBack) - .field("stencilPassOpBack", &DepthStencilState::stencilPassOpBack) - .field("stencilRefBack", &DepthStencilState::stencilRefBack); - function("DepthStencilStateInstance", &GenInstance::instance); - - value_object("BlendTarget") - .field("blend", &BlendTarget::blend) - .field("blendSrc", &BlendTarget::blendSrc) - .field("blendDst", &BlendTarget::blendDst) - .field("blendEq", &BlendTarget::blendEq) - .field("blendSrcAlpha", &BlendTarget::blendSrcAlpha) - .field("blendDstAlpha", &BlendTarget::blendDstAlpha) - .field("blendAlphaEq", &BlendTarget::blendAlphaEq) - .field("blendColorMask", &BlendTarget::blendColorMask); - function("BlendTargetInstance", &GenInstance::instance); - - value_object("BlendState") - .field("isA2C", &BlendState::isA2C) - .field("isIndepend", &BlendState::isIndepend) - .field("blendColor", &BlendState::blendColor) - .field("targets", &BlendState::targets); - function("BlendStateInstance", &GenInstance::instance); - - value_object("Color") - .field("x", &Color::x) - .field("y", &Color::y) - .field("z", &Color::z) - .field("w", &Color::w); - function("Color", &GenInstance::instance); - - value_object("QueueInfo") - .field("type", &QueueInfo::type); - function("QueueInfo", &GenInstance::instance); - - value_object("Rect") - .field("x", &Rect::x) - .field("y", &Rect::y) - .field("width", &Rect::width) - .field("height", &Rect::height); - function("Rect", &GenInstance::instance); - - value_object("Viewport") - .field("left", &Viewport::left) - .field("top", &Viewport::top) - .field("width", &Viewport::width) - .field("height", &Viewport::height) - .field("minDepth", &Viewport::minDepth) - .field("maxDepth", &Viewport::maxDepth); - function("Viewport", &GenInstance::instance); - - value_object("DrawInfo") - .field("vertexCount", &DrawInfo::vertexCount) - .field("firstVertex", &DrawInfo::firstVertex) - .field("indexCount", &DrawInfo::indexCount) - .field("firstIndex", &DrawInfo::firstIndex) - .field("vertexOffset", &DrawInfo::vertexOffset) - .field("instanceCount", &DrawInfo::instanceCount) - .field("firstInstance", &DrawInfo::firstInstance); - function("DrawInfo", &GenInstance::instance); - - value_object("TextureBlit") - .field("srcSubres", &TextureBlit::srcSubres) - .field("srcOffset", &TextureBlit::srcOffset) - .field("srcExtent", &TextureBlit::srcExtent) - .field("dstSubres", &TextureBlit::dstSubres) - .field("dstOffset", &TextureBlit::dstOffset) - .field("dstExtent", &TextureBlit::dstExtent); - function("TextureBlit", &GenInstance::instance); - - // struct with pointers - class_("TextureInfoInstance") - .constructor<>() - .function("setType", &TextureInfoInstance::setType) - .function("setUsage", &TextureInfoInstance::setUsage) - .function("setFormat", &TextureInfoInstance::setFormat) - .function("setWidth", &TextureInfoInstance::setWidth) - .function("setHeight", &TextureInfoInstance::setHeight) - .function("setFlags", &TextureInfoInstance::setFlags) - .function("setLevelCount", &TextureInfoInstance::setLevelCount) - .function("setLayerCount", &TextureInfoInstance::setLayerCount) - .function("setSamples", &TextureInfoInstance::setSamples) - .function("setDepth", &TextureInfoInstance::setDepth) - .function("setImageBuffer", &TextureInfoInstance::setImageBuffer, allow_raw_pointer>()); - - class_("TextureViewInfoInstance") - .constructor<>() - .function("setTexture", &TextureViewInfoInstance::setTexture, allow_raw_pointer>()) - .function("setType", &TextureViewInfoInstance::setType) - .function("setFormat", &TextureViewInfoInstance::setFormat) - .function("setBaseLevel", &TextureViewInfoInstance::setBaseLevel) - .function("setLevelCount", &TextureViewInfoInstance::setLevelCount) - .function("setBaseLayer", &TextureViewInfoInstance::setBaseLayer) - .function("setLayerCount", &TextureViewInfoInstance::setLayerCount); - - class_("FramebufferInfoInstance") - .constructor<>() - .function("setRenderPass", &FramebufferInfoInstance::setRenderPass, allow_raw_pointer>()) - .function("setColorTextures", &FramebufferInfoInstance::setColorTextures, allow_raw_pointer>()) - .function("setDepthStencilTexture", &FramebufferInfoInstance::setDepthStencilTexture, allow_raw_pointer>()); - - class_("SwapchainInfoInstance") - .constructor<>() - .function("setWindowHandle", &SwapchainInfoInstance::setWindowHandle) - .function("setVsyncMode", &SwapchainInfoInstance::setVsyncMode) - .function("setWidth", &SwapchainInfoInstance::setWidth) - .function("setHeight", &SwapchainInfoInstance::setHeight); - - class_("BufferViewInfoInstance") - .constructor<>() - .function("setBuffer", &BufferViewInfoInstance::setBuffer, allow_raw_pointer>()) - .function("setOffset", &BufferViewInfoInstance::setOffset) - .function("setRange", &BufferViewInfoInstance::setRange); - - class_("DescriptorSetInfoInstance") - .constructor<>() - .function("setDescriptorSetLayout", &DescriptorSetInfoInstance::setDescriptorSetLayout, allow_raw_pointer>()); - - class_("PipelineStateInfoInstance") - .constructor<>() - .function("setShader", &PipelineStateInfoInstance::setShader, allow_raw_pointer>()) - .function("setPipelineLayout", &PipelineStateInfoInstance::setPipelineLayout, allow_raw_pointer>()) - .function("setRenderPass", &PipelineStateInfoInstance::setRenderPass, allow_raw_pointer>()) - .function("setInputState", &PipelineStateInfoInstance::setInputState) - .function("setRasterizerState", &PipelineStateInfoInstance::setRasterizerState) - .function("setDepthStencilState", &PipelineStateInfoInstance::setDepthStencilState) - .function("setBlendState", &PipelineStateInfoInstance::setBlendState) - .function("setPrimitiveMode", &PipelineStateInfoInstance::setPrimitiveMode) - .function("setDynamicStateFlags", &PipelineStateInfoInstance::setDynamicStateFlags) - .function("setPipelineBindPoint", &PipelineStateInfoInstance::setPipelineBindPoint) - .function("setSubpass", &PipelineStateInfoInstance::setSubpass); - - class_("InputAssemblerInfoInstance") - .constructor<>() - .function("setAttributes", &InputAssemblerInfoInstance::setAttributes) - .function("setBuffers", &InputAssemblerInfoInstance::setBuffers) - .function("setIndexBuffer", &InputAssemblerInfoInstance::setIndexBuffer, allow_raw_pointer>()) - .function("setIndirectBuffer", &InputAssemblerInfoInstance::setIndirectBuffer, allow_raw_pointer>()); - - class_("CommandBufferInfoInstance") - .constructor<>() - .function("setQueue", &CommandBufferInfoInstance::setQueue, allow_raw_pointer>()) - .function("setType", &CommandBufferInfoInstance::setType, allow_raw_pointer>()); - - class_("SPVShaderInfoInstance") - .constructor<>() - .function("setName", &SPVShaderInfoInstance::setName) - .function("setStages", &SPVShaderInfoInstance::setStages) - .function("setAttributes", &SPVShaderInfoInstance::setAttributes) - .function("setBlocks", &SPVShaderInfoInstance::setBlocks) - .function("setBuffers", &SPVShaderInfoInstance::setBuffers) - .function("setSamplerTextures", &SPVShaderInfoInstance::setSamplerTextures) - .function("setTextures", &SPVShaderInfoInstance::setTextures) - .function("setSamplers", &SPVShaderInfoInstance::setSamplers) - .function("setImages", &SPVShaderInfoInstance::setImages) - .function("setSubpasses", &SPVShaderInfoInstance::setSubpasses); - - class_("SPVShaderStageInstance") - .constructor<>() - .function("setStage", &SPVShaderStageInstance::setStage) - .function("setSPVData", &SPVShaderStageInstance::setSPVData); - - class_("DescriptorSetLayoutBindingInstance") - .constructor<>() - .function("setBinding", &DescriptorSetLayoutBindingInstance::setBinding) - .function("setDescriptorType", &DescriptorSetLayoutBindingInstance::setDescriptorType) - .function("setCount", &DescriptorSetLayoutBindingInstance::setCount) - .function("setStageFlags", &DescriptorSetLayoutBindingInstance::setStageFlags) - .function("setImmutableSamplers", &DescriptorSetLayoutBindingInstance::setImmutableSamplers); - - class_("BufferInfoInstance") - .constructor<>() - .function("setUsage", &BufferInfoInstance::setUsage) - .function("setMemUsage", &BufferInfoInstance::setMemUsage) - .function("setSize", &BufferInfoInstance::setSize) - .function("setStride", &BufferInfoInstance::setStride) - .function("setFlags", &BufferInfoInstance::setFlags); - - class_("DescriptorSetLayoutInfoInstance") - .constructor<>() - .function("setBindings", &DescriptorSetLayoutInfoInstance::setBindings); - + // register_vector("Uint32Vector"); + + EXPORT_STRUCT_POD(Size, x, y, z); + EXPORT_STRUCT_POD(DeviceCaps, maxVertexAttributes, maxVertexUniformVectors, maxFragmentUniformVectors, maxTextureUnits, maxImageUnits, maxVertexTextureUnits, maxColorRenderTargets, + maxShaderStorageBufferBindings, maxShaderStorageBlockSize, maxUniformBufferBindings, maxUniformBlockSize, maxTextureSize, maxCubeMapTextureSize, uboOffsetAlignment, + maxComputeSharedMemorySize, maxComputeWorkGroupInvocations, maxComputeWorkGroupSize, maxComputeWorkGroupCount, supportQuery, clipSpaceMinZ, screenSpaceSignY, clipSpaceSignY); + EXPORT_STRUCT_POD(Offset, x, y, z); + EXPORT_STRUCT_POD(Rect, x, y, width, height); + EXPORT_STRUCT_POD(Extent, width, height, depth); + EXPORT_STRUCT_POD(TextureSubresLayers, mipLevel, baseArrayLayer, layerCount); + EXPORT_STRUCT_POD(TextureCopy, srcSubres, srcOffset, dstSubres, dstOffset, extent); + EXPORT_STRUCT_POD(TextureBlit, srcSubres, srcOffset, srcExtent, dstSubres, dstOffset, dstExtent); + EXPORT_STRUCT_POD(BufferTextureCopy, buffOffset, buffStride, buffTexHeight, texOffset, texExtent, texSubres); + EXPORT_STRUCT_POD(Viewport, left, top, width, height, minDepth, maxDepth); + EXPORT_STRUCT_POD(Color, x, y, z, w); + EXPORT_STRUCT_POD(BindingMappingInfo, maxBlockCounts, maxSamplerTextureCounts, maxSamplerCounts, maxTextureCounts, maxBufferCounts, maxImageCounts, maxSubpassInputCounts, setIndices); + // SwapchainInfo ignore windowHandle + EXPORT_STRUCT_NPOD(SwapchainInfo, vsyncMode, width, height); + EXPORT_STRUCT_POD(DeviceInfo, bindingMappingInfo); + EXPORT_STRUCT_POD(BufferInfo, usage, memUsage, size, stride, flags); + EXPORT_STRUCT_NPOD(BufferViewInfo, buffer, offset, range); + EXPORT_STRUCT_POD(DrawInfo, vertexCount, firstVertex, indexCount, firstIndex, vertexOffset, instanceCount, firstInstance); + EXPORT_STRUCT_NPOD(DispatchInfo, groupCountX, groupCountY, groupCountZ, indirectBuffer, indirectOffset); + EXPORT_STRUCT_POD(IndirectBuffer, drawInfos); + EXPORT_STRUCT_NPOD(TextureInfo, type, usage, format, width, height, flags, layerCount, levelCount, samples, depth, externalRes); + EXPORT_STRUCT_NPOD(TextureViewInfo, texture, type, format, baseLevel, levelCount, baseLayer, layerCount); + EXPORT_STRUCT_POD(SamplerInfo, minFilter, magFilter, mipFilter, addressU, addressV, addressW, maxAnisotropy, cmpFunc); + EXPORT_STRUCT_POD(Uniform, name, type, count); + EXPORT_STRUCT_POD(UniformBlock, set, binding, name, members, count); + EXPORT_STRUCT_POD(UniformSamplerTexture, set, binding, name, type, count); + EXPORT_STRUCT_POD(UniformSampler, set, binding, name, count); + EXPORT_STRUCT_POD(UniformTexture, set, binding, name, type, count); + EXPORT_STRUCT_POD(UniformStorageImage, set, binding, name, type, count, memoryAccess); + EXPORT_STRUCT_POD(UniformStorageBuffer, set, binding, name, count, memoryAccess); + EXPORT_STRUCT_POD(UniformInputAttachment, set, binding, name, count); + EXPORT_STRUCT_POD(ShaderStage, stage, source); + EXPORT_STRUCT_POD(Attribute, name, format, isNormalized, stream, isInstanced, location); + EXPORT_STRUCT_POD(ShaderInfo, name, stages, attributes, blocks, buffers, samplerTextures, samplers, textures, images, subpassInputs); + EXPORT_STRUCT_NPOD(InputAssemblerInfo, attributes, vertexBuffers, indexBuffer, indirectBuffer); + EXPORT_STRUCT_NPOD(ColorAttachment, format, sampleCount, loadOp, storeOp, barrier, isGeneralLayout); + EXPORT_STRUCT_NPOD(DepthStencilAttachment, format, sampleCount, depthLoadOp, depthStoreOp, stencilLoadOp, stencilStoreOp, barrier, isGeneralLayout); + EXPORT_STRUCT_POD(SubpassInfo, inputs, colors, resolves, preserves, depthStencil, depthStencilResolve, depthResolveMode, stencilResolveMode); + + // MAYBE TODO(Zeqiang): all ts related backend no need to care about barriers. + EXPORT_STRUCT_POD(SubpassDependency, srcSubpass, dstSubpass, bufferBarrierCount, textureBarrierCount); + EXPORT_STRUCT_POD(RenderPassInfo, colorAttachments, depthStencilAttachment, subpasses, dependencies); + EXPORT_STRUCT_POD(GeneralBarrierInfo, prevAccesses, nextAccesses, type); + EXPORT_STRUCT_NPOD(TextureBarrierInfo, prevAccesses, nextAccesses, type, baseMipLevel, levelCount, baseSlice, sliceCount, discardContents, srcQueue, dstQueue); + EXPORT_STRUCT_NPOD(BufferBarrierInfo, prevAccesses, nextAccesses, type, offset, size, discardContents, srcQueue, dstQueue); + EXPORT_STRUCT_NPOD(FramebufferInfo, renderPass, colorTextures, depthStencilTexture); + EXPORT_STRUCT_NPOD(DescriptorSetLayoutBinding, binding, descriptorType, count, stageFlags, immutableSamplers); + EXPORT_STRUCT_POD(DescriptorSetLayoutInfo, bindings); + EXPORT_STRUCT_NPOD(DescriptorSetInfo, layout); + EXPORT_STRUCT_NPOD(PipelineLayoutInfo, setLayouts); + EXPORT_STRUCT_POD(InputState, attributes); + EXPORT_STRUCT_POD(RasterizerState, isDiscard, polygonMode, shadeModel, cullMode, isFrontFaceCCW, depthBiasEnabled, depthBias, depthBiasClamp, depthBiasSlop, isDepthClip, isMultisample, lineWidth); + EXPORT_STRUCT_POD(DepthStencilState, depthTest, depthWrite, depthFunc, stencilTestFront, stencilFuncFront, stencilReadMaskFront, stencilWriteMaskFront, stencilFailOpFront, stencilZFailOpFront, stencilPassOpFront, + stencilRefFront, stencilTestBack, stencilFuncBack, stencilReadMaskBack, stencilWriteMaskBack, stencilFailOpBack, stencilZFailOpBack, stencilPassOpBack, stencilRefBack); + EXPORT_STRUCT_POD(BlendTarget, blend, blendSrc, blendDst, blendEq, blendSrcAlpha, blendDstAlpha, blendAlphaEq, blendColorMask); + EXPORT_STRUCT_POD(BlendState, isA2C, isIndepend, blendColor, targets) + // MAYBE TODO(Zeqiang): no subpass in TS now + EXPORT_STRUCT_NPOD(PipelineStateInfo, shader, pipelineLayout, renderPass, inputState, rasterizerState, depthStencilState, blendState, primitive, dynamicStates, bindPoint); + EXPORT_STRUCT_NPOD(CommandBufferInfo, queue); + EXPORT_STRUCT_POD(QueueInfo, type); + EXPORT_STRUCT_POD(QueryPoolInfo, type, maxQueryObjects, forceWait); + // EXPORT_STRUCT_POD(FormatInfo, name, size, count, type, hasAlpha, hasDepth, hasStencil, isCompressed); + EXPORT_STRUCT_POD(MemoryStatus, bufferSize, textureSize); + EXPORT_STRUCT_POD(DynamicStencilStates, writeMask, compareMask, reference); + EXPORT_STRUCT_POD(DynamicStates, viewport, scissor, blendConstant, lineWidth, depthBiasConstant, depthBiasClamp, depthBiasSlope, depthMinBounds, depthMaxBounds, stencilStatesFront, stencilStatesBack); //--------------------------------------------------CLASS--------------------------------------------------------------------------- - class_("Swapchain") - .function("initialize", &cc::gfx::Swapchain::initialize, allow_raw_pointer>()) - .function("destroy", &cc::gfx::Swapchain::destroy) - .function("resize", select_overload(&cc::gfx::Swapchain::resize)) - .function("destroySurface", &cc::gfx::Swapchain::destroySurface) - .function("createSurface", &cc::gfx::Swapchain::createSurface, allow_raw_pointer>()) - .function("getWidth", &cc::gfx::Swapchain::getWidth) - .function("getHeight", &cc::gfx::Swapchain::getHeight); + class_("Swapchain") + .function("initialize", &Swapchain::initialize, allow_raw_pointer>()) + .function("destroy", &Swapchain::destroy) + .function("resize", select_overload(&Swapchain::resize)) + .function("destroySurface", &Swapchain::destroySurface) + .function("createSurface", &Swapchain::createSurface, allow_raw_pointer>()) + .property("width", &Swapchain::getWidth) + .property("height", &Swapchain::getHeight) + .property("surfaceTransform", &Swapchain::getSurfaceTransform) + .property("objectID", &Swapchain::getObjectID); class_>("CCWGPUSwapchain") - .function("getColorTexture", select_overload(&cc::gfx::CCWGPUSwapchain::getColorTexture), allow_raw_pointer>()) - .function("getDepthStencilTexture", select_overload(&cc::gfx::CCWGPUSwapchain::getDepthStencilTexture), allow_raw_pointer>()); + .property("depthStencilTexture", &CCWGPUSwapchain::getDepthStencilTexture, &CCWGPUSwapchain::setDepthStencilTexture) + .property("colorTexture", &CCWGPUSwapchain::getColorTexture, &CCWGPUSwapchain::setColorTexture); class_("Device") - .function("initialize", &Device::initialize, allow_raw_pointer>()) + .function("initialize", &Device::initialize) .function("destroy", &Device::destroy, pure_virtual()) .function("present", &Device::present, pure_virtual()) - .function("createQueue", select_overload(&Device::createQueue), - /* pure_virtual(), */ allow_raw_pointer>()) + .function("createQueue", select_overload(&Device::createQueue), allow_raw_pointer>()) + .function("createSwapchain", select_overload(&Device::createSwapchain), allow_raw_pointer>()) + .function("createRenderPass", select_overload(&Device::createRenderPass)) + .function("createFramebuffer", select_overload(&Device::createFramebuffer), allow_raw_pointer>()) + .function("createBuffer", select_overload(&Device::createBuffer), allow_raw_pointer>()) + .function("createBufferView", select_overload(&Device::createBuffer), allow_raw_pointer>()) + .function("createTexture", select_overload(&Device::createTexture), allow_raw_pointer>()) + .function("createTextureView", select_overload(&Device::createTexture), allow_raw_pointer>()) + .function("createDescriptorSetLayout", select_overload(&Device::createDescriptorSetLayout), allow_raw_pointer>()) + .function("createInputAssembler", select_overload(&Device::createInputAssembler), allow_raw_pointer>()) + .function("createPipelineState", select_overload(&Device::createPipelineState), allow_raw_pointer>()) + .function("createDescriptorSet", select_overload(&Device::createDescriptorSet), allow_raw_pointer>()) + .function("createPipelineLayout", select_overload(&Device::createPipelineLayout), allow_raw_pointer>()) .function("getSampler", &Device::getSampler, allow_raw_pointer>()) - .function("createRenderPass", select_overload(&Device::createRenderPass), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createPipelineLayout", select_overload(&Device::createPipelineLayout), - /* pure_virtual(), */ allow_raw_pointer>()) - // .function("createGlobalBarrier", select_overload(&Device::createGlobalBarrier), - // /* pure_virtual(), */ allow_raw_pointer>()) + .function("getGeneralBarrier", &Device::getGeneralBarrier, allow_raw_pointer>()) // .function("createTextureBarrier", select_overload(&Device::createTextureBarrier), // /* pure_virtual(), */ allow_raw_pointer>()) - .function("getCommandBuffer", &Device::getCommandBuffer, allow_raw_pointers()) - .function("getQueue", &Device::getQueue, allow_raw_pointers()) - .function("acquire", select_overload &)>(&Device::acquire), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("present", select_overload(&Device::present), - /* pure_virtual(), */ allow_raw_pointer>()); + // .function("flushCommands", &Device::flushCommands, allow_raw_pointers()) + .function("present", select_overload(&Device::present)) + .property("queue", &Device::getQueue) + .property("commandBuffer", &Device::getCommandBuffer) + .property("capabilities", &Device::getCapabilities) + .property("name", &Device::getDeviceName) + .property("renderer", &Device::getRenderer) + .property("vendor", &Device::getVendor) + .property("numDrawCalls", &Device::getNumDrawCalls) + .property("numInstances", &Device::getNumInstances) + .property("numTris", &Device::getNumTris); class_>("CCWGPUDevice") - .class_function("getInstance", &CCWGPUDevice::getInstance, allow_raw_pointer>()) - .function("debug", &CCWGPUDevice::debug) - .function("createSwapchain", select_overload(&CCWGPUDevice::createSwapchain), - /* pure_virtual(), */ allow_raw_pointers()) - .function("createCommandBuffer", select_overload(&CCWGPUDevice::createCommandBuffer), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createFramebuffer", select_overload(&CCWGPUDevice::createFramebuffer), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createBuffer", select_overload(&CCWGPUDevice::createBuffer), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createBufferView", select_overload(&CCWGPUDevice::createBuffer), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createTexture", select_overload(&CCWGPUDevice::createTexture), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createTextureView", select_overload(&CCWGPUDevice::createTexture), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createShader", select_overload(&CCWGPUDevice::createShader), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createDescriptorSetLayout", select_overload(&CCWGPUDevice::createDescriptorSetLayout), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createInputAssembler", select_overload(&CCWGPUDevice::createInputAssembler), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createPipelineState", select_overload(&CCWGPUDevice::createPipelineState), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createDescriptorSet", select_overload(&CCWGPUDevice::createDescriptorSet), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("copyTextureToBuffers", select_overload(&CCWGPUDevice::copyTextureToBuffers), - /* pure_virtual(), */ allow_raw_pointers()) - .function("copyBuffersToTexture", select_overload(&CCWGPUDevice::copyBuffersToTexture), - /* pure_virtual(), */ allow_raw_pointers()); - - class_("RenderPass") - .class_function("computeHash", select_overload(&RenderPass::computeHash), allow_raw_pointer>()) - .function("initialize", &cc::gfx::RenderPass::initialize, allow_raw_pointer>()) - .function("destroy", &cc::gfx::RenderPass::destroy) - .function("getColorAttachments", &cc::gfx::RenderPass::getColorAttachments) - .function("DepthStencilAttachment", &cc::gfx::RenderPass::getDepthStencilAttachment) - .function("SubpassInfoList", &cc::gfx::RenderPass::getSubpasses) - .function("SubpassDependencyList", &cc::gfx::RenderPass::getDependencies) - .function("getHash", &cc::gfx::RenderPass::getHash); - class_>("CCWGPURenderPass") + // .class_function("getInstance", &CCWGPUDevice::getInstance, allow_raw_pointer>()) .constructor<>() - .function("getThis", select_overload(&cc::gfx::getThis), allow_raw_pointer>()); + .function("debug", &CCWGPUDevice::debug) - class_("Texture") + .function("acquire", select_overload &)>(&CCWGPUDevice::acquire), + /* pure_virtual(), */ allow_raw_pointer>()) + .function("createShaderNative", select_overload(&CCWGPUDevice::createShader), + /* pure_virtual(), */ allow_raw_pointer>()) + .function("copyTextureToBuffers", select_overload(&CCWGPUDevice::copyTextureToBuffers), + /* pure_virtual(), */ allow_raw_pointers()) + .function("copyBuffersToTexture", select_overload &)>(&CCWGPUDevice::copyBuffersToTexture), + /* pure_virtual(), */ allow_raw_pointers()) + .function("getFormatFeatures", select_overload(&CCWGPUDevice::getFormatFeatures)) + .function("hasFeature", &CCWGPUDevice::hasFeature) + .property("gfxAPI", &CCWGPUDevice::getGFXAPI) + .property("memoryStatus", &CCWGPUDevice::getMemStatus); + + class_("RenderPass") + .class_function("computeHash", select_overload(&RenderPass::computeHash), allow_raw_pointer>()) + .function("destroy", &RenderPass::destroy) + .function("initialize", select_overload(&CCWGPURenderPass::initialize), allow_raw_pointer>()) + .property("colorAttachments", &RenderPass::getColorAttachments) + .property("depthStencilAttachment", &RenderPass::getDepthStencilAttachment) + .property("subpasses", &RenderPass::getSubpasses) + .property("dependencies", &RenderPass::getDependencies) + .property("hash", &RenderPass::getHash) + .property("objectID", &RenderPass::getObjectID); + class_>("CCWGPURenderPass") + .constructor<>(); + + class_("Texture") .class_function("computeHash", select_overload(&Texture::computeHash), allow_raw_pointer>()) - .function("initialize", select_overload(&cc::gfx::Texture::initialize), allow_raw_pointer>()) - .function("initialize", select_overload(&cc::gfx::Texture::initialize), allow_raw_pointer>()) - .function("destroy", &cc::gfx::Texture::destroy) - .function("resize", &cc::gfx::Texture::resize); - class_>("CCWGPUTexture") + .function("initialize", select_overload(&Texture::initialize), allow_raw_pointer>()) + .function("initializeView", select_overload(&Texture::initialize), allow_raw_pointer>()) + .function("destroy", &Texture::destroy) + .function("resize", &Texture::resize) + .function("getInfo", &Texture::getInfo) + .function("getViewInfo", &Texture::getViewInfo) + .property("width", &Texture::getWidth) + .property("height", &Texture::getHeight) + .property("size", &Texture::getSize) + .property("isTextureView", &Texture::isTextureView) + .property("objectID", &Texture::getObjectID); + class_>("CCWGPUTexture") + .property("depth", &CCWGPUTexture::getDepth) + .property("layerCount", &CCWGPUTexture::getLayerCount) + .property("levelCount", &CCWGPUTexture::getLevelCount) + .property("type", &CCWGPUTexture::getTextureType) + .property("usage", &CCWGPUTexture::getTextureUsage) + .property("format", &CCWGPUTexture::getTextureFormat) + .property("samples", &CCWGPUTexture::getTextureSamples) + .property("flags", &CCWGPUTexture::getTextureFlags) .constructor<>(); - class_("Framebuffer") + class_("Framebuffer") .class_function("computeHash", select_overload(&Framebuffer::computeHash), allow_raw_pointer>()) - .function("initialize", &cc::gfx::Framebuffer::initialize, allow_raw_pointer>()) - .function("destroy", &cc::gfx::Framebuffer::destroy) - .function("getRenderPass", &cc::gfx::Framebuffer::getRenderPass, allow_raw_pointer>()) - .function("getColorTextures", &cc::gfx::Framebuffer::getColorTextures, allow_raw_pointer>()) - .function("getDepthStencilTexture", &cc::gfx::Framebuffer::getDepthStencilTexture, allow_raw_pointer>()); + .function("destroy", &Framebuffer::destroy) + .function("initialize", &Framebuffer::initialize, allow_raw_pointer>()) + .property("objectID", &Framebuffer::getObjectID); class_>("CCWGPUFramebuffer") - .constructor<>(); + .constructor<>() + .property("renderPass", &CCWGPUFramebuffer::getRenderPass, &CCWGPUFramebuffer::setRenderPass) + .property("colorTextures", &CCWGPUFramebuffer::getColorTextures, &CCWGPUFramebuffer::setColorTextures) + .property("depthStencilTexture", &CCWGPUFramebuffer::getDepthStencilTexture, &CCWGPUFramebuffer::setDepthStencilTexture); class_("Sampler") - .function("getInfo", &Sampler::getInfo); + .function("getInfo", &Sampler::getInfo) + .property("hash", &Sampler::getHash) + .property("objectID", &Sampler::getObjectID); class_>("CCWGPUSampler") .constructor(); class_("Buffer") - .function("initialize", select_overload(&Buffer::initialize), allow_raw_pointer>()) - .function("initialize", select_overload(&Buffer::initialize), allow_raw_pointer>()) .function("resize", &Buffer::resize) - .function("destroy", &Buffer::destroy); + .function("destroy", &Buffer::destroy) + .property("size", &Buffer::getSize) + .property("stride", &Buffer::getStride) + .property("count", &Buffer::getCount) + .property("usage", &Buffer::getUsage) + .property("memUsage", &Buffer::getMemUsage) + .property("flags", &Buffer::getFlags) + .property("objectID", &Buffer::getObjectID); class_>("CCWGPUBuffer") - .function("update", select_overload(&CCWGPUBuffer::update), allow_raw_pointer>()) - .function("updateDrawInfo", select_overload(&CCWGPUBuffer::update), allow_raw_pointer>()) + // .function("update", select_overload(&CCWGPUBuffer::update), allow_raw_pointer>()) + .function("update", select_overload(&CCWGPUBuffer::update)) .constructor<>(); class_("DescriptorSetLayout") .function("initialize", &DescriptorSetLayout::initialize) - .function("destroy", &DescriptorSetLayout::destroy); + .function("destroy", &DescriptorSetLayout::destroy) + .property("bindings", &DescriptorSetLayout::getBindings) + .property("bindingIndices", &DescriptorSetLayout::getBindingIndices) + .property("descriptorIndices", &DescriptorSetLayout::getDescriptorIndices) + .property("objectID", &DescriptorSetLayout::getObjectID); class_>("CCWGPUDescriptorSetLayout") .constructor<>(); @@ -987,110 +262,148 @@ EMSCRIPTEN_BINDINGS(WEBGPU_DEVICE_WASM_EXPORT) { .function("destroy", &DescriptorSet::destroy) .function("update", &DescriptorSet::update) .function("bindBuffer", select_overload(&DescriptorSet::bindBuffer), allow_raw_pointer>()) + .function("bindBuffer", select_overload(&DescriptorSet::bindBuffer), allow_raw_pointer>()) .function("bindTexture", select_overload(&DescriptorSet::bindTexture), allow_raw_pointer>()) - .function("bindSampler", select_overload(&DescriptorSet::bindSampler), allow_raw_pointer>()); + .function("bindTexture", select_overload(&DescriptorSet::bindTexture), allow_raw_pointer>()) + .function("bindSampler", select_overload(&DescriptorSet::bindSampler), allow_raw_pointer>()) + .function("bindSampler", select_overload(&DescriptorSet::bindSampler), allow_raw_pointer>()) + .function("getBuffer", select_overload(&DescriptorSet::getBuffer), allow_raw_pointers()) + .function("getBuffer", select_overload(&DescriptorSet::getBuffer), allow_raw_pointers()) + .function("getTexture", select_overload(&DescriptorSet::getTexture), allow_raw_pointers()) + .function("getTexture", select_overload(&DescriptorSet::getTexture), allow_raw_pointers()) + .function("getSampler", select_overload(&DescriptorSet::getSampler), allow_raw_pointers()) + .function("getSampler", select_overload(&DescriptorSet::getSampler), allow_raw_pointers()) + .property("layout", &DescriptorSet::getLayout) + .property("objectID", &DescriptorSet::getObjectID); class_>("CCWGPUDescriptorSet") .constructor<>(); class_("PipelineLayout") .function("initialize", &PipelineLayout::initialize) - .function("destroy", &PipelineLayout::destroy); + .function("destroy", &PipelineLayout::destroy) + .property("setLayouts", &PipelineLayout::getSetLayouts) + .property("objectID", &PipelineLayout::getObjectID); class_>("CCWGPUPipelineLayout") .constructor<>(); class_("Shader") .function("initialize", &Shader::initialize) - .function("destroy", &Shader::destroy); + .function("destroy", &Shader::destroy) + .property("name", &Shader::getName) + .property("attributes", &Shader::getAttributes) + .property("blocks", &Shader::getBlocks) + .property("samplers", &Shader::getSamplers) + .property("stages", &Shader::getStages) + .property("buffers", &Shader::getBuffers) + .property("samplerTextures", &Shader::getSamplerTextures) + .property("textures", &Shader::getTextures) + .property("images", &Shader::getImages) + .property("subpassInputs", &Shader::getSubpassInputs) + .property("objectID", &Shader::getObjectID); class_>("CCWGPUShader") .constructor<>(); class_("InputAssembler") .function("initialize", &InputAssembler::initialize) - .function("destroy", &InputAssembler::destroy); + .function("destroy", &InputAssembler::destroy) + .property("drawInfo", &InputAssembler::getDrawInfo, &InputAssembler::setDrawInfo) + .property("vertexCount", &InputAssembler::getVertexCount, &InputAssembler::setVertexCount) + .property("firstVertex", &InputAssembler::getFirstVertex, &InputAssembler::setFirstVertex) + .property("indexCount", &InputAssembler::getIndexCount, &InputAssembler::setIndexCount) + .property("firstIndex", &InputAssembler::getFirstIndex, &InputAssembler::setFirstIndex) + .property("vertexOffset", &InputAssembler::getVertexOffset, &InputAssembler::setVertexOffset) + .property("instanceCount", &InputAssembler::getInstanceCount, &InputAssembler::setInstanceCount) + .property("firstInstance", &InputAssembler::getFirstInstance, &InputAssembler::setFirstInstance) + .property("attributesHash", &InputAssembler::getAttributesHash) + .property("attributes", &InputAssembler::getAttributes) + .property("vertexBuffers", &InputAssembler::getVertexBuffers) + .property("indexBuffer", &InputAssembler::getIndexBuffer) + .property("indirectBuffer", &InputAssembler::getIndirectBuffer) + .property("objectID", &InputAssembler::getObjectID); class_>("CCWGPUInputAssembler") - .function("update", &CCWGPUInputAssembler::update) .constructor<>(); class_("CommandBuffer") .function("initialize", &CommandBuffer::initialize) .function("destroy", &CommandBuffer::destroy) - .function("begin", select_overload(&CommandBuffer::begin), allow_raw_pointers()) .function("end", &CommandBuffer::end) .function("endRenderPass", &CommandBuffer::endRenderPass) - .function("bindPipelineState", &CommandBuffer::bindPipelineState, allow_raw_pointer>()) - .function("bindDescriptorSet", select_overload &)>(&CommandBuffer::bindDescriptorSet), allow_raw_pointers()) - .function("bindInputAssembler", &CommandBuffer::bindInputAssembler, allow_raw_pointer>()) - .function("setViewport", &CommandBuffer::setViewport) - .function("setScissor", &CommandBuffer::setScissor) .function("setDepthBias", &CommandBuffer::setDepthBias) .function("setBlendConstants", &CommandBuffer::setBlendConstants) .function("setDepthBound", &CommandBuffer::setDepthBound) .function("setStencilWriteMask", &CommandBuffer::setStencilWriteMask) .function("setStencilCompareMask", &CommandBuffer::setStencilCompareMask) .function("nextSubpass", &CommandBuffer::nextSubpass) - .function("draw", select_overload(&CommandBuffer::draw)) .function("copyBuffersToTexture", select_overload(&CommandBuffer::copyBuffersToTexture), allow_raw_pointers()) .function("blitTexture", select_overload(&CommandBuffer::blitTexture), allow_raw_pointers()) .function("execute", select_overload(&CommandBuffer::execute), allow_raw_pointer>()) .function("dispatch", &CommandBuffer::dispatch) - .function("begin4", select_overload(&CommandBuffer::begin)) - .function("begin3", select_overload(&CommandBuffer::begin), allow_raw_pointers()) - .function("begin2", select_overload(&CommandBuffer::begin), allow_raw_pointers()) - .function("execute", select_overload(&CommandBuffer::execute)) - .function("bindDescriptorSet2", select_overload(&CommandBuffer::bindDescriptorSet), allow_raw_pointer>()) - .function("drawIA", select_overload(&CommandBuffer::draw), allow_raw_pointer>()) + .function("begin", select_overload(&CommandBuffer::begin)) + .function("begin", select_overload(&CommandBuffer::begin), allow_raw_pointers()) + .function("begin", select_overload(&CommandBuffer::begin), allow_raw_pointers()) + .function("begin", select_overload(&CommandBuffer::begin), allow_raw_pointers()) + .function("execute", select_overload(&CommandBuffer::execute), allow_raw_pointers()) .function("blitTexture2", select_overload(&CommandBuffer::blitTexture), allow_raw_pointers()) - .function("getQueue", &CommandBuffer::getQueue, allow_raw_pointer>()); + .function("draw", select_overload(&CommandBuffer::draw), allow_raw_pointers()) + .function("type", &CommandBuffer::getType) + .property("queue", &CommandBuffer::getQueue) + .property("numDrawCalls", &CommandBuffer::getNumDrawCalls) + .property("numInstances", &CommandBuffer::getNumInstances) + .property("numTris", &CommandBuffer::getNumTris) + .property("objectID", &CommandBuffer::getObjectID); class_>("CCWGPUCommandBuffer") .constructor<>() + .function("setViewport", select_overload(&CCWGPUCommandBuffer::setViewport)) + .function("setScissor", select_overload(&CCWGPUCommandBuffer::setScissor)) .function("beginRenderPass", select_overload(&CCWGPUCommandBuffer::beginRenderPass), allow_raw_pointers()) + .function("bindDescriptorSet", select_overload &)>(&CCWGPUCommandBuffer::bindDescriptorSet), allow_raw_pointers()) + .function("bindPipelineState", select_overload(&CCWGPUCommandBuffer::bindPipelineState), allow_raw_pointer>()) + .function("bindInputAssembler", select_overload(&CCWGPUCommandBuffer::bindInputAssembler), allow_raw_pointer>()) + .function("drawByInfo", select_overload(&CCWGPUCommandBuffer::draw)) .function("updateIndirectBuffer", select_overload(&CCWGPUCommandBuffer::updateIndirectBuffer), allow_raw_pointers()) .function("updateBuffer", select_overload(&CCWGPUCommandBuffer::updateBuffer), allow_raw_pointers()); class_("Queue") .function("initialize", &Queue::initialize) .function("destroy", &Queue::destroy) - .function("submit", select_overload(&Queue::submit)); - class_("CCWGPUQueue") + .function("submit", select_overload(&Queue::submit)) + .property("type", &Queue::getType) + .property("objectID", &Queue::getObjectID); + class_>("CCWGPUQueue") .constructor<>(); class_("PipelineState") .function("initialize", &Queue::initialize) - .function("destroy", &Queue::destroy); - class_("CCWGPUPipelineState") + .function("destroy", &Queue::destroy) + .property("shader", &PipelineState::getShader) + .property("pipelineLayout", &PipelineState::getPipelineLayout) + .property("primitive", &PipelineState::getPrimitive) + .property("rasterizerState", &PipelineState::getRasterizerState) + .property("depthStencilState", &PipelineState::getDepthStencilState) + .property("blendState", &PipelineState::getBlendState) + .property("inputState", &PipelineState::getInputState) + .property("dynamicStates", &PipelineState::getDynamicStates) + .property("renderPass", &PipelineState::getRenderPass) + .property("objectID", &PipelineState::getObjectID); + class_>("CCWGPUPipelineState") .constructor<>(); - //--------------------------------------------------CONTAINER----------------------------------------------------------------------- - register_vector("vector_int"); - register_vector("vector_uint32"); - register_vector("AccessTypeList"); - register_vector("SubpassInfoList"); - register_vector("ColorAttachmentList"); - register_vector("SubpassDependencyList"); - register_vector("TextureList"); - register_vector("BufferTextureCopyList"); - register_vector("SamplerList"); - register_vector("DescriptorSetLayoutBindingList"); - register_vector("DescriptorSetLayoutList"); - register_vector("UniformStorageImageList"); - register_vector("ShaderStageList"); - register_vector("AttributeList"); - register_vector("UniformBlockList"); - register_vector("UniformStorageBufferList"); - register_vector("UniformSamplerTextureList"); - register_vector("UniformTextureList"); - register_vector("UniformSamplerList"); - register_vector("UniformInputAttachmentList"); - register_vector("UniformList"); - register_vector("BlendTargetList"); - register_vector("CommandBufferList"); - register_vector("ColorList"); - register_vector("TextureBlitList"); - register_vector("DrawInfoList"); - register_vector("StringList"); - register_vector("BufferList"); - register_vector("SwapchainList"); - register_vector("SPVShaderStageList"); -}; + class_("GeneralBarrier") + .constructor() + .property("objectID", &GeneralBarrier::getObjectID); + class_("WGPUGeneralBarrier") + .constructor(); -} // namespace cc::gfx \ No newline at end of file + class_("BufferBarrier") + .constructor() + .property("objectID", &BufferBarrier::getObjectID); + class_("WGPUBufferBarrier") + .constructor(); + + class_("TextureBarrier") + .constructor() + .property("objectID", &TextureBarrier::getObjectID); + class_("WGPUTextureBarrier") + .constructor(); +}; +} // namespace cc::gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.cpp b/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.cpp index 156252b5d8..965386bfd8 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.cpp @@ -30,7 +30,11 @@ using namespace emscripten; namespace cc { namespace gfx { -CCWGPUFramebuffer::CCWGPUFramebuffer() : wrapper(val::object()) { +CCWGPUFramebuffer::CCWGPUFramebuffer() : Framebuffer() { +} + +CCWGPUFramebuffer::~CCWGPUFramebuffer() { + doDestroy(); } void CCWGPUFramebuffer::doInit(const FramebufferInfo &info) { diff --git a/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.h b/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.h index a66ddbef64..d0fcc4b039 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.h @@ -24,7 +24,9 @@ ****************************************************************************/ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "gfx-base/GFXFramebuffer.h" namespace cc { @@ -32,13 +34,19 @@ namespace gfx { class CCWGPUSwapchain; -class CCWGPUFramebuffer final : public emscripten::wrapper { +class CCWGPUFramebuffer final : public Framebuffer { public: CCWGPUFramebuffer(); - ~CCWGPUFramebuffer() = default; + ~CCWGPUFramebuffer(); inline CCWGPUSwapchain *swapchain() { return _swapchain; } + using Framebuffer::initialize; + + inline void setRenderPass(RenderPass *rp) { _renderPass = rp; } + inline void setColorTextures(const TextureList &colors) { _colorTextures = colors; } + inline void setDepthStencilTexture(Texture *dsTex) { _depthStencilTexture = dsTex; } + protected: void doInit(const FramebufferInfo &info) override; void doDestroy() override; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.cpp b/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.cpp index 8e591ec0e3..01771be27d 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.cpp @@ -26,32 +26,25 @@ #include "WGPUInputAssembler.h" #include "WGPUObject.h" -using namespace emscripten; namespace cc { namespace gfx { -CCWGPUInputAssembler::CCWGPUInputAssembler() : wrapper(val::object()) { +CCWGPUInputAssembler::CCWGPUInputAssembler() : InputAssembler() { +} + +CCWGPUInputAssembler::~CCWGPUInputAssembler() { + doDestroy(); } void CCWGPUInputAssembler::doInit(const InputAssemblerInfo &info) { _gpuInputAssemblerObj = ccnew CCWGPUInputAssemblerObject; - // // typedef struct WGPUVertexState { - // // WGPUChainedStruct const * nextInChain; - // // WGPUShaderModule module; - // // char const * entryPoint; - // // uint32_t bufferCount; - // // WGPUVertexBufferLayout const * buffers; - // // } WGPUVertexState; - - // _gpuInputAssemblerObj->wgpuVertexState.nextInChain = nullptr; - // _gpuInputAssemblerObj->wgpuVertexState.module = } void CCWGPUInputAssembler::doDestroy() { -} - -void CCWGPUInputAssembler::update(const DrawInfo &info) { - _drawInfo = info; + if (_gpuInputAssemblerObj) { + delete _gpuInputAssemblerObj; + _gpuInputAssemblerObj = nullptr; + } } } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.h b/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.h index 65a9db4fe7..bc4094a677 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.h @@ -24,24 +24,26 @@ ****************************************************************************/ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "gfx-base/GFXInputAssembler.h" namespace cc { namespace gfx { class CCWGPUInputAssemblerObject; - -class CCWGPUInputAssembler final : public emscripten::wrapper { +class CCWGPUBuffer; +class CCWGPUInputAssembler final : public InputAssembler { public: CCWGPUInputAssembler(); - ~CCWGPUInputAssembler() = default; + ~CCWGPUInputAssembler(); + + using InputAssembler::destroy; + using InputAssembler::initialize; inline CCWGPUInputAssemblerObject *gpuInputAssemblerObject() { return _gpuInputAssemblerObj; } - // ems export - void update(const DrawInfo &info); - protected: void doInit(const InputAssemblerInfo &info) override; void doDestroy() override; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUObject.h b/native/cocos/renderer/gfx-wgpu/WGPUObject.h index deeab6dbe3..9e62b8bb45 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUObject.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUObject.h @@ -29,8 +29,10 @@ #include "WGPUDef.h" #include "base/Utils.h" #include "base/std/container/map.h" +#include "base/std/container/set.h" #include "base/std/container/unordered_map.h" #include "base/std/container/vector.h" +#include "base/threading/Semaphore.h" #include "gfx-base/GFXDef.h" class WGPURenderPassDescriptor; @@ -41,10 +43,10 @@ namespace cc { namespace gfx { constexpr uint8_t CC_WGPU_MAX_ATTACHMENTS = 16; - -constexpr uint8_t CC_WGPU_MAX_STREAM = 256; //not sure - +constexpr uint8_t CC_WGPU_MAX_STREAM = 256; // not sure constexpr decltype(nullptr) wgpuDefaultHandle = nullptr; +constexpr ccstd::hash_t WGPU_HASH_SEED = 0x811C9DC5; +constexpr uint8_t CC_WGPU_MAX_FRAME_COUNT = 3; const DescriptorType COMBINED_ST_IN_USE = DescriptorType::SAMPLER_TEXTURE | DescriptorType::INPUT_ATTACHMENT; @@ -63,20 +65,27 @@ struct CCWGPUResource { CCWGPUTexture *commonTexture = nullptr; CCWGPUTexture *storageTexture = nullptr; - CCWGPUSampler *sampler = nullptr; + CCWGPUSampler *filterableSampler = nullptr; + CCWGPUSampler *unfilterableSampler = nullptr; +}; + +struct CCWGPUInstanceObject { + WGPUInstance wgpuInstance = wgpuDefaultHandle; + WGPUSurface wgpuSurface = wgpuDefaultHandle; + WGPUAdapter wgpuAdapter = wgpuDefaultHandle; }; struct CCWGPUDeviceObject { WGPUDevice wgpuDevice = wgpuDefaultHandle; WGPUQueue wgpuQueue = wgpuDefaultHandle; + CCWGPUInstanceObject instance; CCWGPUResource defaultResources; }; struct CCWGPUSwapchainObject { WGPUSwapChain wgpuSwapChain = wgpuDefaultHandle; WGPUSurface wgpuSurface = wgpuDefaultHandle; - WGPUInstance wgpuInstance = wgpuDefaultHandle; CCWGPUTexture *swapchainColor = nullptr; CCWGPUTexture *swapchainDepthStencil = nullptr; @@ -95,14 +104,14 @@ struct CCWGPUTextureObject { WGPUTextureView selfView = wgpuDefaultHandle; }; -//The indirect drawIndexed parameters encoded in the buffer must be a tightly packed block -//of five 32-bit unsigned integer values (20 bytes total), given in the same order as the arguments for drawIndexed(). -// let drawIndexedIndirectParameters = new Uint32Array(5); -// drawIndexedIndirectParameters[0] = indexCount; -// drawIndexedIndirectParameters[1] = instanceCount; -// drawIndexedIndirectParameters[2] = firstIndex; -// drawIndexedIndirectParameters[3] = baseVertex; -// drawIndexedIndirectParameters[4] = 0; // firstInstance. Must be 0. +// The indirect drawIndexed parameters encoded in the buffer must be a tightly packed block +// of five 32-bit unsigned integer values (20 bytes total), given in the same order as the arguments for drawIndexed(). +// let drawIndexedIndirectParameters = new Uint32Array(5); +// drawIndexedIndirectParameters[0] = indexCount; +// drawIndexedIndirectParameters[1] = instanceCount; +// drawIndexedIndirectParameters[2] = firstIndex; +// drawIndexedIndirectParameters[3] = baseVertex; +// drawIndexedIndirectParameters[4] = 0; // firstInstance. Must be 0. struct CCWGPUDrawIndexedIndirectObject { uint32_t indexCount = 0; uint32_t instanceCount = 0; @@ -112,8 +121,8 @@ struct CCWGPUDrawIndexedIndirectObject { }; static_assert(sizeof(CCWGPUDrawIndexedIndirectObject) == 20, "WGPU drawIndexedIndirect structure validation failed!"); -//The indirect draw parameters encoded in the buffer must be a tightly packed block -//of four 32-bit unsigned integer values (16 bytes total), given in the same order as the arguments for draw(). +// The indirect draw parameters encoded in the buffer must be a tightly packed block +// of four 32-bit unsigned integer values (16 bytes total), given in the same order as the arguments for draw(). // let drawIndirectParameters = new Uint32Array(4); // drawIndirectParameters[0] = vertexCount; @@ -191,7 +200,6 @@ struct CCWGPUQueueObject { }; struct CCWGPUDescriptorSetObject { - uint32_t index = 0; CCWGPUDescriptorSet *descriptorSet = nullptr; uint32_t dynamicOffsetCount = 0; const uint32_t *dynamicOffsets = nullptr; @@ -227,6 +235,7 @@ struct CCWGPUStateCache { struct CCWGPUCommandBufferObject { bool renderPassBegan = false; + WGPUCommandBuffer wgpuCommandBuffer = wgpuDefaultHandle; WGPUCommandEncoder wgpuCommandEncoder = wgpuDefaultHandle; WGPURenderPassEncoder wgpuRenderPassEncoder = wgpuDefaultHandle; WGPUComputePassEncoder wgpuComputeEncoder = wgpuDefaultHandle; @@ -245,6 +254,158 @@ struct CCWGPUQueryPoolObject { ccstd::vector idPool; }; +template +class RecycleBin { +public: + RecycleBin() = default; + ~RecycleBin() = default; + RecycleBin(const RecycleBin &) = delete; + RecycleBin &operator=(const RecycleBin &) = delete; + + void collect(T t) { + _recycleBin.emplace(t); + } + + void purge() { + for (auto &t : _recycleBin) { + purge(t); + } + _recycleBin.clear(); + } + +private: + void purge(T t); + + ccstd::set _recycleBin; +}; + +template <> +inline void RecycleBin::purge(WGPUBuffer buffer) { + wgpuBufferDestroy(buffer); + wgpuBufferRelease(buffer); +} + +template <> +inline void RecycleBin::purge(WGPUQuerySet querySet) { + wgpuQuerySetDestroy(querySet); + wgpuQuerySetRelease(querySet); +} + +template <> +inline void RecycleBin::purge(WGPUTexture texture) { + wgpuTextureDestroy(texture); + wgpuTextureRelease(texture); +} + +struct CCWGPURecycleBin { + RecycleBin bufferBin; + RecycleBin textureBin; + RecycleBin queryBin; +}; + +namespace { +inline void onStagingBufferMapDone(WGPUBufferMapAsyncStatus status, void *userdata) { + if (status == WGPUBufferMapAsyncStatus_Success) { + auto *semaphore = static_cast(userdata); + semaphore->signal(); + } +} +} // namespace +constexpr uint32_t INIT_BUFFER_SIZE = 1024 * 1024 * 1; // 1MB + +class CCWGPUStagingBuffer { + CCWGPUStagingBuffer(const CCWGPUStagingBuffer &) = delete; + CCWGPUStagingBuffer &operator=(const CCWGPUStagingBuffer &) = delete; + CCWGPUStagingBuffer() = default; + ~CCWGPUStagingBuffer() = default; + +public: + explicit CCWGPUStagingBuffer(WGPUDevice device, const std::function &recycleFunc) + : _device(device), _size(INIT_BUFFER_SIZE), _recycleFunc(recycleFunc) { + WGPUBufferDescriptor desc = { + .label = "staging buffer", + .usage = WGPUBufferUsage_CopySrc | WGPUBufferUsage_MapWrite, + .size = _size, + .mappedAtCreation = true, + }; + _buffer = wgpuDeviceCreateBuffer(device, &desc); + _mappedData = wgpuBufferGetMappedRange(_buffer, 0, _size); + } + + uint32_t alloc(uint32_t size) { + // 1. what if it's still unmapped + if (!_mapped) { + Semaphore sem{0}; + wgpuBufferMapAsync(_buffer, WGPUMapMode_Write, 0, _size, onStagingBufferMapDone, &sem); + sem.wait(); + _mappedData = wgpuBufferGetMappedRange(_buffer, 0, _size); + _mapped = true; + } + + const auto oldOffset = _offset; + if (_offset + size > _size) { + const auto oldBuffer = _buffer; + const auto oldSize = _size; + const auto *oldMappedData = _mappedData; + + _size = utils::nextPOT(_offset + size); + WGPUBufferDescriptor desc = { + .label = "staging buffer", + .usage = WGPUBufferUsage_CopySrc | WGPUBufferUsage_MapWrite, + .size = _size, + .mappedAtCreation = true, + }; + _buffer = wgpuDeviceCreateBuffer(_device, &desc); + _mappedData = wgpuBufferGetMappedRange(_buffer, 0, _size); + _offset = 0; + + if (_mapped) { + memcpy(_mappedData, oldMappedData, oldSize); + _offset = oldOffset; + } else { + // do nothing, unmap means this buffer has flush its data to gpu + } + _recycleFunc(oldBuffer); + } + _offset += size; + return oldOffset; + } + + void destroy() { + if (_mapped) { + wgpuBufferUnmap(_buffer); + } + if (_recycleFunc) { + _recycleFunc(_buffer); + } + } + + void unmap() { + if (_mapped) { + wgpuBufferUnmap(_buffer); + _mapped = false; + } + _offset = 0; + } + + void *getMappedData(uint32_t offset) { + return static_cast(_mappedData) + offset; + } + + WGPUBuffer getBuffer() { + return _buffer; + } + +private: + WGPUDevice _device{wgpuDefaultHandle}; + WGPUBuffer _buffer{wgpuDefaultHandle}; + void *_mappedData{nullptr}; + uint32_t _size{0}; + uint32_t _offset{0}; + std::function _recycleFunc; + bool _mapped{false}; +}; + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.cpp b/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.cpp index 9727ea1ec5..65ca01c858 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.cpp @@ -33,9 +33,15 @@ namespace cc { namespace gfx { +ccstd::map CCWGPUPipelineLayout::layoutMap; + using namespace emscripten; -CCWGPUPipelineLayout::CCWGPUPipelineLayout() : wrapper(val::object()) { +CCWGPUPipelineLayout::CCWGPUPipelineLayout() : PipelineLayout() { +} + +CCWGPUPipelineLayout::~CCWGPUPipelineLayout() { + doDestroy(); } void CCWGPUPipelineLayout::doInit(const PipelineLayoutInfo &info) { @@ -43,31 +49,42 @@ void CCWGPUPipelineLayout::doInit(const PipelineLayoutInfo &info) { } void CCWGPUPipelineLayout::prepare(const ccstd::set &setInUse) { + ccstd::hash_t hash = _setLayouts.size() * 2 + 1; + ccstd::hash_combine(hash, _setLayouts.size()); ccstd::vector layouts; - // _bgLayouts.clear(); for (size_t i = 0; i < _setLayouts.size(); i++) { auto *descriptorSetLayout = static_cast(_setLayouts[i]); if (setInUse.find(i) == setInUse.end()) { // give it default bindgrouplayout if not in use layouts.push_back(static_cast(CCWGPUDescriptorSetLayout::defaultBindGroupLayout())); - // _bgLayouts.push_back(static_cast(CCWGPUDescriptorSetLayout::defaultBindGroupLayout())); + ccstd::hash_combine(hash, i); + ccstd::hash_combine(hash, 9527); } else { if (!descriptorSetLayout->gpuLayoutEntryObject()->bindGroupLayout) { - descriptorSetLayout->prepare(); + printf("bgl in ppl is null\n"); + while (1) { + } } layouts.push_back(descriptorSetLayout->gpuLayoutEntryObject()->bindGroupLayout); - // _bgLayouts.push_back(descriptorSetLayout->gpuLayoutEntryObject()->bindGroupLayout); + ccstd::hash_combine(hash, i); + ccstd::hash_combine(hash, descriptorSetLayout->getHash()); } } + _hash = hash; + WGPUPipelineLayoutDescriptor descriptor = { .nextInChain = nullptr, .label = nullptr, .bindGroupLayoutCount = layouts.size(), .bindGroupLayouts = layouts.data(), }; - - _gpuPipelineLayoutObj->wgpuPipelineLayout = wgpuDeviceCreatePipelineLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + if (layoutMap.find(hash) != layoutMap.end()) { + _gpuPipelineLayoutObj->wgpuPipelineLayout = static_cast(layoutMap[hash]); + } else { + _gpuPipelineLayoutObj->wgpuPipelineLayout = wgpuDeviceCreatePipelineLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + layoutMap.emplace(hash, _gpuPipelineLayoutObj->wgpuPipelineLayout); + } } void CCWGPUPipelineLayout::doDestroy() { @@ -80,4 +97,4 @@ void CCWGPUPipelineLayout::doDestroy() { } } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.h b/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.h index 5cd33872bf..8a94aec3b8 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.h @@ -24,26 +24,35 @@ ****************************************************************************/ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif +#include "WGPUUtils.h" +#include "base/std/container/map.h" #include "base/std/container/set.h" #include "gfx-base/GFXPipelineLayout.h" - namespace cc { namespace gfx { struct CCWGPUPipelineLayoutObject; +class DescriptorSet; -class CCWGPUPipelineLayout final : public emscripten::wrapper { +class CCWGPUPipelineLayout final : public PipelineLayout { public: CCWGPUPipelineLayout(); - ~CCWGPUPipelineLayout() = default; + ~CCWGPUPipelineLayout(); inline CCWGPUPipelineLayoutObject *gpuPipelineLayoutObject() { return _gpuPipelineLayoutObj; } - //bindgroup not ready yet so delay creation + // bindgroup not ready yet so delay creation void prepare(const ccstd::set &setInUse); - // const ccstd::vector & layouts()const{return _bgLayouts;} + const ccstd::vector &layouts() const { return _bgLayouts; } + const ccstd::vector &cclayouts() const { return _ccbgLayouts; } + + static ccstd::map layoutMap; + + inline ccstd::hash_t getHash() const { return _hash; } protected: void doInit(const PipelineLayoutInfo &info) override; @@ -51,7 +60,12 @@ protected: CCWGPUPipelineLayoutObject *_gpuPipelineLayoutObj = nullptr; - // ccstd::vector _bgLayouts; + ccstd::vector _bgLayouts; + ccstd::vector _ccbgLayouts; + + ccstd::hash_t _hash{0}; + + friend void createPipelineLayoutFallback(const ccstd::vector &descriptorSets, PipelineLayout *pipelineLayout); }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.cpp b/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.cpp index 2769a0f778..ef40d51c5d 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.cpp @@ -37,21 +37,120 @@ namespace cc { namespace gfx { +ccstd::map CCWGPUPipelineState::pipelineMap; -using namespace emscripten; +namespace { +using ccstd::hash_combine; +ccstd::hash_t hash(const WGPURenderPipelineDescriptor &desc) { + ccstd::hash_t hash = 9527; + hash_combine(hash, desc.layout); + hash_combine(hash, desc.vertex.module); + hash_combine(hash, desc.vertex.entryPoint); + hash_combine(hash, desc.vertex.constantCount); + for (uint32_t i = 0; i < desc.vertex.constantCount; ++i) { + hash_combine(hash, desc.vertex.constants[i].key); + hash_combine(hash, desc.vertex.constants[i].value); + } -CCWGPUPipelineState::CCWGPUPipelineState() : wrapper(val::object()) { + hash_combine(hash, desc.vertex.bufferCount); + for (size_t i = 0; i < desc.vertex.bufferCount; ++i) { + const auto &buffer = desc.vertex.buffers[i]; + hash_combine(hash, buffer.arrayStride); + hash_combine(hash, buffer.stepMode); + hash_combine(hash, buffer.attributeCount); + for (size_t j = 0; j < buffer.attributeCount; ++j) { + const auto &attribute = buffer.attributes[j]; + hash_combine(hash, attribute.shaderLocation); + hash_combine(hash, attribute.offset); + hash_combine(hash, attribute.format); + } + } + + hash_combine(hash, desc.primitive.topology); + hash_combine(hash, desc.primitive.stripIndexFormat); + hash_combine(hash, desc.primitive.frontFace); + hash_combine(hash, desc.primitive.cullMode); + + if (desc.depthStencil) { + hash_combine(hash, desc.depthStencil->format); + hash_combine(hash, desc.depthStencil->depthWriteEnabled); + hash_combine(hash, desc.depthStencil->depthCompare); + hash_combine(hash, desc.depthStencil->stencilFront.compare); + hash_combine(hash, desc.depthStencil->stencilFront.failOp); + hash_combine(hash, desc.depthStencil->stencilFront.depthFailOp); + hash_combine(hash, desc.depthStencil->stencilFront.passOp); + hash_combine(hash, desc.depthStencil->stencilBack.compare); + hash_combine(hash, desc.depthStencil->stencilBack.failOp); + hash_combine(hash, desc.depthStencil->stencilBack.depthFailOp); + hash_combine(hash, desc.depthStencil->stencilBack.passOp); + hash_combine(hash, desc.depthStencil->stencilReadMask); + hash_combine(hash, desc.depthStencil->stencilWriteMask); + hash_combine(hash, desc.depthStencil->depthBias); + hash_combine(hash, desc.depthStencil->depthBiasSlopeScale); + hash_combine(hash, desc.depthStencil->depthBiasClamp); + } else { + hash_combine(hash, 0); + } + + hash_combine(hash, desc.multisample.count); + hash_combine(hash, desc.multisample.mask); + hash_combine(hash, desc.multisample.alphaToCoverageEnabled); + + if (desc.fragment) { + hash_combine(hash, desc.fragment->module); + hash_combine(hash, desc.fragment->entryPoint); + hash_combine(hash, desc.fragment->constantCount); + for (uint32_t i = 0; i < desc.fragment->constantCount; ++i) { + hash_combine(hash, desc.fragment->constants[i].key); + hash_combine(hash, desc.fragment->constants[i].value); + } + hash_combine(hash, desc.fragment->targetCount); + for (uint32_t i = 0; i < desc.fragment->targetCount; ++i) { + hash_combine(hash, desc.fragment->targets[i].format); + if (desc.fragment->targets[i].blend) { + hash_combine(hash, desc.fragment->targets[i].blend->color.operation); + hash_combine(hash, desc.fragment->targets[i].blend->color.srcFactor); + hash_combine(hash, desc.fragment->targets[i].blend->color.dstFactor); + hash_combine(hash, desc.fragment->targets[i].blend->alpha.operation); + hash_combine(hash, desc.fragment->targets[i].blend->alpha.srcFactor); + hash_combine(hash, desc.fragment->targets[i].blend->alpha.dstFactor); + } else { + hash_combine(hash, 0); + } + hash_combine(hash, desc.fragment->targets[i].writeMask); + } + } else { + hash_combine(hash, 0); + } + return hash; +} + +ccstd::hash_t hash(const WGPUComputePipelineDescriptor &desc) { + ccstd::hash_t hash = 9527; + hash_combine(hash, desc.layout); + // hash_combine(hash, desc.compute); + return hash; +} + +} // namespace + +CCWGPUPipelineState::CCWGPUPipelineState() : PipelineState() { +} + +CCWGPUPipelineState::~CCWGPUPipelineState() { + doDestroy(); } void CCWGPUPipelineState::doInit(const PipelineStateInfo &info) { _gpuPipelineStateObj = ccnew CCWGPUPipelineStateObject; } -void CCWGPUPipelineState::check(RenderPass *renderPass) { +void CCWGPUPipelineState::check(RenderPass *renderPass, bool forceUpdate) { if (_renderPass != renderPass) { _renderPass = renderPass; - _forceUpdate = true; + // _forceUpdate = true; } + _forceUpdate |= forceUpdate; } void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { @@ -63,6 +162,10 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { return; } + if (!_gpuPipelineStateObj->redundantAttr.empty()) { + _gpuPipelineStateObj->redundantAttr.clear(); + } + auto maxStreamAttr = std::max_element(_inputState.attributes.begin(), _inputState.attributes.end(), [&](const Attribute &lhs, const Attribute &rhs) { return lhs.stream < rhs.stream; }); @@ -80,9 +183,31 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { const AttributeList &attrs = _shader->getAttributes(); uint64_t offset[256] = {0}; // ccstd::vector wgpuAttrs; - bool isInstance = attrs.empty() ? false : attrs[0].isInstanced; - uint8_t index = 0; + for (size_t i = 0; i < _inputState.attributes.size(); ++i) { + const auto &attr = _inputState.attributes[i]; + const auto &attrName = attr.name; + auto iter = std::find_if(attrs.begin(), attrs.end(), [attrName](const Attribute &attr) { + return strcmp(attrName.c_str(), attr.name.c_str()) == 0; + }); + if (iter != attrs.end()) { + Format format = attr.format; + WGPUVertexAttribute attrInfo = { + .format = toWGPUVertexFormat(format), + .offset = offset[attr.stream], + .shaderLocation = (*iter).location, + }; + wgpuAttrsVec[attr.stream].push_back(attrInfo); + offset[attr.stream] += GFX_FORMAT_INFOS[static_cast(format)].size; + vbLayouts[attr.stream].stepMode = attr.isInstanced ? WGPUVertexStepMode_Instance : WGPUVertexStepMode_Vertex; + } else { + // all none-input attr are put in 1st buffer layout with offset = 0; + Format format = attr.format; + offset[attr.stream] += GFX_FORMAT_INFOS[static_cast(format)].size; + } + } + + // printf("cr shname %s %d\n", _shader->getName().c_str(), streamCount); // wgpuAttrsVec[0] ∪ wgpuAttrsVec[1] ∪ ... ∪ wgpuAttrsVec[n] == shader.attrs for (size_t i = 0; i < attrs.size(); i++) { ccstd::string attrName = attrs[i].name; @@ -90,16 +215,7 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { return strcmp(attrName.c_str(), attr.name.c_str()) == 0; }); - if (iter != _inputState.attributes.end()) { - Format format = (*iter).format; - WGPUVertexAttribute attr = { - .format = toWGPUVertexFormat(format), - .offset = offset[(*iter).stream], - .shaderLocation = attrs[i].location, - }; - wgpuAttrsVec[(*iter).stream].push_back(attr); - offset[(*iter).stream] += GFX_FORMAT_INFOS[static_cast(format)].size; - } else { + if (iter == _inputState.attributes.end()) { // all none-input attr are put in 1st buffer layout with offset = 0; Format format = attrs[i].format; WGPUVertexAttribute attr = { @@ -109,8 +225,8 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { }; if (GFX_FORMAT_INFOS[static_cast(format)].size > GFX_FORMAT_INFOS[static_cast((*longestAttr).format)].size) { - printf("found attr %s %s in shader exceed size of longest attr %s %s\n", attrName.c_str(), GFX_FORMAT_INFOS[static_cast(format)].name.c_str(), - (*longestAttr).name.c_str(), GFX_FORMAT_INFOS[static_cast((*longestAttr).format)].name.c_str()); + // printf("found attr %s %s in shader exceed size of longest attr %s %s\n", attrName.c_str(), GFX_FORMAT_INFOS[static_cast(format)].name.c_str(), + // (*longestAttr).name.c_str(), GFX_FORMAT_INFOS[static_cast((*longestAttr).format)].name.c_str()); _gpuPipelineStateObj->redundantAttr.push_back(attr); if (GFX_FORMAT_INFOS[static_cast(format)].size > _gpuPipelineStateObj->maxAttrLength) { _gpuPipelineStateObj->maxAttrLength = GFX_FORMAT_INFOS[static_cast(format)].size; @@ -119,41 +235,32 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { wgpuAttrsVec[mostToleranceStream].push_back(attr); } } - } - // input state has attr which shader hasnt. - for (size_t i = 0; i < _inputState.attributes.size(); ++i) { - ccstd::string attrName = _inputState.attributes[i].name; - const auto &attribute = _inputState.attributes[i]; - auto iter = std::find_if(attrs.begin(), attrs.end(), [attrName](const Attribute &attr) { - return strcmp(attrName.c_str(), attr.name.c_str()) == 0; - }); - if (iter == attrs.end()) { - Format format = attribute.format; - offset[attribute.stream] += GFX_FORMAT_INFOS[static_cast(format)].size; - } + // printf("sl %s, %d, %d\n", attrName.c_str(), attrs[i].location, attrs[i].stream); } if (_gpuPipelineStateObj->maxAttrLength > 0) { wgpuAttrsVec.push_back(_gpuPipelineStateObj->redundantAttr); vbLayouts.resize(vbLayouts.size() + 1); } + // _gpuPipelineStateObj->slotCount = vbLayouts.size(); + // std::set locSet; for (size_t i = 0; i < wgpuAttrsVec.size(); ++i) { - vbLayouts[i] = { - .arrayStride = offset[i], - .stepMode = isInstance ? WGPUVertexStepMode_Instance : WGPUVertexStepMode_Vertex, - .attributeCount = wgpuAttrsVec[i].size(), - .attributes = wgpuAttrsVec[i].data(), - }; - } + vbLayouts[i].arrayStride = offset[i]; + vbLayouts[i].attributeCount = static_cast(wgpuAttrsVec[i].size()); + vbLayouts[i].attributes = wgpuAttrsVec[i].data(); + // for (size_t j = 0; j < wgpuAttrsVec[i].size(); ++j) { + // printf("wg %d, %llu, %d\n", wgpuAttrsVec[i][j].shaderLocation, wgpuAttrsVec[i][j].offset, wgpuAttrsVec[i][j].format); - // WGPUVertexBufferLayout vertexBufferLayout = { - // .arrayStride = stride, // TODO_Zeqiang: ??? - // .stepMode = isInstance ? WGPUVertexStepMode_Instance : WGPUVertexStepMode_Vertex, - // .attributeCount = wgpuAttrs.size(), - // .attributes = wgpuAttrs.data(), - // }; + // // if (locSet.find(wgpuAttrsVec[i][j].shaderLocation) != locSet.end() && wgpuAttrsVec[i][j].shaderLocation != 0) { + // // printf("duplicate location %d\n", wgpuAttrsVec[i][j].shaderLocation); + // // while (1) { + // // } + // // } + // // locSet.insert(wgpuAttrsVec[i][j].shaderLocation); + // } + } WGPUVertexState vertexState = { .nextInChain = nullptr, @@ -168,7 +275,7 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { WGPUPrimitiveState primitiveState = { .nextInChain = nullptr, .topology = toWGPUPrimTopology(_primitive), - .stripIndexFormat = stripTopology ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Undefined, //TODO_Zeqiang: ??? + .stripIndexFormat = stripTopology ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Undefined, // TODO_Zeqiang: ??? .frontFace = _rasterizerState.isFrontFaceCCW ? WGPUFrontFace::WGPUFrontFace_CCW : WGPUFrontFace::WGPUFrontFace_CW, .cullMode = _rasterizerState.cullMode == CullMode::FRONT ? WGPUCullMode::WGPUCullMode_Front : _rasterizerState.cullMode == CullMode::BACK ? WGPUCullMode::WGPUCullMode_Back @@ -181,7 +288,6 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { .depthFailOp = toWGPUStencilOperation(_depthStencilState.stencilZFailOpFront), .passOp = toWGPUStencilOperation(_depthStencilState.stencilPassOpFront), }; - WGPUStencilFaceState stencilBack = { .compare = toWGPUCompareFunction(_depthStencilState.stencilFuncBack), .failOp = toWGPUStencilOperation(_depthStencilState.stencilFailOpBack), @@ -216,17 +322,20 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { for (size_t i = 0, targetIndex = 0; i < colors.size(); i++) { colorTargetStates[i].format = toWGPUTextureFormat(colors[i].format); + auto colorBO = _blendState.targets[targetIndex].blendEq; blendState[i].color = { - .operation = toWGPUBlendOperation(_blendState.targets[targetIndex].blendEq), - .srcFactor = toWGPUBlendFactor(_blendState.targets[targetIndex].blendSrc), - .dstFactor = toWGPUBlendFactor(_blendState.targets[targetIndex].blendDst), + .operation = toWGPUBlendOperation(colorBO), + .srcFactor = toWGPUBlendFactor(colorBO == BlendOp::MAX ? BlendFactor::ONE : _blendState.targets[targetIndex].blendSrc), + .dstFactor = toWGPUBlendFactor(colorBO == BlendOp::MAX ? BlendFactor::ONE : _blendState.targets[targetIndex].blendDst), }; + auto alphaBO = _blendState.targets[targetIndex].blendAlphaEq; blendState[i].alpha = { - .operation = toWGPUBlendOperation(_blendState.targets[targetIndex].blendAlphaEq), - .srcFactor = toWGPUBlendFactor(_blendState.targets[targetIndex].blendSrcAlpha), - .dstFactor = toWGPUBlendFactor(_blendState.targets[targetIndex].blendDstAlpha), + .operation = toWGPUBlendOperation(alphaBO), + .srcFactor = toWGPUBlendFactor(alphaBO == BlendOp::MAX ? BlendFactor::ONE : _blendState.targets[targetIndex].blendSrcAlpha), + .dstFactor = toWGPUBlendFactor(alphaBO == BlendOp::MAX ? BlendFactor::ONE : _blendState.targets[targetIndex].blendDstAlpha), }; - colorTargetStates[i].blend = &blendState[i]; + // only textureSampleType with float can be blended. + colorTargetStates[i].blend = textureSampleTypeTrait(colors[i].format) == WGPUTextureSampleType_Float ? &blendState[i] : nullptr; colorTargetStates[i].writeMask = toWGPUColorWriteMask(_blendState.targets[targetIndex].blendColorMask); if (targetIndex < _blendState.targets.size() - 1) { ++targetIndex; @@ -240,19 +349,11 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { .targets = colorTargetStates.data(), }; - pipelineLayout->prepare(setInUse); - // const auto setLayouts = pipelineLayout->getSetLayouts(); - // for (size_t i = 0; i < setLayouts.size(); ++i) { - // const auto* layout = setLayouts[i]; - // if (layout) { - // printf("---set %d---\n", i); - // static_cast(layout)->print(); - // } - // } + // pipelineLayout->prepare(setInUse); WGPURenderPipelineDescriptor piplineDesc = { .nextInChain = nullptr, - .label = nullptr, + .label = static_cast(_shader)->getName().c_str(), .layout = pipelineLayout->gpuPipelineLayoutObject()->wgpuPipelineLayout, .vertex = vertexState, .primitive = primitiveState, @@ -260,22 +361,45 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { .multisample = msState, .fragment = &fragmentState, }; - _gpuPipelineStateObj->wgpuRenderPipeline = wgpuDeviceCreateRenderPipeline(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &piplineDesc); + + auto hashVal = hash(piplineDesc); + _hash = hashVal; + + auto iter = pipelineMap.find(hashVal); + if (iter == pipelineMap.end()) { + _gpuPipelineStateObj->wgpuRenderPipeline = wgpuDeviceCreateRenderPipeline(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &piplineDesc); + printf("ppl %s\n", static_cast(_shader)->getName().c_str()); + pipelineMap[hashVal] = _gpuPipelineStateObj->wgpuRenderPipeline; + } else { + _gpuPipelineStateObj->wgpuRenderPipeline = static_cast(iter->second); + } _ppl = pipelineLayout; _forceUpdate = false; } else if (_bindPoint == PipelineBindPoint::COMPUTE) { - if (_gpuPipelineStateObj->wgpuComputePipeline) + if (_gpuPipelineStateObj->wgpuComputePipeline && !_forceUpdate) return; WGPUProgrammableStageDescriptor psDesc = { .module = static_cast(_shader)->gpuShaderObject()->wgpuShaderComputeModule, .entryPoint = "main", }; - pipelineLayout->prepare(setInUse); + // pipelineLayout->prepare(setInUse); WGPUComputePipelineDescriptor piplineDesc = { .layout = pipelineLayout->gpuPipelineLayoutObject()->wgpuPipelineLayout, .compute = psDesc, }; - _gpuPipelineStateObj->wgpuComputePipeline = wgpuDeviceCreateComputePipeline(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &piplineDesc); + auto hashVal = hash(piplineDesc); + _hash = hashVal; + + auto iter = pipelineMap.find(hashVal); + if (iter == pipelineMap.end()) { + _gpuPipelineStateObj->wgpuComputePipeline = wgpuDeviceCreateComputePipeline(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &piplineDesc); + printf("ppl %s\n", static_cast(_shader)->getName().c_str()); + pipelineMap[hashVal] = _gpuPipelineStateObj->wgpuComputePipeline; + } else { + _gpuPipelineStateObj->wgpuComputePipeline = static_cast(iter->second); + } + _ppl = pipelineLayout; + _forceUpdate = false; } else { printf("unsupport pipeline bind point"); } @@ -291,8 +415,9 @@ void CCWGPUPipelineState::doDestroy() { } delete _gpuPipelineStateObj; + _gpuPipelineStateObj = nullptr; } } } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.h b/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.h index 6fca6fcc2b..e6ea201e99 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.h @@ -24,7 +24,10 @@ ****************************************************************************/ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif +#include "base/std/container/map.h" #include "base/std/container/set.h" #include "gfx-base/GFXPipelineState.h" @@ -33,19 +36,23 @@ namespace gfx { struct CCWGPUPipelineStateObject; -class CCWGPUPipelineState final : public emscripten::wrapper { +class CCWGPUPipelineState final : public PipelineState { public: CCWGPUPipelineState(); - ~CCWGPUPipelineState() = default; + ~CCWGPUPipelineState(); inline CCWGPUPipelineStateObject *gpuPipelineStateObject() { return _gpuPipelineStateObj; } - void check(RenderPass *renderPass); - + void check(RenderPass *renderPass, bool forceUpdate = false); void prepare(const ccstd::set &setInUse); + PipelineLayout *layout() const { return _pipelineLayout; } void *ppl() const { return _ppl; } + static ccstd::map pipelineMap; + + inline ccstd::hash_t getHash() const { return _hash; } + protected: void doInit(const PipelineStateInfo &info) override; void doDestroy() override; @@ -54,6 +61,7 @@ protected: void *_ppl = nullptr; bool _forceUpdate = false; + ccstd::hash_t _hash{0}; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.cpp b/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.cpp index f154de7953..dae0bbd6c9 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.cpp @@ -36,7 +36,7 @@ CCWGPUQueryPool::CCWGPUQueryPool() { } CCWGPUQueryPool::~CCWGPUQueryPool() { - destroy(); + doDestroy(); } void CCWGPUQueryPool::doInit(const QueryPoolInfo & /*info*/) { @@ -46,14 +46,14 @@ void CCWGPUQueryPool::doInit(const QueryPoolInfo & /*info*/) { _gpuQueryPool->maxQueryObjects = _maxQueryObjects; _gpuQueryPool->idPool.resize(_maxQueryObjects, 0U); - //TODO_Zeqiang: wgpu query + // TODO_Zeqiang: wgpu query - //cmdFuncGLES3CreateQuery(device, _gpuQueryPool); + // cmdFuncGLES3CreateQuery(device, _gpuQueryPool); } void CCWGPUQueryPool::doDestroy() { if (_gpuQueryPool) { - //cmdFuncGLES3DestroyQuery(GLES3Device::getInstance(), _gpuQueryPool); + // cmdFuncGLES3DestroyQuery(GLES3Device::getInstance(), _gpuQueryPool); delete _gpuQueryPool; _gpuQueryPool = nullptr; } diff --git a/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp b/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp index 1d5837a0c6..a0bad34207 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp @@ -35,7 +35,11 @@ namespace gfx { using namespace emscripten; -CCWGPUQueue::CCWGPUQueue() : wrapper(val::object()) { +CCWGPUQueue::CCWGPUQueue() : Queue() { +} + +CCWGPUQueue::~CCWGPUQueue() { + doDestroy(); } void CCWGPUQueue::doInit(const QueueInfo &info) { @@ -50,9 +54,20 @@ void CCWGPUQueue::doDestroy() { wgpuQueueRelease(_gpuQueueObject->wgpuQueue); } delete _gpuQueueObject; + _gpuQueueObject = nullptr; } } +namespace { + +void wgpuQueueSubmitCallback(WGPUQueueWorkDoneStatus status, void *userdata) { + auto *recycleBin = static_cast(userdata); + recycleBin->bufferBin.purge(); + recycleBin->textureBin.purge(); + recycleBin->queryBin.purge(); +} +} // namespace + void CCWGPUQueue::submit(CommandBuffer *const *cmdBuffs, uint32_t count) { // ccstd::vector commandBuffs(count); // for (size_t i = 0; i < count; i++) { @@ -64,7 +79,25 @@ void CCWGPUQueue::submit(CommandBuffer *const *cmdBuffs, uint32_t count) { // auto* commandBuff = static_cast(cmdBuffs[i]); // wgpuCommandBufferRelease(commandBuff->gpuCommandBufferObject()->wgpuCommandBuffer); // } + + // CCWGPUDevice::getInstance()->stagingBuffer()->unmap(); + + ccstd::vector wgpuCmdBuffs(count); + for (size_t i = 0; i < count; ++i) { + const auto *cmdBuff = static_cast(cmdBuffs[i]); + wgpuCmdBuffs[i] = cmdBuff->gpuCommandBufferObject()->wgpuCommandBuffer; + + _numDrawCalls += cmdBuff->getNumDrawCalls(); + _numInstances += cmdBuff->getNumInstances(); + _numTriangles += cmdBuff->getNumTris(); + } + + wgpuQueueSubmit(_gpuQueueObject->wgpuQueue, count, wgpuCmdBuffs.data()); + std::for_each(wgpuCmdBuffs.begin(), wgpuCmdBuffs.end(), [](auto wgpuCmdBuffer) { wgpuCommandBufferRelease(wgpuCmdBuffer); }); + + auto *recycleBin = CCWGPUDevice::getInstance()->recycleBin(); + wgpuQueueOnSubmittedWorkDone(_gpuQueueObject->wgpuQueue, 0, wgpuQueueSubmitCallback, recycleBin); } } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUQueue.h b/native/cocos/renderer/gfx-wgpu/WGPUQueue.h index 163ed709c2..c6e6469123 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUQueue.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUQueue.h @@ -25,7 +25,9 @@ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "gfx-base/GFXQueue.h" namespace cc { @@ -33,21 +35,28 @@ namespace gfx { struct CCWGPUQueueObject; -class CCWGPUQueue final : public emscripten::wrapper { +class CCWGPUQueue final : public Queue { public: - EMSCRIPTEN_WRAPPER(CCWGPUQueue); CCWGPUQueue(); - ~CCWGPUQueue() = default; + ~CCWGPUQueue(); void submit(CommandBuffer *const *cmdBuffs, uint32_t count) override; - inline CCWGPUQueueObject *gpuQueueObject() { return _gpuQueueObject; } + inline uint32_t getNumDrawCalls() const { return _numDrawCalls; } + inline uint32_t getNumInstances() const { return _numInstances; } + inline uint32_t getNumTris() const { return _numTriangles; } + + inline void resetStatus() { _numDrawCalls = _numInstances = _numTriangles = 0; } protected: void doInit(const QueueInfo &info) override; void doDestroy() override; CCWGPUQueueObject *_gpuQueueObject = nullptr; + + uint32_t _numDrawCalls = 0; + uint32_t _numInstances = 0; + uint32_t _numTriangles = 0; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp index e3d1442357..22c10b664c 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp @@ -41,7 +41,7 @@ public: for (size_t i = 0; i < info.colorAttachments.size(); i++) { colors[i].loadOp = toWGPULoadOp(info.colorAttachments[i].loadOp); colors[i].storeOp = toWGPUStoreOp(info.colorAttachments[i].storeOp); - colors[i].clearColor = defaultClearColor; + colors[i].clearValue = defaultClearColor; // TODO_Zeqaing : subpass if (info.colorAttachments[i].sampleCount != SampleCount::ONE) samples = info.colorAttachments[i].sampleCount; @@ -52,7 +52,7 @@ public: depthStencils[0].depthStoreOp = toWGPUStoreOp(info.depthStencilAttachment.depthStoreOp); depthStencils[0].stencilLoadOp = toWGPULoadOp(info.depthStencilAttachment.stencilLoadOp); depthStencils[0].stencilStoreOp = toWGPUStoreOp(info.depthStencilAttachment.stencilStoreOp); - depthStencils[0].clearDepth = defaultClearDepth; + depthStencils[0].depthClearValue = defaultClearDepth; depthStencils[0].depthReadOnly = false; depthStencils[0].stencilReadOnly = false; if (samples == SampleCount::ONE) @@ -60,7 +60,7 @@ public: renderPassDesc = ccnew WGPURenderPassDescriptor; - //TODO_Zeqiang: Metal-like subpass + // TODO_Zeqiang: Metal-like subpass renderPassDesc->colorAttachmentCount = info.colorAttachments.size(); renderPassDesc->colorAttachments = colors.data(); renderPassDesc->depthStencilAttachment = depthStencils.data(); @@ -81,7 +81,11 @@ public: int sampleCount = 1; }; -CCWGPURenderPass::CCWGPURenderPass() : wrapper(val::object()) { +CCWGPURenderPass::CCWGPURenderPass() : RenderPass() { +} + +CCWGPURenderPass::~CCWGPURenderPass() { + doDestroy(); } void CCWGPURenderPass::doInit(const RenderPassInfo &info) { diff --git a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.h b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.h index 1f86efeee6..08d5103742 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.h +++ b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.h @@ -25,7 +25,9 @@ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "gfx-base/GFXRenderPass.h" namespace cc { @@ -34,14 +36,15 @@ namespace gfx { struct CCWGPURenderPassObject; class CCWGPURenderPassHelper; -class CCWGPURenderPass final : public emscripten::wrapper { +class CCWGPURenderPass final : public RenderPass { public: - EMSCRIPTEN_WRAPPER(CCWGPURenderPass); CCWGPURenderPass(); - ~CCWGPURenderPass() = default; + ~CCWGPURenderPass(); inline CCWGPURenderPassObject *gpuRenderPassObject() { return _renderPassObject; } + using RenderPass::initialize; + protected: void doInit(const RenderPassInfo &info) override; void doDestroy() override; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUSampler.cpp b/native/cocos/renderer/gfx-wgpu/WGPUSampler.cpp index 8ef8d292e7..64972e3a9f 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUSampler.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUSampler.cpp @@ -32,16 +32,17 @@ namespace cc { namespace gfx { -namespace anoymous { -CCWGPUSampler *defaultSampler = nullptr; -} +namespace { +CCWGPUSampler *dftFilterableSampler = nullptr; +CCWGPUSampler *dftUnfilterableSampler = nullptr; +} // namespace using namespace emscripten; -CCWGPUSampler::CCWGPUSampler(const SamplerInfo &info) : wrapper(val::object(), info) { +CCWGPUSampler::CCWGPUSampler(const SamplerInfo &info) : Sampler(info) { WGPUSamplerDescriptor descriptor = { .nextInChain = nullptr, - .label = nullptr, + .label = (std::to_string(static_cast(info.minFilter)) + " " + std::to_string(static_cast(info.magFilter)) + " " + std::to_string(static_cast(info.mipFilter))).c_str(), .addressModeU = toWGPUAddressMode(info.addressU), .addressModeV = toWGPUAddressMode(info.addressV), .addressModeW = toWGPUAddressMode(info.addressW), @@ -50,7 +51,7 @@ CCWGPUSampler::CCWGPUSampler(const SamplerInfo &info) : wrapper(val::ob .mipmapFilter = toWGPUFilterMode(info.mipFilter), .lodMinClamp = 0.0f, .lodMaxClamp = std::numeric_limits::max(), - .compare = WGPUCompareFunction_Undefined, //toWGPUCompareFunction(info.cmpFunc), + .compare = WGPUCompareFunction_Undefined, // toWGPUCompareFunction(info.cmpFunc), .maxAnisotropy = static_cast(info.maxAnisotropy), }; @@ -62,21 +63,38 @@ CCWGPUSampler::~CCWGPUSampler() { wgpuSamplerRelease(_wgpuSampler); } -CCWGPUSampler *CCWGPUSampler::defaultSampler() { - if (!anoymous::defaultSampler) { +CCWGPUSampler *CCWGPUSampler::defaultFilterableSampler() { + if (!dftFilterableSampler) { SamplerInfo info = { .minFilter = Filter::LINEAR, .magFilter = Filter::LINEAR, - .mipFilter = Filter::NONE, + .mipFilter = Filter::LINEAR, .addressU = Address::WRAP, .addressV = Address::WRAP, .addressW = Address::WRAP, .maxAnisotropy = 0, .cmpFunc = ComparisonFunc::ALWAYS, }; - anoymous::defaultSampler = ccnew CCWGPUSampler(info); + dftFilterableSampler = ccnew CCWGPUSampler(info); } - return anoymous::defaultSampler; + return dftFilterableSampler; +} + +CCWGPUSampler *CCWGPUSampler::defaultUnfilterableSampler() { + if (!dftUnfilterableSampler) { + SamplerInfo info = { + .minFilter = Filter::POINT, + .magFilter = Filter::POINT, + .mipFilter = Filter::POINT, + .addressU = Address::WRAP, + .addressV = Address::WRAP, + .addressW = Address::WRAP, + .maxAnisotropy = 0, + .cmpFunc = ComparisonFunc::ALWAYS, + }; + dftUnfilterableSampler = ccnew CCWGPUSampler(info); + } + return dftUnfilterableSampler; } } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUSampler.h b/native/cocos/renderer/gfx-wgpu/WGPUSampler.h index b49737d854..7873b7f64b 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUSampler.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUSampler.h @@ -24,7 +24,9 @@ ****************************************************************************/ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "gfx-base/states/GFXSampler.h" #include "WGPUobject.h" @@ -32,19 +34,18 @@ namespace cc { namespace gfx { -class CCWGPUSampler final : public emscripten::wrapper { +class CCWGPUSampler final : public Sampler { public: - EMSCRIPTEN_WRAPPER(CCWGPUSampler); explicit CCWGPUSampler(const SamplerInfo &info); ~CCWGPUSampler(); - inline WGPUSampler gpuSampler() { return _wgpuSampler; } + inline WGPUSampler gpuSampler() const { return _wgpuSampler; } - static CCWGPUSampler *defaultSampler(); + static CCWGPUSampler *defaultFilterableSampler(); + static CCWGPUSampler *defaultUnfilterableSampler(); - //stamp current state + // stamp current state void stamp() {} - bool internalChanged() const { return false; } protected: diff --git a/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp b/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp index 18291820c9..43d7cf09c0 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp @@ -28,18 +28,29 @@ #include "WGPUDevice.h" #include "WGPUObject.h" #include "WGPUUtils.h" +#define USE_NATRIVE_SPIRV 0 +#if USE_NATRIVE_SPIRV + #include "gfx-base/SPIRVUtils.h" + #ifndef SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS + #define SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS + #endif + #include "spirv_cross/spirv_msl.hpp" +#endif namespace cc { namespace gfx { - using namespace emscripten; +SPIRVUtils *CCWGPUShader::spirv = nullptr; -CCWGPUShader::CCWGPUShader() : wrapper(val::object()) { +CCWGPUShader::CCWGPUShader() : Shader() { } -void CCWGPUShader::initialize(const SPVShaderInfoInstance &spvInfo) { +CCWGPUShader::~CCWGPUShader() { + doDestroy(); +} + +void CCWGPUShader::initialize(const ShaderInfo &info, const std::vector> &spirvs) { _gpuShaderObject = ccnew CCWGPUShaderObject; - const ShaderInfo &info = spvInfo.info; _name = info.name; _stages = info.stages; @@ -53,10 +64,98 @@ void CCWGPUShader::initialize(const SPVShaderInfoInstance &spvInfo) { _subpassInputs = info.subpassInputs; _gpuShaderObject->name = info.name; - for (size_t i = 0; i < spvInfo.stages.size(); i++) { - const auto &stage = spvInfo.stages[i]; - auto *spvData = spvInfo.stages[i].spv.data(); - size_t size = spvInfo.stages[i].spv.size(); + for (size_t i = 0; i < info.stages.size(); i++) { + const auto &stage = info.stages[i]; + auto *spvData = spirvs[i].data(); + size_t size = spirvs[i].size(); + + WGPUShaderModuleSPIRVDescriptor spv = {}; + spv.chain.sType = WGPUSType_ShaderModuleSPIRVDescriptor; + spv.codeSize = size; + spv.code = spvData; + WGPUShaderModuleDescriptor desc = {}; + desc.nextInChain = reinterpret_cast(&spv); + desc.label = _name.c_str(); + if (stage.stage == ShaderStageFlagBit::VERTEX) { + _gpuShaderObject->wgpuShaderVertexModule = wgpuDeviceCreateShaderModule(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &desc); + } else if (stage.stage == ShaderStageFlagBit::FRAGMENT) { + _gpuShaderObject->wgpuShaderFragmentModule = wgpuDeviceCreateShaderModule(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &desc); + } else if (stage.stage == ShaderStageFlagBit::COMPUTE) { + _gpuShaderObject->wgpuShaderComputeModule = wgpuDeviceCreateShaderModule(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &desc); + } else { + printf("unsupport shader stage."); + } + } +} + +const std::string spirvProcess(const uint32_t *data, size_t size, const UniformSamplerTextureList &list) { +#if USE_NATRIVE_SPIRV + spirv_cross::CompilerMSL compiler(data, size); + auto executionModel = compiler.get_execution_model(); + + auto active = compiler.get_active_interface_variables(); + spirv_cross::ShaderResources resources = compiler.get_shader_resources(active); + compiler.set_enabled_interface_variables(std::move(active)); + + // Set some options. + spirv_cross::CompilerMSL::Options options; + options.enable_decoration_binding = true; + options.set_msl_version(2, 3, 0); + compiler.set_msl_options(options); + + printf("size should be eq %d ,%d\n", list.size(), resources.sampled_images.size()); + + for (size_t i = 0; i < resources.sampled_images.size(); ++i) { + const auto &sampler = resources.sampled_images[i]; + auto set = compiler.get_decoration(sampler.id, spv::DecorationDescriptorSet); + auto binding = compiler.get_decoration(sampler.id, spv::DecorationBinding); + int size = 1; + // const spirv_cross::SPIRType &type = msl.get_type(sampler.type_id); + // if (type.array_size_literal[0]) { + // size = type.array[0]; + // } + + // for (int i = 0; i < size; ++i) { + spirv_cross::MSLResourceBinding newBinding; + newBinding.stage = executionModel; + newBinding.desc_set = set; + newBinding.binding = list[i].binding; + newBinding.msl_texture = binding; + newBinding.msl_sampler = binding + 16; + compiler.add_msl_resource_binding(newBinding); + + // if (gpuShader->samplers.find(mappedBinding) == gpuShader->samplers.end()) { + // gpuShader->samplers[mappedBinding] = {sampler.name, set, binding, newBinding.msl_texture, newBinding.msl_sampler, shaderType}; + // } else { + // gpuShader->samplers[mappedBinding].stages |= shaderType; + // } + // ++gpuShader->samplerIndex; + // } + } + + const std::string &msl = compiler.compile(); + return msl; +#else + return std::string{}; +#endif +} + +void CCWGPUShader::doInit(const ShaderInfo &info) { +#if USE_NATRIVE_SPIRV + _gpuShaderObject = ccnew CCWGPUShaderObject; + if (!spirv) { + spirv = SPIRVUtils::getInstance(); + spirv->initialize(1); + } + _gpuShaderObject->name = info.name; + for (auto &stage : info.stages) { + spirv->compileGLSL(stage.stage, "#version 450\n" + stage.source); + // const auto &data = spirv->getOutputData(); + + std::string glsl = spirvProcess(spirv->getOutputData(), spirv->getOutputSize() / sizeof(uint32_t), _samplerTextures); + spirv->compileGLSL(stage.stage, glsl); + auto *spvData = spirv->getOutputData(); + size_t size = spirv->getOutputSize() / sizeof(uint32_t); WGPUShaderModuleSPIRVDescriptor spv = {}; spv.chain.sType = WGPUSType_ShaderModuleSPIRVDescriptor; @@ -75,9 +174,8 @@ void CCWGPUShader::initialize(const SPVShaderInfoInstance &spvInfo) { printf("unsupport shader stage."); } } -} - -void CCWGPUShader::doInit(const ShaderInfo &info) { +// printf("sahdername: %s\n", info.name.c_str()); +#endif } void CCWGPUShader::doDestroy() { @@ -92,6 +190,7 @@ void CCWGPUShader::doDestroy() { wgpuShaderModuleRelease(_gpuShaderObject->wgpuShaderComputeModule); } delete _gpuShaderObject; + _gpuShaderObject = nullptr; } } diff --git a/native/cocos/renderer/gfx-wgpu/WGPUShader.h b/native/cocos/renderer/gfx-wgpu/WGPUShader.h index c46c694c8c..8f8729572e 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUShader.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUShader.h @@ -24,31 +24,37 @@ ****************************************************************************/ #pragma once - -#include -#include "WGPUDef.h" +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "gfx-base/GFXShader.h" namespace cc { namespace gfx { struct CCWGPUShaderObject; +class SPIRVUtils; -class CCWGPUShader final : public emscripten::wrapper { +class CCWGPUShader final : public Shader { public: - EMSCRIPTEN_WRAPPER(CCWGPUShader); CCWGPUShader(); - ~CCWGPUShader() = default; + ~CCWGPUShader(); inline CCWGPUShaderObject *gpuShaderObject() { return _gpuShaderObject; } - void initialize(const SPVShaderInfoInstance &info); + void initialize(const ShaderInfo &info) { doInit(info); } + + // ems export + EXPORT_EMS( + void initialize(const ShaderInfo &info, emscripten::val &spirvs);) + void initialize(const ShaderInfo &info, const std::vector> &spirvs); protected: void doInit(const ShaderInfo &info) override; void doDestroy() override; CCWGPUShaderObject *_gpuShaderObject = nullptr; + static SPIRVUtils *spirv; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.cpp b/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.cpp index 5fba3a178c..d35e75249b 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.cpp @@ -37,17 +37,22 @@ CCWGPUSwapchain::CCWGPUSwapchain(CCWGPUDevice *device) { CCWGPUSwapchain::~CCWGPUSwapchain() { _device = nullptr; + doDestroy(); } void CCWGPUSwapchain::doInit(const SwapchainInfo &info) { - WGPUSurfaceDescriptorFromCanvasHTMLSelector canvDesc = {}; - canvDesc.chain.sType = WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector; - canvDesc.selector = "canvas"; + printf("swapchain init %d, %d\n", info.width, info.height); + // WGPUSurfaceDescriptorFromCanvasHTMLSelector canvDesc = {}; + // canvDesc.chain.sType = WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector; + // canvDesc.selector = "canvas"; - WGPUSurfaceDescriptor surfDesc = {}; - surfDesc.nextInChain = reinterpret_cast(&canvDesc); - WGPUSurface surface = wgpuInstanceCreateSurface(nullptr, &surfDesc); + // WGPUSurfaceDescriptor surfDesc = {}; + // surfDesc.nextInChain = reinterpret_cast(&canvDesc); + // WGPUSurface surface = wgpuInstanceCreateSurface(nullptr, &surfDesc); + auto *device = CCWGPUDevice::getInstance(); + CCWGPUDeviceObject *gpuDeviceObj = device->gpuDeviceObject(); + auto surface = gpuDeviceObj->instance.wgpuSurface; WGPUPresentMode presentMode; switch (info.vsyncMode) { case VsyncMode::OFF: @@ -69,7 +74,6 @@ void CCWGPUSwapchain::doInit(const SwapchainInfo &info) { presentMode = WGPUPresentMode_Fifo; } - auto *device = CCWGPUDevice::getInstance(); WGPUSwapChainDescriptor swapChainDesc; swapChainDesc.nextInChain = nullptr; swapChainDesc.label = "defaultSwapChain"; @@ -79,7 +83,6 @@ void CCWGPUSwapchain::doInit(const SwapchainInfo &info) { swapChainDesc.height = info.height; swapChainDesc.presentMode = presentMode; - CCWGPUDeviceObject *gpuDeviceObj = device->gpuDeviceObject(); WGPUSwapChain swapChain = wgpuDeviceCreateSwapChain(gpuDeviceObj->wgpuDevice, surface, &swapChainDesc); _gpuSwapchainObj = ccnew CCWGPUSwapchainObject; _gpuSwapchainObj->wgpuSwapChain = swapChain; @@ -92,6 +95,10 @@ void CCWGPUSwapchain::doInit(const SwapchainInfo &info) { .height = info.height, }; + printf("swapchain init %d, %d\n", info.width, info.height); + + printf("swapchain tex init %d, %d\n", textureInfo.width, textureInfo.height); + _colorTexture = _gpuSwapchainObj->swapchainColor = ccnew CCWGPUTexture; initTexture(textureInfo, _gpuSwapchainObj->swapchainColor); textureInfo.format = Format::DEPTH_STENCIL; @@ -104,14 +111,16 @@ void CCWGPUSwapchain::doInit(const SwapchainInfo &info) { } void CCWGPUSwapchain::doDestroy() { - // wgpuSurfaceRelease(_gpuSwapchainObj->wgpuSurface); - // wgpuSwapChainRelease(_gpuSwapchainObj->wgpuSwapChain); + wgpuSwapChainRelease(_gpuSwapchainObj->wgpuSwapChain); CCWGPUDevice::getInstance()->unRegisterSwapchain(this); - delete _gpuSwapchainObj->swapchainColor; - delete _gpuSwapchainObj->swapchainDepthStencil; - delete _gpuSwapchainObj; + if (_gpuSwapchainObj) { + delete _gpuSwapchainObj->swapchainColor; + delete _gpuSwapchainObj->swapchainDepthStencil; + delete _gpuSwapchainObj; + _gpuSwapchainObj = nullptr; + } } void CCWGPUSwapchain::doResize(uint32_t width, uint32_t height, SurfaceTransform transform) { @@ -119,16 +128,10 @@ void CCWGPUSwapchain::doResize(uint32_t width, uint32_t height, SurfaceTransform _depthStencilTexture->resize(height, height); } -CCWGPUTexture *CCWGPUSwapchain::getColorTexture() { - return static_cast(_colorTexture); -} - -CCWGPUTexture *CCWGPUSwapchain::getDepthStencilTexture() { - return static_cast(_depthStencilTexture); -} - void CCWGPUSwapchain::update() { - static_cast(_colorTexture)->gpuTextureObject()->selfView = wgpuSwapChainGetCurrentTextureView(_gpuSwapchainObj->wgpuSwapChain); + auto swapchainView = static_cast(_colorTexture.get())->gpuTextureObject()->selfView; + wgpuTextureViewRelease(swapchainView); + static_cast(_colorTexture.get())->gpuTextureObject()->selfView = wgpuSwapChainGetCurrentTextureView(_gpuSwapchainObj->wgpuSwapChain); } void CCWGPUSwapchain::doDestroySurface() { diff --git a/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.h b/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.h index 2d78812b9e..8e9c064d7f 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.h @@ -42,9 +42,8 @@ public: inline CCWGPUSwapchainObject *gpuSwapchainObject() { return _gpuSwapchainObj; } - CCWGPUTexture *getColorTexture(); - - CCWGPUTexture *getDepthStencilTexture(); + inline void setColorTexture(Texture *tex) { _colorTexture = tex; } + inline void setDepthStencilTexture(Texture *tex) { _depthStencilTexture = tex; } void update(); diff --git a/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp b/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp index fadbbd29f9..654845c276 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp @@ -33,22 +33,27 @@ namespace cc { namespace gfx { -namespace anoymous { -CCWGPUTexture *defaultCommonTexture = nullptr; -CCWGPUTexture *defaultStorageTexture = nullptr; -} // namespace anoymous +namespace { +CCWGPUTexture *dftCommonTexture = nullptr; +CCWGPUTexture *dftStorageTexture = nullptr; +} // namespace using namespace emscripten; -CCWGPUTexture::CCWGPUTexture() : wrapper(val::object()) { +CCWGPUTexture::CCWGPUTexture() : Texture() { _gpuTextureObj = ccnew CCWGPUTextureObject; } +CCWGPUTexture::~CCWGPUTexture() { + doDestroy(); +} + void CCWGPUTexture::doInit(const TextureInfo &info) { uint8_t depthOrArrayLayers = info.depth; if (info.type == TextureType::CUBE) { depthOrArrayLayers = 6; } + WGPUTextureDescriptor descriptor = { .nextInChain = nullptr, .label = nullptr, @@ -61,6 +66,7 @@ void CCWGPUTexture::doInit(const TextureInfo &info) { }; _gpuTextureObj->wgpuTexture = wgpuDeviceCreateTexture(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + CCWGPUDevice::getInstance()->getMemoryStatus().textureSize += _size; WGPUTextureViewDescriptor texViewDesc = { .nextInChain = nullptr, @@ -99,6 +105,7 @@ void CCWGPUTexture::doInit(const TextureViewInfo &info) { void CCWGPUTexture::doInit(const SwapchainTextureInfo &info) { if (_swapchain) { + printf("swapchain %d, %d\n", info.width, info.height); auto *swapchain = static_cast(_swapchain); if (info.format == Format::DEPTH || info.format == Format::DEPTH_STENCIL) { WGPUTextureDescriptor descriptor = { @@ -112,6 +119,7 @@ void CCWGPUTexture::doInit(const SwapchainTextureInfo &info) { .sampleCount = 1, }; _gpuTextureObj->wgpuTexture = wgpuDeviceCreateTexture(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + CCWGPUDevice::getInstance()->getMemoryStatus().textureSize += _size; WGPUTextureAspect aspect = info.format == Format::DEPTH ? WGPUTextureAspect_DepthOnly : WGPUTextureAspect_All; WGPUTextureViewDescriptor texViewDesc = { @@ -136,16 +144,17 @@ void CCWGPUTexture::doInit(const SwapchainTextureInfo &info) { void CCWGPUTexture::doDestroy() { if (_gpuTextureObj) { if (_gpuTextureObj->wgpuTexture) { - wgpuTextureDestroy(_gpuTextureObj->wgpuTexture); - wgpuTextureRelease(_gpuTextureObj->wgpuTexture); + CCWGPUDevice::getInstance()->moveToTrash(_gpuTextureObj->wgpuTexture); + CCWGPUDevice::getInstance()->getMemoryStatus().textureSize -= _size; } if (_gpuTextureObj->wgpuTextureView) { wgpuTextureViewRelease(_gpuTextureObj->wgpuTextureView); } - if (_gpuTextureObj->selfView) { + if (_gpuTextureObj->selfView && !_isTextureView) { wgpuTextureViewRelease(_gpuTextureObj->selfView); } delete _gpuTextureObj; + _gpuTextureObj = nullptr; } _internalChanged = true; } @@ -156,9 +165,14 @@ void CCWGPUTexture::doResize(uint32_t width, uint32_t height, uint32_t size) { printf("Resize is not support on texture view!"); return; } + // swapchain color tex using canvas + if (_swapchain && _info.format != Format::DEPTH && _info.format != Format::DEPTH_STENCIL) { + auto *swapchain = static_cast(_swapchain); + _gpuTextureObj->selfView = wgpuSwapChainGetCurrentTextureView(swapchain->gpuSwapchainObject()->wgpuSwapChain); + return; + } if (_gpuTextureObj->wgpuTexture) { - wgpuTextureDestroy(_gpuTextureObj->wgpuTexture); - wgpuTextureRelease(_gpuTextureObj->wgpuTexture); + CCWGPUDevice::getInstance()->moveToTrash(_gpuTextureObj->wgpuTexture); } if (_gpuTextureObj->wgpuTextureView) { wgpuTextureViewRelease(_gpuTextureObj->wgpuTextureView); @@ -167,6 +181,9 @@ void CCWGPUTexture::doResize(uint32_t width, uint32_t height, uint32_t size) { wgpuTextureViewRelease(_gpuTextureObj->selfView); } + CCWGPUDevice::getInstance()->getMemoryStatus().textureSize -= _size; + CCWGPUDevice::getInstance()->getMemoryStatus().textureSize += size; + uint8_t depthOrArrayLayers = _info.depth; if (_info.type == TextureType::CUBE) { depthOrArrayLayers = 6; @@ -176,7 +193,7 @@ void CCWGPUTexture::doResize(uint32_t width, uint32_t height, uint32_t size) { .label = nullptr, .usage = toWGPUTextureUsage(_info.usage), .dimension = toWGPUTextureDimension(_info.type), - .size = {_info.width, _info.height, depthOrArrayLayers}, + .size = {width, height, depthOrArrayLayers}, .format = toWGPUTextureFormat(_info.format), .mipLevelCount = _info.levelCount, .sampleCount = toWGPUSampleCount(_info.samples), @@ -204,7 +221,7 @@ void CCWGPUTexture::stamp() { } CCWGPUTexture *CCWGPUTexture::defaultCommonTexture() { - if (!anoymous::defaultCommonTexture) { + if (!dftCommonTexture) { TextureInfo info = { .type = TextureType::TEX2D, .usage = TextureUsageBit::SAMPLED, @@ -218,15 +235,15 @@ CCWGPUTexture *CCWGPUTexture::defaultCommonTexture() { .depth = 1, .externalRes = nullptr, }; - anoymous::defaultCommonTexture = ccnew CCWGPUTexture; - anoymous::defaultCommonTexture->initialize(info); + dftCommonTexture = ccnew CCWGPUTexture; + dftCommonTexture->initialize(info); } - return anoymous::defaultCommonTexture; + return dftCommonTexture; } CCWGPUTexture *CCWGPUTexture::defaultStorageTexture() { - if (!anoymous::defaultStorageTexture) { + if (!dftStorageTexture) { TextureInfo info = { .type = TextureType::TEX2D, .usage = TextureUsageBit::STORAGE, @@ -240,11 +257,11 @@ CCWGPUTexture *CCWGPUTexture::defaultStorageTexture() { .depth = 1, .externalRes = nullptr, }; - anoymous::defaultStorageTexture = ccnew CCWGPUTexture; - anoymous::defaultStorageTexture->initialize(info); + dftStorageTexture = ccnew CCWGPUTexture; + dftStorageTexture->initialize(info); } - return anoymous::defaultStorageTexture; + return dftStorageTexture; } CCWGPUSwapchain *CCWGPUTexture::swapchain() { diff --git a/native/cocos/renderer/gfx-wgpu/WGPUTexture.h b/native/cocos/renderer/gfx-wgpu/WGPUTexture.h index 1985c36702..c451e8c1de 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUTexture.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUTexture.h @@ -24,7 +24,10 @@ ****************************************************************************/ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif +#include "WGPUDef.h" #include "gfx-base/GFXTexture.h" namespace cc { @@ -33,13 +36,12 @@ namespace gfx { struct CCWGPUTextureObject; class CCWGPUSwapchain; -class CCWGPUTexture final : public emscripten::wrapper { +class CCWGPUTexture final : public Texture { public: - EMSCRIPTEN_WRAPPER(CCWGPUTexture); CCWGPUTexture(); - ~CCWGPUTexture() = default; + ~CCWGPUTexture(); - inline CCWGPUTextureObject *gpuTextureObject() { return _gpuTextureObj; } + inline CCWGPUTextureObject *gpuTextureObject() const { return _gpuTextureObj; } static CCWGPUTexture *defaultCommonTexture(); @@ -53,6 +55,15 @@ public: // resource handler changed? inline bool internalChanged() const { return _internalChanged; } + inline uint32_t getDepth() const { return _info.depth; }; + inline uint32_t getLayerCount() const { return _info.layerCount; }; + inline uint32_t getLevelCount() const { return _info.levelCount; }; + inline auto getTextureType() const { return _info.type; }; + inline auto getTextureUsage() const { return _info.usage; }; + inline auto getTextureFormat() const { return _info.format; }; + inline auto getTextureSamples() const { return _info.samples; }; + inline auto getTextureFlags() const { return _info.flags; }; + protected: void doInit(const TextureInfo &info) override; void doInit(const TextureViewInfo &info) override; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUUtils.cpp b/native/cocos/renderer/gfx-wgpu/WGPUUtils.cpp new file mode 100644 index 0000000000..42b888b61e --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/WGPUUtils.cpp @@ -0,0 +1,49 @@ +#include "WGPUUtils.h" +#include "WGPUDescriptorSet.h" +#include "WGPUDescriptorSetLayout.h" +#include "WGPUDevice.h" +#include "WGPUObject.h" +#include "WGPUPipelineLayout.h" + +namespace cc::gfx { + +void createPipelineLayoutFallback(const ccstd::vector& descriptorSets, PipelineLayout* pipelineLayout) { + ccstd::hash_t hash = descriptorSets.size() * 2 + 1; + ccstd::hash_combine(hash, descriptorSets.size()); + std::string label = ""; + ccstd::vector descriptorSetLayouts; + for (size_t i = 0; i < descriptorSets.size(); ++i) { + auto* descriptorSet = static_cast(descriptorSets[i]); + if (descriptorSet && descriptorSet->getHash() != 0) { + auto* descriptorSetLayout = static_cast(descriptorSet->getLayout()); + auto* wgpuBindGroupLayout = static_cast(CCWGPUDescriptorSetLayout::getBindGroupLayoutByHash(descriptorSet->getHash())); + descriptorSetLayouts.push_back(wgpuBindGroupLayout); + ccstd::hash_combine(hash, i); + ccstd::hash_combine(hash, descriptorSet->getHash()); + label += std::to_string(descriptorSet->getHash()) + "-" + descriptorSet->label + "-" + std::to_string(descriptorSetLayout->getHash()) + " "; + } else { + descriptorSetLayouts.push_back(static_cast(CCWGPUDescriptorSetLayout::defaultBindGroupLayout())); + ccstd::hash_combine(hash, i); + ccstd::hash_combine(hash, 0); + } + } + + auto* ccPipelineLayout = static_cast(pipelineLayout); + WGPUPipelineLayoutDescriptor descriptor = { + .nextInChain = nullptr, + .label = label.c_str(), + .bindGroupLayoutCount = descriptorSetLayouts.size(), + .bindGroupLayouts = descriptorSetLayouts.data(), + }; + + auto iter = ccPipelineLayout->layoutMap.find(hash); + if (iter == ccPipelineLayout->layoutMap.end()) { + ccPipelineLayout->layoutMap[hash] = wgpuDeviceCreatePipelineLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + ccPipelineLayout->gpuPipelineLayoutObject()->wgpuPipelineLayout = static_cast(ccPipelineLayout->layoutMap[hash]); + printf("create new ppl\n"); + } else { + ccPipelineLayout->gpuPipelineLayoutObject()->wgpuPipelineLayout = static_cast(iter->second); + } + ccPipelineLayout->_hash = hash; +} +} // namespace cc::gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUUtils.h b/native/cocos/renderer/gfx-wgpu/WGPUUtils.h index feed8d4b32..9a73bb7946 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUUtils.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUUtils.h @@ -1,5 +1,6 @@ #pragma once #include +#include "base/std/container/vector.h" #include "cocos/base/Macros.h" #include "cocos/base/TypeDef.h" #include "gfx-base/GFXDef-common.h" @@ -146,6 +147,10 @@ static WGPUTextureSampleType textureSampleTypeTrait(Format format) { } } +static bool isFilterable(Format format) { + return textureSampleTypeTrait(format) != WGPUTextureSampleType_UnfilterableFloat; +} + static WGPUTextureAspect textureAspectTrait(Format format) { switch (format) { case Format::DEPTH: @@ -283,7 +288,7 @@ static WGPUAddressMode toWGPUAddressMode(Address addrMode) { static WGPUFilterMode toWGPUFilterMode(Filter filter) { switch (filter) { case Filter::NONE: - return WGPUFilterMode::WGPUFilterMode_Linear; + return WGPUFilterMode::WGPUFilterMode_Nearest; case Filter::POINT: return WGPUFilterMode::WGPUFilterMode_Nearest; case Filter::LINEAR: @@ -364,9 +369,9 @@ static WGPUShaderStageFlags toWGPUShaderStageFlag(ShaderStageFlagBit flag) { return result; } -//TODO_Zeqiang: more flexible strategy +// TODO_Zeqiang: more flexible strategy static uint32_t toWGPUSampleCount(SampleCount sampleCount) { - //TODO_Zeqiang: msaa + // TODO_Zeqiang: msaa return 1; switch (sampleCount) { case SampleCount::ONE: @@ -433,7 +438,7 @@ static WGPUBufferUsageFlags toWGPUBufferUsage(BufferUsageBit usage) { return res; } -static WGPUColor toWGPUColor(const Color &color) { +static WGPUColor toWGPUColor(const Color& color) { return WGPUColor{color.x, color.y, color.z, color.w}; } @@ -583,9 +588,52 @@ static WGPUFlags toWGPUColorWriteMask(ColorMask mask) { return result; } +static ccstd::string getAdapterTypeName(WGPUAdapterType type) { + switch(type) { + case WGPUAdapterType_DiscreteGPU: + return "WGPUAdapterType_DiscreteGPU"; + case WGPUAdapterType_IntegratedGPU: + return "WGPUAdapterType_IntegratedGPU"; + case WGPUAdapterType_CPU: + return "WGPUAdapterType_CPU"; + case WGPUAdapterType_Unknown: + return "WGPUAdapterType_Unknown"; + default: + return "unknown adapter by cc.gfx!"; + } +} + +static ccstd::string getBackendTypeName(WGPUBackendType type) { + switch(type) { + case WGPUBackendType_Null: + return "WGPUBackendType_Null"; + case WGPUBackendType_WebGPU: + return "WGPUBackendType_WebGPU"; + case WGPUBackendType_D3D11: + return "WGPUBackendType_D3D11"; + case WGPUBackendType_D3D12: + return "WGPUBackendType_D3D12"; + case WGPUBackendType_Metal: + return "WGPUBackendType_Metal"; + case WGPUBackendType_Vulkan: + return "WGPUBackendType_Vulkan"; + case WGPUBackendType_OpenGL: + return "WGPUBackendType_OpenGL"; + case WGPUBackendType_OpenGLES: + return "WGPUBackendType_OpenGLES"; + default: + return "unknown backend by cc.gfx!"; + } +} + +class DescriptorSet; +class PipelineLayout; +// descriptor set layout in descriptor set not consistent with the binding in pipeline layout. +void createPipelineLayoutFallback(const ccstd::vector& descriptorSets, PipelineLayout* pipelineLayout); + static constexpr WGPUColor defaultClearColor{0.2, 0.2, 0.2, 1.0}; static constexpr float defaultClearDepth = 1.0f; } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/states/WGPUBufferBarrier.cpp b/native/cocos/renderer/gfx-wgpu/states/WGPUBufferBarrier.cpp new file mode 100644 index 0000000000..412d73a6be --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/states/WGPUBufferBarrier.cpp @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2019-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "WGPUBufferBarrier.h" + +namespace cc { +namespace gfx { + +WGPUBufferBarrier::WGPUBufferBarrier(const BufferBarrierInfo &info) : BufferBarrier(info) { +} + +ccstd::hash_t WGPUBufferBarrier::computeHash(const BufferBarrierInfo &info) { + return 0; +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/states/WGPUBufferBarrier.h b/native/cocos/renderer/gfx-wgpu/states/WGPUBufferBarrier.h new file mode 100644 index 0000000000..875bbeb3c5 --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/states/WGPUBufferBarrier.h @@ -0,0 +1,45 @@ +/**************************************************************************** + Copyright (c) 2019-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include +#include "gfx-base/states/GFXBufferBarrier.h" + +namespace cc { +namespace gfx { + +class CC_DLL WGPUBufferBarrier : public BufferBarrier { +public: + explicit WGPUBufferBarrier(const BufferBarrierInfo &info); + + static ccstd::hash_t computeHash(const BufferBarrierInfo &info); + + // inline const GeneralBarrierInfo &getInfo() const { return _info; } + // inline const ccstd::hash_t &getHash() const { return _hash; } +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/states/WGPUGeneralBarrier.cpp b/native/cocos/renderer/gfx-wgpu/states/WGPUGeneralBarrier.cpp new file mode 100644 index 0000000000..85199e2b2e --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/states/WGPUGeneralBarrier.cpp @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2019-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "WGPUGeneralBarrier.h" + +namespace cc { +namespace gfx { + +WGPUGeneralBarrier::WGPUGeneralBarrier(const GeneralBarrierInfo &info) : GeneralBarrier(info) { +} + +ccstd::hash_t WGPUGeneralBarrier::computeHash(const GeneralBarrierInfo &info) { + return 0; +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/states/WGPUGeneralBarrier.h b/native/cocos/renderer/gfx-wgpu/states/WGPUGeneralBarrier.h new file mode 100644 index 0000000000..f995478bab --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/states/WGPUGeneralBarrier.h @@ -0,0 +1,45 @@ +/**************************************************************************** + Copyright (c) 2019-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include +#include "gfx-base/states/GFXGeneralBarrier.h" + +namespace cc { +namespace gfx { + +class CC_DLL WGPUGeneralBarrier : public GeneralBarrier { +public: + explicit WGPUGeneralBarrier(const GeneralBarrierInfo &info); + + static ccstd::hash_t computeHash(const GeneralBarrierInfo &info); + + // inline const GeneralBarrierInfo &getInfo() const { return _info; } + // inline const ccstd::hash_t &getHash() const { return _hash; } +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/states/WGPUTextureBarrier.cpp b/native/cocos/renderer/gfx-wgpu/states/WGPUTextureBarrier.cpp new file mode 100644 index 0000000000..445461bae5 --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/states/WGPUTextureBarrier.cpp @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2019-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "WGPUTextureBarrier.h" + +namespace cc { +namespace gfx { + +WGPUTextureBarrier::WGPUTextureBarrier(const TextureBarrierInfo &info) : TextureBarrier(info) { +} + +ccstd::hash_t WGPUTextureBarrier::computeHash(const TextureBarrierInfo &info) { + return 0; +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/states/WGPUTextureBarrier.h b/native/cocos/renderer/gfx-wgpu/states/WGPUTextureBarrier.h new file mode 100644 index 0000000000..0f38a42e66 --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/states/WGPUTextureBarrier.h @@ -0,0 +1,42 @@ +/**************************************************************************** + Copyright (c) 2019-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include +#include "gfx-base/states/GFXTextureBarrier.h" + +namespace cc { +namespace gfx { + +class CC_DLL WGPUTextureBarrier : public TextureBarrier { +public: + explicit WGPUTextureBarrier(const TextureBarrierInfo &info); + + static ccstd::hash_t computeHash(const TextureBarrierInfo &info); +}; + +} // namespace gfx +} // namespace cc diff --git a/scripts/build-engine/.vscode/launch.json b/scripts/build-engine/.vscode/launch.json index 5b9ae88daa..127a470180 100644 --- a/scripts/build-engine/.vscode/launch.json +++ b/scripts/build-engine/.vscode/launch.json @@ -1,5 +1,5 @@ { - // 使用 IntelliSense 了解相关属性。 + // 使用 IntelliSense 了解相关属性。 // 悬停以查看现有属性的描述。 // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", @@ -28,6 +28,7 @@ "base", "gfx-webgl", "gfx-webgl2", + "gfx-webgpu", "3d", "2d", "ui", diff --git a/scripts/build-engine/src/constant-manager.ts b/scripts/build-engine/src/constant-manager.ts index c85e0b6960..bdfcf53f21 100644 --- a/scripts/build-engine/src/constant-manager.ts +++ b/scripts/build-engine/src/constant-manager.ts @@ -6,7 +6,7 @@ export type ModeType = 'EDITOR' | 'PREVIEW' | 'BUILD' | 'TEST'; export type PlatformType = 'HTML5' | 'NATIVE' | 'WECHAT' | 'BAIDU' | 'XIAOMI' | 'ALIPAY' | 'BYTEDANCE' | 'OPPO' | 'VIVO' | 'HUAWEI' | 'COCOSPLAY' | 'QTT' | 'LINKSURE'; -export type InternalFlagType = 'SERVER_MODE' | 'NOT_PACK_PHYSX_LIBS'; +export type InternalFlagType = 'SERVER_MODE' | 'NOT_PACK_PHYSX_LIBS' | 'WEBGPU'; export type PublicFlagType = 'DEBUG' | 'NET_MODE'; export type FlagType = InternalFlagType | PublicFlagType; diff --git a/scripts/build-engine/src/index.ts b/scripts/build-engine/src/index.ts index 3d81f4faf0..e03386708e 100644 --- a/scripts/build-engine/src/index.ts +++ b/scripts/build-engine/src/index.ts @@ -29,6 +29,7 @@ import { filePathToModuleRequest } from './utils'; import { assetRef as rpAssetRef, pathToAssetRefURL } from './rollup-plugins/asset-ref'; import { codeAsset } from './rollup-plugins/code-asset'; import { ModeType, PlatformType } from './constant-manager'; +import { assetUrl } from './rollup-plugins/asset-url'; export { ModeType, PlatformType, FlagType, ConstantOptions, BuildTimeConstants, CCEnvConstants } from './constant-manager'; export { StatsQuery }; @@ -275,9 +276,11 @@ async function doBuild ({ // HACK: get platform, mode, flags from build time constants const flags: Record = {}; - ['SERVER_MODE', 'NOT_PACK_PHYSX_LIBS', 'DEBUG', 'NET_MODE'].forEach((key) => { + ['SERVER_MODE', 'NOT_PACK_PHYSX_LIBS', 'DEBUG', 'NET_MODE', 'WEBGPU'].forEach((key) => { flags[key] = buildTimeConstants[key]; }); + // Wether use webgpu + const useWebGPU = flags['WEBGPU']; let platform = options.platform as PlatformType; if (!platform) { ["HTML5", "NATIVE", "WECHAT", "BAIDU", "XIAOMI", "ALIPAY", "BYTEDANCE", "OPPO", "VIVO", "HUAWEI", "COCOSPLAY", "QTT", "LINKSURE"].some(key => { @@ -537,6 +540,11 @@ async function doBuild ({ defaultHandler(warning); }; + rollupPlugins.unshift(assetUrl({ + engineRoot, + useWebGPU, + })); + const rollupOptions: rollup.InputOptions = { input: rollupEntries, plugins: rollupPlugins, diff --git a/scripts/build-engine/src/rollup-plugins/asset-url.ts b/scripts/build-engine/src/rollup-plugins/asset-url.ts new file mode 100644 index 0000000000..e71f51a1a1 --- /dev/null +++ b/scripts/build-engine/src/rollup-plugins/asset-url.ts @@ -0,0 +1,65 @@ +import type * as rollup from 'rollup'; +import fs from 'fs-extra'; +import ps, { join } from 'path'; + +interface IOptions { + engineRoot: string, + useWebGPU?: boolean; +} +const URL_PROTOCOL = 'url:'; +const PREFIX = `\0${URL_PROTOCOL}`; + +export function assetUrl ({ + engineRoot, + useWebGPU = false, +}: IOptions): rollup.Plugin { + const files = new Set(); + return { + name: '@cocos/build-engine|external-asset', + + async resolveId (this, source, importer) { + if (source.startsWith(URL_PROTOCOL) && importer) { + const subPath = source.substring(URL_PROTOCOL.length); + const externalAssetPath = join(engineRoot, subPath); + return PREFIX + externalAssetPath; + } + + return null; + }, + + async load (id) { + if (id.startsWith(PREFIX)) { + const path = id.substring(PREFIX.length); + if (!useWebGPU) { + return `export default '';`; + } + const referenceId = this.emitFile({ + type: 'asset', + name: ps.basename(path), + source: await fs.readFile(path), + }); + files.add(referenceId); + return `export default import.meta.ROLLUP_FILE_URL_${referenceId};`; + } + return null; + }, + + // Generates the `import.meta.ROLLUP_FILE_URL_referenceId`. + resolveFileUrl ({ + // > The path and file name of the emitted asset, relative to `output.dir` without a leading `./`. + fileName, + // > The path and file name of the emitted file, + // > relative to the chunk the file is referenced from. + // > This will path will contain no leading `./` but may contain a leading `../`. + relativePath, + + referenceId, + }) { + if (files.has(referenceId)) { + return `'${fileName}'`; + } else { + return undefined; + } + }, + }; +} \ No newline at end of file diff --git a/scripts/build-engine/tests/stats-query/cc.config.json b/scripts/build-engine/tests/stats-query/cc.config.json index 4a3f1448fe..a990cd947e 100644 --- a/scripts/build-engine/tests/stats-query/cc.config.json +++ b/scripts/build-engine/tests/stats-query/cc.config.json @@ -5,6 +5,7 @@ "base": { "modules": [ "base" ], "dependentAssets": ["0835f102-5471-47a3-9a76-01c07ac9cdb2", "b5475517-23b9-4873-bc1a-968d96616081", "0ed97c56-390e-4dd1-96b7-e7f2d93a98ed", "b23391b6-52eb-46a6-8da1-6244d9d315fb"] }, "gfx-webgl": { "modules": [ "gfx-webgl" ] }, "gfx-webgl2": { "modules": [ "gfx-webgl2" ] }, + "gfx-webgpu": { "modules": [ "gfx-webgpu" ] }, "3d": { "modules": [ "3d" ] }, "animation": { "modules": ["animation"] }, "skeletal-animation": { "modules": ["animation", "skeletal-animation"] }, diff --git a/templates/cmake/emscripten.cmake b/templates/cmake/emscripten.cmake new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/general/sealed-global-variables.json b/tests/general/sealed-global-variables.json index 133756b8f6..3354b8c7d6 100644 --- a/tests/general/sealed-global-variables.json +++ b/tests/general/sealed-global-variables.json @@ -8,7 +8,7 @@ "cc.AmbientInfo", "cc.AnimCurve", "cc.AnimationClip", - "cc.Animation", + "cc.Animation", "cc.AnimationComponent", "cc.AnimationManager", "cc.AnimationState", @@ -25,7 +25,7 @@ "cc.Boolean", "cc.BoxColliderComponent", "cc.BufferAsset", - "cc.Button", + "cc.Button", "cc.ButtonComponent", "cc.CCBoolean", "cc.CCFloat", @@ -119,18 +119,18 @@ "cc.GFX_MAX_TEXTURE_UNITS", "cc.GFX_MAX_VERTEX_ATTRIBUTES", "cc.Game", - "cc.Graphics", + "cc.Graphics", "cc.GraphicsComponent", "cc.ImageAsset", "cc.Integer", "cc.JsonAsset", "cc.LabelAtlas", - "cc.Label", + "cc.Label", "cc.LabelComponent", - "cc.LabelOutline", + "cc.LabelOutline", "cc.LabelOutlineComponent", "cc.Layers", - "cc.Layout", + "cc.Layout", "cc.LayoutComponent", "cc.LightComponent", "cc.LineComponent", @@ -146,9 +146,9 @@ "cc.NodeEventProcessor", "cc.NodePool", "cc.Object", - "cc.PageView", + "cc.PageView", "cc.PageViewComponent", - "cc.PageViewIndicator", + "cc.PageViewIndicator", "cc.PageViewIndicatorComponent", "cc.ParticleAsset", "cc.ParticleSystemComponent", @@ -161,7 +161,7 @@ "cc.Prefab", "cc.Primitive", "cc.PrivateNode", - "cc.ProgressBar", + "cc.ProgressBar", "cc.ProgressBarComponent", "cc.Quat", "cc.RatioSampler", @@ -173,19 +173,19 @@ "cc.RenderTexture", "cc.RenderableComponent", "cc.ResolutionPolicy", - "cc.RichText", + "cc.RichText", "cc.RichTextComponent", "cc.RigidBodyComponent", "cc.Root", - "cc.SafeArea", + "cc.SafeArea", "cc.SafeAreaComponent", "cc.Scene", "cc.SceneAsset", "cc.SceneGlobals", "cc.Scheduler", - "cc.ScrollBar", + "cc.ScrollBar", "cc.ScrollBarComponent", - "cc.ScrollView", + "cc.ScrollView", "cc.ScrollViewComponent", "cc.Shadows", "cc.ShadowsInfo", @@ -197,13 +197,13 @@ "cc.SkinningModelUnit", "cc.Skybox", "cc.SkyboxInfo", - "cc.Slider", + "cc.Slider", "cc.SliderComponent", "cc.SphereColliderComponent", "cc.SphereLightComponent", "cc.SpotLightComponent", "cc.SpriteAtlas", - "cc.Sprite", + "cc.Sprite", "cc.SpriteComponent", "cc.SpriteFrame", "cc.String", @@ -215,14 +215,14 @@ "cc.Texture2D", "cc.TextureBase", "cc.TextureCube", - "cc.Toggle", + "cc.Toggle", "cc.ToggleComponent", - "cc.ToggleContainer", + "cc.ToggleContainer", "cc.ToggleContainerComponent", "cc.Touch", "cc.Tween", "cc.UI", - "cc.UIMeshRenderer", + "cc.UIMeshRenderer", "cc.UIModelComponent", "cc.UIReorderComponent", "cc.UITransformComponent", @@ -234,7 +234,7 @@ "cc.VisibilityFlags", "cc.WebGL2Device", "cc.WebGLDevice", - "cc.Widget", + "cc.Widget", "cc.WidgetComponent", "cc._BaseNode", "cc._JavaScript", diff --git a/tsconfig.json b/tsconfig.json index 6d4555fe2e..6cfec7d726 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -26,6 +26,7 @@ "./@types/editor-extends", "./@types/webGL.extras", "./@types/webGL2.extras", + "./@types/url", "./node_modules/@cocos/cannon/CANNON", "./node_modules/@cocos/bullet/bullet", "./node_modules/@cocos/physx/PhysX",