Compare commits

..

15 Commits

Author SHA1 Message Date
hyde zhou fffd9a514a bump version to 4.0.0-alpha.34 (#339) 2026-09-14 17:55:42 +08:00
Cocos Robot 5678d0d17c [ci skip][AUTO]: Automated clang-format update: f264405b7e (#330) (#331)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-09-14 17:03:08 +08:00
Cocos Robot 2ce7b89be5 [ci skip][AUTO]: Automated clang-format update: ffc817b76f (#336) (#337)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-09-14 17:02:34 +08:00
zxx43 6b455561f4 optimize noise function (#338)
* optimize noise function

* format
2026-09-14 16:06:30 +08:00
MagicX 60f9352c56 fix(mesh): hoose index format by max index value in createMesh (#336)
* Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks (custom pipeline).

* Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks. (old pipeline)

* CI error: Function parameter names cannot be omitted.

* Move the devil string to macro

* fix(mesh): hoose index format by max index value in createMesh
2026-09-14 14:10:33 +08:00
李吉林 f66365f959 add @visible(false) for TerrainInfo (#334) 2026-09-11 15:09:24 +08:00
MagicXHouse a3c3fcbea5 Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks. (#330)
* Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks (custom pipeline).

* Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks. (old pipeline)

* CI error: Function parameter names cannot be omitted.

* Move the devil string to macro
2026-09-08 19:35:05 +08:00
Ming 2a75cfb9da fix(webgpu): fix error pipelinelayout order (#329)
Co-authored-by: vanitynie <vanitynie@qq.com>
2026-09-08 11:27:06 +08:00
yangchao 0c3f4534b8 fix: normalize asset root path for source_group on windows (#324) 2026-09-07 21:41:36 +08:00
hyde zhou 7f806abad6 bump version to 4.0.0-alpha.33 (#328) 2026-09-07 20:00:19 +08:00
Ming df98a99bb6 fix(wgpu): correct swapped maxComputeWorkGroupSize/Count capabilities (#327)
Co-authored-by: vanitynie <vanitynie@qq.com>
2026-09-07 19:00:55 +08:00
Ming a5090e5ae4 add compute shader on webgpu (#323)
* feat(webgpu): support compute shader on webgpu

* fix(webgpu): fix webComputePassBuilder addTexture and descriptor set bind

* fix(webgpu): mark compute producer passes valid and force-prepare bound descriptor sets

* feat(profiler): add compute dispatch counter

* perf(webgpu): cache compute pipeline states

* refactor(webgpu): simplify descriptor set prepare and dedupe bind group collection

- WebGPUDescriptorSet.prepare(): build the bind group when it was never created,
  so command buffers no longer need a force-prepare branch.
- WebGPUCommandBuffer: extract _collectBindGroups() shared by the draw and
  compute paths; drop the defaultResource bind group fallback since prepare()
  now guarantees a valid bind group.
- executor: guard PreRenderVisitor.dispatch with the COMPUTE_SHADER feature
  (symmetric with PostRenderVisitor.compute) and drop the redundant pass check.

* fix(webgpu): respect storage buffer access type in bind group layout

* fix(types): narrow types to pass tsc  check

* chore(webgpu): clean up redundant assertions and long line in pipeline state

---------

Co-authored-by: VanityNie <vanitynie@qq.com>
2026-09-07 14:36:06 +08:00
zxx43 3b71bf6935 fix particle2d preview error (#326) 2026-09-05 18:58:01 +08:00
J.C 54fd070848 wrong const value passed for webgl2 to op with image 3d (#297) 2026-09-04 15:06:32 +08:00
llsansun 6722aac669 When copying the old buffer value, if the old value is undefined (o… (#321)
* When copying the old buffer value, if the old value is `undefined` (out‑of‑bounds access to an empty array), preserve the default value of `-1` instead of writing `undefined`.

* opt
2026-09-02 18:02:58 +08:00
36 changed files with 664 additions and 237 deletions
+7 -2
View File
@@ -172,13 +172,18 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
// Fill index buffer.
let indexBuffer: ArrayBuffer | null = null;
let idxCount = 0;
const idxStride = 2;
let idxStride = 2;
let indexFormat = Format.R16UI;
if (geometry.indices) {
const { indices } = geometry;
idxCount = indices.length;
if (indices.some((i) => i > 0xFFFF)) {
idxStride = 4;
indexFormat = Format.R32UI;
}
indexBuffer = new ArrayBuffer(idxStride * idxCount);
const indexBufferView = new DataView(indexBuffer);
writeBuffer(indexBufferView, indices, Format.R16UI);
writeBuffer(indexBufferView, indices, indexFormat);
}
// Create primitive.
+10
View File
@@ -88,6 +88,14 @@ export abstract class CommandBuffer extends GFXObject {
return this._numTris;
}
/**
* @en Number of compute dispatches currently recorded.
* @zh 计算调度(dispatch)次数。
*/
get numDispatches (): number {
return this._numDispatches;
}
/** @mangle */
protected _queue: Queue | null = null;
/** @mangle */
@@ -95,6 +103,8 @@ export abstract class CommandBuffer extends GFXObject {
/** @mangle */
protected _numDrawCalls = 0;
/** @mangle */
protected _numDispatches = 0;
/** @mangle */
protected _numInstances = 0;
/** @mangle */
protected _numTris = 0;
+10
View File
@@ -127,6 +127,14 @@ export abstract class Device {
return this._numTris;
}
/**
* @en Number of compute dispatches currently recorded.
* @zh 计算调度(dispatch)次数。
*/
get numDispatches (): number {
return this._numDispatches;
}
/**
* @en Total memory size currently allocated.
* @zh 内存状态。
@@ -168,6 +176,8 @@ export abstract class Device {
/** @mangle */
protected _numDrawCalls = 0;
/** @mangle */
protected _numDispatches = 0;
/** @mangle */
protected _numInstances = 0;
/** @mangle */
protected _numTris = 0;
+3 -3
View File
@@ -2986,7 +2986,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
if (!isCompressed) {
gl.texSubImage3D(
WebGLConstants.TEXTURE_2D_ARRAY,
WebGLConstants.TEXTURE_3D,
mipLevel,
offset.x,
offset.y,
@@ -3000,7 +3000,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
);
} else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL as number) {
gl.compressedTexSubImage3D(
WebGLConstants.TEXTURE_2D_ARRAY,
WebGLConstants.TEXTURE_3D,
mipLevel,
offset.x,
offset.y,
@@ -3013,7 +3013,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
);
} else { // WEBGL_compressed_texture_etc1
gl.compressedTexImage3D(
WebGLConstants.TEXTURE_2D_ARRAY,
WebGLConstants.TEXTURE_3D,
mipLevel,
gpuTexture.glInternalFmt,
destWidth,
+89 -28
View File
@@ -40,6 +40,7 @@ import {
TextureBlit,
DescriptorSetInfo,
Format,
DispatchInfo,
} from '../base/define';
import { Framebuffer } from '../base/framebuffer';
import { InputAssembler } from '../base/input-assembler';
@@ -179,6 +180,7 @@ export class WebGPUCommandBuffer extends CommandBuffer {
private _wgpuRenderPass!: WebGPURenderPass;
private _renderPassFuncQueue: ((renPassEncoder: GPURenderPassEncoder) => void)[] = [];
private _computeFuncQueue: ((computePassEncoder: GPUComputePassEncoder) => void)[] = [];
public initialize (info: CommandBufferInfo): boolean {
this._type = info.type;
@@ -222,13 +224,16 @@ export class WebGPUCommandBuffer extends CommandBuffer {
this._curStencilWriteMask = null;
this._curStencilCompareMask = null;
this._numDrawCalls = 0;
this._numDispatches = 0;
this._numInstances = 0;
this._numTris = 0;
this._computeFuncQueue.length = 0;
}
public end (): void {
this._isStateValid = false;
this._isInRenderPass = false;
this._computeFuncQueue.length = 0;
}
public beginRenderPass (
@@ -650,22 +655,20 @@ export class WebGPUCommandBuffer extends CommandBuffer {
this.cmdPackage.cmds.concat(cmdPackage.cmds.array);
this._numDrawCalls += WebGPUCmdBuff._numDrawCalls;
this._numDispatches += WebGPUCmdBuff._numDispatches;
this._numInstances += WebGPUCmdBuff._numInstances;
this._numTris += WebGPUCmdBuff._numTris;
}
}
protected bindStates (): void {
if (!this._curGPUPipelineState) {
return;
}
const gpuPipelineLayout = this._curGPUPipelineState.gpuPipelineLayout as IWebGPUGPUPipelineLayout;
private _prepareDescriptorSets (): void {
const wgpuPipLayout = (currPipelineState?.pipelineLayout as WebGPUPipelineLayout);
const device = WebGPUDeviceManager.instance;
for (let i = 0; i < groupSets.length; i++) {
const currSetIdx = groupSets[i];
const currDesc = descriptorSets[currSetIdx];
if (currDesc && currDesc.gpuDescriptorSet) {
// prepare() builds the bind group if it was never created, or rebuilds it on resource change.
currDesc.prepare();
} else {
const currLayout = wgpuPipLayout.setLayouts[currSetIdx];
@@ -675,23 +678,13 @@ export class WebGPUCommandBuffer extends CommandBuffer {
newDescSet.prepare(true);
}
}
const gpuIA = this._curGPUInputAssembler!;
// only 4x MSAA is supported
gpuIA.samples = samples > 1 ? 4 : 1;
this._curWebGPUPipelineState!.prepare(gpuIA);
// ----------------------------wgpu pipline state-----------------------------
const wgpuPipeline = this._curGPUPipelineState.nativePipeline as GPURenderPipeline;
const pplFunc = (passEncoder: GPURenderPassEncoder): void => {
passEncoder.setPipeline(wgpuPipeline);
};
this._renderPassFuncQueue.push(pplFunc);
if (this._curGPUPipelineState.pipelineState?.depthStencil) {
const stencilRef = this._curGPUPipelineState.stencilRef;
const stencilRefFunc = (passEncoder: GPURenderPassEncoder): void => {
passEncoder.setStencilReference(stencilRef);
};
this._renderPassFuncQueue.push(stencilRefFunc);
}
}
/**
* Collect the bind groups and dynamic offsets for the currently bound descriptor sets.
* Shared by the draw (bindStates) and compute (dispatch) paths.
*/
private _collectBindGroups (): { wgpuBindGroups: GPUBindGroup[]; wgpuDynOffsets: number[][] } {
const currGPUDescSize = groupSets.length;
const wgpuBindGroups = new Array<GPUBindGroup>(currGPUDescSize);
const wgpuDynOffsets = new Array<number[]>(currGPUDescSize);
@@ -703,7 +696,7 @@ export class WebGPUCommandBuffer extends CommandBuffer {
wgpuDynOffsets[currSetIdx] = [...this._curDynamicOffsets[currSetIdx]];
if (!descObj.dynamicOffsetCount) {
wgpuDynOffsets[currSetIdx] = [];
} else if (descObj && descObj.dynamicOffsetCount !== wgpuDynOffsets[currSetIdx].length) {
} else if (descObj.dynamicOffsetCount !== wgpuDynOffsets[currSetIdx].length) {
wgpuDynOffsets[currSetIdx].length = descObj.dynamicOffsetCount;
for (let j = 0; j < descObj.dynamicOffsetCount; j++) {
const currOffset = wgpuDynOffsets[currSetIdx][j];
@@ -719,16 +712,84 @@ export class WebGPUCommandBuffer extends CommandBuffer {
}
}
}
return { wgpuBindGroups, wgpuDynOffsets };
}
public dispatch (info: DispatchInfo): void {
if (!this._curGPUPipelineState) {
return;
}
// Prepare descriptor sets (same logic as bindStates)
this._prepareDescriptorSets();
// Create compute pipeline
this._curWebGPUPipelineState!.prepare(null!);
const computePipeline = this._curGPUPipelineState.nativePipeline as GPUComputePipeline;
// Build bind groups for compute pass
const { wgpuBindGroups, wgpuDynOffsets } = this._collectBindGroups();
const func = (passEncoder: GPUComputePassEncoder): void => {
passEncoder.setPipeline(computePipeline);
const gpuBindGroupSize = wgpuBindGroups.length;
for (let i = 0; i < gpuBindGroupSize; i++) {
passEncoder.setBindGroup(i, wgpuBindGroups[i], wgpuDynOffsets[i]);
}
passEncoder.dispatchWorkgroups(info.groupCountX, info.groupCountY, info.groupCountZ);
};
this._computeFuncQueue.push(func);
++this._numDispatches;
this._isStateValid = false;
}
public submitComputePass (): void {
if (this._computeFuncQueue.length === 0) {
return;
}
const device = WebGPUDeviceManager.instance;
const nativeDevice = device.nativeDevice!;
const cmdEncoder = nativeDevice.createCommandEncoder();
const computePassEncoder = cmdEncoder.beginComputePass();
this._computeFuncQueue.forEach((cb) => {
cb(computePassEncoder);
});
computePassEncoder.end();
nativeDevice.queue.submit([cmdEncoder.finish()]);
this._computeFuncQueue.length = 0;
}
protected bindStates (): void {
if (!this._curGPUPipelineState) {
return;
}
const gpuPipelineLayout = this._curGPUPipelineState.gpuPipelineLayout as IWebGPUGPUPipelineLayout;
this._prepareDescriptorSets();
const gpuIA = this._curGPUInputAssembler!;
// only 4x MSAA is supported
gpuIA.samples = samples > 1 ? 4 : 1;
this._curWebGPUPipelineState!.prepare(gpuIA);
// ----------------------------wgpu pipline state-----------------------------
const wgpuPipeline = this._curGPUPipelineState.nativePipeline as GPURenderPipeline;
const pplFunc = (passEncoder: GPURenderPassEncoder): void => {
passEncoder.setPipeline(wgpuPipeline);
};
this._renderPassFuncQueue.push(pplFunc);
const pipelineDesc = this._curGPUPipelineState.pipelineState;
if (pipelineDesc && 'depthStencil' in pipelineDesc && pipelineDesc.depthStencil) {
const stencilRef = this._curGPUPipelineState.stencilRef;
const stencilRefFunc = (passEncoder: GPURenderPassEncoder): void => {
passEncoder.setStencilReference(stencilRef);
};
this._renderPassFuncQueue.push(stencilRefFunc);
}
const { wgpuBindGroups, wgpuDynOffsets } = this._collectBindGroups();
const bgfunc = (passEncoder: GPURenderPassEncoder): void => {
const gpuBindGroupSize = wgpuBindGroups.length;
for (let i = 0; i < gpuBindGroupSize; i++) {
let currBindGroup = wgpuBindGroups[i];
if (!currBindGroup) {
currBindGroup = (device.defaultResource.descSet as WebGPUDescriptorSet).gpuDescriptorSet.bindGroup;
}
// FIXME: this is a special sentence that 2 in 3 parameters I'm not certain.
passEncoder.setBindGroup(i, currBindGroup, wgpuDynOffsets[i]);
passEncoder.setBindGroup(i, wgpuBindGroups[i], wgpuDynOffsets[i]);
}
};
this._renderPassFuncQueue.push(bgfunc);
+10 -5
View File
@@ -35,6 +35,7 @@ import {
TextureUsageBit,
ShaderStageFlags,
DescriptorType,
MemoryAccessBit,
Color, Rect, Viewport, BufferTextureCopy,
SamplerInfo,
FormatSize,
@@ -1423,11 +1424,15 @@ export function createBindGroupLayoutEntry (currBind: DescriptorSetLayoutBinding
case DescriptorType.STORAGE_BUFFER:
case DescriptorType.DYNAMIC_STORAGE_BUFFER:
entry.buffer = {
type: 'storage',
hasDynamicOffset: type === DescriptorType.DYNAMIC_STORAGE_BUFFER,
minBindingSize: undefined,
};
{
const readOnly = (currBind.access & MemoryAccessBit.READ_ONLY) !== 0
&& (currBind.access & MemoryAccessBit.WRITE_ONLY) === 0;
entry.buffer = {
type: readOnly ? 'read-only-storage' : 'storage',
hasDynamicOffset: type === DescriptorType.DYNAMIC_STORAGE_BUFFER,
minBindingSize: undefined,
};
}
break;
case DescriptorType.SAMPLER_TEXTURE:
+20 -7
View File
@@ -170,9 +170,17 @@ export class WebGPUDescriptorSet extends DescriptorSet {
if (descType & (DescriptorType.DYNAMIC_STORAGE_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER)) {
this._dynamicOffsets.push(bindIdx);
}
} else if (descType & DESCRIPTOR_SAMPLER_TYPE) {
if ((descType & DescriptorType.SAMPLER) !== DescriptorType.SAMPLER) {
// texture
} else if (descType & (DESCRIPTOR_SAMPLER_TYPE | DescriptorType.STORAGE_IMAGE)) {
const isStorageImage = (descType & DescriptorType.STORAGE_IMAGE) === DescriptorType.STORAGE_IMAGE;
if (isStorageImage) {
// storage texture (compute read/write): bind the texture view, no sampler
let currTex = this._textures[i] as WebGPUTexture;
if (!currTex || (currTex.hasChange && !currTex.gpuTexture)) {
currTex = device.defaultResource.texture;
}
this._bindTextureEntry(binding, currTex);
} else if ((descType & DescriptorType.SAMPLER) !== DescriptorType.SAMPLER) {
// sampled texture
let currTex = this._textures[i] as WebGPUTexture;
// null or destroyed?
if (!currTex || (currTex.hasChange && !currTex.gpuTexture)) {
@@ -185,9 +193,9 @@ export class WebGPUDescriptorSet extends DescriptorSet {
this._bindTextureEntry(binding, currTex);
}
if (!((descType & DescriptorType.STORAGE_IMAGE) === DescriptorType.STORAGE_IMAGE
|| (descType & DescriptorType.INPUT_ATTACHMENT) === DescriptorType.INPUT_ATTACHMENT
|| (descType & DescriptorType.TEXTURE) === DescriptorType.TEXTURE)) {
if (!isStorageImage
&& !((descType & DescriptorType.INPUT_ATTACHMENT) === DescriptorType.INPUT_ATTACHMENT
|| (descType & DescriptorType.TEXTURE) === DescriptorType.TEXTURE)) {
// sampler
const currSampler = (this._samplers[i] || device.defaultResource.sampler) as WebGPUSampler;
this._bindSamplerEntry(binding, currSampler);
@@ -219,7 +227,12 @@ export class WebGPUDescriptorSet extends DescriptorSet {
}
public prepare (force: boolean = false): void {
const breakUpdate = !this._isResourceChange() && !force;
const gpuDescriptorSet = this._gpuDescriptorSet;
if (!gpuDescriptorSet) {
return;
}
// Rebuild when forced, when the bind group has never been built, or when resources changed.
const breakUpdate = gpuDescriptorSet.bindGroup && !this._isResourceChange() && !force;
if (breakUpdate) return;
this._isDirty = true;
this._applyBindGroup();
+19 -1
View File
@@ -53,7 +53,7 @@ import { WebGPUTexture } from './webgpu-texture';
import { DefaultResources, hashCombineNum, hashCombineStr, webGPU, WebGPUDeviceManager } from './define';
import {
Filter, Format,
QueueType, Feature, BufferTextureCopy, Rect, DescriptorSetInfo,
QueueType, Feature, BufferTextureCopy, Rect, Size, DescriptorSetInfo,
BufferInfo, BufferViewInfo, CommandBufferInfo, DeviceInfo,
FramebufferInfo, InputAssemblerInfo, QueueInfo, RenderPassInfo, SamplerInfo,
ShaderInfo, PipelineLayoutInfo, DescriptorSetLayoutInfo, TextureInfo, TextureViewInfo, GeneralBarrierInfo, TextureBarrierInfo,
@@ -552,6 +552,22 @@ export class WebGPUDevice extends Device {
this._caps.max3DTextureSize = limits.maxTextureDimension3D;
this._caps.uboOffsetAlignment = limits.minUniformBufferOffsetAlignment;
// Compute limits are read from the device (not the adapter): no elevated
// compute limits are requested, so these are the values validation enforces.
const deviceLimits = device.limits;
this._caps.maxComputeSharedMemorySize = deviceLimits.maxComputeWorkgroupStorageSize;
this._caps.maxComputeWorkGroupInvocations = deviceLimits.maxComputeInvocationsPerWorkgroup;
this._caps.maxComputeWorkGroupSize = new Size(
deviceLimits.maxComputeWorkgroupSizeX,
deviceLimits.maxComputeWorkgroupSizeY,
deviceLimits.maxComputeWorkgroupSizeZ,
);
this._caps.maxComputeWorkGroupCount = new Size(
deviceLimits.maxComputeWorkgroupsPerDimension,
deviceLimits.maxComputeWorkgroupsPerDimension,
deviceLimits.maxComputeWorkgroupsPerDimension,
);
const features = this._adapter!.features;
// FIXME: require by query
this._multiDrawIndirect = false;
@@ -560,6 +576,7 @@ export class WebGPUDevice extends Device {
this._features[Feature.ELEMENT_INDEX_UINT] = true;
this._features[Feature.INSTANCED_ARRAYS] = true;
this._features[Feature.MULTIPLE_RENDER_TARGETS] = true;
this._features[Feature.COMPUTE_SHADER] = true;
this.initFormatFeatures(features);
this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS));
@@ -684,6 +701,7 @@ export class WebGPUDevice extends Device {
public present (): void {
const queue = (this._queue as unknown as WebGPUQueue);
this._numDrawCalls = queue.numDrawCalls;
this._numDispatches = queue.numDispatches;
this._numInstances = queue.numInstances;
this._numTris = queue.numTris;
queue.clear();
+2 -2
View File
@@ -241,8 +241,8 @@ export interface IWebGPUGPUPipelineState {
bs: BlendState;
dynamicStates: DynamicStateFlagBit[];
gpuRenderPass: IWebGPUGPURenderPass | null;
pipelineState: GPURenderPipelineDescriptor | undefined;
nativePipeline: GPUPipelineBase | undefined;
pipelineState: GPURenderPipelineDescriptor | GPUComputePipelineDescriptor | undefined;
nativePipeline: GPURenderPipeline | GPUComputePipeline | undefined;
}
export interface IWebGPUGPUDescriptor {
+161 -118
View File
@@ -26,7 +26,7 @@ import { PipelineState, PipelineStateInfo } from '../base/pipeline-state';
import { IWebGPUGPUInputAssembler, IWebGPUGPUPipelineState } from './webgpu-gpu-objects';
import { WebGPURenderPass } from './webgpu-render-pass';
import { WebGPUShader } from './webgpu-shader';
import { BlendOp, CullMode, DynamicStateFlagBit, Format, FormatInfos, PrimitiveMode, ShaderStageFlagBit } from '../base/define';
import { BlendOp, CullMode, DynamicStateFlagBit, Format, FormatInfos, PipelineBindPoint, PrimitiveMode, ShaderStageFlagBit } from '../base/define';
import { WebGPUPipelineLayout } from './webgpu-pipeline-layout';
import {
GFXFormatToWGPUFormat,
@@ -81,124 +81,156 @@ export class WebGPUPipelineState extends PipelineState {
}
}
// colorstates
const colorAttachments = this._renderPass.colorAttachments;
const colorDescs: GPUColorTargetState[] = [];
const colAttachmentSize = colorAttachments.length;
const pipelineLayoutObj = info.pipelineLayout as WebGPUPipelineLayout;
for (let i = 0; i < colAttachmentSize; i++) {
const colDesc: GPUColorTargetState = {
format: GFXFormatToWGPUFormat(colorAttachments[i].format),
writeMask: WebGPUBlendMask(this._bs.targets[i].blendColorMask),
};
if (this._bs.targets[i].blend) {
colDesc.blend = {
color: {
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDst],
operation: WebGPUBlendOps[this._bs.targets[i].blendEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendEq],
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrc],
},
alpha: {
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDstAlpha],
operation: WebGPUBlendOps[this._bs.targets[i].blendAlphaEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendAlphaEq],
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrcAlpha],
},
};
}
colorDescs.push(colDesc);
}
let vertexStage: GPUProgrammableStage;
let fragmentStage: GPUProgrammableStage;
const shaderStages = (this._shader as WebGPUShader).gpuShader.gpuStages;
const stageSize = shaderStages.length;
for (let i = 0; i < stageSize; i++) {
if (shaderStages[i].type === ShaderStageFlagBit.VERTEX) { vertexStage = shaderStages[i].gpuShader!; }
if (shaderStages[i].type === ShaderStageFlagBit.FRAGMENT) { fragmentStage = shaderStages[i].gpuShader!; }
}
const gpuShader = info.shader as WebGPUShader;
const pipelineLayoutObj = info.pipelineLayout as WebGPUPipelineLayout;
const shaderStages = gpuShader.gpuShader.gpuStages;
const shaderAttrs = gpuShader.attributes;
const attrsSize = shaderAttrs.length;
for (let i = 0; i < attrsSize; i++) {
this._locations.set(shaderAttrs[i].name, shaderAttrs[i].location);
}
const stripTopology = (info.primitive === PrimitiveMode.LINE_STRIP || info.primitive === PrimitiveMode.TRIANGLE_STRIP);
const renderPplDesc: GPURenderPipelineDescriptor = {
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
vertex: {
module: vertexStage!.module,
entryPoint: 'main',
buffers: [],
},
primitive: {
topology: WebPUPrimitives[info.primitive],
frontFace: this._rs.isFrontFaceCCW ? 'ccw' : 'cw',
cullMode: this._rs.cullMode === CullMode.NONE ? 'none' : (this._rs.cullMode === CullMode.FRONT) ? 'front' : 'back',
},
fragment: {
module: fragmentStage!.module,
entryPoint: 'main',
targets: colorDescs,
},
};
if (stripTopology) renderPplDesc.primitive!.stripIndexFormat = 'uint16';
// depthstencil states
let stencilRef = 0;
if (this._renderPass.depthStencilAttachment?.format !== Format.UNKNOWN) {
const dssDesc = {} as GPUDepthStencilState;
dssDesc.format = GFXFormatToWGPUFormat(this._renderPass.depthStencilAttachment!.format);
dssDesc.depthWriteEnabled = this._dss.depthWrite;
dssDesc.depthCompare = this._dss.depthTest ? WebGPUCompereFunc[this._dss.depthFunc] : 'always';
let stencilReadMask = 0;
let stencilWriteMask = 0;
if (this._dss.stencilTestFront) {
dssDesc.stencilFront = {
compare: WebGPUCompereFunc[this._dss.stencilFuncFront],
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpFront],
passOp: WebGPUStencilOp[this._dss.stencilPassOpFront],
failOp: WebGPUStencilOp[this._dss.stencilFailOpFront],
};
stencilReadMask |= this._dss.stencilReadMaskFront;
stencilWriteMask |= this._dss.stencilWriteMaskFront;
stencilRef |= this._dss.stencilRefFront;
if (info.bindPoint === PipelineBindPoint.COMPUTE) {
// ---- Compute Pipeline ----
let computeStage: GPUProgrammableStage | undefined;
const stageSize = shaderStages.length;
for (let i = 0; i < stageSize; i++) {
if (shaderStages[i].type === ShaderStageFlagBit.COMPUTE) {
computeStage = shaderStages[i].gpuShader!;
}
}
if (this._dss.stencilTestBack) {
dssDesc.stencilBack = {
compare: WebGPUCompereFunc[this._dss.stencilFuncBack],
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpBack],
passOp: WebGPUStencilOp[this._dss.stencilPassOpBack],
failOp: WebGPUStencilOp[this._dss.stencilFailOpBack],
};
stencilReadMask |= this._dss.stencilReadMaskBack;
stencilWriteMask |= this._dss.stencilWriteMaskBack;
stencilRef |= this._dss.stencilRefBack;
}
dssDesc.stencilReadMask = stencilReadMask;
dssDesc.stencilWriteMask = stencilWriteMask;
dssDesc.depthBias = this._rs.depthBias;
dssDesc.depthBiasSlopeScale = this._rs.depthBiasSlop;
dssDesc.depthBiasClamp = this._rs.depthBiasClamp;
renderPplDesc.depthStencil = dssDesc;
}
this._gpuPipelineState = {
gpuPrimitive: WebPUPrimitives[info.primitive],
gpuShader: gpuShader.gpuShader,
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
rs: info.rasterizerState,
dss: info.depthStencilState,
stencilRef,
bs: info.blendState,
gpuRenderPass: (info.renderPass as WebGPURenderPass).gpuRenderPass,
dynamicStates,
pipelineState: renderPplDesc,
nativePipeline: undefined,
};
const computeDesc: GPUComputePipelineDescriptor = {
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
compute: computeStage!,
};
this._gpuPipelineState = {
gpuPrimitive: 'triangle-list' as GPUPrimitiveTopology,
gpuShader: gpuShader.gpuShader,
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
rs: info.rasterizerState,
dss: info.depthStencilState,
stencilRef: 0,
bs: info.blendState,
gpuRenderPass: null,
dynamicStates,
pipelineState: computeDesc,
nativePipeline: undefined,
};
} else {
// ---- Render Pipeline ----
// colorstates
const colorAttachments = this._renderPass.colorAttachments;
const colorDescs: GPUColorTargetState[] = [];
const colAttachmentSize = colorAttachments.length;
for (let i = 0; i < colAttachmentSize; i++) {
const colDesc: GPUColorTargetState = {
format: GFXFormatToWGPUFormat(colorAttachments[i].format),
writeMask: WebGPUBlendMask(this._bs.targets[i].blendColorMask),
};
if (this._bs.targets[i].blend) {
colDesc.blend = {
color: {
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDst],
operation: WebGPUBlendOps[this._bs.targets[i].blendEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendEq],
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrc],
},
alpha: {
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDstAlpha],
operation: WebGPUBlendOps[
this._bs.targets[i].blendAlphaEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendAlphaEq],
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrcAlpha],
},
};
}
colorDescs.push(colDesc);
}
let vertexStage: GPUProgrammableStage;
let fragmentStage: GPUProgrammableStage;
const stageSize = shaderStages.length;
for (let i = 0; i < stageSize; i++) {
if (shaderStages[i].type === ShaderStageFlagBit.VERTEX) { vertexStage = shaderStages[i].gpuShader!; }
if (shaderStages[i].type === ShaderStageFlagBit.FRAGMENT) { fragmentStage = shaderStages[i].gpuShader!; }
}
const shaderAttrs = gpuShader.attributes;
const attrsSize = shaderAttrs.length;
for (let i = 0; i < attrsSize; i++) {
this._locations.set(shaderAttrs[i].name, shaderAttrs[i].location);
}
const stripTopology = (info.primitive === PrimitiveMode.LINE_STRIP || info.primitive === PrimitiveMode.TRIANGLE_STRIP);
const renderPplDesc: GPURenderPipelineDescriptor = {
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
vertex: {
module: vertexStage!.module,
entryPoint: 'main',
buffers: [],
},
primitive: {
topology: WebPUPrimitives[info.primitive],
frontFace: this._rs.isFrontFaceCCW ? 'ccw' : 'cw',
cullMode: this._rs.cullMode === CullMode.NONE ? 'none' : (this._rs.cullMode === CullMode.FRONT) ? 'front' : 'back',
},
fragment: {
module: fragmentStage!.module,
entryPoint: 'main',
targets: colorDescs,
},
};
if (stripTopology) renderPplDesc.primitive!.stripIndexFormat = 'uint16';
// depthstencil states
let stencilRef = 0;
if (this._renderPass.depthStencilAttachment?.format !== Format.UNKNOWN) {
const dssDesc = {} as GPUDepthStencilState;
dssDesc.format = GFXFormatToWGPUFormat(this._renderPass.depthStencilAttachment!.format);
dssDesc.depthWriteEnabled = this._dss.depthWrite;
dssDesc.depthCompare = this._dss.depthTest ? WebGPUCompereFunc[this._dss.depthFunc] : 'always';
let stencilReadMask = 0;
let stencilWriteMask = 0;
if (this._dss.stencilTestFront) {
dssDesc.stencilFront = {
compare: WebGPUCompereFunc[this._dss.stencilFuncFront],
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpFront],
passOp: WebGPUStencilOp[this._dss.stencilPassOpFront],
failOp: WebGPUStencilOp[this._dss.stencilFailOpFront],
};
stencilReadMask |= this._dss.stencilReadMaskFront;
stencilWriteMask |= this._dss.stencilWriteMaskFront;
stencilRef |= this._dss.stencilRefFront;
}
if (this._dss.stencilTestBack) {
dssDesc.stencilBack = {
compare: WebGPUCompereFunc[this._dss.stencilFuncBack],
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpBack],
passOp: WebGPUStencilOp[this._dss.stencilPassOpBack],
failOp: WebGPUStencilOp[this._dss.stencilFailOpBack],
};
stencilReadMask |= this._dss.stencilReadMaskBack;
stencilWriteMask |= this._dss.stencilWriteMaskBack;
stencilRef |= this._dss.stencilRefBack;
}
dssDesc.stencilReadMask = stencilReadMask;
dssDesc.stencilWriteMask = stencilWriteMask;
dssDesc.depthBias = this._rs.depthBias;
dssDesc.depthBiasSlopeScale = this._rs.depthBiasSlop;
dssDesc.depthBiasClamp = this._rs.depthBiasClamp;
renderPplDesc.depthStencil = dssDesc;
}
this._gpuPipelineState = {
gpuPrimitive: WebPUPrimitives[info.primitive],
gpuShader: gpuShader.gpuShader,
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
rs: info.rasterizerState,
dss: info.depthStencilState,
stencilRef,
bs: info.blendState,
gpuRenderPass: (info.renderPass as WebGPURenderPass).gpuRenderPass,
dynamicStates,
pipelineState: renderPplDesc,
nativePipeline: undefined,
};
}
}
protected _getShaderLocation (name: string): number | undefined {
@@ -215,9 +247,22 @@ export class WebGPUPipelineState extends PipelineState {
if (this._gpuPipelineState!.nativePipeline && !forceUpdate) {
return;
}
const webgpuDevice = (WebGPUDeviceManager.instance);
const nativeDevice = webgpuDevice.nativeDevice;
const pipelineState = this._gpuPipelineState!.pipelineState!;
// Compute pipeline: no vertex attributes, no multisample
if ('compute' in pipelineState) {
const nativePipeline = nativeDevice?.createComputePipeline(
pipelineState,
);
this._gpuPipelineState!.nativePipeline = nativePipeline;
return;
}
// Render pipeline
const gpuShader = this.shader;
const shaderAttrs = gpuShader.attributes;
const pipelineState = this._gpuPipelineState!.pipelineState!;
const vertexAttrs: GPUVertexBufferLayout[] = [];
const emptyPushAttr: string[] = [];
const streamCount = ia.gpuVertexBuffers.length;
@@ -272,8 +317,6 @@ export class WebGPUPipelineState extends PipelineState {
pipelineState.vertex.buffers = vertexAttrs;
pipelineState.multisample = { count: ia.samples };
const webgpuDevice = (WebGPUDeviceManager.instance);
const nativeDevice = webgpuDevice.nativeDevice;
const nativePipeline = nativeDevice?.createRenderPipeline(pipelineState);
this._gpuPipelineState!.nativePipeline = nativePipeline;
}
+3
View File
@@ -29,6 +29,7 @@ import { QueueInfo } from '../base/define';
export class WebGPUQueue extends Queue {
public numDrawCalls = 0;
public numDispatches = 0;
public numInstances = 0;
public numTris = 0;
@@ -51,6 +52,7 @@ export class WebGPUQueue extends Queue {
for (let i = 0; i < cmdBuffSize; i++) {
const cmdBuff = cmdBuffs[i] as WebGPUCommandBuffer;
this.numDrawCalls += cmdBuff.numDrawCalls;
this.numDispatches += cmdBuff.numDispatches;
this.numInstances += cmdBuff.numInstances;
this.numTris += cmdBuff.numTris;
}
@@ -59,6 +61,7 @@ export class WebGPUQueue extends Queue {
public clear (): void {
this.numDrawCalls = 0;
this.numDispatches = 0;
this.numInstances = 0;
this.numTris = 0;
}
+1 -1
View File
@@ -797,7 +797,7 @@ export class ParticleSystem2D extends UIRenderer {
}
private _startPreview (): void {
if (this._preview) {
if (!this._preview) {
this.resetSystem();
}
}
+14 -4
View File
@@ -29,7 +29,8 @@ import { Vec2, Vec3 } from '../core/math';
* @zh 此类生成噪声纹理。
*/
export class ParticleNoise {
private permutation: number[] = [151, 160, 137, 91, 90, 15,
private static readonly DEFAULT_PERMUTATION: readonly number[] = [
151, 160, 137, 91, 90, 15,
131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23,
190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33,
88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166,
@@ -44,9 +45,19 @@ export class ParticleNoise {
138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,
];
private static build512 (src: readonly number[] | number[]): Uint8Array {
const p = new Uint8Array(512);
for (let i = 0; i < 256; i++) { p[256 + i] = p[i] = src[i]; }
return p;
}
private permutation: number[] = ParticleNoise.DEFAULT_PERMUTATION as number[];
private permutation512: Uint8Array = ParticleNoise.build512(ParticleNoise.DEFAULT_PERMUTATION);
constructor (permutation?: number[]) {
if (permutation) {
this.permutation = permutation;
this.permutation = permutation.slice();
this.permutation512 = ParticleNoise.build512(this.permutation);
}
}
@@ -61,8 +72,7 @@ export class ParticleNoise {
* @returns @en Texture pixel generated. @zh 返回生成的噪声纹理值。
*/
public noise (x: number, y: number, z: number, min = 0, max = 1): number {
const p: number[] = new Array(512);
for (let i = 0; i < 256; i++) { p[256 + i] = p[i] = this.permutation[i]; }
const p: Uint8Array = this.permutation512;
const X = Math.floor(x) & 255; // FIND UNIT CUBE THAT
const Y = Math.floor(y) & 255; // CONTAINS POINT.
+4
View File
@@ -60,6 +60,7 @@ interface IProfilerState {
frame: ICounterOption;
fps: ICounterOption;
draws: ICounterOption;
dispatches: ICounterOption;
instances: ICounterOption;
tricount: ICounterOption;
logic: ICounterOption;
@@ -73,6 +74,7 @@ interface IProfilerState {
const _profileInfo = {
fps: { desc: `Framerate (FPS)`, below: 30, average: _average, isInteger: true },
draws: { desc: 'Draw call', isInteger: true },
dispatches: { desc: 'Dispatch call', isInteger: true },
frame: { desc: 'Frame time (ms)', min: 0, max: 50, average: _average },
instances: { desc: 'Instance Count', isInteger: true },
tricount: { desc: 'Triangle', isInteger: true },
@@ -586,6 +588,8 @@ export class Profiler extends System {
const device = this._device!;
(profilerStats.draws.counter as PerfCounter).value = device.numDrawCalls;
// Native (JSB) devices expose no dispatch stats yet; WebGPU does. Treat missing as 0.
(profilerStats.dispatches.counter as PerfCounter).value = device.numDispatches ?? 0;
(profilerStats.instances.counter as PerfCounter).value = device.numInstances;
(profilerStats.bufferMemory.counter as PerfCounter).value = device.memoryStatus.bufferSize / (1024 * 1024);
(profilerStats.textureMemory.counter as PerfCounter).value = device.memoryStatus.textureSize / (1024 * 1024);
+14
View File
@@ -231,7 +231,21 @@ class PassVisitor implements RenderGraphVisitor {
compute (value: ComputePass): void {
this._currPass = value;
const rg = context.renderGraph;
if (rg.getValid(this.passID)) {
// Avoid revisiting a valid pass and recursive dependency cycles.
return;
}
rg.setValid(this.passID, true);
// Trace READ dependencies only; WRITE dependencies are produced by this pass.
const resourceGraph = this.context.resourceGraph;
for (const [computeName, cViews] of value.computeViews) {
if (!cViews.length || cViews[0].accessType !== AccessType.READ) continue;
const vertID = resourceGraph.find(computeName);
if (vertID !== 0xFFFFFFFF) {
this._resVisitor.resID = vertID;
resourceGraph.visitVertex(this._resVisitor, vertID);
}
}
}
resolve (value: ResolvePass): void {
// noop
+11 -13
View File
@@ -48,6 +48,7 @@ import {
Device,
deviceManager,
DispatchInfo,
Feature,
Format,
Framebuffer,
FramebufferInfo,
@@ -56,9 +57,7 @@ import {
InputAssemblerInfo,
LoadOp,
MemoryUsageBit,
PipelineBindPoint,
PipelineState,
PipelineStateInfo,
Rect,
RenderPass,
RenderPassInfo,
@@ -1910,26 +1909,23 @@ class PreRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor {
renderScene.preRecord();
}
dispatch (value: Dispatch): void {
if (!context.device.hasFeature(Feature.COMPUTE_SHADER)) return;
let pso: PipelineState | null = null;
const devicePass = this.currPass as DeviceComputePass;
const pass = value.material?.passes[value.passID];
pass?.update();
const shader = pass?.getShaderVariant();
if (pass !== null && shader !== null) {
const psoInfo = new PipelineStateInfo(
shader,
pass?.pipelineLayout,
);
psoInfo.bindPoint = PipelineBindPoint.COMPUTE;
pso = deviceManager.gfxDevice.createPipelineState(psoInfo);
if (pass && shader) {
pso = PipelineStateManager.getOrCreateComputePipelineState(deviceManager.gfxDevice, pass, shader);
}
const cmdBuff = context.commandBuffer;
if (pso) {
if (pso && pass) {
cmdBuff.bindPipelineState(pso);
const layoutStage = devicePass.renderLayout;
const layoutDesc = layoutStage!.descriptorSet!;
cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, layoutDesc);
cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
}
const gx = value.threadGroupCountX;
@@ -1965,10 +1961,12 @@ class PostRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor
computeSubpass (value: ComputeSubpass): void {
// do nothing
}
resolve (value: ResolvePass): void {
// do nothing
}
compute (value: ComputePass): void {
if (!context.device.hasFeature(Feature.COMPUTE_SHADER)) return;
const cmdBuff = context.commandBuffer;
(cmdBuff as any).submitComputePass();
}
resolve (value: ResolvePass): void {
// do nothing
}
copy (value: CopyPass): void {
+5 -1
View File
@@ -864,7 +864,11 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild
this._renderGraph.setName(this._vertID, name);
}
addTexture (name: string, slotName: string, sampler: Sampler | null = null): void {
throw new Error('Method not implemented.');
this._addComputeResource(name, AccessType.READ, slotName);
if (sampler) {
const descriptorID = this._lg.attributeIndex.get(slotName)!;
this._data.samplers.set(descriptorID, sampler);
}
}
addStorageBuffer (name: string, accessType: AccessType, slotName: string): void {
this._addComputeResource(name, accessType, slotName);
@@ -1264,15 +1264,6 @@ export class WebProgramLibrary implements ProgramLibrary {
if (passSet) {
info.setLayouts.push(passSet);
}
const phaseSet = getDescriptorSetLayout(
this.layoutGraph,
subpassOrPassID,
phaseID,
UpdateFrequency.PER_PHASE,
);
if (phaseSet) {
info.setLayouts.push(phaseSet);
}
const batchSet = getProgramDescriptorSetLayout(
device,
lg,
@@ -1293,6 +1284,15 @@ export class WebProgramLibrary implements ProgramLibrary {
if (instanceSet) {
info.setLayouts.push(instanceSet);
}
const phaseSet = getDescriptorSetLayout(
this.layoutGraph,
subpassOrPassID,
phaseID,
UpdateFrequency.PER_PHASE,
);
if (phaseSet) {
info.setLayouts.push(phaseSet);
}
programData.pipelineLayout = device.createPipelineLayout(info);
return programData.pipelineLayout;
}
+32 -1
View File
@@ -22,7 +22,7 @@
THE SOFTWARE.
*/
import { Shader, RenderPass, InputAssembler, Device, PipelineState, InputState, PipelineStateInfo } from '../gfx';
import { Shader, RenderPass, InputAssembler, Device, PipelineState, InputState, PipelineStateInfo, PipelineBindPoint } from '../gfx';
import { Pass } from '../render-scene/core/pass';
export class PipelineStateManager {
@@ -30,6 +30,8 @@ export class PipelineStateManager {
private static _PSOHashMap: Map<number, PipelineState> = new Map<number, PipelineState>();
private static _computePSOHashMap: Map<number, PipelineState> = new Map<number, PipelineState>();
// pass is only needed on TS.
static getOrCreatePipelineState (device: Device, pass: Pass, shader: Shader, renderPass: RenderPass, ia: InputAssembler): PipelineState {
const hash1 = pass.hash;
@@ -59,4 +61,33 @@ export class PipelineStateManager {
return pso;
}
/**
* @en Get or create a compute pipeline state.
* A compute pipeline only depends on the shader variant and the pipeline layout,
* both carried by the pass, so the cache key is `pass.hash ^ shader.typedID`,
* mirroring the graphics-side hash mechanism without renderPass/inputState factors.
* @zh 获取或创建计算管线状态。
* 计算管线仅依赖于着色器变体与管线布局(均由 pass 携带),
* 因此缓存键为 `pass.hash ^ shader.typedID`,与图形侧哈希机制一致但不包含 renderPass/顶点布局因子。
*/
static getOrCreateComputePipelineState (device: Device, pass: Pass, shader: Shader): PipelineState {
const hash1 = pass.hash;
const hash2 = shader.typedID;
const newHash = hash1 ^ hash2;
let pso = this._computePSOHashMap.get(newHash);
if (!pso) {
const pipelineLayout = pass.pipelineLayout;
const psoInfo = new PipelineStateInfo(
shader,
pipelineLayout,
);
psoInfo.bindPoint = PipelineBindPoint.COMPUTE;
pso = device.createPipelineState(psoInfo);
this._computePSOHashMap.set(newHash, pso);
}
return pso;
}
}
+5 -3
View File
@@ -1537,6 +1537,7 @@ export class Terrain extends Component {
* @zh 获得地形信息
*/
@type(TerrainInfo)
@visible(false)
public get info (): TerrainInfo {
const ti = new TerrainInfo();
ti.tileSize = this.tileSize;
@@ -1815,11 +1816,11 @@ export class Terrain extends Component {
* @zh 获得纹理层
*/
public getLayer (id: number): TerrainLayer | null {
if (id === -1) {
if (id === -1 || id === undefined) {
return null;
}
return this._layerList[id];
return this._layerList[id] || null;
}
/**
@@ -2584,7 +2585,8 @@ export class Terrain extends Component {
const index1 = j * this.blockCount[0] + i;
for (let l = 0; l < TERRAIN_MAX_BLEND_LAYERS; ++l) {
layerBuffer[index0 * TERRAIN_MAX_BLEND_LAYERS + l] = this._layerBuffer[index1 * TERRAIN_MAX_BLEND_LAYERS + l];
const oldVal = this._layerBuffer[index1 * TERRAIN_MAX_BLEND_LAYERS + l];
layerBuffer[index0 * TERRAIN_MAX_BLEND_LAYERS + l] = oldVal !== undefined ? oldVal : -1;
}
}
}
+11 -2
View File
@@ -222,13 +222,22 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ccs
// Fill index buffer.
ArrayBuffer::Ptr indexBuffer;
uint32_t idxCount = 0;
const uint32_t idxStride = 2;
uint32_t idxStride = 2;
gfx::Format indexFormat = gfx::Format::R16UI;
if (geometry.indices.has_value()) {
const ccstd::vector<uint32_t> &indices = geometry.indices.value();
uint32_t maxIndex = 0;
for (uint32_t idx : indices) {
maxIndex = std::max(maxIndex, idx);
}
if (maxIndex > std::numeric_limits<uint16_t>::max()) {
idxStride = 4;
indexFormat = gfx::Format::R32UI;
}
idxCount = static_cast<uint32_t>(indices.size());
indexBuffer = ccnew ArrayBuffer(idxStride * idxCount);
DataView indexBufferView(indexBuffer);
writeBuffer(indexBufferView, indices, gfx::Format::R16UI);
writeBuffer(indexBufferView, indices, indexFormat);
}
// Create primitive.
@@ -99,8 +99,8 @@ CCWGPUDevice::CCWGPUDevice() : Device() {
_caps.maxComputeSharedMemorySize = 32768;
_caps.maxComputeWorkGroupInvocations = 256;
_caps.maxComputeWorkGroupSize = {65535, 65535, 65535};
_caps.maxComputeWorkGroupCount = {256, 256, 64};
_caps.maxComputeWorkGroupSize = {256, 256, 64};
_caps.maxComputeWorkGroupCount = {65535, 65535, 65535};
instance = this;
}
@@ -582,8 +582,8 @@ void CCWGPUDevice::initLimits() {
_caps.maxComputeSharedMemorySize = limits.maxComputeWorkgroupStorageSize;
_caps.maxComputeWorkGroupInvocations = limits.maxComputeInvocationsPerWorkgroup;
_caps.maxComputeWorkGroupSize = {limits.maxComputeWorkgroupsPerDimension, limits.maxComputeWorkgroupsPerDimension, limits.maxComputeWorkgroupsPerDimension};
_caps.maxComputeWorkGroupCount = {limits.maxComputeWorkgroupSizeX, limits.maxComputeWorkgroupSizeY, limits.maxComputeWorkgroupSizeZ};
_caps.maxComputeWorkGroupSize = {limits.maxComputeWorkgroupSizeX, limits.maxComputeWorkgroupSizeY, limits.maxComputeWorkgroupSizeZ};
_caps.maxComputeWorkGroupCount = {limits.maxComputeWorkgroupsPerDimension, limits.maxComputeWorkgroupsPerDimension, limits.maxComputeWorkgroupsPerDimension};
#endif
}
+3
View File
@@ -688,6 +688,9 @@ static constexpr uint32_t CLUSTER_LIGHT_BINDING = 4;
static constexpr uint32_t CLUSTER_LIGHT_INDEX_BINDING = 5;
static constexpr uint32_t CLUSTER_LIGHT_GRID_BINDING = 6;
constexpr const char *GEOMETRY_RENDERER_COMMAND = "geometry-renderer";
constexpr const char *DEBUG_RENDERER_COMMAND = "debug-renderer";
void localDescriptorSetLayoutResizeMaxJoints(uint32_t maxCount);
} // namespace pipeline
@@ -47,6 +47,34 @@
namespace cc {
namespace pipeline {
#if CC_USE_DEBUG_RENDERER
DebugRendererRenderCommand::DebugRendererRenderCommand(PipelineSceneData *sceneData)
: _sceneData(sceneData) {
}
void DebugRendererRenderCommand::beginRenderCommand(const RenderCommandContext &ctx) {
renderDebugRenderer(ctx.renderPass, ctx.cmdBuff, _sceneData, ctx.camera);
}
void DebugRendererRenderCommand::endRenderCommand(const RenderCommandContext & /*ctx*/) {
}
#endif
#if CC_USE_GEOMETRY_RENDERER
GeometryRendererRenderCommand::GeometryRendererRenderCommand(PipelineSceneData *sceneData)
: _sceneData(sceneData) {
}
void GeometryRendererRenderCommand::beginRenderCommand(const RenderCommandContext &ctx) {
if (ctx.camera && ctx.camera->getGeometryRenderer()) {
ctx.camera->getGeometryRenderer()->render(ctx.renderPass, ctx.cmdBuff, _sceneData);
}
}
void GeometryRendererRenderCommand::endRenderCommand(const RenderCommandContext & /*ctx*/) {
}
#endif
framegraph::StringHandle RenderPipeline::fgStrHandleOutDepthTexture = framegraph::FrameGraph::stringToHandle("depthTexture");
framegraph::StringHandle RenderPipeline::fgStrHandleOutColorTexture = framegraph::FrameGraph::stringToHandle("outputTexture");
framegraph::StringHandle RenderPipeline::fgStrHandlePostprocessPass = framegraph::FrameGraph::stringToHandle("pipelinePostPass");
@@ -87,6 +115,10 @@ bool RenderPipeline::activate(gfx::Swapchain * /*swapchain*/) {
_pipelineSceneData->activate(_device);
#if CC_USE_DEBUG_RENDERER
CC_DEBUG_RENDERER->activate(_device);
addRenderCommand(cc::pipeline::DEBUG_RENDERER_COMMAND, std::make_shared<DebugRendererRenderCommand>(getPipelineSceneData()));
#endif
#if CC_USE_GEOMETRY_RENDERER
addRenderCommand(cc::pipeline::GEOMETRY_RENDERER_COMMAND, std::make_shared<GeometryRendererRenderCommand>(getPipelineSceneData()));
#endif
// generate macros here rather than construct func because _clusterEnabled
@@ -115,6 +147,15 @@ void RenderPipeline::onGlobalPipelineStateChanged() {
// do nothing
}
void RenderPipeline::addRenderCommand(const ccstd::string &name, std::shared_ptr<RenderCommand> ptr) {
_renderCommands[name] = std::move(ptr);
}
RenderCommand *RenderPipeline::getRenderCommand(const ccstd::string &name) const {
const auto iter = _renderCommands.find(name);
return iter == _renderCommands.end() ? nullptr : iter->second.get();
}
void RenderPipeline::destroyQuadInputAssembler() {
CC_SAFE_DESTROY_AND_DELETE(_quadIB);
@@ -34,11 +34,14 @@
#include "renderer/core/PassUtils.h"
#include "scene/Model.h"
#include <memory>
namespace cc {
namespace gfx {
class CommandBuffer;
class DescriptorSet;
class DescriptorSetLayout;
class RenderPass;
} // namespace gfx
namespace scene {
class Camera;
@@ -54,6 +57,53 @@ class PipelineSceneData;
class GlobalDSManager;
class RenderStage;
class GeometryRenderer;
struct RenderCommandContext {
gfx::RenderPass *renderPass{nullptr};
gfx::CommandBuffer *cmdBuff{nullptr};
PipelineSceneData *sceneData{nullptr};
const scene::Camera *camera{nullptr};
};
class RenderCommand {
public:
RenderCommand() noexcept = default;
RenderCommand(RenderCommand &&rhs) = delete;
RenderCommand(RenderCommand const &rhs) = delete;
RenderCommand &operator=(RenderCommand &&rhs) = delete;
RenderCommand &operator=(RenderCommand const &rhs) = delete;
virtual ~RenderCommand() noexcept = default;
virtual void beginRenderCommand(const RenderCommandContext &ctx) = 0;
virtual void endRenderCommand(const RenderCommandContext &ctx) = 0;
};
#if CC_USE_DEBUG_RENDERER
class DebugRendererRenderCommand final : public RenderCommand {
public:
explicit DebugRendererRenderCommand(PipelineSceneData *sceneData);
void beginRenderCommand(const RenderCommandContext &ctx) override;
void endRenderCommand(const RenderCommandContext &ctx) override;
private:
PipelineSceneData *_sceneData{nullptr};
};
#endif
#if CC_USE_GEOMETRY_RENDERER
class GeometryRendererRenderCommand final : public RenderCommand {
public:
explicit GeometryRendererRenderCommand(PipelineSceneData *sceneData);
void beginRenderCommand(const RenderCommandContext &ctx) override;
void endRenderCommand(const RenderCommandContext &ctx) override;
private:
PipelineSceneData *_sceneData{nullptr};
};
#endif
struct CC_DLL RenderPipelineInfo {
uint32_t tag = 0;
RenderFlowList flows;
@@ -140,6 +190,9 @@ public:
#endif
}
void addRenderCommand(const ccstd::string &name, std::shared_ptr<RenderCommand> ptr);
RenderCommand *getRenderCommand(const ccstd::string &name) const;
inline void resetRenderQueue(bool reset) { _resetRenderQueue = reset; }
inline bool isRenderQueueReset() const { return _resetRenderQueue; }
@@ -194,6 +247,7 @@ protected:
ccstd::unordered_map<Vec4, gfx::InputAssembler *, Hasher<Vec4>> _quadIA;
framegraph::FrameGraph _fg;
ccstd::unordered_map<ccstd::string, std::shared_ptr<RenderCommand>> _renderCommands;
ccstd::unordered_map<gfx::ClearFlags, gfx::RenderPass *> _renderPasses;
// use cluster culling or not
@@ -63,6 +63,7 @@ struct CustomRenderGraphContext {
const RenderGraph* renderGraph{nullptr};
const ResourceGraph* resourceGraph{nullptr};
gfx::CommandBuffer* primaryCommandBuffer{nullptr};
gfx::RenderPass* currentRenderPass{nullptr};
};
class CustomRenderPass : public Customization {
@@ -44,12 +44,6 @@
#include "details/GraphView.h"
#include "details/GslUtils.h"
#include "details/Range.h"
#if CC_USE_DEBUG_RENDERER
#include "cocos/renderer/pipeline/helper/Utils.h"
#endif
#if CC_USE_GEOMETRY_RENDERER
#include "cocos/renderer/pipeline/GeometryRenderer.h"
#endif
namespace cc {
@@ -704,10 +698,14 @@ struct RenderGraphVisitor : boost::dfs_visitor<> {
ctx.cmdBuff, ctx.currentPass, ctx.subpassIndex, sceneData.flags);
#if CC_USE_GEOMETRY_RENDERER
if (any(sceneData.flags & SceneFlags::GEOMETRY) &&
camera && camera->getGeometryRenderer()) {
camera->getGeometryRenderer()->render(
ctx.currentPass, ctx.cmdBuff, ctx.ppl->getPipelineSceneData());
const auto& renderData = get(RenderGraph::DataTag{}, ctx.g, sceneID);
if (!renderData.custom.empty()) {
const auto& commands = ctx.ppl->custom.renderCommands;
auto iter = commands.find(renderData.custom);
if (iter != commands.end()) {
ctx.customContext.currentRenderPass = ctx.currentPass;
iter->second->beginRenderCommand(ctx.customContext, sceneID);
}
}
#endif
@@ -786,24 +784,18 @@ struct RenderGraphVisitor : boost::dfs_visitor<> {
}
void begin(const Blit& blit, RenderGraph::vertex_descriptor vertID) const {
tryBindPassDescriptorSet(vertID);
tryBindQueueDescriptorSets(vertID);
const auto& renderData = get(RenderGraph::DataTag{}, ctx.g, vertID);
if (!renderData.custom.empty()) {
const auto& commands = ctx.ppl->custom.renderCommands;
auto iter = commands.find(renderData.custom);
if (iter != commands.end()) {
ctx.customContext.currentRenderPass = ctx.currentPass;
iter->second->beginRenderCommand(ctx.customContext, vertID);
return;
}
}
#if CC_USE_DEBUG_RENDERER
if (blit.blitType == BlitType::DRAW_PROFILE) {
auto* renderPass = ctx.currentPass;
auto* cmdBuff = ctx.cmdBuff;
renderDebugRenderer(renderPass, cmdBuff, ctx.ppl->getPipelineSceneData(), cc::pipeline::profilerCamera);
}
#endif
tryBindPassDescriptorSet(vertID);
tryBindQueueDescriptorSets(vertID);
switch (blit.blitType) {
case BlitType::FULLSCREEN_QUAD:
@@ -48,6 +48,10 @@
#include "profiler/DebugRenderer.h"
#endif
#if CC_USE_GEOMETRY_RENDERER
#include "cocos/renderer/pipeline/GeometryRenderer.h"
#endif
namespace cc {
namespace render {
@@ -106,6 +110,54 @@ void addSubresourceNode<gfx::Format::DEPTH_STENCIL>(ResourceGraph::vertex_descri
} // namespace
#if CC_USE_DEBUG_RENDERER
namespace {
class DebugRendererRenderCommand final : public CustomRenderCommand {
public:
explicit DebugRendererRenderCommand(pipeline::PipelineSceneData *sceneData)
: _sceneData(sceneData) {}
void beginRenderCommand(const CustomRenderGraphContext &rg, RenderGraph::vertex_descriptor vertID) override {
std::ignore = vertID;
if (rg.currentRenderPass) {
DebugRenderer::getInstance()->render(rg.currentRenderPass, rg.primaryCommandBuffer, _sceneData);
}
}
void endRenderCommand(const CustomRenderGraphContext &rg, RenderGraph::vertex_descriptor vertID) override {
std::ignore = rg;
std::ignore = vertID;
}
private:
pipeline::PipelineSceneData *_sceneData{nullptr};
};
} // namespace
#endif
#if CC_USE_GEOMETRY_RENDERER
class GeometryRendererRenderCommand final : public CustomRenderCommand {
public:
explicit GeometryRendererRenderCommand(pipeline::PipelineSceneData *sceneData)
: _sceneData(sceneData) {}
void beginRenderCommand(const CustomRenderGraphContext &rg, RenderGraph::vertex_descriptor vertID) override {
const auto &sceneData = get(SceneTag{}, vertID, *rg.renderGraph);
if (sceneData.camera && sceneData.camera->getGeometryRenderer()) {
sceneData.camera->getGeometryRenderer()->render(rg.currentRenderPass, rg.primaryCommandBuffer, _sceneData);
}
}
void endRenderCommand(const CustomRenderGraphContext &rg, RenderGraph::vertex_descriptor vertID) override {
std::ignore = vertID;
std::ignore = rg;
}
private:
pipeline::PipelineSceneData *_sceneData{nullptr};
};
#endif
NativePipeline::NativePipeline(const allocator_type &alloc) noexcept
: device(gfx::Device::getInstance()),
globalDSManager(std::make_unique<pipeline::GlobalDSManager>()),
@@ -1385,6 +1437,10 @@ bool NativePipeline::activate(gfx::Swapchain *swapchainIn) {
pipelineSceneData->activate(device);
#if CC_USE_DEBUG_RENDERER
DebugRenderer::getInstance()->activate(device);
addCustomRenderCommand(cc::pipeline::DEBUG_RENDERER_COMMAND, std::make_shared<DebugRendererRenderCommand>(getPipelineSceneData()));
#endif
#if CC_USE_GEOMETRY_RENDERER
addCustomRenderCommand(cc::pipeline::GEOMETRY_RENDERER_COMMAND, std::make_shared<GeometryRendererRenderCommand>(getPipelineSceneData()));
#endif
// generate macros here rather than construct func because _clusterEnabled
// switch may be changed in root.ts setRenderPipeline() function which is after
@@ -913,6 +913,13 @@ SceneBuilder *NativeRenderQueueBuilder::addScene(
data);
}
#if CC_USE_GEOMETRY_RENDERER
if (any(sceneFlags & SceneFlags::GEOMETRY)) {
auto &data = get(RenderGraph::DataTag{}, *renderGraph, sceneID);
data.custom = cc::pipeline::GEOMETRY_RENDERER_COMMAND;
}
#endif
if (any(sceneFlags & SceneFlags::UI)) {
CC_EXPECTS(camera);
const auto passOrSubpassId = parent(nodeID, *renderGraph);
@@ -1086,6 +1093,31 @@ void NativeRenderQueueBuilder::addProfiler(const scene::Camera *camera) {
*renderGraph,
passOrSubpassId);
#if CC_USE_DEBUG_RENDERER
const auto debugId = addVertex2(
BlitTag{},
std::forward_as_tuple("DebugRenderer"),
std::forward_as_tuple(),
std::forward_as_tuple(),
std::forward_as_tuple(),
std::forward_as_tuple(
IntrusivePtr<Material>{},
RenderGraph::null_vertex(),
SceneFlags::NONE,
nullptr,
BlitType::FULLSCREEN_QUAD),
*renderGraph,
queueId);
auto &debugData = get(RenderGraph::DataTag{}, *renderGraph, debugId);
debugData.custom = cc::pipeline::DEBUG_RENDERER_COMMAND;
setCameraUBOValues(
*camera,
*layoutGraph,
*pipelineRuntime->getPipelineSceneData(),
camera->getScene() ? camera->getScene()->getMainLight() : nullptr,
debugData);
#endif
const auto sceneId = addVertex2(
BlitTag{},
std::forward_as_tuple("Profiler"),
@@ -647,8 +647,8 @@ void LightingStage::fgTransparent(scene::Camera *camera) {
_planarShadowQueue->recordCommandBuffer(_device, table.getRenderPass(), cmdBuff);
#if CC_USE_GEOMETRY_RENDERER
if (camera->getGeometryRenderer()) {
camera->getGeometryRenderer()->render(table.getRenderPass(), cmdBuff, pipeline->getPipelineSceneData());
if (auto *command = pipeline->getRenderCommand(cc::pipeline::GEOMETRY_RENDERER_COMMAND)) {
command->beginRenderCommand({table.getRenderPass(), cmdBuff, pipeline->getPipelineSceneData(), camera});
}
#endif
};
@@ -228,7 +228,9 @@ void PostProcessStage::render(scene::Camera *camera) {
_uiPhase->render(camera, renderPass);
renderProfiler(renderPass, cmdBuff, pipeline->getProfiler(), camera);
#if CC_USE_DEBUG_RENDERER
renderDebugRenderer(renderPass, cmdBuff, pipeline->getPipelineSceneData(), camera);
if (auto *command = pipeline->getRenderCommand(cc::pipeline::DEBUG_RENDERER_COMMAND)) {
command->beginRenderCommand({renderPass, cmdBuff, pipeline->getPipelineSceneData(), camera});
}
#endif
};
@@ -23,9 +23,6 @@
****************************************************************************/
#include "ForwardStage.h"
#if CC_USE_GEOMETRY_RENDERER
#include "../GeometryRenderer.h"
#endif
#include "../InstancedBuffer.h"
#include "../PipelineSceneData.h"
#include "../PipelineUBO.h"
@@ -262,15 +259,17 @@ void ForwardStage::render(scene::Camera *camera) {
}
#if CC_USE_GEOMETRY_RENDERER
if (camera->getGeometryRenderer()) {
camera->getGeometryRenderer()->render(renderPass, cmdBuff, pipeline->getPipelineSceneData());
if (auto *command = pipeline->getRenderCommand(cc::pipeline::GEOMETRY_RENDERER_COMMAND)) {
command->beginRenderCommand({renderPass, cmdBuff, pipeline->getPipelineSceneData(), camera});
}
#endif
_uiPhase->render(camera, renderPass);
renderProfiler(renderPass, cmdBuff, _pipeline->getProfiler(), camera);
#if CC_USE_DEBUG_RENDERER
renderDebugRenderer(renderPass, cmdBuff, _pipeline->getPipelineSceneData(), camera);
if (auto *command = pipeline->getRenderCommand(cc::pipeline::DEBUG_RENDERER_COMMAND)) {
command->beginRenderCommand({renderPass, cmdBuff, pipeline->getPipelineSceneData(), camera});
}
#endif
};
+6
View File
@@ -105,6 +105,12 @@ using namespace cc;
%ignore cc::pipeline::GeometryRenderer::activate;
%ignore cc::pipeline::GeometryRenderer::render;
%ignore cc::pipeline::GeometryRenderer::destroy;
%ignore cc::pipeline::RenderCommand;
%ignore cc::pipeline::RenderCommandContext;
%ignore cc::pipeline::DebugRendererRenderCommand;
%ignore cc::pipeline::GeometryRendererRenderCommand;
%ignore cc::pipeline::RenderPipeline::addRenderCommand;
%ignore cc::pipeline::RenderPipeline::getRenderCommand;
// ----- Rename Section ------
// Brief: Classes, methods or attributes needs to be renamed
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "cocos-creator",
"version": "4.0.0-alpha.32",
"version": "4.0.0-alpha.34",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "cocos-creator",
"version": "4.0.0-alpha.32",
"version": "4.0.0-alpha.34",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cocos-creator",
"version": "4.0.0-alpha.32",
"version": "4.0.0-alpha.34",
"description": "Cocos Creator is a cross-platform 2D & 3D game engine written in C++ and TypeScript, licensed under MIT.",
"homepage": "http://www.cocos.com",
"license": "MIT",
+3 -2
View File
@@ -49,8 +49,9 @@ endmacro()
macro(cc_windows_after_target _target_name)
source_group(TREE ${RES_DIR}/data PREFIX "Resources" FILES ${CC_ASSET_FILES})
get_filename_component(CC_ASSET_ROOT "${RES_DIR}/data" ABSOLUTE)
source_group(TREE ${CC_ASSET_ROOT} PREFIX "Resources" FILES ${CC_ASSET_FILES})
source_group(TREE ${CC_PROJECT_DIR} PREFIX "Source Files" FILES ${CC_PROJ_SOURCES})
source_group(TREE ${CC_PROJECT_DIR}/../common PREFIX "Source Files" FILES ${CC_COMMON_SOURCES})