Files
cocos4/cocos/rendering/instanced-buffer.ts
Ming 60a24625b2 fix(webgl): sync buffer size with actual GL BUFFER_SIZE on resize (#389)
* fix(webgl): sync buffer size with actual GL BUFFER_SIZE on resize

* fix(webgl): move buffer update size check to CmdFuncUpdateBuffer

* fix(webgl): add buffer resize failure warning and fallback strategy

* fix(2d): guard MeshBuffer upload and IA draw when buffer resize fails

* fix(gfx): update EmptyBuffer size on resize for unit tests

---------

Co-authored-by: vanitynie <vanitynie@qq.com>
2026-10-30 17:39:22 +08:00

250 lines
9.9 KiB
TypeScript

/*
Copyright (c) 2020-2023 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 documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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 { Pass } from '../render-scene';
import { SubModel } from '../render-scene/scene';
import { UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING,
UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, ENABLE_PROBE_BLEND,
IRenderPass,
getPassPool } from './define';
import { BufferUsageBit, MemoryUsageBit, Device, InputAssembler, InputAssemblerInfo,
Attribute, Buffer, BufferInfo, CommandBuffer, Shader, DescriptorSet } from '../gfx';
import type { Texture } from '../gfx';
import { RecyclePool } from '../core/memop';
export function instancingCompareFn (l: InstancedBuffer, r: InstancedBuffer): number {
const ls = l.sortRender;
const rs = r.sortRender;
return (ls.hash - rs.hash) || (ls.shaderId - rs.shaderId);
}
export interface IInstancedItem {
count: number;
capacity: number;
vb: Buffer;
data: Uint8Array;
ia: InputAssembler;
stride: number;
shader: Shader | null;
descriptorSet: DescriptorSet;
lightingMap: Texture;
reflectionProbeCubemap: Texture;
reflectionProbePlanarMap: Texture;
useReflectionProbeType: number;
reflectionProbeBlendCubemap: Texture | null;
}
const INITIAL_CAPACITY = 32;
const MAX_CAPACITY = 1024;
export class InstancedBuffer {
public instances: IInstancedItem[] = [];
public declare pass: Pass;
public hasPendingModels = false;
public dynamicOffsets: number[] = [];
public sortRender: IRenderPass;
private declare _passPool: RecyclePool<IRenderPass>;
private declare _device: Device;
private readonly _instanceMap = new Map<string, IInstancedItem[]>();
constructor (pass: Pass) {
this._device = pass.device;
this.pass = pass;
this._passPool = getPassPool();
// Sorting instances of the same material is meaningless;
// the primary focus here is sorting different instances
this.sortRender = this._passPool.add();
}
public destroy (): void {
this.instances.forEach((instance) => {
instance.vb.destroy();
instance.ia.destroy();
});
this._passPool.reset();
this.instances.length = 0;
this._instanceMap.clear();
}
public merge (subModel: SubModel, passIdx: number, shaderImplant: Shader | null = null): void {
const attrs = subModel.instancedAttributeBlock;
const stride = attrs.buffer.length;
if (!stride) { return; } // we assume per-instance attributes are always present
const sourceIA = subModel.inputAssembler;
const subModelDescriptorSet = subModel.descriptorSet;
const lightingMap = subModelDescriptorSet.getTexture(UNIFORM_LIGHTMAP_TEXTURE_BINDING);
const reflectionProbeCubemap = subModelDescriptorSet.getTexture(UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING);
const reflectionProbePlanarMap = subModelDescriptorSet.getTexture(UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING);
const reflectionProbeBlendCubemap = ENABLE_PROBE_BLEND
? subModelDescriptorSet.getTexture(UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING)
: null;
const useReflectionProbeType = subModel.useReflectionProbeType;
let shader = shaderImplant;
if (!shader) {
shader = subModel.shaders[passIdx];
}
const descriptorSet = subModel.descriptorSet;
const hash = (subModel.passes[passIdx].priority as number) << 16 | (subModel.priority as number) << 8 | passIdx;
this.sortRender.hash = hash;
this.sortRender.shaderId = shader.typedID;
this.sortRender.passIdx = passIdx;
const key = `${sourceIA.indexBuffer?.objectID ?? 0}/${lightingMap.objectID}/${useReflectionProbeType}/`
+ `${reflectionProbeCubemap.objectID}/${reflectionProbePlanarMap.objectID}/`
+ `${ENABLE_PROBE_BLEND ? reflectionProbeBlendCubemap!.objectID : 0}/${stride}`;
const mappedInstances = this._instanceMap.get(key);
if (mappedInstances) {
for (let i = 0; i < mappedInstances.length; ++i) {
const instance = mappedInstances[i];
if (instance.count >= MAX_CAPACITY) { continue; }
this._appendInstance(instance, attrs.buffer, shader, descriptorSet);
return;
}
}
this._createInstance(
key,
sourceIA,
attrs.attributes,
attrs.buffer,
stride,
shader,
descriptorSet,
lightingMap,
useReflectionProbeType,
reflectionProbeCubemap,
reflectionProbePlanarMap,
reflectionProbeBlendCubemap,
);
}
private _appendInstance (instance: IInstancedItem, data: Uint8Array, shader: Shader, descriptorSet: DescriptorSet): void {
if (instance.count >= instance.capacity) { // resize buffers
const requiredCapacity = instance.count + 1;
const targetCapacity = Math.min(Math.max(instance.capacity << 1, requiredCapacity), MAX_CAPACITY);
const targetSize = instance.stride * targetCapacity;
instance.vb.resize(targetSize);
if (instance.vb.size < targetSize) {
const requiredSize = instance.stride * requiredCapacity;
if (instance.vb.size < requiredSize) {
instance.vb.resize(requiredSize);
}
}
instance.capacity = Math.floor(instance.vb.size / instance.stride);
if (instance.count >= instance.capacity) {
instance.count = instance.capacity;
return;
}
const newSize = instance.stride * instance.capacity;
if (newSize > instance.data.byteLength) {
const oldData = instance.data;
instance.data = new Uint8Array(newSize);
instance.data.set(oldData.subarray(0, instance.count * instance.stride));
}
}
instance.shader = shader;
instance.descriptorSet = descriptorSet;
instance.data.set(data, instance.stride * instance.count++);
this.hasPendingModels = true;
}
private _createInstance (
key: string,
sourceIA: InputAssembler,
instancedAttributes: Attribute[],
instanceData: Uint8Array,
stride: number,
shader: Shader,
descriptorSet: DescriptorSet,
lightingMap: Texture,
useReflectionProbeType: number,
reflectionProbeCubemap: Texture,
reflectionProbePlanarMap: Texture,
reflectionProbeBlendCubemap: Texture | null,
): void {
const newSize = stride * INITIAL_CAPACITY;
const vb = this._device.createBuffer(new BufferInfo(
BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST,
MemoryUsageBit.HOST | MemoryUsageBit.DEVICE,
newSize,
stride,
));
const data = new Uint8Array(newSize);
const vertexBuffers = sourceIA.vertexBuffers.slice();
const attributes = sourceIA.attributes.slice();
const indexBuffer = sourceIA.indexBuffer;
for (let i = 0; i < instancedAttributes.length; i++) {
const attr = instancedAttributes[i];
const newAttr = new Attribute(attr.name, attr.format, attr.isNormalized, vertexBuffers.length, true);
attributes.push(newAttr);
}
data.set(instanceData);
vertexBuffers.push(vb);
const iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer);
const ia = this._device.createInputAssembler(iaInfo);
const instance = {
count: 1,
capacity: INITIAL_CAPACITY,
vb,
data,
ia,
stride,
shader,
descriptorSet,
lightingMap,
reflectionProbeCubemap,
reflectionProbePlanarMap,
useReflectionProbeType,
reflectionProbeBlendCubemap,
} as IInstancedItem;
this.instances.push(instance);
let mappedInstances = this._instanceMap.get(key);
if (!mappedInstances) {
mappedInstances = [];
this._instanceMap.set(key, mappedInstances);
}
mappedInstances.push(instance);
this.hasPendingModels = true;
}
public uploadBuffers (cmdBuff: CommandBuffer): void {
for (let i = 0; i < this.instances.length; ++i) {
const instance = this.instances[i];
if (!instance.count) { continue; }
instance.ia.instanceCount = instance.count;
cmdBuff.updateBuffer(instance.vb, instance.data.buffer as ArrayBuffer, instance.count * instance.stride);
}
}
public clear (): void {
this.instances.forEach((instance) => {
instance.count = 0;
});
this.hasPendingModels = false;
this._passPool.reset();
}
}