diff --git a/.github/workflows/native-linter-android.yml b/.github/workflows/native-linter-android.yml index 58403783ca..a00f6a78cc 100644 --- a/.github/workflows/native-linter-android.yml +++ b/.github/workflows/native-linter-android.yml @@ -26,6 +26,10 @@ jobs: # Checks out a copy of your repository on the ubuntu-latest machine - name: Checkout code uses: actions/checkout@v2 + - name: Install CMake & Clang Tidy + run: | + sudo apt update --fix-missing + sudo apt install -y cmake llvm clang-tidy-11 - name: Download external run: | EXT_VERSION=`node ./.github/workflows/get-native-external-version.js` @@ -71,9 +75,6 @@ jobs: skipedDebug: - added|modified|deleted: '**' - exclude: 'native/cocos/editor-support/**' - - name: Install CMake & Clang Tidy - run: | - sudo apt install -y cmake llvm clang-tidy-11 - name: Generate Compile database shell: bash diff --git a/EngineErrorMap.md b/EngineErrorMap.md index 9340c012b4..46162067f5 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -1939,6 +1939,10 @@ Can not add a page without UITransform. Can not set the scroll view content when it hasn't UITransform or its parent hasn't UITransform. +### 4303 + +The %s scrollBar on the '%s' node is not available, please check it. + ### 4400 Invalid RichText img tag! The sprite frame name can't be found in the ImageAtlas! @@ -3323,4 +3327,8 @@ The asset replacing failed, can not found override asset('%s') for '%s' ### 16301 -node '%s' doesn't have any ModelRenderer component, this component will not work. please add ModelRenderer component first \ No newline at end of file +node '%s' doesn't have any ModelRenderer component, this component will not work. please add ModelRenderer component first + +### 16302 + +There is no reflection probe in the scene or no probe is near the current object. No reflection probe will take effect on this object. Please create a new reflection probe or move existing ones closer. \ No newline at end of file diff --git a/cocos/2d/assembler/graphics/webgl/index.ts b/cocos/2d/assembler/graphics/webgl/index.ts index 4494456f61..1a060e4975 100644 --- a/cocos/2d/assembler/graphics/webgl/index.ts +++ b/cocos/2d/assembler/graphics/webgl/index.ts @@ -27,8 +27,6 @@ import { IAssemblerManager } from '../../../renderer/base'; import { Graphics } from '../../../components'; import { graphicsAssembler as graphics } from './graphics-assembler'; -export { earcut } from './earcut'; - const graphicsAssemblerManager: IAssemblerManager = { getAssembler (sprite: UIRenderer) { return graphics; diff --git a/cocos/2d/assembler/label/index.ts b/cocos/2d/assembler/label/index.ts index e4d6893f30..7335dc3e4c 100644 --- a/cocos/2d/assembler/label/index.ts +++ b/cocos/2d/assembler/label/index.ts @@ -26,7 +26,6 @@ import { BitmapFont } from '../../assets'; import { Label } from '../../components'; import { IAssemblerManager } from '../../renderer/base'; import { bmfont } from './bmfont'; -import { CanvasPool } from './font-utils'; import { letter } from './letter'; import { ttf } from './ttf'; @@ -54,7 +53,6 @@ export { ttf, bmfont, letter, - CanvasPool, }; Label.Assembler = labelAssembler; diff --git a/cocos/2d/assembler/sprite/tiled.ts b/cocos/2d/assembler/sprite/tiled.ts index 3ecf97e99f..79a961ede6 100644 --- a/cocos/2d/assembler/sprite/tiled.ts +++ b/cocos/2d/assembler/sprite/tiled.ts @@ -23,7 +23,7 @@ */ import { JSB } from 'internal:constants'; -import { IUV, SpriteFrame } from '../../assets'; +import { IUV, SpriteFrame } from '../../assets/sprite-frame'; import { Mat4, Vec3, Color } from '../../../core'; import { IRenderData, RenderData } from '../../renderer/render-data'; import { IBatcher } from '../../renderer/i-batcher'; @@ -34,13 +34,13 @@ import { StaticVBChunk } from '../../renderer/static-vb-accessor'; const m = new Mat4(); -let origin:IUV; -let leftInner:IUV; -let rightInner:IUV; -let rightOuter:IUV; -let bottomInner:IUV; -let topInner:IUV; -let topOuter:IUV; +let origin: IUV; +let leftInner: IUV; +let rightInner: IUV; +let rightOuter: IUV; +let bottomInner: IUV; +let topInner: IUV; +let topOuter: IUV; let tempRenderDataLength = 0; const tempRenderData: IRenderData[] = []; let QUAD_INDICES; @@ -357,8 +357,8 @@ export const tiled: IAssembler = { let coefV = 0; const hRepeat = centerWidth === 0 ? sizableWidth : sizableWidth / centerWidth; const vRepeat = centerHeight === 0 ? sizableHeight : sizableHeight / centerHeight; - const tempXVerts :any = []; - const tempYVerts :any = []; + const tempXVerts: any = []; + const tempYVerts: any = []; for (let yIndexUV = 0; yIndexUV < row; ++yIndexUV) { if (sizableHeight > centerHeight) { diff --git a/cocos/2d/assets/bitmap-font.ts b/cocos/2d/assets/bitmap-font.ts index fa85d05769..f83bbae551 100644 --- a/cocos/2d/assets/bitmap-font.ts +++ b/cocos/2d/assets/bitmap-font.ts @@ -102,19 +102,22 @@ export class FontAtlas { */ @ccclass('cc.BitmapFont') export class BitmapFont extends Font { + /** + * @deprecated since v3.7.0, Useless Code. + */ @serializable @editable public fntDataStr = ''; /** - * @en [[SpriteFrame]] of the bitmap font + * @en [[SpriteFrame]] of the bitmap font. * @zh 位图字体所使用的精灵。 */ @type(SpriteFrame) public spriteFrame: SpriteFrame | null = null; /** - * @en The font size + * @en The font size. * @zh 文字尺寸。 */ @serializable @@ -122,13 +125,16 @@ export class BitmapFont extends Font { public fontSize = -1; /** - * @en Font configuration + * @en Font configuration. * @zh 字体配置。 */ @serializable @editable public fntConfig: IConfig | null = null; + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public declare fontDefDictionary: FontAtlas; onLoaded () { diff --git a/cocos/2d/assets/index.ts b/cocos/2d/assets/index.ts index 9221cd1b1a..3f5cb48518 100644 --- a/cocos/2d/assets/index.ts +++ b/cocos/2d/assets/index.ts @@ -22,8 +22,6 @@ THE SOFTWARE. */ - - export * from './sprite-frame'; export { SpriteAtlas } from './sprite-atlas'; export { TTFFont } from './ttf-font'; diff --git a/cocos/2d/assets/sprite-atlas.ts b/cocos/2d/assets/sprite-atlas.ts index c879236aa1..b77ac7cac3 100644 --- a/cocos/2d/assets/sprite-atlas.ts +++ b/cocos/2d/assets/sprite-atlas.ts @@ -46,14 +46,18 @@ interface ISpriteFrameList { */ @ccclass('cc.SpriteAtlas') export class SpriteAtlas extends Asset { + /** + * @en All sprite frames in the sprite atlas. + * @zh 精灵图集中的所有精灵。 + */ @serializable @editable public spriteFrames: ISpriteFrameList = js.createMap(); /** * @en Get the [[Texture2D]] asset of the atlas. - * @zh 获取精灵图集的贴图。请注意,由于结构调整优化,在 v1.1 版本之前,此函数的返回值为 imageAsset,在 v1.1 版本之后修正为 texture,想要获取 imageAsset 可使用 getTexture().image 获取 - * @returns The texture2d asset + * @zh 获取精灵图集的贴图。 + * @returns @en The texture2d asset. @zh 二维贴图资源。 */ public getTexture () { const keys = Object.keys(this.spriteFrames); @@ -69,8 +73,8 @@ export class SpriteAtlas extends Asset { * @en Gets the [[SpriteFrame]] correspond to the given key in sprite atlas. * @zh 根据键值获取精灵。 * - * @param key The SpriteFrame name - * @returns The SpriteFrame asset + * @param key @en The SpriteFrame name. @zh 精灵名字。 + * @returns @en The SpriteFrame asset. @zh 精灵资源。 */ public getSpriteFrame (key: string) { const sf = this.spriteFrames[key]; @@ -86,7 +90,7 @@ export class SpriteAtlas extends Asset { /** * @en Returns all sprite frames in the sprite atlas. * @zh 获取精灵图集所有精灵。 - * @returns All sprite frames + * @returns @en All sprite frames. @zh 所有的精灵资源。 */ public getSpriteFrames () { const frames: Array = []; diff --git a/cocos/2d/assets/sprite-frame.ts b/cocos/2d/assets/sprite-frame.ts index cbec49bd62..dec42f4be9 100644 --- a/cocos/2d/assets/sprite-frame.ts +++ b/cocos/2d/assets/sprite-frame.ts @@ -50,6 +50,9 @@ enum MeshType { POLYGON = 1, // Todo: Polygon mode need add } +/** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ export interface IUV { u: number; v: number; @@ -99,22 +102,22 @@ interface ISpriteFrameOriginal { } /** - * @en Information object interface for initialize a [[SpriteFrame]] asset - * @zh 用于初始化 [[SpriteFrame]] 资源的对象接口描述 + * @en Information object interface for initialize a [[SpriteFrame]] asset. + * @zh 用于初始化 [[SpriteFrame]] 资源的对象接口描述。 */ interface ISpriteFrameInitInfo { /** - * @en The texture of the sprite frame, could be `TextureBase` - * @zh 贴图对象资源,可以是 `TextureBase` 类型 + * @en The texture of the sprite frame, could be `TextureBase`. + * @zh 贴图对象资源,可以是 `TextureBase` 类型。 */ texture?: TextureBase; /** - * @en The original size of the sprite frame + * @en The original size of the sprite frame. * @zh 精灵帧原始尺寸。 */ originalSize?: Size; /** - * @en The rect of the sprite frame in atlas texture + * @en The rect of the sprite frame in atlas texture. * @zh 精灵帧裁切矩形。 */ rect?: Rect; @@ -156,7 +159,7 @@ interface ISpriteFrameInitInfo { */ isRotate?: boolean; /** - * @en Whether the uv is flipped + * @en Whether the uv is flipped. * @zh 是否转置 UV。 */ isFlipUv?: boolean; @@ -166,17 +169,17 @@ const temp_uvs: IUV[] = [{ u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, /** * @en - * A `SpriteFrame` support several types + * A `SpriteFrame` support several types. * 1. Rectangle sprite frame * 2. Sliced 9 sprite frame * 3. Mesh sprite frame * It mainly contains:
- * - texture: A `TextureBase` that will be used by render process
- * - rectangle: A rectangle of the texture - * - Sliced 9 border insets: The distance of each side from the internal rect to the sprite frame rect - * - vertices: Vertex list for the mesh type sprite frame - * - uv: The quad uv - * - uvSliced: The sliced 9 uv + * - texture: A `TextureBase` that will be used by render process.
+ * - rectangle: A rectangle of the texture. + * - Sliced 9 border insets: The distance of each side from the internal rect to the sprite frame rect. + * - vertices: Vertex list for the mesh type sprite frame. + * - uv: The quad uv. + * - uvSliced: The sliced 9 uv. * * @zh * 精灵帧资源。 @@ -187,10 +190,10 @@ const temp_uvs: IUV[] = [{ u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, * 它主要包含下列数据:
* - 纹理:会被渲染流程使用的 `TextureBase` 资源。
* - 矩形:在纹理中的矩形区域。 - * - 九宫格信息:九宫格的内部矩形四个边距离 SpriteFrame 外部矩形的距离 - * - 网格信息:网格类型精灵帧的所有顶点列表 - * - uv: 四边形 UV - * - uvSliced: 九宫格 UV + * - 九宫格信息:九宫格的内部矩形四个边距离 SpriteFrame 外部矩形的距离。 + * - 网格信息:网格类型精灵帧的所有顶点列表。 + * - uv: 四边形 UV。 + * - uvSliced: 九宫格 UV。 * 可通过 `SpriteFrame` 获取该组件。 * * @example @@ -240,9 +243,11 @@ const temp_uvs: IUV[] = [{ u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, @ccclass('cc.SpriteFrame') export class SpriteFrame extends Asset { /** - * @en Create a SpriteFrame object by an image asset or an native image asset - * @zh 通过 Image 资源或者平台相关 Image 对象创建一个 SpriteFrame 对象 - * @param imageSourceOrImageAsset ImageAsset or ImageSource, ImageSource support HTMLCanvasElement HTMLImageElement IMemoryImageSource + * @en Create a SpriteFrame object by an image asset or an native image asset. + * @zh 通过 Image 资源或者平台相关 Image 对象创建一个 SpriteFrame 资源。 + * @param imageSourceOrImageAsset @en ImageAsset or ImageSource, ImageSource could be HTMLCanvasElement, HTMLImageElement, IMemoryImageSource. + * @zh 图像资源或图像原始图像源,图像原始图像源支持 HTMLCanvasElement HTMLImageElement IMemoryImageSource 三种资源。 + * @returns @en SpriteFrame asset. @zh 精灵资源。 */ public static createWithImage (imageSourceOrImageAsset: ImageSource | ImageAsset) { const img = imageSourceOrImageAsset instanceof ImageAsset ? imageSourceOrImageAsset : new ImageAsset(imageSourceOrImageAsset); @@ -254,8 +259,8 @@ export class SpriteFrame extends Asset { } /** - * @en uv update event - * @zh uv 更新事件 + * @en uv update event. + * @zh uv 更新事件。 */ public static EVENT_UV_UPDATED = 'uv_updated'; public static MeshType = MeshType; @@ -414,8 +419,8 @@ export class SpriteFrame extends Asset { } /** - * @en The texture of the sprite frame, could be `TextureBase` - * @zh 贴图对象资源,可以是 `TextureBase` 类型 + * @en The texture of the sprite frame, could be `TextureBase`. + * @zh 贴图对象资源,可以是 `TextureBase` 类型。 */ get texture () { return this._texture; @@ -435,7 +440,7 @@ export class SpriteFrame extends Asset { } /** - * @en The uuid of the atlas asset, if exist + * @en The uuid of the atlas asset, if exists. * @zh 图集资源的 uuid。 */ get atlasUuid () { @@ -447,21 +452,24 @@ export class SpriteFrame extends Asset { } /** - * @en The pixel width of the sprite frame - * @zh 精灵帧的像素宽度 + * @en The pixel width of the sprite frame. + * @zh 精灵帧的像素宽度。 */ get width () { return this._texture.width; } /** - * @en The pixel height of the sprite frame - * @zh 精灵帧的像素高度 + * @en The pixel height of the sprite frame. + * @zh 精灵帧的像素高度。 */ get height () { return this._texture.height; } + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ set _textureSource (value: TextureBase) { // Optimization for build if (globalThis.Build) { @@ -475,8 +483,8 @@ export class SpriteFrame extends Asset { } /** - * @en Whether flip the uv in X direction - * @zh 延 X 轴方向, 翻转 UV + * @en Whether flip the uv in X direction. + * @zh 沿 X 轴方向, 翻转 UV。 */ get flipUVX () { return this._isFlipUVX; @@ -488,8 +496,8 @@ export class SpriteFrame extends Asset { } /** - * @en Whether flip the uv in Y direction - * @zh 延 Y 轴方向, 翻转 UV + * @en Whether flip the uv in Y direction. + * @zh 沿 Y 轴方向, 翻转 UV。 */ get flipUVY () { return this._isFlipUVY; @@ -500,6 +508,10 @@ export class SpriteFrame extends Asset { this._calculateUV(); } + /** + * @en Sets whether sprite can be packed into dynamic atlas. + * @zh 设置精灵是否允许参与自动合图。 + */ get packable () { return this._packable; } @@ -507,57 +519,64 @@ export class SpriteFrame extends Asset { this._packable = value; } + /** + * @en Original information before packed to dynamic atlas, includes texture, width, height. It's null before being packed to dynamic atlas. + * @zh 精灵自动合图之前的原始 texture 和宽高信息。在参与自动合图之前此值为 null。 + */ get original () { return this._original; } /** - * @en Number of pixels corresponding to unit size in world space (pixels per meter) - * @zh 世界空间中的单位大小对应的像素数量(像素每米) + * @en Number of pixels corresponding to unit size in world space (pixels per unit). + * @zh 世界空间中的单位大小对应的像素数量(像素每单位)。 */ get pixelsToUnit () { return this._pixelsToUnit; } /** - * @en Local origin position when generating the mesh - * @zh 生成 mesh 时本地坐标原点位置 + * @en Local origin position when generating the mesh. + * @zh 生成 mesh 时本地坐标原点位置。 */ get pivot () { return this._pivot; } /** - * @en mesh information, you should call the [[ensureMeshData]] function before using it - * @zh mesh 信息,你应该在使用它之前调用 [[ensureMeshData]] 函数来确保其可用 + * @en mesh information, you should call the [[ensureMeshData]] function before using it. + * @zh mesh 信息,你应该在使用它之前调用 [[ensureMeshData]] 函数来确保其可用。 */ get mesh () { return this._mesh; } /** - * @internal + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ get trimmedBorder () { return this._trimmedBorder; } /** - * @en Vertex list for the mesh type sprite frame - * @zh 网格类型精灵帧的所有顶点列表 + * @en Vertex list for the mesh type sprite frame. + * @zh 网格类型精灵帧的所有顶点列表。 */ public vertices: IVertices | null = null; /** - * @en UV for quad vertices - * @zh 矩形的顶点 UV + * @en UV for quad vertices. + * @zh 矩形的顶点 UV。 */ public uv: number[] = []; + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public unbiasUV: number[] = []; /** - * @en UV for sliced 9 vertices + * @en UV for sliced 9 vertices. * @zh 九宫格的顶点 UV。 */ public uvSliced: IUV[] = []; @@ -631,7 +650,7 @@ export class SpriteFrame extends Asset { * @zh * 返回是否已加载精灵帧。 * - * @deprecated since v3.3 + * @deprecated since v3.3, Useless Code. */ public textureLoaded () { return !!this.texture; @@ -642,7 +661,7 @@ export class SpriteFrame extends Asset { * Returns whether the sprite frame is rotated in the texture. * @zh * 获取 SpriteFrame 是否旋转。 - * @deprecated since v1.2, please use [[rotated]] instead + * @deprecated since v1.2, please use [[rotated]] instead. */ public isRotated () { return this._rotated; @@ -653,8 +672,8 @@ export class SpriteFrame extends Asset { * Set whether the sprite frame is rotated in the texture. * @zh * 设置 SpriteFrame 是否旋转。 - * @param value - * @deprecated since v1.2, please use [[rotated]] instead + * @param rotated @en rotated. @zh 是否旋转。 + * @deprecated since v1.2, please use [[rotated]] instead. */ public setRotated (rotated: boolean) { this.rotated = rotated; @@ -665,7 +684,9 @@ export class SpriteFrame extends Asset { * If it's an atlas texture, a transparent pixel area is proposed for the actual mapping of the current texture. * @zh 获取 SpriteFrame 的纹理矩形区域。 * 如果是一个 atlas 的贴图,则为当前贴图的实际剔除透明像素区域。 - * @deprecated since v1.2, please use [[rect]] + * @param out @en The output rect. @zh 输出的矩形区域。 + * @returns @en The rect. @zh 矩形区域。 + * @deprecated since v1.2, please use [[rect]]. */ public getRect (out?: Rect) { if (out) { @@ -679,7 +700,8 @@ export class SpriteFrame extends Asset { /** * @en Sets the rect of the sprite frame in the texture. * @zh 设置 SpriteFrame 的纹理矩形区域。 - * @deprecated since v1.2, please use [[rect]] + * @param rect @en The new rect. @zh 想要设置的 rect。 + * @deprecated since v1.2, please use [[rect]]. */ public setRect (rect: Rect) { this.rect = rect; @@ -688,7 +710,9 @@ export class SpriteFrame extends Asset { /** * @en Returns the original size before trimmed. * @zh 获取修剪前的原始大小。 - * @deprecated since v1.2, please use [[originalSize]] + * @param out @en The output original size. @zh 输出的原始大小。 + * @returns @en The original size. @zh 原始大小。 + * @deprecated since v1.2, please use [[originalSize]]. */ public getOriginalSize (out?: Size) { if (out) { @@ -702,17 +726,18 @@ export class SpriteFrame extends Asset { /** * @en Sets the original size before trimmed. * @zh 设置修剪前的原始大小。 - * @param size The new original size - * @deprecated since v1.2, please use [[originalSize]] + * @param size @en The new original size. @zh 新设置的原始大小。 + * @deprecated since v1.2, please use [[originalSize]]. */ public setOriginalSize (size: Size) { this.originalSize = size; } /** - * @en Returns the offset of the frame + * @en Gets the offset of the frame. * @zh 获取偏移量。 - * @param out The output offset object + * @param out @en The output offset object. @zh 输出的偏移量。 + * @returns @en The offset object. @zh 偏移量。 * @deprecated since v1.2, please use [[offset]] */ public getOffset (out?: Vec2) { @@ -725,9 +750,9 @@ export class SpriteFrame extends Asset { } /** - * @en Sets the offset of the frame + * @en Sets the offset of the frame. * @zh 设置偏移量。 - * @param offset The new offset + * @param offset @en The new offset. @zh 新设置的偏移量。 * @deprecated since v1.2, please use [[offset]] */ public setOffset (offset: Vec2) { @@ -735,41 +760,46 @@ export class SpriteFrame extends Asset { } /** - * @en Gets the related GFX [[gfx.Texture]] resource - * @zh 获取渲染贴图的 GFX 资源 + * @en Gets the related GFX [[gfx.Texture]] resource. + * @zh 获取渲染贴图的 GFX 资源。 + * @returns @en Gfx Texture resource. @zh GFX 贴图资源。 */ public getGFXTexture () { return this._texture.getGFXTexture(); } /** - * @en Gets the sampler resource of its texture - * @zh 贴图资源的采样器 + * @en Gets the GFX sampler of its texture. + * @zh 贴图资源的采样器。 + * @returns @en The GFX sampler resource. @zh GFX贴图采样器。 */ public getGFXSampler () { return this._texture.getGFXSampler(); } /** - * @en Gets the hash of its texture - * @zh 贴图资源的哈希值 + * @en Gets the hash of its texture. + * @zh 贴图资源的哈希值。 + * @returns @en Texture`s hash. @zh 贴图哈希值。 */ public getHash () { return this._texture.getHash(); } /** - * @en Gets the sampler hash of its texture - * @zh 贴图资源的采样器哈希值 + * @en Gets the sampler hash of its texture. + * @zh 贴图资源的采样器哈希值。 + * @returns @en Sampler`s hash. @zh 采样器哈希值。 */ public getSamplerInfo () { return this._texture.getSamplerInfo(); } /** - * @en Resets the sprite frame data + * @en Resets the sprite frame data. * @zh 重置 SpriteFrame 数据。 - * @param info SpriteFrame initialization information + * @param info @en SpriteFrame initialization information. @zh SpriteFrame 初始化信息。 + * @param clearData @en Clear Data before initialization. @zh 是否在初始化前清空原有数据。 */ public reset (info?: ISpriteFrameInitInfo, clearData = false) { let calUV = false; @@ -837,9 +867,10 @@ export class SpriteFrame extends Asset { } /** - * @en Check whether the rect of the sprite frame is out of the texture boundary + * @en Check whether the rect of the sprite frame is out of the texture boundary. * @zh 判断精灵计算的矩形区域是否越界。 - * @param texture + * @param texture @en Texture resources for sprite frame. @zh SpriteFrame 的贴图资源。 + * @returns @en Out of the texture boundary or not. @zh 矩形区域是否越界。 */ public checkRect (texture: TextureBase) { const rect = this._rect; @@ -884,8 +915,8 @@ export class SpriteFrame extends Asset { } /** - * @en Make sure the mesh is available, you should call it before using the mesh - * @zh 确保 mesh 可用,你应该在使用 mesh 之前调用它 + * @en Make sure the mesh is available, you should call it before using the mesh. + * @zh 确保 mesh 可用,你应该在使用 mesh 之前调用它。 */ public ensureMeshData () { if (this._mesh) return; @@ -1375,6 +1406,10 @@ export class SpriteFrame extends Asset { } } + /** + * @en clone a sprite frame. + * @zh 克隆当前 sprite frame。 + */ public clone (): SpriteFrame { const sp = new SpriteFrame(); const v = this.vertices; @@ -1434,10 +1469,21 @@ export class SpriteFrame extends Asset { } } + /** + * @en complete loading callback. + * @zh 加载完成回调。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public onLoaded () { this._calcTrimmedBorder(); } + /** + * @en default init. + * @zh 默认初始化。 + * @param uuid @en Asset uuid. @zh 资源 uuid。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public initDefault (uuid?: string) { super.initDefault(uuid); const texture = new Texture2D(); @@ -1446,6 +1492,12 @@ export class SpriteFrame extends Asset { this._calculateUV(); } + /** + * @en Check whether the sprite frame is validate. + * @zh 检查当前 sprite frame 对象是否是有效的。 + * @returns @en validate or not. @zh 是否有效。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public validate () { return this._texture && this._rect && this._rect.width !== 0 && this._rect.height !== 0; } diff --git a/cocos/2d/assets/ttf-font.ts b/cocos/2d/assets/ttf-font.ts index c4127e6923..f5ca236d54 100644 --- a/cocos/2d/assets/ttf-font.ts +++ b/cocos/2d/assets/ttf-font.ts @@ -59,6 +59,12 @@ export class TTFFont extends Font { return { uuid: this._uuid, __nativeName__: this._native, ext: path.extname(this._native), __isNative__: true }; } + /** + * @en default init. + * @zh 默认初始化。 + * @param uuid @en Asset uuid. @zh 资源 uuid。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public initDefault (uuid?: string) { this._fontFamily = 'Arial'; super.initDefault(uuid); diff --git a/cocos/2d/components/graphics.ts b/cocos/2d/components/graphics.ts index 139d1b9794..e36d97e8f0 100644 --- a/cocos/2d/components/graphics.ts +++ b/cocos/2d/components/graphics.ts @@ -53,7 +53,7 @@ const stride = getAttributeStride(attributes); * Graphics component. * * @zh - * 自定义图形类 + * 自定义图形类。 */ @ccclass('cc.Graphics') @help('i18n:cc.Graphics') @@ -200,20 +200,6 @@ export class Graphics extends UIRenderer { this._color.set(value); } - get srcBlendFactor () { - return this._srcBlendFactor; - } - - set srcBlendFactor (value) { - } - - get dstBlendFactor () { - return this._dstBlendFactor; - } - - set dstBlendFactor (value) { - } - public static LineJoin = LineJoin; public static LineCap = LineCap; public impl: Impl | null = null; @@ -240,7 +226,10 @@ export class Graphics extends UIRenderer { private _graphicsUseSubMeshes: RenderingSubMesh[] = []; //nativeObj - protected declare _graphicsNativeProxy:NativeUIModelProxy; + protected declare _graphicsNativeProxy: NativeUIModelProxy; + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get graphicsNativeProxy () { return this._graphicsNativeProxy; } @@ -280,7 +269,7 @@ export class Graphics extends UIRenderer { public onDestroy () { this._sceneGetter = null; if (JSB) { - this.graphicsNativeProxy.destroy(); + this._graphicsNativeProxy.destroy(); this.model = null; } else { if (this.model) { @@ -632,6 +621,9 @@ export class Graphics extends UIRenderer { } } + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public activeSubModel (idx: number) { if (!this.model) { warnID(4500, this.node.name); @@ -730,6 +722,9 @@ export class Graphics extends UIRenderer { } } + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public updateRenderer () { super.updateRenderer(); if (JSB) { diff --git a/cocos/2d/components/label-shadow.ts b/cocos/2d/components/label-shadow.ts index 37e20c3558..f8308c1fc6 100644 --- a/cocos/2d/components/label-shadow.ts +++ b/cocos/2d/components/label-shadow.ts @@ -29,8 +29,8 @@ import { Color, Vec2 } from '../../core'; import { Label } from './label'; /** - * @en Shadow effect for Label component, only for system fonts or TTF fonts - * @zh 用于给 Label 组件添加阴影效果,只能用于系统字体或 ttf 字体 + * @en Shadow effect for Label component, only for system fonts or TTF fonts. + * @zh 用于给 Label 组件添加阴影效果,只能用于系统字体或 ttf 字体。 * @example * import { Node, Label, LabelShadow } from 'cc'; * // Create a new node and add label components. @@ -82,7 +82,7 @@ export class LabelShadow extends Component { /** * @en - * Offset between font and shadow + * Offset between font and shadow. * * @zh * 字体与阴影的偏移。 @@ -105,10 +105,10 @@ export class LabelShadow extends Component { /** * @en - * A non-negative float specifying the level of shadow blur + * A non-negative float specifying the level of shadow blur. * * @zh - * 阴影的模糊程度 + * 阴影的模糊程度。 * * @example * ```ts diff --git a/cocos/2d/components/label.ts b/cocos/2d/components/label.ts index 327553ee07..5f1d0bfd2a 100644 --- a/cocos/2d/components/label.ts +++ b/cocos/2d/components/label.ts @@ -97,7 +97,7 @@ ccenum(VerticalTextAlignment); /** * @en Enum for Overflow. * - * @zh 文本超载类型。 + * @zh 文本溢出行为类型。 */ export enum Overflow { /** @@ -160,23 +160,6 @@ export enum CacheMode { ccenum(CacheMode); -/** - * @zh - * Type 类型。 - */ -/** - * @zh - * TTF字体。 - */ -/** - * @zh - * 位图字体。 - */ -/** - * @zh - * 系统字体。 - */ - /** * @en * The Label Component. @@ -189,12 +172,32 @@ ccenum(CacheMode); @executionOrder(110) @menu('2D/Label') export class Label extends UIRenderer { + /** + * @en Enum for horizontal text alignment. + * + * @zh 文本横向对齐类型。 + */ public static HorizontalAlign = HorizontalTextAlignment; + /** + * @en Enum for vertical text alignment. + * + * @zh 文本垂直对齐类型。 + */ public static VerticalAlign = VerticalTextAlignment; + /** + * @en Enum for label overflow mode. + * + * @zh 文本溢出行为类型。 + */ public static Overflow = Overflow; + /** + * @en Enum for cache mode. + * + * @zh 文本图集缓存类型。 + */ public static CacheMode = CacheMode; /** - * @internal + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ public static _canvasPool = CanvasPool.getInstance(); @@ -597,18 +600,30 @@ export class Label extends UIRenderer { this.markForUpdateRenderData(); } + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get spriteFrame () { return this._texture; } + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get ttfSpriteFrame () { return this._ttfSpriteFrame; } + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get assemblerData () { return this._assemblerData; } + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get fontAtlas () { return this._fontAtlas; } @@ -739,6 +754,11 @@ export class Label extends UIRenderer { super.onDestroy(); } + /** + * @en update render data. + * @zh 更新渲染相关数据。 + * @param force @en Whether to force an immediate update. @zh 是否立马强制更新渲染数据。 + */ public updateRenderData (force = false) { if (force) { this._flushAssembler(); @@ -762,6 +782,9 @@ export class Label extends UIRenderer { this.markForUpdateRenderData(); } + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public setEntityColor (color: Color) { if (JSB) { if (this._font instanceof BitmapFont) { diff --git a/cocos/2d/components/mask.ts b/cocos/2d/components/mask.ts index 9d71abc73c..31096feb0c 100644 --- a/cocos/2d/components/mask.ts +++ b/cocos/2d/components/mask.ts @@ -160,9 +160,9 @@ export class Mask extends Component { /** * @en - * Reverse mask + * Reverse mask. * @zh - * 反向遮罩 + * 反向遮罩。 */ @displayOrder(14) @tooltip('i18n:mask.inverted') @@ -260,6 +260,10 @@ export class Mask extends Component { } } + /** + * @en Rendering component for providing stencil buffer information. + * @zh 用于提供 stencil buffer 信息的渲染组件。 + */ get subComp () { return this._graphics || this._sprite; } @@ -299,10 +303,6 @@ export class Mask extends Component { this.node.on(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this); } - /** - * @zh - * 图形内容重塑。 - */ public onRestore () { this._changeRenderType(); this._updateGraphics(); @@ -319,9 +319,9 @@ export class Mask extends Component { } /** - * Hit test with point in World Space. - * - * @param worldPt point in World Space. + * @en Hit test with point in World Space. + * @zh 世界空间中的点击测试。 + * @param worldPt @en point in World Space. @zh 世界空间中的点击点。 */ public isHit (worldPt: Vec2) { const uiTrans = this.node._uiProps.uiTransformComp!; diff --git a/cocos/2d/components/rich-text.ts b/cocos/2d/components/rich-text.ts index 893edd09a1..8bd1e2e37c 100644 --- a/cocos/2d/components/rich-text.ts +++ b/cocos/2d/components/rich-text.ts @@ -234,10 +234,10 @@ export class RichText extends Component { /** * @en - * Custom System font of RichText + * Custom System font of RichText. * * @zh - * 富文本定制系统字体 + * 富文本定制系统字体。 */ @tooltip('i18n:richtext.font_family') get fontFamily () { @@ -425,7 +425,17 @@ export class RichText extends Component { } } } + /** + * @en Enum for horizontal text alignment. + * + * @zh 文本横向对齐类型。 + */ public static HorizontalAlign = HorizontalTextAlignment; + /** + * @en Enum for vertical text alignment. + * + * @zh 文本垂直对齐类型。 + */ public static VerticalAlign = VerticalTextAlignment; @serializable diff --git a/cocos/2d/components/sprite.ts b/cocos/2d/components/sprite.ts index 0510f346bd..2d7c6fa36f 100644 --- a/cocos/2d/components/sprite.ts +++ b/cocos/2d/components/sprite.ts @@ -386,6 +386,10 @@ export class Sprite extends UIRenderer { } } + /** + * @en Grayscale mode. + * @zh 是否以灰度模式渲染。 + */ @editable @displayOrder(5) @tooltip('i18n:sprite.gray_scale') @@ -431,9 +435,25 @@ export class Sprite extends UIRenderer { } } + /** + * @en Enum for fill type. + * @zh 填充类型。 + */ public static FillType = FillType; + /** + * @en Enum for sprite type. + * @zh Sprite 类型。 + */ public static Type = SpriteType; + /** + * @en Sprite's size mode, including trimmed size, raw size, and none. + * @zh 精灵尺寸调整模式。 + */ public static SizeMode = SizeMode; + /** + * @en Event types for sprite. + * @zh sprite 的事件类型。 + */ public static EventType = EventType; @serializable @@ -501,9 +521,8 @@ export class Sprite extends UIRenderer { * If there is no atlas, the switch fails. * * @zh - * 精灵图集内的精灵替换 - * - * @returns + * 选取使用精灵图集中的其他精灵。 + * @param name @en Name of the spriteFrame to switch. @zh 要切换的 spriteFrame 名字。 */ public changeSpriteFrameFromAtlas (name: string) { if (!this._atlas) { @@ -514,6 +533,9 @@ export class Sprite extends UIRenderer { this.spriteFrame = sprite; } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ public changeMaterialForDefine () { let texture; const lastInstanceMaterialType = this._instanceMaterialType; diff --git a/cocos/2d/components/ui-mesh-renderer.ts b/cocos/2d/components/ui-mesh-renderer.ts index 31e59571d8..b1e9301125 100644 --- a/cocos/2d/components/ui-mesh-renderer.ts +++ b/cocos/2d/components/ui-mesh-renderer.ts @@ -61,6 +61,10 @@ export class UIMeshRenderer extends Component { } } + /** + * @en Get the model component on this node + * @zh 获取同节点的 model 组件 + */ public get modelComponent () { return this._modelComponent; } @@ -123,6 +127,7 @@ export class UIMeshRenderer extends Component { * @zh 渲染数据组装程序,这个方法会在所有子节点数据组装之前更新并组装当前组件的渲染数据到 UI 的顶点数据缓冲区中。 * 一般在 UI 渲染流程中调用,用于组装所有的渲染数据到顶点数据缓冲区。 * 注意:不要手动调用该函数,除非你理解整个流程。 + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ public _render (render: IBatcher) { if (this._modelComponent) { @@ -140,12 +145,18 @@ export class UIMeshRenderer extends Component { return false; } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ public fillBuffers (render: IBatcher) { if (this.enabled) { this._render(render); } } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ // Native updateAssembler public updateRenderer () { if (JSB) { @@ -221,16 +232,28 @@ export class UIMeshRenderer extends Component { } } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ // interface public markForUpdateRenderData (enable = true) { uiRendererManager.markDirtyRenderer(this); } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ public stencilStage: Stage = Stage.DISABLED; + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ public setNodeDirty () { } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ public setTextureDirty () { } @@ -238,6 +261,9 @@ export class UIMeshRenderer extends Component { return (this.enabled && this._modelComponent !== null); } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ get renderEntity () { if (DEBUG) { assert(this._renderEntity, 'this._renderEntity should not be invalid'); @@ -246,6 +272,9 @@ export class UIMeshRenderer extends Component { } protected _renderData: RenderData | null = null; + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ get renderData () { return this._renderData; } diff --git a/cocos/2d/components/ui-static-batch.ts b/cocos/2d/components/ui-static-batch.ts index f3994b203f..987a3c363d 100644 --- a/cocos/2d/components/ui-static-batch.ts +++ b/cocos/2d/components/ui-static-batch.ts @@ -44,6 +44,10 @@ import { director } from '../../game'; * 该组件放在所有需要被静态合批的节点对象的根节点上,子节点放置对象必须是精灵和文本,其余对象不参与静态合批。 * 用户必须通过手动方式启用收集静态合批数据[[markAsDirty]],否则合批方式仍然采用动态合批(采集数据的流程相同)。此后渲染的内容是采用收集到的合批渲染数据,子节点的任何修改将不再有效。 * 注意:子节点下不要放置 Mask,Graphics,以及 UI 模型或者粒子之类对象,否则会在启用完静态合批后跳过渲染。 + * + * @deprecated Since v3.4.1, We have adopted a new rendering batching policy in v3.4.1, + * which will result in an effective performance improvement for normal dynamic batching components, + * so manual management with the UIStaticBatch component is no longer recommended and will be removed in the future */ @ccclass('cc.UIStaticBatch') @help('i18n:cc.UIStaticBatch') diff --git a/cocos/2d/framework/canvas.ts b/cocos/2d/framework/canvas.ts index 7775156a5d..c37be72094 100644 --- a/cocos/2d/framework/canvas.ts +++ b/cocos/2d/framework/canvas.ts @@ -84,6 +84,10 @@ export class Canvas extends RenderRoot2D { } } + /** + * @en The camera component that will be aligned with this canvas + * @zh 将与此 canvas 对齐的相机组件 + */ @type(Camera) @tooltip('i18n:canvas.camera') get cameraComponent () { @@ -98,6 +102,10 @@ export class Canvas extends RenderRoot2D { this._onResizeCamera(); } + /** + * @en Align canvas with screen + * @zh 是否使用屏幕对齐画布 + */ @tooltip('i18n:canvas.align') get alignCanvasWithScreen () { return this._alignCanvasWithScreen; @@ -109,12 +117,6 @@ export class Canvas extends RenderRoot2D { this._onResizeCamera(); } - // /** - // * @zh - // * 当前激活的画布组件,场景同一时间只能有一个激活的画布。 - // */ - // public static instance: Canvas | null = null; - @type(Camera) protected _cameraComponent: Camera | null = null; @serializable diff --git a/cocos/2d/framework/render-root-2d.ts b/cocos/2d/framework/render-root-2d.ts index 5ce8881885..faacc9441c 100644 --- a/cocos/2d/framework/render-root-2d.ts +++ b/cocos/2d/framework/render-root-2d.ts @@ -28,6 +28,10 @@ import { Component } from '../../scene-graph/component'; import { cclegacy } from '../../core'; import { UITransform } from './ui-transform'; +/** + * @en The entry node for 2D object data collection, all 2D rendering objects need to be rendered under the RenderRoot node. + * @zh 2D 对象数据收集的入口节点,所有的 2D渲染对象需在 RenderRoot 节点下才可以被渲染。 + */ @ccclass('cc.RenderRoot2D') @executionOrder(100) @menu('2D/RenderRoot2D') diff --git a/cocos/2d/framework/sprite-renderer.ts b/cocos/2d/framework/sprite-renderer.ts index b2f8fb2c54..84cd1b71f0 100644 --- a/cocos/2d/framework/sprite-renderer.ts +++ b/cocos/2d/framework/sprite-renderer.ts @@ -50,8 +50,8 @@ enum SpriteMode { @executeInEditMode export class SpriteRenderer extends ModelRenderer { /** - * @en The spriteFrame that the component should render - * @zh 该组件应渲染的 spriteFrame + * @en The spriteFrame that the component should render. + * @zh 该组件应渲染的 spriteFrame。 */ @type(SpriteFrame) get spriteFrame () { @@ -78,8 +78,8 @@ export class SpriteRenderer extends ModelRenderer { } /** - * @en Rendering model of the component - * @zh 该组件的渲染模型 + * @en Rendering model of the component. + * @zh 该组件的渲染模型。 */ get model () { return this._model; diff --git a/cocos/2d/framework/ui-component.ts b/cocos/2d/framework/ui-component.ts index bc0813e90f..80ea93a6bc 100644 --- a/cocos/2d/framework/ui-component.ts +++ b/cocos/2d/framework/ui-component.ts @@ -31,10 +31,10 @@ import { Stage } from '../renderer/stencil-manager'; /** * @en Legacy 2D base class for rendering component, please use [[UIRenderer]] instead. - * This component will setup NodeUIProperties.uiComp in its owner [[Node]] + * This component will setup NodeUIProperties.uiComp in its owner [[Node]]. * @zh 旧的 2D 渲染组件基类,请使用 [[UIRenderer]] 替代。 * 这个组件会设置 [[Node]] 上的 NodeUIProperties.uiComp。 - * @deprecated since v3.4.1 + * @deprecated since v3.4.1, please use [[UIRenderer]] instead. */ @ccclass('cc.UIComponent') @requireComponent(UITransform) @@ -71,18 +71,31 @@ export class UIComponent extends Component { * @zh 后置渲染数据组装程序,它会在所有子节点的渲染数据组装完成后被调用。 * 它可能会组装额外的渲染数据到顶点数据缓冲区,也可能只是重置一些渲染状态。 * 注意:不要手动调用该函数,除非你理解整个流程。 + * @deprecated since v3.4.1, please use [[UIRenderer]] instead. */ public postUpdateAssembler (render: IBatcher) { } + /** + * @deprecated since v3.4.1, please use [[UIRenderer]] instead. + */ public markForUpdateRenderData (enable = true) { } - public stencilStage : Stage = Stage.DISABLED; + /** + * @deprecated since v3.4.1, please use [[UIRenderer]] instead. + */ + public stencilStage: Stage = Stage.DISABLED; + /** + * @deprecated since v3.4.1, please use [[UIRenderer]] instead. + */ public setNodeDirty () { } + /** + * @deprecated since v3.4.1, please use [[UIRenderer]] instead. + */ public setTextureDirty () { } } diff --git a/cocos/2d/framework/ui-renderer.ts b/cocos/2d/framework/ui-renderer.ts index e9745603dc..cc5e26b463 100644 --- a/cocos/2d/framework/ui-renderer.ts +++ b/cocos/2d/framework/ui-renderer.ts @@ -117,16 +117,19 @@ export class UIRenderer extends Renderer { * @en The blend factor enums * @zh 混合模式枚举类型 * @see [[gfx.BlendFactor]] + * @internal */ public static BlendState = BlendFactor; /** * @en The render data assembler * @zh 渲染数据组装器 + * @internal */ public static Assembler: IAssemblerManager = null!; /** * @en The post render data assembler * @zh 后置渲染数据组装器 + * @internal */ public static PostAssembler: IAssemblerManager | null = null; @@ -197,21 +200,21 @@ export class UIRenderer extends Renderer { protected _renderData: RenderData | null = null; /** - * @internal + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ get renderData () { return this._renderData; } /** - * @internal + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ get useVertexOpacity () { return this._useVertexOpacity; } /** - * @internal + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. * @en The component stencil stage (please do not any modification directly on this object) * @zh 组件模板缓冲状态 (注意:请不要直接修改它的值) */ @@ -252,18 +255,24 @@ export class UIRenderer extends Renderer { protected _dstBlendFactorCache = BlendFactor.ONE_MINUS_SRC_ALPHA; /** - * @internal + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ public _dirtyVersion = -1; /** - * @internal + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ public _internalId = -1; + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ get batcher () { return director.root!.batcher2D; } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ get renderEntity () { if (DEBUG) { assert(this._renderEntity, 'this._renderEntity should not be invalid'); @@ -348,7 +357,7 @@ export class UIRenderer extends Renderer { /** * @en Request new render data object. * @zh 请求新的渲染数据对象。 - * @return The new render data + * @return @en The new render data. @zh 新的渲染数据。 */ public requestRenderData (drawInfoType = RenderDrawInfoType.COMP) { const data = RenderData.add(); @@ -370,7 +379,9 @@ export class UIRenderer extends Renderer { this._renderData = null; } - // test code: to replace prev part updateAssembler + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ public updateRenderer () { if (this._assembler) { this._assembler.updateRenderData(this); @@ -379,7 +390,9 @@ export class UIRenderer extends Renderer { this._renderEntity.enabled = this._renderFlag; } - // test code: to replace after part updateAssembler + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ public fillBuffers (render: IBatcher) { if (this._renderFlag) { this._render(render); @@ -444,6 +457,9 @@ export class UIRenderer extends Renderer { } } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ // for common public static setEntityColorDirtyRecursively (node: Node, dirty: boolean) { const render = node._uiProps.uiComp as UIRenderer; @@ -461,18 +477,27 @@ export class UIRenderer extends Renderer { } } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ public setEntityColor (color: Color) { if (JSB) { this._renderEntity.color = color; } } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ public setEntityOpacity (opacity: number) { if (JSB) { this._renderEntity.localOpacity = opacity; } } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ public setEntityEnabled (enabled: boolean) { if (JSB) { this._renderEntity.enabled = enabled; @@ -554,12 +579,18 @@ export class UIRenderer extends Renderer { protected _flushAssembler?(): void; + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ public setNodeDirty () { if (this.renderData) { this.renderData.nodeDirty = true; } } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ public setTextureDirty () { if (this.renderData) { this.renderData.textureDirty = true; diff --git a/cocos/2d/framework/ui-transform.ts b/cocos/2d/framework/ui-transform.ts index fb0603e8f2..cc4ca5295a 100644 --- a/cocos/2d/framework/ui-transform.ts +++ b/cocos/2d/framework/ui-transform.ts @@ -62,7 +62,6 @@ export class UITransform extends Component { */ @displayOrder(0) @tooltip('i18n:ui_transform.content_size') - // @constget get contentSize (): Readonly { return this._contentSize; } @@ -87,6 +86,12 @@ export class UITransform extends Component { this._markRenderDataDirty(); } + /** + * @en + * component width. + * @zh + * 组件宽度。 + */ get width () { return this._contentSize.width; } @@ -111,6 +116,12 @@ export class UITransform extends Component { this._markRenderDataDirty(); } + /** + * @en + * component height. + * @zh + * 组件高度。 + */ get height () { return this._contentSize.height; } @@ -159,6 +170,13 @@ export class UITransform extends Component { this._markRenderDataDirty(); } + /** + * @en + * The x-axis anchor of the node. + * + * @zh + * 锚点位置的 X 坐标。 + */ get anchorX () { return this._anchorPoint.x; } @@ -173,6 +191,13 @@ export class UITransform extends Component { this._markRenderDataDirty(); } + /** + * @en + * The y-axis anchor of the node. + * + * @zh + * 锚点位置的 Y 坐标。 + */ get anchorY () { return this._anchorPoint.y; } @@ -194,7 +219,7 @@ export class UITransform extends Component { * * @zh * 渲染先后顺序,按照广度渲染排列,按同级节点下进行一次排列。 - * @deprecated + * @deprecated Since v3.1 */ get priority () { return this._priority; @@ -274,7 +299,7 @@ export class UITransform extends Component { * @zh * 设置节点 UI Transform 的原始大小,不受该节点是否被缩放或者旋转的影响。 * - * @param size - The size of the UI transformation. + * @param size @en The size of the UI transform. @zh UI Transform 的 Size 大小。 * @example * ```ts * import { Size } from 'cc'; @@ -290,8 +315,8 @@ export class UITransform extends Component { * @zh * 设置节点 UI Transform 的原始大小,不受该节点是否被缩放或者旋转的影响。 * - * @param width - The width of the UI transformation. - * @param height - The height of the UI transformation. + * @param width @en The width of the UI transform. @zh UI Transform 的宽。 + * @param height @en The height of the UI transform. @zh UI Transform 的高。 * @example * ```ts * import { Size } from 'cc'; @@ -443,7 +468,7 @@ export class UITransform extends Component { * @zh 屏幕空间中的点击测试。 * @en Hit test with point in Screen Space. * - * @param screenPoint point in Screen Space. + * @param screenPoint @en point in Screen Space. @zh 屏幕坐标中的点。 */ public hitTest (screenPoint: Vec2, windowId = 0) { const w = this._contentSize.width; @@ -574,13 +599,13 @@ export class UITransform extends Component { /** * @en - * Returns a "local" axis aligned bounding box of the node.
+ * Returns an axis aligned bounding box of this node in local space coordinate.
* The returned box is relative only to its parent. * * @zh * 返回父节坐标系下的轴向对齐的包围盒。 * - * @return - 节点大小的包围盒 + * @returns @en An axis aligned bounding box of this node in local space coordinate. @zh 本地坐标系下的包围盒。 * @example * ```ts * const boundingBox = uiTransform.getBoundingBox(); @@ -602,14 +627,14 @@ export class UITransform extends Component { /** * @en - * Returns a "world" axis aligned bounding box of the node.
+ * Returns an axis aligned bounding box of this node in world space coordinate.
* The bounding box contains self and active children's world bounding box. * * @zh * 返回节点在世界坐标系下的对齐轴向的包围盒(AABB)。 * 该边框包含自身和已激活的子节点的世界边框。 * - * @returns - 返回世界坐标系下包围盒。 + * @returns @en An axis aligned bounding box of this node in world space coordinate. @zh 世界坐标系下包围盒。 * @example * ```ts * const newRect = uiTransform.getBoundingBoxToWorld(); @@ -632,7 +657,8 @@ export class UITransform extends Component { * * @param parentMat @en The parent node matrix. * @zh 父节点矩阵。 - * @returns + * @returns @en The minimum bounding box containing the current bounding box and its child nodes. + * @zh 包含当前节点包围盒及其子节点包围盒的最小包围盒。 */ public getBoundingBoxTo (parentMat: Mat4) { Mat4.fromRTS(_matrix, this.node.getRotation(), this.node.getPosition(), this.node.getScale()); @@ -674,7 +700,9 @@ export class UITransform extends Component { * Compute the corresponding aabb in world space for raycast. * * @zh - * 计算出此 UI_2D 节点在世界空间下的 aabb 包围盒 + * 计算出此 UI_2D 节点在世界空间下的 aabb 包围盒。 + * @param out @en The out object of aabb bounding box of the node in world space. @zh 输出节点在世界空间下的 aabb 包围盒。 + * @returns @en The aabb bounding box of the node in world space. @zh 节点在世界空间下的 aabb 包围盒。 */ public getComputeAABB (out?: geometry.AABB) { const width = this._contentSize.width; @@ -741,6 +769,10 @@ export class UITransform extends Component { } } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + * @engineInternal + */ public static _sortSiblings () { UITransform.priorityChangeNodeMap.forEach((node, ID) => { UITransform._sortChildrenSibling(node); @@ -750,6 +782,10 @@ export class UITransform extends Component { UITransform.priorityChangeNodeMap.clear(); } + /** + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + * @engineInternal + */ public static _cleanChangeMap () { UITransform.priorityChangeNodeMap.clear(); } diff --git a/cocos/2d/index.ts b/cocos/2d/index.ts index f8ab7e74ba..296768138a 100644 --- a/cocos/2d/index.ts +++ b/cocos/2d/index.ts @@ -23,11 +23,9 @@ */ import { - CanvasPool, graphicsAssembler, labelAssembler, spriteAssembler, - earcut, } from './assembler'; import { RenderData, MeshRenderData } from './renderer/render-data'; import { MeshBuffer } from './renderer/mesh-buffer'; @@ -48,18 +46,16 @@ export * from './utils'; export { MeshBuffer, StencilManager, - CanvasPool, - spriteAssembler, - labelAssembler, - graphicsAssembler, - earcut, + spriteAssembler, // use less + labelAssembler, // use less + graphicsAssembler, // use less }; cclegacy.UI = { - MeshBuffer, - spriteAssembler, - graphicsAssembler, - labelAssembler, + MeshBuffer, // use less + spriteAssembler, // use less + graphicsAssembler, // use less + labelAssembler, // use less RenderData, MeshRenderData, }; diff --git a/cocos/2d/renderer/base.ts b/cocos/2d/renderer/base.ts index e86f6aed05..20312364a9 100644 --- a/cocos/2d/renderer/base.ts +++ b/cocos/2d/renderer/base.ts @@ -29,10 +29,16 @@ import { UIRenderer } from '../framework/ui-renderer'; +/** + * @internal + */ export interface IAssembler { [key: string]: any; } +/** + * @internal + */ export interface IAssemblerManager { getAssembler (component: UIRenderer): IAssembler; } diff --git a/cocos/2d/renderer/batcher-2d.ts b/cocos/2d/renderer/batcher-2d.ts index c8face29cc..e00a2ac355 100644 --- a/cocos/2d/renderer/batcher-2d.ts +++ b/cocos/2d/renderer/batcher-2d.ts @@ -22,14 +22,14 @@ THE SOFTWARE. */ -import { JSB } from 'internal:constants'; +import { DEBUG, JSB } from 'internal:constants'; import { Camera, Model } from '../../render-scene/scene'; import type { UIStaticBatch } from '../components/ui-static-batch'; import { Material } from '../../asset/assets/material'; import { RenderRoot2D, UIRenderer } from '../framework'; import { Texture, Device, Attribute, Sampler, DescriptorSetInfo, Buffer, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet, InputAssembler, deviceManager, PrimitiveMode } from '../../gfx'; -import { CachedArray, Pool, Mat4, cclegacy, assertIsTrue } from '../../core'; +import { CachedArray, Pool, Mat4, cclegacy, assertIsTrue, assert } from '../../core'; import { Root } from '../../root'; import { Node } from '../../scene-graph'; import { Stage, StencilManager } from './stencil-manager'; @@ -53,6 +53,8 @@ const _dsInfo = new DescriptorSetInfo(null!); const m4_1 = new Mat4(); /** + * @en + * UI render flow * @zh * UI 渲染流程 */ @@ -119,12 +121,12 @@ export class Batcher2D implements IBatcher { // DescriptorSet Cache Map private _descriptorSetCache = new DescriptorSetCache(); - private _meshDataArray :MeshRenderData[] = []; + private _meshDataArray: MeshRenderData[] = []; // mask use - private _maskClearModel :Model | null = null; - private _maskClearMtl :Material | null = null; - private _maskModelMesh :RenderingSubMesh | null = null; + private _maskClearModel: Model | null = null; + private _maskClearMtl: Material | null = null; + private _maskModelMesh: RenderingSubMesh | null = null; constructor (private _root: Root) { this.device = _root.device; @@ -144,9 +146,9 @@ export class Batcher2D implements IBatcher { } this._batches.destroy(); - this._bufferAccessors.forEach((accessor: StaticVBAccessor) => { + for (const accessor of this._bufferAccessors.values()) { accessor.destroy(); - }); + } this._bufferAccessors.clear(); if (this._drawBatchPool) { @@ -276,14 +278,15 @@ export class Batcher2D implements IBatcher { if (JSB) { this._nativeObj.uploadBuffers(); } else if (this._batches.length > 0) { - this._meshDataArray.forEach((rd) => { - rd.uploadBuffers(); - }); + const length = this._meshDataArray.length; + for (let i = 0; i < length; i++) { + this._meshDataArray[i].uploadBuffers(); + } - this._bufferAccessors.forEach((accessor: StaticVBAccessor) => { + for (const accessor of this._bufferAccessors.values()) { accessor.uploadBuffers(); accessor.reset(); - }); + } this._descriptorSetCache.update(); } @@ -303,12 +306,13 @@ export class Batcher2D implements IBatcher { this._drawBatchPool.free(batch); } // Reset buffer accessors - this._bufferAccessors.forEach((accessor: StaticVBAccessor) => { + for (const accessor of this._bufferAccessors.values()) { accessor.reset(); - }); - this._meshDataArray.forEach((rd) => { - rd.freeIAPool(); - }); + } + const length = this._meshDataArray.length; + for (let i = 0; i < length; i++) { + this._meshDataArray[i].freeIAPool(); + } this._meshDataArray.length = 0; this._staticVBBuffer = null; @@ -411,6 +415,9 @@ export class Batcher2D implements IBatcher { this._currDepthStencilStateStage = depthStencilStateStage; this._currLayer = comp.node.layer; if (frame) { + if (DEBUG) { + assert(frame.isValid, 'frame should not be invalid, it may have been released'); + } this._currTexture = frame.getGFXTexture(); this._currSampler = frame.getGFXSampler(); this._currTextureHash = frame.getHash(); @@ -928,10 +935,7 @@ export class Batcher2D implements IBatcher { //sync mesh buffer to naive public syncMeshBuffersToNative (accId: number, buffers: MeshBuffer[]) { if (JSB) { - const nativeBuffers:NativeUIMeshBuffer[] = []; - buffers.forEach((x) => { - nativeBuffers.push(x.nativeObj); - }); + const nativeBuffers = buffers.map((buf) => buf.nativeObj); this._nativeObj.syncMeshBuffersToNative(accId, nativeBuffers); } } @@ -1083,8 +1087,11 @@ class DescriptorSetCache { public update () { const caches = this._localDescriptorSetCache; + const length = caches.length; + if (length === 0) { return; } const uselessArray: number[] = []; - caches.forEach((value) => { + for (let i = 0; i < length; i++) { + const value = caches[i]; if (value.isValid()) { value.uploadLocalData(); } else { @@ -1092,7 +1099,7 @@ class DescriptorSetCache { const pos = caches.indexOf(value); uselessArray.push(pos); } - }); + } for (let i = uselessArray.length - 1; i >= 0; i--) { caches.splice(uselessArray[i], 1); } @@ -1100,9 +1107,11 @@ class DescriptorSetCache { public reset () { const caches = this._localDescriptorSetCache; - caches.forEach((value) => { + const length = caches.length; + for (let i = 0; i < length; i++) { + const value = caches[i]; this._localCachePool.free(value); - }); + } this._localDescriptorSetCache.length = 0; } @@ -1116,9 +1125,9 @@ class DescriptorSetCache { } public destroy () { - this._descriptorSetCache.forEach((value, key, map) => { + for (const value of this._descriptorSetCache.values()) { value.destroy(); - }); + } this._descriptorSetCache.clear(); this._dsCacheHashByTexture.clear(); this._localDescriptorSetCache.length = 0; diff --git a/cocos/2d/renderer/buffer-accessor.ts b/cocos/2d/renderer/buffer-accessor.ts index 314acfe4a9..8ef1612a51 100644 --- a/cocos/2d/renderer/buffer-accessor.ts +++ b/cocos/2d/renderer/buffer-accessor.ts @@ -24,7 +24,7 @@ import { Attribute, Device } from '../../gfx'; import type { MeshBuffer } from './mesh-buffer'; -import { getAttributeStride, getComponentPerVertex } from './vertex-format'; +import { getAttributeStride } from './vertex-format'; export class BufferAccessor { public get attributes (): Readonly { return this._attributes; } diff --git a/cocos/2d/renderer/mesh-buffer.ts b/cocos/2d/renderer/mesh-buffer.ts index b938988f62..1d464e2894 100644 --- a/cocos/2d/renderer/mesh-buffer.ts +++ b/cocos/2d/renderer/mesh-buffer.ts @@ -34,7 +34,7 @@ interface IIARef { indexBuffer: Buffer; } -export enum MeshBufferSharedBufferView{ +enum MeshBufferSharedBufferView { byteOffset, vertexOffset, indexOffset, @@ -42,15 +42,35 @@ export enum MeshBufferSharedBufferView{ count, } +/** + * @en Mesh buffer used for 2d rendering, used internally and not of concern to the user. + * @zh 2d 渲染使用的网格缓冲数据,内部使用,用户不须关心。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ export class MeshBuffer { + /** + * @en The vertex attributes of the buffer. + * @zh buffer 的顶点属性。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get attributes () { return this._attributes; } + /** + * @en Number of bytes in vertex format. + * @zh 顶点格式的字节数。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get vertexFormatBytes () { return this._vertexFormatBytes; } protected _byteOffset = 0; + /** + * @en byte offset. + * @zh 字节偏移量。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get byteOffset () { return this._byteOffset; } - set byteOffset (val:number) { + set byteOffset (val: number) { this._byteOffset = val; if (JSB) { this._sharedBuffer[MeshBufferSharedBufferView.byteOffset] = val; @@ -58,10 +78,15 @@ export class MeshBuffer { } protected _vertexOffset = 0; + /** + * @en Vertexes offset. + * @zh 顶点数偏移。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get vertexOffset () { return this._vertexOffset; } - set vertexOffset (val:number) { + set vertexOffset (val: number) { this._vertexOffset = val; if (JSB) { this._sharedBuffer[MeshBufferSharedBufferView.vertexOffset] = val; @@ -69,10 +94,15 @@ export class MeshBuffer { } protected _indexOffset = 0; + /** + * @en Indices offset. + * @zh 索引偏移。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get indexOffset () { return this._indexOffset; } - set indexOffset (val:number) { + set indexOffset (val: number) { this._indexOffset = val; if (JSB) { this._sharedBuffer[MeshBufferSharedBufferView.indexOffset] = val; @@ -80,10 +110,15 @@ export class MeshBuffer { } protected _dirty = false; + /** + * @en Dirty flag. + * @zh 脏标记。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get dirty () { return this._dirty; } - set dirty (val:boolean) { + set dirty (val: boolean) { this._dirty = val; if (JSB) { this._sharedBuffer[MeshBufferSharedBufferView.dirty] = val ? 1 : 0; @@ -91,18 +126,28 @@ export class MeshBuffer { } protected _floatsPerVertex = 0; + /** + * @en Float numbers per vertex. + * @zh 每顶点的浮点数长度。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get floatsPerVertex () { return this._floatsPerVertex; } - set floatsPerVertex (val:number) { + set floatsPerVertex (val: number) { this._floatsPerVertex = val; } protected _vData: Float32Array = null!; + /** + * @en Vertexes data. + * @zh 顶点数据。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get vData () { return this._vData; } - set vData (val:Float32Array) { + set vData (val: Float32Array) { this._vData = val; //还得看是否需要共享.buffer if (JSB) { @@ -111,10 +156,15 @@ export class MeshBuffer { } protected _iData: Uint16Array = null!; + /** + * @en Indices data. + * @zh 索引数据。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get iData () { return this._iData; } - set iData (val:Uint16Array) { + set iData (val: Uint16Array) { this._iData = val; if (JSB) { this._nativeObj.iData = val; @@ -132,23 +182,43 @@ export class MeshBuffer { private _nextFreeIAHandle = 0; //nativeObj - protected declare _nativeObj:NativeUIMeshBuffer; + protected declare _nativeObj: NativeUIMeshBuffer; + /** + * @en Native object. + * @zh 原生对象。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get nativeObj () { return this._nativeObj; } //sharedBuffer protected declare _sharedBuffer: Uint32Array; + /** + * @en Native shared buffer. + * @zh 原生共享缓冲。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get sharedBuffer () { return this._sharedBuffer; } + /** + * @en Initial native shared buffer. + * @zh 初始化原生共享缓冲。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public initSharedBuffer () { if (JSB) { this._sharedBuffer = new Uint32Array(MeshBufferSharedBufferView.count); } } + /** + * @en Synchronized native shared buffer. + * @zh 同步原生共享缓冲。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public syncSharedBufferToNative () { if (JSB) { this._nativeObj.syncSharedBufferToNative(this._sharedBuffer); @@ -163,6 +233,15 @@ export class MeshBuffer { this.syncSharedBufferToNative(); } + /** + * @en Initialize mesh buffer. + * @zh 初始化对象。 + * @param device @en The GFX device. @zh GFX设备。 + * @param attrs @en The vertex attributes of the buffer. @zh 缓冲区的顶点属性。 + * @param vFloatCount @en The vertexes float count. @zh 每顶点所需的 float 数量。 + * @param iCount @en The indices count. @zh 索引数量。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public initialize (device: Device, attrs: Attribute[], vFloatCount: number, iCount: number) { this._initVDataCount = vFloatCount; this._initIDataCount = iCount; @@ -183,6 +262,11 @@ export class MeshBuffer { } } + /** + * @en Reset state. + * @zh 重置状态。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public reset () { this._nextFreeIAHandle = 0; this.dirty = false; @@ -209,6 +293,11 @@ export class MeshBuffer { this._iaPool.length = 0; } + /** + * @en Set dirty flag. + * @zh 设置脏标签。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public setDirty () { this.dirty = true; } @@ -222,7 +311,11 @@ export class MeshBuffer { return false; } - //有返回值暂时没写 + /** + * @en require Free input assembler. + * @zh 请求可用的输入汇集器。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public requireFreeIA (device: Device) { if (this._iaPool.length <= this._nextFreeIAHandle) { this._iaPool.push(this.createNewIA(device)); @@ -231,7 +324,11 @@ export class MeshBuffer { return ia; } - //参数暂时没传 + /** + * @en recycle input assembler. + * @zh 回收输入汇集器。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public recycleIA (ia: InputAssembler) { const pool = this._iaPool; for (let i = 0; i < this._nextFreeIAHandle; ++i) { @@ -245,6 +342,11 @@ export class MeshBuffer { } } + /** + * @en check capacity. + * @zh 检查可分配余量。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public checkCapacity (vertexCount: number, indexCount: number) { const maxVertex = (this.vertexOffset + vertexCount) * this._floatsPerVertex; const maxIndex = this.indexOffset + indexCount; @@ -254,6 +356,11 @@ export class MeshBuffer { return true; } + /** + * @en Upload and update buffers data. + * @zh 上传更新缓冲内容。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public uploadBuffers () { if (this.byteOffset === 0 || !this._dirty) { return; @@ -292,7 +399,6 @@ export class MeshBuffer { this.dirty = false; } - //有返回值,暂时没原生化 private createNewIA (device: Device): IIARef { let ia; let vertexBuffers; diff --git a/cocos/2d/renderer/stencil-manager.ts b/cocos/2d/renderer/stencil-manager.ts index e9e524f02a..8434fbf52c 100644 --- a/cocos/2d/renderer/stencil-manager.ts +++ b/cocos/2d/renderer/stencil-manager.ts @@ -27,7 +27,11 @@ import { Material } from '../../asset/assets'; import { UIRenderer } from '../framework/ui-renderer'; import { UIMeshRenderer } from '../components/ui-mesh-renderer'; -// Stage types +/** + * @en Stencil stage types enum. + * @zh 模板状态类型枚举。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ export enum Stage { // Stencil disabled DISABLED = 0, @@ -45,6 +49,11 @@ export enum Stage { ENTER_LEVEL_INVERTED = 6, } +/** + * @en Native stencil buffer format enum. + * @zh 原生模板缓冲格式枚举。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ export enum StencilSharedBufferView { stencilTest, func, @@ -57,6 +66,11 @@ export enum StencilSharedBufferView { count, } +/** + * @en Stencil state manager. + * @zh 模板状态管理器。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ export class StencilManager { public static sharedManager: StencilManager | null = null; private _maskStack: any[] = []; @@ -71,31 +85,61 @@ export class StencilManager { ref: 1, }; - private _stage:Stage = Stage.DISABLED; + private _stage: Stage = Stage.DISABLED; + /** + * @en Stencil stage. + * @zh 模板缓冲阶段。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get stage () { return this._stage; } - set stage (val:Stage) { + set stage (val: Stage) { this._stage = val; } + /** + * @en Stencil pattern. + * @zh 模板缓冲样式。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ get pattern () { return this._stencilPattern; } + /** + * @en Add mask nesting. + * @zh 添加mask嵌套。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public pushMask (mask: any) { this._maskStack.push(mask); } + /** + * @en clear stencil stage. + * @zh 清空模板状态。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public clear (comp: UIRenderer | UIMeshRenderer) { const isInverted = (comp.stencilStage !== Stage.ENTER_LEVEL); return isInverted ? Stage.CLEAR_INVERTED : Stage.CLEAR; } + /** + * @en Open stencil stage to enabled. + * @zh 开启模板状态。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public enableMask () { this.stage = Stage.ENABLED; } + /** + * @en exit stencil. + * @zh 退出模板状态。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public exitMask () { if (this._maskStack.length === 0) { // cc.errorID(9001); @@ -109,15 +153,25 @@ export class StencilManager { } } + /** + * @en Get write mask count. + * @zh 获取写入模板缓冲的位数。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public getWriteMask () { return 1 << (this._maskStack.length - 1); } + /** + * @en Get write mask count when exit. + * @zh 获取退出时模板缓冲的位数。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public getExitWriteMask () { return 1 << this._maskStack.length; } - public getStencilRef () { + private getStencilRef () { let result = 0; for (let i = 0; i < this._maskStack.length; ++i) { result += (0x00000001 << i); @@ -125,10 +179,20 @@ export class StencilManager { return result; } + /** + * @en Get mask nesting count. + * @zh 获取mask嵌套数量。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public getMaskStackSize () { return this._maskStack.length; } + /** + * @en Reset stencil stage. + * @zh 重置模板状态。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public reset () { // reset stack and stage this._maskStack.length = 0; @@ -145,6 +209,11 @@ export class StencilManager { private stencilStateMap = new Map(); private stencilStateMapWithDepth = new Map(); + /** + * @en Get stencil stage. + * @zh 获取模板状态。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public getStencilStage (stage: Stage, mat?: Material) { let key = 0; let depthTest = false; @@ -195,6 +264,11 @@ export class StencilManager { return depthStencilState; } + /** + * @en Get stencil hash. + * @zh 获取模板状态的哈希值。 + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public getStencilHash (stage: Stage) { return (stage << 8) | this._maskStack.length; } diff --git a/cocos/2d/renderer/vertex-format.ts b/cocos/2d/renderer/vertex-format.ts index 21529c1f89..b2b30689a7 100644 --- a/cocos/2d/renderer/vertex-format.ts +++ b/cocos/2d/renderer/vertex-format.ts @@ -34,7 +34,7 @@ export const vfmt = [ ]; /** - * @en Vertex format with the following layout + * @en Vertex format with the following layout. * 1. Vector 3 position attribute (Float32) * 2. Vector 4 color attribute (Float32) * @zh 包含以下数据的顶点格式 @@ -62,6 +62,16 @@ export const vfmtPosUvColor = [ new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F), ]; +/** + * @en Vertex format with the following layout + * 1. Vector 3 position attribute (Float32) + * 2. Vector 2 uv attribute (Float32) + * 3. Byte 4 color attribute (Byte) + * @zh 包含以下数据的顶点格式 + * 1. 三维位置属性(Float32) + * 2. 二维贴图 UV 属性(Float32) + * 3. RGBA 颜色属性(Byte) + */ export const vfmtPosUvColor4B = [ new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), @@ -78,7 +88,7 @@ export const vfmtPosUvColor4B = [ * 1. 三维位置属性(Float32) * 2. 二维贴图 UV 属性(Float32) * 3. 第一套 RGBA 颜色属性(Float32) - * 3. 第二套 RGBA 颜色属性(Float32) + * 4. 第二套 RGBA 颜色属性(Float32) */ export const vfmtPosUvTwoColor = [ new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), @@ -87,6 +97,18 @@ export const vfmtPosUvTwoColor = [ new Attribute(AttributeName.ATTR_COLOR2, Format.RGBA32F), ]; +/** + * @en Vertex format with the following layout + * 1. Vector 3 position attribute (Float32) + * 2. Vector 2 uv attribute (Float32) + * 3. First byte 4 color attribute (Byte) + * 4. Second byte 4 color attribute (Byte) + * @zh 包含以下数据的顶点格式 + * 1. 三维位置属性(Float32) + * 2. 二维贴图 UV 属性(Float32) + * 3. 第一套 RGBA 颜色属性(Byte) + * 4. 第二套 RGBA 颜色属性(Byte) + */ export const vfmtPosUvTwoColor4B = [ new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), diff --git a/cocos/2d/utils/dynamic-atlas/atlas-manager.ts b/cocos/2d/utils/dynamic-atlas/atlas-manager.ts index 3d3a6d2fd3..7affddb9f7 100644 --- a/cocos/2d/utils/dynamic-atlas/atlas-manager.ts +++ b/cocos/2d/utils/dynamic-atlas/atlas-manager.ts @@ -273,6 +273,10 @@ export class DynamicAtlasManager extends System { } } +/** + * @en Dynamic Atlas Manager,use to auto merge sprite frame. + * @zh 动态合图管理器,用于引擎的自动合图功能。 + */ export const dynamicAtlasManager: DynamicAtlasManager = DynamicAtlasManager.instance = new DynamicAtlasManager(); director.registerSystem('dynamicAtlasManager', dynamicAtlasManager, 0); diff --git a/cocos/2d/utils/font-loader.ts b/cocos/2d/utils/font-loader.ts index 6a1e48f554..579de5d42f 100644 --- a/cocos/2d/utils/font-loader.ts +++ b/cocos/2d/utils/font-loader.ts @@ -24,7 +24,6 @@ import { warnID } from '../../core'; import { safeMeasureText } from './text-utils'; -import { CompleteCallback, IDownloadParseOptions } from '../../asset/asset-manager/shared'; import downloader from '../../asset/asset-manager/downloader'; import factory from '../../asset/asset-manager/factory'; import { TTFFont } from '../assets/ttf-font'; @@ -35,7 +34,7 @@ const ccdocument = ccwindow.document; interface IFontLoadHandle { fontFamilyName: string; refWidth: number; - onComplete: CompleteCallback; + onComplete: ((err: Error | null, data?: any | null) => void); startTime: number; } @@ -110,7 +109,7 @@ function checkFontLoaded () { } // refer to https://github.com/typekit/webfontloader/blob/master/src/core/nativefontwatchrunner.js -function nativeCheckFontLoaded (start: number, font: string, callback: CompleteCallback): void { +function nativeCheckFontLoaded (start: number, font: string, callback: ((err: Error | null, data?: any | null) => void)): void { const loader = new Promise((resolve, reject) => { const check = () => { const now = Date.now(); @@ -151,7 +150,7 @@ function nativeCheckFontLoaded (start: number, font: string, callback: CompleteC }); } -export function loadFont (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) { +export function loadFont (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) { const fontFamilyName = getFontFamily(url); // Already loaded fonts if (_fontFaces[fontFamilyName]) { @@ -228,7 +227,7 @@ export function getFontFamily (fontHandle: string): string { return fontFamilyName; } -function createFont (id: string, data: string, options: IDownloadParseOptions, onComplete: CompleteCallback) { +function createFont (id: string, data: string, options: Record, onComplete: ((err: Error | null, data?: TTFFont | null) => void)) { const out = new TTFFont(); out._nativeUrl = id; out._nativeAsset = data; diff --git a/cocos/2d/utils/html-text-parser.ts b/cocos/2d/utils/html-text-parser.ts index 2ab9b0cdae..6b781c3b49 100644 --- a/cocos/2d/utils/html-text-parser.ts +++ b/cocos/2d/utils/html-text-parser.ts @@ -33,7 +33,8 @@ const eventRegx = /^(click)(\s)*=|(param)(\s)*=/; const imageAttrReg = /(\s)*src(\s)*=|(\s)*height(\s)*=|(\s)*width(\s)*=|(\s)*align(\s)*=|(\s)*offset(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/; /** - * A utils class for parsing HTML texts. The parsed results will be an object array. + * @en A utils class for parsing HTML texts. The parsed results will be an object array. + * @zh 一个用于解析HTML文本的工具类。解析后的结果将是一个对象数组。 * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ export interface IHtmlTextParserResultObj{ @@ -42,6 +43,8 @@ export interface IHtmlTextParserResultObj{ } /** + * @en Html Text Parser Stack interface + * @zh Html 文本解析器接口 * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ export interface IHtmlTextParserStack{ @@ -62,6 +65,8 @@ export interface IHtmlTextParserStack{ } /** + * @en Html Text Parser Stack + * @zh Html 文本解析器 * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ export class HtmlTextParser { diff --git a/cocos/2d/utils/index.ts b/cocos/2d/utils/index.ts index 4f0ef61268..0e63c451e8 100644 --- a/cocos/2d/utils/index.ts +++ b/cocos/2d/utils/index.ts @@ -25,5 +25,4 @@ import './font-loader'; export * from './html-text-parser'; -export * from './text-utils'; export { dynamicAtlasManager } from './dynamic-atlas/atlas-manager'; diff --git a/cocos/3d/assets/mesh.jsb.ts b/cocos/3d/assets/mesh.jsb.ts index 7bac5290cb..8f562b41fb 100644 --- a/cocos/3d/assets/mesh.jsb.ts +++ b/cocos/3d/assets/mesh.jsb.ts @@ -147,9 +147,13 @@ Object.defineProperty(meshAssetProto, 'maxPosition', { }); meshAssetProto.onLoaded = function () { - // might be undefined - if (this._struct != undefined) { - this.setStruct(this._struct); + // might be undefined or null + const meshStruct = this._struct; + if (meshStruct) { + // Synchronize to native if the struct contains valid values. + if (meshStruct.vertexBundles.length !== 0 || meshStruct.primitives.length !== 0) { + this.setStruct(this._struct); + } } // Set to null to release memory in JS this._struct = null; diff --git a/cocos/3d/framework/mesh-renderer.ts b/cocos/3d/framework/mesh-renderer.ts index b83f95537b..46bec5096b 100644 --- a/cocos/3d/framework/mesh-renderer.ts +++ b/cocos/3d/framework/mesh-renderer.ts @@ -27,7 +27,7 @@ import { displayOrder, group, range } from 'cc.decorator'; import { Texture2D, TextureCube } from '../../asset/assets'; import { Material } from '../../asset/assets/material'; import { Mesh } from '../assets/mesh'; -import { Vec4, Enum, cclegacy, CCBoolean, CCFloat, assertIsTrue, _decorator, CCInteger, EventTarget } from '../../core'; +import { Vec4, Enum, cclegacy, CCBoolean, CCFloat, assertIsTrue, _decorator, CCInteger, EventTarget, warnID } from '../../core'; import { scene } from '../../render-scene'; import { MorphModel } from '../models/morph-model'; import { Root } from '../../root'; @@ -300,7 +300,7 @@ export class MeshRenderer extends ModelRenderer { @serializable @editable @disallowAnimation - @displayOrder(1) + @displayOrder(3) public bakeSettings = new ModelBakeSettings(this); @serializable @@ -327,7 +327,7 @@ export class MeshRenderer extends ModelRenderer { */ @type(CCFloat) @tooltip('i18n:model.shadow_bias') - @group({ id: 'DynamicShadow', name: 'DynamicShadowSettings', displayOrder: 0 }) + @group({ id: 'DynamicShadow', name: 'DynamicShadowSettings', displayOrder: 2 }) @disallowAnimation get shadowBias () { return this._shadowBias; @@ -374,6 +374,25 @@ export class MeshRenderer extends ModelRenderer { this._updateCastShadow(); } + /** + * @en Is received direction Light. + * @zh 是否接收平行光光照。 + * @param visibility @en direction light visibility. @zh 方向光的可见性。 + */ + public onUpdateReceiveDirLight (visibility: number, forceClose = false) { + if (!this._model) { return; } + if (forceClose) { + this._model.receiveDirLight = false; + return; + } + if (this.node && ((visibility & this.node.layer) === this.node.layer) + || (visibility & this._model.visFlags)) { + this._model.receiveDirLight = true; + } else { + this._model.receiveDirLight = false; + } + } + /** * @en receive shadow. * @zh 实时光照下是否接受阴影。 @@ -398,6 +417,7 @@ export class MeshRenderer extends ModelRenderer { * 注意,设置时,所有形变目标的权重都将归零。 */ @type(Mesh) + @displayOrder(1) @tooltip('i18n:model.mesh') get mesh () { return this._mesh; @@ -418,6 +438,7 @@ export class MeshRenderer extends ModelRenderer { this._updateReceiveShadow(); this._updateUseLightProbe(); this._updateUseReflectionProbe(); + this._updateReceiveDirLight(); } /** @@ -484,6 +505,7 @@ export class MeshRenderer extends ModelRenderer { this._updateUseLightProbe(); this._updateBakeToReflectionProbe(); this._updateUseReflectionProbe(); + this._updateReceiveDirLight(); } // Redo, Undo, Prefab restore, etc. @@ -499,11 +521,13 @@ export class MeshRenderer extends ModelRenderer { this._updateUseLightProbe(); this._updateBakeToReflectionProbe(); this._updateUseReflectionProbe(); + this._updateReceiveDirLight(); } public onEnable () { super.onEnable(); this.node.on(NodeEventType.MOBILITY_CHANGED, this.onMobilityChanged, this); + this.node.on(NodeEventType.LIGHT_PROBE_BAKING_CHANGED, this.onLightProbeBakingChanged, this); this.bakeSettings.on(ModelBakeSettings.USE_LIGHT_PROBE_CHANGED, this.onUseLightProbeChanged, this); this.bakeSettings.on(ModelBakeSettings.REFLECTION_PROBE_CHANGED, this.onReflectionProbeChanged, this); this.bakeSettings.on(ModelBakeSettings.BAKE_TO_REFLECTION_PROBE_CHANGED, this.onBakeToReflectionProbeChanged, this); @@ -519,6 +543,7 @@ export class MeshRenderer extends ModelRenderer { this._updateUseReflectionProbe(); this._onUpdateLocalShadowBias(); this._updateUseLightProbe(); + this._updateReceiveDirLight(); this._attachToScene(); } @@ -527,6 +552,7 @@ export class MeshRenderer extends ModelRenderer { this._detachFromScene(); } this.node.off(NodeEventType.MOBILITY_CHANGED, this.onMobilityChanged, this); + this.node.off(NodeEventType.LIGHT_PROBE_BAKING_CHANGED, this.onLightProbeBakingChanged, this); this.bakeSettings.off(ModelBakeSettings.USE_LIGHT_PROBE_CHANGED, this.onUseLightProbeChanged, this); this.bakeSettings.off(ModelBakeSettings.REFLECTION_PROBE_CHANGED, this.onReflectionProbeChanged, this); this.bakeSettings.off(ModelBakeSettings.BAKE_TO_REFLECTION_PROBE_CHANGED, this.onBakeToReflectionProbeChanged, this); @@ -648,6 +674,7 @@ export class MeshRenderer extends ModelRenderer { this.bakeSettings.uvParam.w = lum; this._onUpdateLightingmap(); + this._updateReceiveDirLight(); } public updateProbeCubemap (cubeMap: TextureCube | null, useDefaultTexture?: boolean) { @@ -718,6 +745,25 @@ export class MeshRenderer extends ModelRenderer { this._onUpdateLightingmap(); this._onUpdateLocalShadowBias(); this._updateUseReflectionProbe(); + this._updateReceiveDirLight(); + } + } + + protected _updateReceiveDirLight () { + if (!this._model) { return; } + const scene = this.node.scene; + if (!scene || !scene.renderScene) { return; } + const mainLight = scene.renderScene.mainLight; + if (!mainLight) { return; } + const visibility = mainLight.visibility; + if (!mainLight.node) { return; } + if (mainLight.node.mobility === MobilityMode.Static + && (this.bakeSettings.texture || (this.node.scene.globals.lightProbeInfo.data + && this.node.scene.globals.lightProbeInfo.data.hasCoefficients() + && this._model.useLightProbe))) { + this.onUpdateReceiveDirLight(visibility, true); + } else { + this.onUpdateReceiveDirLight(visibility); } } @@ -873,6 +919,11 @@ export class MeshRenderer extends ModelRenderer { protected onMobilityChanged () { this._updateUseLightProbe(); + this._updateReceiveDirLight(); + } + + protected onLightProbeBakingChanged () { + this._updateReceiveDirLight(); } protected onUseLightProbeChanged () { @@ -883,8 +934,14 @@ export class MeshRenderer extends ModelRenderer { this._updateUseReflectionProbe(); if (this.bakeSettings.reflectionProbe === ReflectionProbeType.BAKED_CUBEMAP) { cclegacy.internal.reflectionProbeManager.updateUseCubeModels(this._model); + if (!cclegacy.internal.reflectionProbeManager.getUsedReflectionProbe(this._model, ReflectionProbeType.BAKED_CUBEMAP)) { + warnID(16302); + } } else if (this.bakeSettings.reflectionProbe === ReflectionProbeType.PLANAR_REFLECTION) { cclegacy.internal.reflectionProbeManager.updateUsePlanarModels(this._model); + if (!cclegacy.internal.reflectionProbeManager.getUsedReflectionProbe(this._model, ReflectionProbeType.PLANAR_REFLECTION)) { + warnID(16302); + } } } diff --git a/cocos/3d/lights/directional-light-component.ts b/cocos/3d/lights/directional-light-component.ts index 6c7f081187..79b1ce23fe 100644 --- a/cocos/3d/lights/directional-light-component.ts +++ b/cocos/3d/lights/directional-light-component.ts @@ -28,6 +28,8 @@ import { scene } from '../../render-scene'; import { cclegacy, clamp, warnID, CCBoolean, CCFloat, _decorator, settings, Settings, override } from '../../core'; import { Camera, PCFType, Shadows, ShadowType, CSMOptimizationMode, CSMLevel } from '../../render-scene/scene'; import { Root } from '../../root'; +import { MeshRenderer } from '../framework'; +import { director } from '../../game/director'; const { ccclass, menu, executeInEditMode, property, serializable, formerlySerializedAs, tooltip, help, visible, type, editable, slide, range } = _decorator; @@ -115,20 +117,6 @@ export class DirectionalLight extends Light { } } - /** - * @en Turn off the function for directional light. - * @zh 方向光关闭该功能。 - * @engineInternal - */ - @override - @visible(false) - set visibility (vis: number) { - this._visibility = vis; - } - get visibility (): number { - return this._visibility; - } - /** * @en Whether activate real time shadow. * @zh 是否启用实时阴影? @@ -564,4 +552,27 @@ export class DirectionalLight extends Light { this._light.csmTransitionRange = this._csmTransitionRange; } } + + protected _onUpdateReceiveDirLight () { + if (!this._light) { + return; + } + super._onUpdateReceiveDirLight(); + + const scene = director.getScene(); + if (!scene || !scene.renderScene) { + return; + } + if (scene.renderScene.mainLight !== this._light) { + return; + } + const models = scene.renderScene.models; + for (let i = 0; i < models.length; i++) { + const model = models[i]; + if (!model.node) continue; + const meshRender = model.node.getComponent(MeshRenderer); + if (!meshRender) continue; + meshRender.onUpdateReceiveDirLight(this._visibility); + } + } } diff --git a/cocos/3d/lights/light-component.ts b/cocos/3d/lights/light-component.ts index c569dd269c..f5a3104862 100644 --- a/cocos/3d/lights/light-component.ts +++ b/cocos/3d/lights/light-component.ts @@ -221,8 +221,8 @@ export class Light extends Component { } /** - * @en Visibility mask of the light, declaring a set of node layers that will be visible to this light(Does not work with directional light). - * @zh 光照的可见性掩码,声明在当前光照中可见的节点层级集合(对方向光不生效)。 + * @en Visibility mask of the light, declaring a set of node layers that will be visible to this light. + * @zh 光照的可见性掩码,声明在当前光照中可见的节点层级集合。 */ @tooltip('i18n:lights.visibility') @displayOrder(255) @@ -230,6 +230,7 @@ export class Light extends Component { set visibility (vis: number) { this._visibility = vis; if (this._light) { this._light.visibility = vis; } + this._onUpdateReceiveDirLight(); } get visibility (): number { return this._visibility; @@ -315,4 +316,6 @@ export class Light extends Component { } } } + + protected _onUpdateReceiveDirLight () {} } diff --git a/cocos/3d/lod/lodgroup-component.ts b/cocos/3d/lod/lodgroup-component.ts index 7a489042b4..cd6cc75f9c 100644 --- a/cocos/3d/lod/lodgroup-component.ts +++ b/cocos/3d/lod/lodgroup-component.ts @@ -362,6 +362,7 @@ export class LODGroup extends Component { lod.screenUsagePercentage = screenUsagePercentage; this._LODs.splice(index, 0, lod); this._lodGroup.insertLOD(index, lod.lodData); + this._updateDataToScene(); if (this.node) { this._emitChangeNode(this.node); } @@ -386,6 +387,7 @@ export class LODGroup extends Component { } this._LODs.splice(index, 1); this._lodGroup.eraseLOD(index); + this._updateDataToScene(); this._emitChangeNode(this.node); return lod; } @@ -418,6 +420,7 @@ export class LODGroup extends Component { this._LODs[index] = lod; lod.modelAddedCallback = this.onLodModelAddedCallback.bind(this); this.lodGroup.updateLOD(index, lod.lodData); + this._updateDataToScene(); } /** diff --git a/cocos/3d/reflection-probe/reflection-probe-component.ts b/cocos/3d/reflection-probe/reflection-probe-component.ts index 76fac718b7..c8f36de620 100644 --- a/cocos/3d/reflection-probe/reflection-probe-component.ts +++ b/cocos/3d/reflection-probe/reflection-probe-component.ts @@ -23,7 +23,7 @@ */ import { ccclass, executeInEditMode, menu, playOnFocus, serializable, tooltip, type, visible } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; -import { CCObject, Color, Enum, size, Vec3 } from '../../core'; +import { cclegacy, CCObject, Color, Enum, size, Vec3 } from '../../core'; import { TextureCube } from '../../asset/assets'; import { scene } from '../../render-scene'; @@ -34,6 +34,7 @@ import { Layers } from '../../scene-graph/layers'; import { Camera } from '../../misc/camera-component'; import { Node, TransformBit } from '../../scene-graph'; import { ProbeClearFlag, ProbeType } from '../../render-scene/scene/reflection-probe'; +import { absolute } from '../../physics/utils/util'; export enum ProbeResolution { /** @@ -105,10 +106,8 @@ export class ReflectionProbe extends Component { * 获取或设置包围盒的大小。 */ set size (value: Vec3) { - if (value.x < 0) value.x = 0; - if (value.y < 0) value.y = 0; - if (value.z < 0) value.z = 0; this._size.set(value); + absolute(this._size); this.probe.size = this._size; if (this.probe) { ReflectionProbeManager.probeManager.onUpdateProbes(true); @@ -125,11 +124,11 @@ export class ReflectionProbe extends Component { */ @type(Enum(ProbeType)) set probeType (value: number) { + this.probe.probeType = value; if (value !== this._probeType) { const lastSize = this._size.clone(); const lastSizeIsNoExist = Vec3.equals(this._lastSize, Vec3.ZERO); this._probeType = value; - this.probe.probeType = value; if (this._probeType === ProbeType.CUBE) { if (lastSizeIsNoExist) { @@ -294,6 +293,7 @@ export class ReflectionProbe extends Component { onEnable () { if (this._probe) { ReflectionProbeManager.probeManager.register(this._probe); + ReflectionProbeManager.probeManager.onUpdateProbes(true); this._probe.enable(); } } @@ -319,7 +319,7 @@ export class ReflectionProbe extends Component { public update (dt: number) { if (!this.probe) return; - if (EDITOR) { + if (EDITOR && !cclegacy.GAME_VIEW) { if (this.probeType === ProbeType.PLANAR) { const cameraLst: scene.Camera[] | undefined = this.node.scene.renderScene?.cameras; if (cameraLst !== undefined) { diff --git a/cocos/asset/asset-manager/asset-manager.ts b/cocos/asset/asset-manager/asset-manager.ts index fbcd0e121b..758ebc374d 100644 --- a/cocos/asset/asset-manager/asset-manager.ts +++ b/cocos/asset/asset-manager/asset-manager.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-len */ /* Copyright (c) 2019-2023 Xiamen Yaji Software Co., Ltd. @@ -28,33 +29,27 @@ import { error, sys, Settings, settings, path, cclegacy } from '../../core'; import Bundle from './bundle'; import Cache, { ICache } from './cache'; import CacheManager from './cache-manager'; -import dependUtil from './depend-util'; -import downloader from './downloader'; +import dependUtil, { DependUtil } from './depend-util'; +import downloader, { Downloader } from './downloader'; import factory from './factory'; import fetch from './fetch'; import * as helper from './helper'; import load from './load'; import packManager from './pack-manager'; -import parser from './parser'; -import { IPipe, Pipeline } from './pipeline'; +import parser, { Parser } from './parser'; +import { Pipeline } from './pipeline'; import preprocess from './preprocess'; import releaseManager from './release-manager'; import RequestItem from './request-item'; import { - CompleteCallbackWithData, - ProgressCallback, - IBundleOptions, - IOptions, - IRemoteOptions, presets, - Request, references, - IJsonAssetOptions, - assets, BuiltinBundleName, bundles, fetchPipeline, files, parsed, pipeline, transformPipeline, assetsOverrideMap } from './shared'; + assets, BuiltinBundleName, bundles, fetchPipeline, files, parsed, pipeline, transformPipeline, assetsOverrideMap, IRequest } from './shared'; import Task from './task'; import { combine, parse, replaceOverrideAsset } from './url-transformer'; import { asyncify, parseParameters } from './utilities'; +import { IAddressableInfo, IAssetInfo, IPackInfo, ISceneInfo } from './config'; /** * @zh @@ -74,33 +69,33 @@ export interface IAssetManagerOptions { /** * @zh - * 所有 bundle 的版本信息 + * 所有 bundle 的版本信息。 * @en - * Version for all bundles + * Version for all bundles. */ bundleVers?: Record; /** * @zh - * 远程服务器地址 + * 远程服务器地址。 * @en - * Remote server address + * Remote server address. */ server?: string; /** * @zh - * 配置为子包的 bundle + * 配置为子包的 bundle。 * @en - * All subpackages + * All subpackages. */ subpackages?: string[]; /** * @zh - * 配置为远程包的 bundle + * 配置为远程包的 bundle。 * @en - * All remote bundles + * All remote bundles. */ remoteBundles?: string[]; @@ -109,85 +104,90 @@ export interface IAssetManagerOptions { /** * @en * This module controls asset's behaviors and information, include loading, releasing etc. it is a singleton - * All member can be accessed with `assetManager`. + * You can access it via [[assetManager]]. * * @zh - * 此模块管理资源的行为和信息,包括加载,释放等,这是一个单例,所有成员能够通过 `assetManager` 调用 - * + * 此模块管理资源的行为和信息,包括加载,释放等,这是一个单例,你能够通过 `assetManager` 访问它。 */ export class AssetManager { /** * @en - * Normal loading pipeline + * Normal loading pipeline. Asset manager uses this pipeline to load all assets, it has an additional asset parsing process compared to the fetchPipeline. * * @zh - * 正常加载管线 - * + * 正常加载管线。Asset manager 使用此管线来加载所有资源,他与 fetchPipeline 相比额外多了资源的解析过程。 */ public pipeline: Pipeline = pipeline.append(preprocess).append(load); /** * @en - * Fetching pipeline + * Fetching pipeline. Asset manager uses this pipeline to preload all assets, which lacks the asset parsing process compared to the pipeline. * * @zh - * 下载管线 + * 下载管线。Asset manager 使用此管线来预加载所有资源,他与 pipeline 相比缺少了资源的解析过程。 * */ public fetchPipeline: Pipeline = fetchPipeline.append(preprocess).append(fetch); /** * @en - * Url transformer + * Url transformer. Asset manager uses this pipeline to convert the uuid, path, etc. to the path of the final file path to be loaded. + * You can customize this pipeline to redirect the path to the path you want. * * @zh - * Url 转换器 + * Url 转换器。Asset manager 使用此管线将 uuid, 路径等信息转换为最终要加载的文件路径。你可以自定义此管线将路径重定向到你想要的路径。 * */ public transformPipeline: Pipeline = transformPipeline.append(parse).append(replaceOverrideAsset).append(combine); /** * @en - * The collection of bundle which is already loaded, you can remove cache with [[removeBundle]] + * The collection of bundle which is already loaded, you can remove cache with [[removeBundle]]. * * @zh - * 已加载 bundle 的集合, 你能通过 [[removeBundle]] 来移除缓存 + * 已加载 bundle 的集合, 你能通过 [[removeBundle]] 来移除缓存。 * */ public bundles: ICache = bundles; /** * @en - * The collection of asset which is already loaded, you can remove cache with [[releaseAsset]] + * The collection of asset which is already loaded, you can remove cache with [[releaseAsset]]. * * @zh - * 已加载资源的集合, 你能通过 [[releaseAsset]] 来移除缓存 + * 已加载资源的集合, 你能通过 [[releaseAsset]] 来移除缓存。 */ public assets: ICache = assets; /** - * @internal only using in L10N for now + * @internal only using in L10N for now. */ public readonly assetsOverrideMap = assetsOverrideMap; + /** + * @internal + */ public generalImportBase = ''; + /** + * @internal + */ public generalNativeBase = ''; /** * @en - * Manage relationship between asset and its dependencies + * Manage relationship between asset and its dependencies. * * @zh - * 管理资源依赖关系 + * 管理资源间依赖关系。 */ public dependUtil = dependUtil; /** * @en - * Whether or not load asset forcibly, if it is true, asset will be loaded regardless of error + * A flag indicates whether to force loading assets and ignore errors. * * @zh - * 是否强制加载资源, 如果为 true ,加载资源将会忽略报错 + * 是否强制加载资源标志, 如果为 true,加载资源时将会忽略错误。 * */ public force = EDITOR || PREVIEW; @@ -197,57 +197,58 @@ export class AssetManager { * Whether to use image bitmap to load image first. If enabled, images loading will become faster but memory usage will increase. * * @zh - * 是否优先使用 image bitmap 来加载图片,启用之后,图片加载速度会更快, 但内存占用会变高, + * 是否优先使用 image bitmap 来加载图片,启用之后,图片加载速度会更快, 但内存占用会变高。 * */ public allowImageBitmap = !sys.isMobile; /** * @en - * Some useful function + * Some useful functions, such as the convert function between url and uuid. * * @zh - * 一些有用的方法 + * 一些有用的方法, 例如 url 与 uuid 之间的转换方法。 * */ public utils = helper; /** * @en - * Manage all downloading task + * The downloader used by `assetManager`.It manages all downloading tasks. * * @zh - * 管理所有下载任务 + * `assetManager` 所使用的下载器,管理所有下载任务。 * */ public downloader = downloader; /** * @en - * Manage all parsing task + * The parser used by `assetManager`.It manages all parsing tasks. * * @zh - * 管理所有解析任务 + * `assetManager` 所使用的解析器,管理所有解析任务。 * */ public parser = parser; /** * @en - * Manage all packed asset + * Manage all packed assets. * * @zh - * 管理所有合并后的资源 + * 管理所有合并后的资源。 * + * @deprecated Since v3.7, this is an engine internal interface. You usually don't need to care about how resources are merged and split. */ public packManager = packManager; /** * @en - * Whether or not cache the loaded asset + * Whether to cache loaded assets. * * @zh - * 是否缓存已加载的资源 + * 是否缓存已加载的资源。 * */ public cacheAsset = true; @@ -257,45 +258,75 @@ export class AssetManager { * Cache manager is a module which controls all caches downloaded from server in non-web platform. * * @zh - * 缓存管理器是一个模块,在非 WEB 平台上,用于管理所有从服务器上下载下来的缓存 + * 缓存管理器是一个模块,在非 WEB 平台上,用于管理所有从服务器上下载下来的缓存。 * */ public cacheManager: CacheManager | null = null; /** * @en - * The preset of options + * The preset of options. * * @zh - * 可选参数的预设集 + * 可选参数的预设集。 * */ public presets = presets; + /** + * @internal + */ public factory = factory; - public preprocessPipe: IPipe = preprocess; + /** + * @internal + */ + public preprocessPipe = preprocess; - public fetchPipe: IPipe = fetch; + /** + * @internal + */ + public fetchPipe = fetch; - public loadPipe: IPipe = load; + /** + * @internal + */ + public loadPipe = load; + /** + * @internal + */ public references = references; private _releaseManager = releaseManager; - private _files = files; - private _parsed = parsed; private _parsePipeline = BUILD ? null : new Pipeline('parse existing json', [this.loadPipe]); private _projectBundles: string[] = []; + private static _instance: AssetManager; /** * @en - * The builtin 'main' bundle + * A global singleton instance of [[AssetManager]], which you can access directly through [[assetManager]]. * * @zh - * 内置 main 包 + * [[AssetManager]] 的全局单例,你可以直接通过 [[assetManager]] 访问。 + */ + static get instance () { + if (!this._instance) { + this._instance = new AssetManager(); + } + return this._instance; + } + + private constructor () {} + + /** + * @en + * The builtin 'main' bundle. + * + * @zh + * 内置 main 包。 */ public get main (): Bundle | null { return bundles.get(BuiltinBundleName.MAIN) || null; @@ -303,10 +334,10 @@ export class AssetManager { /** * @en - * The builtin 'resources' bundle + * The builtin 'resources' bundle. * * @zh - * 内置 resources 包 + * 内置 resources 包。 * */ public get resources (): Bundle | null { @@ -315,13 +346,14 @@ export class AssetManager { /** * @en - * Initialize assetManager with options + * Initializes assetManager with options. + * This method will be called automatically when the engine starts, you should not call this method manually at any time. * * @zh - * 初始化资源管理器 - * - * @param options - the configuration + * 初始化资源管理器,引擎在启动时,将会自动调用此方法,你不应该在任何时候手动调用此方法。 * + * @param options @en The configuration of asset manager. @zh 资源管理器的配置选项。 + * @internal */ public init (options: IAssetManagerOptions = {}) { const server = options.server || settings.querySettings(Settings.Category.ASSETS, 'server') || ''; @@ -355,13 +387,13 @@ export class AssetManager { /** * @en - * Get the bundle which has been loaded + * Gets the bundle which has been loaded with the name of bundle. * * @zh - * 获取已加载的分包 + * 通过包名称获取已加载的分包。 * - * @param name - The name of bundle - * @return - The loaded bundle + * @param name @en The name of bundle. @zh 资源包的名称。 + * @returns @en The loaded bundle. @zh 已加载的资源包。 * * @example * // ${project}/assets/test1 @@ -376,16 +408,14 @@ export class AssetManager { /** * @en - * Remove this bundle. NOTE: The asset within this bundle will not be released automatically, - * you can call [[AssetManager.Bundle.releaseAll]] manually before remove it if you need + * Removes this bundle. NOTE: The asset within this bundle will not be released automatically, + * you can call [[AssetManager.Bundle.releaseAll]] manually before removing it if you need. * * @zh - * 移除此包, 注意:这个包内的资源不会自动释放, 如果需要的话你可以在摧毁之前手动调用 [[AssetManager.Bundle.releaseAll]] 进行释放 + * 移除此包, 注意:这个包内的资源不会自动释放, 如果需要的话你可以在摧毁之前手动调用 [[AssetManager.Bundle.releaseAll]] 进行释放。 * - * @param bundle - The bundle to be removed + * @param bundle @en The bundle to be removed. @zh 准备移除的 Bundle。 * - * @typescript - * removeBundle(bundle: AssetManager.Bundle): void */ public removeBundle (bundle: Bundle) { bundle._destroy(); @@ -394,37 +424,36 @@ export class AssetManager { /** * @en - * General interface used to load assets with a progression callback and a complete callback. You can achieve almost all - * effect you want with combination of `requests` and `options`.It is highly recommended that you use more simple API, - * such as `load`, `loadDir` etc. Every custom parameter in `options` will be distribute to each of `requests`. if request - * already has same one, the parameter in request will be given priority. Besides, if request has dependencies, `options` - * will distribute to dependencies too. Every custom parameter in `requests` will be transferred to handler of `downloader` - * and `parser` as `options`. You can register you own handler downloader or parser to collect these custom parameters for some effect. + * General interface used to load assets with a progression callback and a complete callback. + * It is highly recommended that you use more simple API, such as `load`, `loadDir` etc. You can pass + * some additional data via the `options` parameter, and the parameters in `options` will affect this loading. + * The optional parameter will be transferred to handler of `downloader` and `parser` as `options`. You can + * register you own handler downloader or parser to collect these custom parameters for some effect. * - * Reserved Keyword: `uuid`, `url`, `path`, `dir`, `scene`, `type`, `priority`, `preset`, `audioLoadMode`, `ext`, + * Reserved Keywords for additional parameters: `uuid`, `url`, `path`, `dir`, `scene`, `type`, `priority`, `preset`, `audioLoadMode`, `ext`, * `bundle`, `onFileProgress`, `maxConcurrency`, `maxRequestsPerFrame`, `maxRetryCount`, `version`, `xhrResponseType`, * `xhrWithCredentials`, `xhrMimeType`, `xhrTimeout`, `xhrHeader`, `reloadAsset`, `cacheAsset`, `cacheEnabled`, - * Please DO NOT use these words as custom options! + * Please DO NOT use these words as your own options! * * @zh - * 通用加载资源接口,可传入进度回调以及完成回调,通过组合 `request` 和 `options` 参数,几乎可以实现和扩展所有想要的加载效果。非常建议 - * 你使用更简单的API,例如 `load`、`loadDir` 等。`options` 中的自定义参数将会分发到 `requests` 的每一项中,如果request中已存在同名的 - * 参数则以 `requests` 中为准,同时如果有其他依赖资源,则 `options` 中的参数会继续向依赖项中分发。request中的自定义参数都会以 `options` - * 形式传入加载流程中的 `downloader`, `parser` 的方法中, 你可以扩展 `downloader`, `parser` 收集参数完成想实现的效果。 + * 通用加载资源接口,可传入进度回调以及完成回调,建议你使用更简单的API,例如 `load`、`loadDir` 等。你可以通过 `options` 参数额外传递一些数据,`options` 中的参数将会影响本次加载。 + * 额外参数会传入加载流程中的 `downloader`, `parser` 的处理方法中, 你可以扩展 `downloader`, `parser` 收集参数完成想实现的效果。 * - * 保留关键字: `uuid`, `url`, `path`, `dir`, `scene`, `type`, `priority`, `preset`, `audioLoadMode`, `ext`, `bundle`, `onFileProgress`, + * 额外参数保留关键字: `uuid`, `url`, `path`, `dir`, `scene`, `type`, `priority`, `preset`, `audioLoadMode`, `ext`, `bundle`, `onFileProgress`, * `maxConcurrency`, `maxRequestsPerFrame`, `maxRetryCount`, `version`, `xhrResponseType`, `xhrWithCredentials`, `xhrMimeType`, `xhrTimeout`, `xhrHeader`, - * `reloadAsset`, `cacheAsset`, `cacheEnabled`, 请不要使用这些字段为自定义参数! + * `reloadAsset`, `cacheAsset`, `cacheEnabled`, 请不要使用这些字段为你自己的参数! * - * @param requests - The request you want to load - * @param options - Optional parameters - * @param onProgress - Callback invoked when progression change - * @param onProgress.finished - The number of the items that are already completed - * @param onProgress.total - The total number of the items - * @param onProgress.item - The current request item - * @param onComplete - Callback invoked when finish loading - * @param onComplete.err - The error occurred in loading process. - * @param onComplete.data - The loaded content + * @param requests @en The loading requests. @zh 加载请求。 + * @param options @en Optional parameters. @zh 可选参数。 + * @param onProgress @en Callback invoked when the loading progress change. @zh 加载进度发生变化时执行的回调。 + * @param onProgress.finished + * @en The number of request items that have finished loading. + * @zh 已经完成加载的资源数量。 + * @param onProgress.total @en The number of all request items to be loaded. @zh 所有待加载的资源数量。 + * @param onProgress.item @en The finished request item. @zh 当前完成的加载项。 + * @param onComplete @en Callback invoked when all assets loaded. @zh 所有资源加载完成后的回调。 + * @param onComplete.err @en Error message during loading, or null if loaded successfully. @zh 加载过程中的错误信息,如果加载成功则为 null。 + * @param onComplete.data @en The loaded data, or null if an error occurred during loading. @zh 已加载的数据,如果加载过程中有错误发生,则为 null。 * * @example * assetManager.loadAny({url: 'http://example.com/a.png'}, (err, img) => log(img)); @@ -432,7 +461,7 @@ export class AssetManager { * assetManager.loadAny([{ uuid: '0cbZa5Y71CTZAccaIFluuZ'}, {url: 'http://example.com/a.png'}], (err, assets) => log(assets)); * assetManager.downloader.register('.asset', (url, options, onComplete) => { * url += '?userName=' + options.userName + "&password=" + options.password; - * assetManager.downloader.downloadFile(url, null, onComplete); + * // other logic. * }); * assetManager.parser.register('.asset', (file, options, onComplete) => { * var json = JSON.parse(file); @@ -440,20 +469,20 @@ export class AssetManager { * var model = json[options.model]; * onComplete(null, {skin, model}); * }); - * assetManager.loadAny({ url: 'http://example.com/my.asset', skin: 'xxx', model: 'xxx', userName: 'xxx', password: 'xxx' }); + * assetManager.loadAny({ url: 'http://example.com/my.asset' }, { skin: 'xxx', model: 'xxx', userName: 'xxx', password: 'xxx' }); * */ - public loadAny (requests: Request, options: IOptions | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; - public loadAny (requests: Request, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; - public loadAny (requests: Request, options: IOptions | null, onComplete?: CompleteCallbackWithData | null): void; - public loadAny (requests: string, onComplete?: CompleteCallbackWithData | null): void; - public loadAny (requests: string[], onComplete?: CompleteCallbackWithData | null): void; - public loadAny (requests: Request, onComplete?: CompleteCallbackWithData | null): void; + public loadAny (requests: string | string[] | IRequest | Array, options: { [key: string]: any, preset?: string } | null, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: any) => void) | null): void; + public loadAny (requests: string | string[] | IRequest | Array, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: any) => void) | null): void; + public loadAny (requests: string | string[] | IRequest | Array, options: { [key: string]: any, preset?: string } | null, onComplete?: ((err: Error | null, data: any) => void) | null): void; + public loadAny (requests: string, onComplete?: ((err: Error | null, data: T) => void) | null): void; + public loadAny (requests: string[], onComplete?: ((err: Error | null, data: T[]) => void) | null): void; + public loadAny (requests: string | string[] | IRequest | Array, onComplete?: ((err: Error | null, data: any) => void) | null): void; public loadAny ( - requests: Request, - options?: IOptions | ProgressCallback | CompleteCallbackWithData | null, - onProgress?: ProgressCallback | CompleteCallbackWithData | null, - onComplete?: CompleteCallbackWithData | null, + requests: string | string[] | IRequest | Array, + options?: { [key: string]: any, preset?: string } | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: any) => void) | null, + onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: any) => void) | null, + onComplete?: ((err: Error | null, data: any) => void) | null, ) { const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters(options, onProgress, onComplete); opts.preset = opts.preset || 'default'; @@ -466,40 +495,44 @@ export class AssetManager { * @en * General interface used to preload assets with a progression callback and a complete callback.It is highly recommended that you use * more simple API, such as `preloadRes`, `preloadResDir` etc. Everything about preload is just likes `assetManager.loadAny`, the - * difference is `assetManager.preloadAny` will only download asset but not parse asset. You need to invoke `assetManager.loadAny(preloadTask)` + * difference is `assetManager.preloadAny` will only download asset but not parse asset. You need to invoke `assetManager.loadAny()` * to finish loading asset * * @zh * 通用预加载资源接口,可传入进度回调以及完成回调,非常建议你使用更简单的 API ,例如 `preloadRes`, `preloadResDir` 等。`preloadAny` 和 `loadAny` - * 几乎一样,区别在于 `preloadAny` 只会下载资源,不会去解析资源,你需要调用 `assetManager.loadAny(preloadTask)` 来完成资源加载。 + * 几乎一样,区别在于 `preloadAny` 只会下载资源,不会去解析资源,你需要调用 `assetManager.loadAny()` 来完成资源加载。 * - * @param requests - The request you want to preload - * @param options - Optional parameters - * @param onProgress - Callback invoked when progression change - * @param onProgress.finished - The number of the items that are already completed - * @param onProgress.total - The total number of the items - * @param onProgress.item - The current request item - * @param onComplete - Callback invoked when finish preloading - * @param onComplete.err - The error occurred in preloading process. - * @param onComplete.items - The preloaded content + * @param requests @en The preloading requests. @zh 预加载请求。 + * @param options @en Optional parameters. @zh 可选参数。 + * @param onProgress @en Callback invoked when the preloading progress change. @zh 预加载进度发生变化时执行的回调。 + * @param onProgress.finished + * @en The number of request items that have finished preloading. + * @zh 已经完成加载的资源数量。 + * @param onProgress.total @en The number of all request items to be preloaded. @zh 所有待预加载的资源数量。 + * @param onProgress.item @en The finished request item. @zh 当前完成的预加载项。 + * @param onComplete @en Callback invoked when all assets preloaded. @zh 所有资源预加载完成后的回调。 + * @param onComplete.err + * @en The error occurred in preloading process. Or null if preloaded successfully. + * @zh 预加载过程中的发生的错误,如果预加载成功则为 null。 + * @param onComplete.items @en The preloaded content. @zh 完成预加载的内容。 * * @example * assetManager.preloadAny('0cbZa5Y71CTZAccaIFluuZ', (err) => assetManager.loadAny('0cbZa5Y71CTZAccaIFluuZ')); * */ public preloadAny ( - requests: Request, - options: IOptions | null, - onProgress: ProgressCallback | null, - onComplete: CompleteCallbackWithData|null): void; - public preloadAny (requests: Request, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; - public preloadAny (requests: Request, options: IOptions | null, onComplete?: CompleteCallbackWithData | null): void; - public preloadAny (requests: Request, onComplete?: CompleteCallbackWithData | null): void; + requests: string | string[] | IRequest | Array, + options: { [key: string]: any, preset?: string } | null, + onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, + onComplete: ((err: Error | null, data: RequestItem[]) => void)|null): void; + public preloadAny (requests: string | string[] | IRequest | Array, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: RequestItem[]) => void) | null): void; + public preloadAny (requests: string | string[] | IRequest | Array, options: { [key: string]: any, preset?: string } | null, onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null): void; + public preloadAny (requests: string | string[] | IRequest | Array, onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null): void; public preloadAny ( - requests: Request, - options?: IOptions | ProgressCallback | CompleteCallbackWithData | null, - onProgress?: ProgressCallback | CompleteCallbackWithData | null, - onComplete?: CompleteCallbackWithData | null, + requests: string | string[] | IRequest | Array, + options?: { [key: string]: any, preset?: string } | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void) | null, + onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void) | null, + onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null, ) { const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters(options, onProgress, onComplete); opts.preset = opts.preset || 'preload'; @@ -510,18 +543,25 @@ export class AssetManager { /** * @en - * Load remote asset with url, such as audio, image, text and so on. + * Loads remote asset with url, such as audio, image, text and so on. + * Note that `loadRemote` uses the extension name in the url to determine how to load the asset. + * If you pass in a url without the extension name, you need to specify the `ext` parameter + * in the `options` to indicate how you want the asset loaded. See the third example below. * * @zh - * 使用 url 加载远程资源,例如音频,图片,文本等等。 + * 使用 url 加载远程资源,例如音频,图片,文本等等。需要注意的是 `loadRemote` 是通过 url 中的扩展名判断以何种方式加载该资源, + * 如果你传入的 url 中没有携带后缀名,你需要额外指定 `options` 中的 `ext` 参数来表明你需要何种方式加载该资源。请参考下面的第三个示例。 * - * @param url - The url of asset - * @param options - Some optional parameters - * @param options.audioLoadMode - Indicate which mode audio you want to load - * @param options.ext - If the url does not have a extension name, you can specify one manually. - * @param onComplete - Callback invoked when finish loading - * @param onComplete.err - The error occurred in loading process. - * @param onComplete.asset - The loaded texture + * @param url @en The url of asset. @zh 资源的 URL 链接。 + * @param options @en Some optional parameters. @zh 一些可选参数。 + * @param options.ext + * @en If the url does not have an extension name, you can specify one manually. This will affect the way the assets are loaded. + * @zh 如果 URL 链接中没有包含扩展名,你可以手动指定一个扩展名。这将会影响资源的加载方式。 + * @param onComplete @en Callback invoked when finish loading. @zh 当完成加载时触发的回调函数。 + * @param onComplete.err @en The error occurred in loading process. Or null if loaded successfully. @zh 加载过程中出现的错误,如果加载成功则为 null。 + * @param onComplete.asset + * @en The loaded asset. If there is an error in the loading process, this asset will be null. + * @zh 加载好的资源,如果加载过程出现了错误,资源将会 null。 * * @example * assetManager.loadRemote('http://www.cloud.com/test1.jpg', (err, texture) => console.log(err)); @@ -529,10 +569,10 @@ export class AssetManager { * assetManager.loadRemote('http://www.cloud.com/test3', { ext: '.png' }, (err, texture) => console.log(err)); * */ - public loadRemote (url: string, options: IRemoteOptions | null, onComplete?: CompleteCallbackWithData | null): void; - public loadRemote (url: string, onComplete?: CompleteCallbackWithData | null): void; - public loadRemote (url: string, options?: IRemoteOptions | CompleteCallbackWithData | null, onComplete?: CompleteCallbackWithData | null) { - const { options: opts, onComplete: onComp } = parseParameters>(options, undefined, onComplete); + public loadRemote (url: string, options: { [k: string]: any, ext?: string } | null, onComplete?: ((err: Error | null, data: T) => void) | null): void; + public loadRemote (url: string, onComplete?: ((err: Error | null, data: T) => void) | null): void; + public loadRemote (url: string, options?: { [k: string]: any, ext?: string } | ((err: Error | null, data: T) => void) | null, onComplete?: ((err: Error | null, data: T) => void) | null) { + const { options: opts, onComplete: onComp } = parseParameters<((err: Error | null, data: T) => void)>(options, undefined, onComplete); if (!opts.reloadAsset && this.assets.has(url)) { asyncify(onComp)(null, this.assets.get(url)); @@ -555,26 +595,42 @@ export class AssetManager { /** * @en - * load bundle + * loads bundle with bundle name or URL. When you have configured a bundle in your project, you can load the bundle by the name configured in your project. + * Or when you put the bundle on the server, you can also load it by the full url address. + * + * Note: When you load a remote bundle by name, the bundle will be cached locally after download and will continue to use that cache in future, even if + * the version of the bundle file on your server has changed. When you need to load the latest bundle, you can pass an additional `version` parameter in the + * optional parameters and the asset system will compare this version number with the local cache, if the comparison fails, the asset system will pull + * the latest version of the bundle data from the server again. * * @zh - * 加载资源包 + * 通过包名称或 url 加载资源包。当你在项目中配置了 Bundle 后,你可以通过项目中配置的名称来加载该 Bundle。 + * 或者当你将 bundle 放在服务器上时,你也可以通过完整的 url 地址进行加载。 * - * @param nameOrUrl - The name or root path of bundle - * @param options - Some optional paramter, same like downloader.downloadFile - * @param options.version - The version of this bundle, you can check config.json in this bundle - * @param onComplete - Callback when bundle loaded or failed - * @param onComplete.err - The occurred error, null indicates success - * @param onComplete.bundle - The loaded bundle + * 注意:当你用名称加载远程 bundle 时,该 bundle 在下载后将会缓存在本地并在后续持续使用该缓存,即使你服务器上的 bundle 文件版本已经发生变化。当你需要加载 + * 最新的 bundle 时,你可以在可选参数中额外传入一个 `version` 参数,资源系统将比对此版本号与本地缓存是否一致,如果比对失败,则资源系统将重新从服务器上拉取 + * 最新版本的 bundle 数据。 + * + * @param nameOrUrl @en The name or root path of bundle. @zh 待加载的 bundle 在项目中的名称或在服务器上的 url 路径。 + * @param options @en Some optional parameters. @zh 一些可选参数。 + * @param options.version + * @en The version of the bundle, which you can get in the editor's build system, or directly by looking at the md5 hash value in the `config.json` path in the bundle directory after the build. + * @zh bundle 的版本号,你可以在编辑器的构建系统中获取,或者直接查看构建后的 bundle 目录中 config.json 路径中的 md5 hash 值。 + * @param onComplete @en Callback invoked when bundle loaded or failed. @zh bundle 加载完成的回调。 + * @param onComplete.err @en The occurred error during the loading, Or null if loaded successfully. @zh 加载过程中发生的错误,如果加载成功则为 null。 + * @param onComplete.bundle + * @en The loaded bundle. If there is an error in the loading process, this bundle will be null. + * @zh 加载完成的 bundle。如果加载过程中出现了错误,则为 null。 * * @example + * loadBundle('myBundle', (err, bundle) => console.log(bundle)); * loadBundle('http://localhost:8080/test', null, (err, bundle) => console.log(err)); * */ - public loadBundle (nameOrUrl: string, options: IBundleOptions | null, onComplete?: CompleteCallbackWithData | null): void; - public loadBundle (nameOrUrl: string, onComplete?: CompleteCallbackWithData | null): void; - public loadBundle (nameOrUrl: string, options?: IBundleOptions | CompleteCallbackWithData | null, onComplete?: CompleteCallbackWithData | null) { - const { options: opts, onComplete: onComp } = parseParameters>(options, undefined, onComplete); + public loadBundle (nameOrUrl: string, options: { [k: string]: any, version?: string } | null, onComplete?: ((err: Error | null, data: Bundle) => void) | null): void; + public loadBundle (nameOrUrl: string, onComplete?: ((err: Error | null, data: Bundle) => void) | null): void; + public loadBundle (nameOrUrl: string, options?: { [k: string]: any, version?: string } | ((err: Error | null, data: Bundle) => void) | null, onComplete?: ((err: Error | null, data: Bundle) => void) | null) { + const { options: opts, onComplete: onComp } = parseParameters<((err: Error | null, data: Bundle) => void)>(options, undefined, onComplete); const bundleName = path.basename(nameOrUrl); @@ -611,7 +667,7 @@ export class AssetManager { * 比如说,当你释放一个 texture 资源,这个 texture 和它的 gl 贴图数据都会被释放。 * 注意,这个函数可能会导致资源贴图或资源所依赖的贴图不可用,如果场景中存在节点仍然依赖同样的贴图,它们可能会变黑并报 GL 错误。 * - * @param asset - The asset to be released + * @param asset @en The asset to be released. @zh 被释放的资源。 * * @example * // release a texture which is no longer need @@ -627,7 +683,7 @@ export class AssetManager { * Release all unused assets. Refer to [[releaseAsset]] for detailed information. * * @zh - * 释放所有没有用到的资源。详细信息请参考 [[releaseAsset]] + * 释放所有没有用到的资源。详细信息请参考 [[releaseAsset]]。 * * @engineInternal * @@ -643,7 +699,7 @@ export class AssetManager { * Release all assets. Refer to [[releaseAsset]] for detailed information. * * @zh - * 释放所有资源。详细信息请参考 [[releaseAsset]] + * 释放所有资源。详细信息请参考 [[releaseAsset]]。 * */ public releaseAll () { @@ -657,25 +713,25 @@ export class AssetManager { * @param json * @param options * @param onComplete - * @private + * @internal */ public loadWithJson ( json: Record, - options: IJsonAssetOptions | null, - onProgress: ProgressCallback | null, - onComplete: CompleteCallbackWithData | null): void; - public loadWithJson (json: Record, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; - public loadWithJson (json: Record, options: IJsonAssetOptions | null, onComplete?: CompleteCallbackWithData | null): void; - public loadWithJson (json: Record, onComplete?: CompleteCallbackWithData | null): void; + options: { [key: string]: any, assetId?: string } | null, + onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, + onComplete: ((err: Error | null, data: T) => void) | null): void; + public loadWithJson (json: Record, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: T) => void) | null): void; + public loadWithJson (json: Record, options: { [key: string]: any, assetId?: string }, onComplete?: ((err: Error | null, data: T) => void) | null): void; + public loadWithJson (json: Record, onComplete?: ((err: Error | null, data: T) => void) | null): void; public loadWithJson ( json: Record, - options?: IJsonAssetOptions | CompleteCallbackWithData | null, - onProgress?: ProgressCallback | CompleteCallbackWithData | null, - onComplete?: CompleteCallbackWithData | null, + options?: { [key: string]: any, assetId?: string } | ((err: Error | null, data: T) => void) | null, + onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T) => void) | null, + onComplete?: ((err: Error | null, data: T) => void) | null, ) { if (BUILD) { throw new Error('Only valid in Editor'); } - const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters>(options, onProgress, onComplete); + const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<((err: Error | null, data: T) => void)>(options, onProgress, onComplete); const item = RequestItem.create(); item.isNative = false; @@ -706,6 +762,10 @@ AssetManager.Cache = Cache; AssetManager.RequestItem = RequestItem; AssetManager.Bundle = Bundle; AssetManager.BuiltinBundleName = BuiltinBundleName; +AssetManager.CacheManager = CacheManager; +AssetManager.Downloader = Downloader; +AssetManager.Parser = Parser; +AssetManager.DependUtil = DependUtil; export declare namespace AssetManager { export { Pipeline }; @@ -714,7 +774,19 @@ export declare namespace AssetManager { export { RequestItem }; export { Bundle }; export { BuiltinBundleName }; + export { CacheManager }; + export type { ICache }; + export type { IAssetInfo, IPackInfo, IAddressableInfo, ISceneInfo, IRequest }; + export { DependUtil }; + export { Downloader }; + export { Parser }; } -export default cclegacy.assetManager = new AssetManager(); +/** + * @en `assetManager` is a global singleton instance of [[AssetManager]]. + * The engine uses `assetManager` to manage all asset and asset bundle, including loading, releasing, etc. + * @zh `assetManager` 为 [[AssetManager]] 的全局单例,引擎使用 `assetManager` 来完成所有资源和资源包的管理工作,包括加载,释放等。 + */ +const assetManager = cclegacy.assetManager = AssetManager.instance; +export default assetManager; cclegacy.AssetManager = AssetManager; diff --git a/cocos/asset/asset-manager/bundle.ts b/cocos/asset/asset-manager/bundle.ts index 457433ead3..3aa70c1bcd 100644 --- a/cocos/asset/asset-manager/bundle.ts +++ b/cocos/asset/asset-manager/bundle.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-len */ /* Copyright (c) 2019-2023 Xiamen Yaji Software Co., Ltd. @@ -28,23 +29,23 @@ import { error, errorID, cclegacy } from '../../core'; import Config, { IAddressableInfo, IAssetInfo, IConfigOption, ISceneInfo } from './config'; import releaseManager from './release-manager'; import RequestItem from './request-item'; -import { assets, AssetType, bundles, CompleteCallbackWithData, CompleteCallbackNoData, IAssetOptions, ProgressCallback, RequestType } from './shared'; +import { assets, bundles, RequestType } from './shared'; import { parseLoadResArgs, parseParameters } from './utilities'; /** * @en - * A bundle contains an amount of assets(includes scene), you can load, preload, release asset which is in this bundle + * A bundle contains an amount of assets(includes scene), you can load, preload, release asset which is in this bundle. * * @zh - * 一个包含一定数量资源(包括场景)的包,你可以加载,预加载,释放此包内的资源 + * 一个包含一定数量资源(包括场景)的包,你可以加载,预加载,释放此包内的资源。 * */ export default class Bundle { private _config: Config = new Config(); /** - * for internal use - * @private + * For internal use. + * @engineInternal */ public get config (): Config { return this._config; @@ -52,10 +53,10 @@ export default class Bundle { /** * @en - * The name of this bundle + * The name of this bundle. * * @zh - * 此 bundle 的名称 + * 此 bundle 的名称。 * */ public get name (): string { @@ -64,10 +65,10 @@ export default class Bundle { /** * @en - * The dependency of this bundle + * The dependent bundles of this bundle. * * @zh - * 此 bundle 的依赖 + * 此 bundle 的依赖包。 * */ public get deps (): string[] { @@ -76,10 +77,10 @@ export default class Bundle { /** * @en - * The root path of this bundle, such like 'http://example.com/bundle1' + * The root path of this bundle, such like 'http://example.com/bundle1'. * * @zh - * 此 bundle 的根路径, 例如 'http://example.com/bundle1' + * 此 bundle 的根路径, 例如 'http://example.com/bundle1'。 * */ public get base (): string { @@ -88,56 +89,57 @@ export default class Bundle { /** * @en - * Get asset's info using path, only valid when asset is in bundle folder. + * Gets asset's info using path, only valid when asset is in bundle folder. * * @zh - * 使用 path 获取资源的配置信息 + * 使用 path 获取资源的配置信息。 * - * @param path - The relative path of asset, such as 'images/a' - * @param type - The constructor of asset, such as `Texture2D` - * @returns The asset info + * @param path @en The relative path of asset, such as 'images/a'. @zh 资源的相对路径,例如 `images/a`。 + * @param type @en The constructor of asset, such as `Texture2D`. @zh 资源的类型,例如 [[Texture2D]]。 + * @returns @en The asset info. @zh 资源的信息。 * * @example - * var info = bundle.getInfoWithPath('image/a', Texture2D); + * const info = bundle.getInfoWithPath('image/a', Texture2D); * */ - public getInfoWithPath (path: string, type?: AssetType | null): IAddressableInfo | null { + public getInfoWithPath (path: string, type?: Constructor | null): IAddressableInfo | null { return this._config.getInfoWithPath(path, type); } /** * @en - * Get all asset's info within specific folder + * Gets all asset's info within specific folder. * * @zh - * 获取在某个指定文件夹下的所有资源信息 + * 获取在某个指定文件夹下的所有资源信息。 * - * @param path - The relative path of folder, such as 'images' - * @param type - The constructor should be used to filter paths - * @param out - The output array - * @returns Infos + * @param path @en The relative path of folder, such as 'images'. @zh 文件夹的相对路径,例如 `images`。 + * @param type + * @en The asset type, can be used to find the information of the specified type of asset in the directory. + * @zh 资源的类型,指定后可以用来查找目录下指定类型的资源信息。 + * @param out @en The output array. @zh 输出数组。 + * @returns @en Queried asset information. @zh 查询到的资源信息。 * * @example - * var infos = []; + * const infos = []; * bundle.getDirWithPath('images', Texture2D, infos); */ - public getDirWithPath (path: string, type?: AssetType | null, out?: IAddressableInfo[]): IAddressableInfo[] { + public getDirWithPath (path: string, type?: Constructor | null, out?: IAddressableInfo[]): IAddressableInfo[] { return this._config.getDirWithPath(path, type, out); } /** * @en - * Get asset's info with uuid + * Get asset's information with uuid. * * @zh - * 通过 uuid 获取资源信息 + * 通过 uuid 获取资源信息。 * - * @method getAssetInfo - * @param uuid - The asset's uuid - * @returns info + * @param uuid @en The asset's uuid. @zh 资源的 uuid。 + * @returns @en The information of asset. @zh 资源的信息。 * * @example - * var info = bundle.getAssetInfo('fcmR3XADNLgJ1ByKhqcC5Z'); + * const info = bundle.getAssetInfo('fcmR3XADNLgJ1ByKhqcC5Z'); * */ public getAssetInfo (uuid: string): IAssetInfo | null { @@ -146,17 +148,16 @@ export default class Bundle { /** * @en - * Get scene'info with name + * Gets scene's information with name. * * @zh - * 通过场景名获取场景信息 + * 通过场景名获取场景信息。 * - * @method getSceneInfo - * @param name - The name of scene - * @return info + * @param name @en The name of scene. @zh 场景名称。 + * @returns @en The information of scene. @zh 场景信息。 * * @example - * var info = bundle.getSceneInfo('first.fire'); + * const info = bundle.getSceneInfo('first.fire'); * */ public getSceneInfo (name: string): ISceneInfo | null { @@ -165,12 +166,13 @@ export default class Bundle { /** * @en - * Initialize this bundle with options + * Initializes this bundle with options. * * @zh - * 初始化此 bundle + * 初始化此 bundle。 * * @param options + * @deprecate Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances. * */ public init (options: IConfigOption) { @@ -180,20 +182,30 @@ export default class Bundle { /** * @en - * Load the asset within this bundle by the path which is relative to bundle's path + * Loads the asset within this bundle by the path which is relative to bundle's path. * * @zh - * 通过相对路径加载分包中的资源。路径是相对分包文件夹路径的相对路径 + * 通过相对路径加载分包中的资源。路径是相对分包文件夹路径的相对路径。 * - * @param paths - Paths of the target assets.The path is relative to the bundle's folder, extensions must be omitted. - * @param type - Only asset of type will be loaded if this argument is supplied. - * @param onProgress - Callback invoked when progression change. - * @param onProgress.finish - The number of the items that are already completed. - * @param onProgress.total - The total number of the items. - * @param onProgress.item - The finished request item. - * @param onComplete - Callback invoked when all assets loaded. - * @param onComplete.error - The error info or null if loaded successfully. - * @param onComplete.assets - The loaded assets. + * @param paths + * @en Paths of the target assets.These paths are relative to the bundle's folder, extension name must be omitted. + * @zh 需要加载的资源的路径。此路径为工程中相对于 bundle 文件夹的相对路径,路径中请不要带扩展名。 + * @param type + * @en Asset type, if this parameter is passed, the asset of the corresponding type will be found in the assets of the corresponding path to finish loading. + * @zh 资源类型,如果传入此参数,则会在对应路径的资源中找到对应类型的资源完成加载。 + * @param onProgress + * @en Callback invoked when the loading progress change. + * @zh 加载进度发生变化时执行的回调。 + * @param onProgress.finish + * @en The number of request items that have been loaded. + * @zh 已经完成加载的资源数量。 + * @param onProgress.total + * @en The number of all request items to be loaded. + * @zh 所有待加载的资源数量。 + * @param onProgress.item @en The finished request item. @zh 当前完成的加载项。 + * @param onComplete @en Callback invoked when all assets loaded. @zh 所有资源加载完成后的回调。 + * @param onComplete.error @en Error message during loading, or null if loaded successfully. @zh 加载过程中的错误信息,如果加载成功则为 null。 + * @param onComplete.assets @en The loaded asset, or null if an error occurred during loading. @zh 已加载的资源,如果加载过程中有错误发生,则为 null。 * * @example * // load the texture (${project}/assets/resources/textures/background.jpg) from resources @@ -211,24 +223,24 @@ export default class Bundle { */ public load ( paths: string, - type: AssetType | null, - onProgress: ProgressCallback | null, - onComplete: CompleteCallbackWithData | null): void; + type: Constructor | null, + onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, + onComplete: ((err: Error | null, data: T) => void) | null): void; public load ( - paths: string[], type: AssetType | null, - onProgress: ProgressCallback | null, - onComplete: CompleteCallbackWithData | null): void; - public load (paths: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; - public load (paths: string[], onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; - public load (paths: string, onComplete?: CompleteCallbackWithData | null): void; - public load (paths: string[], onComplete?: CompleteCallbackWithData | null): void; - public load (paths: string, type: AssetType | null, onComplete?: CompleteCallbackWithData | null): void; - public load (paths: string[], type: AssetType | null, onComplete?: CompleteCallbackWithData | null): void; + paths: string[], type: Constructor | null, + onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, + onComplete: ((err: Error | null, data: T[]) => void) | null): void; + public load (paths: string, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: T) => void) | null): void; + public load (paths: string[], onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: T[]) => void) | null): void; + public load (paths: string, onComplete?: ((err: Error | null, data: T) => void) | null): void; + public load (paths: string[], onComplete?: ((err: Error | null, data: T[]) => void) | null): void; + public load (paths: string, type: Constructor | null, onComplete?: ((err: Error | null, data: T) => void) | null): void; + public load (paths: string[], type: Constructor | null, onComplete?: ((err: Error | null, data: T[]) => void) | null): void; public load ( paths: string|string[], - type?: AssetType | ProgressCallback | CompleteCallbackWithData | null, - onProgress?: ProgressCallback | CompleteCallbackWithData | null, - onComplete?: CompleteCallbackWithData | null, + type?: Constructor | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T|T[]) => void) | null, + onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T|T[]) => void) | null, + onComplete?: ((err: Error | null, data: T|T[]) => void) | null, ) { const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete); const options = { __requestType__: RequestType.PATH, type: _type, bundle: this.name, __outputAsArray__: Array.isArray(paths) }; @@ -237,24 +249,34 @@ export default class Bundle { /** * @en - * Preload the asset within this bundle by the path which is relative to bundle's path. - * After calling this method, you still need to finish loading by calling `Bundle.load`. - * It will be totally fine to call `Bundle.load` at any time even if the preloading is not - * yet finished + * Preloads the asset within this bundle by the path which is relative to bundle's path. + * After calling this method, you still need to finish loading by calling [[Bundle.load]]. + * It will be totally fine to call [[Bundle.load]] at any time even if the preloading is not + * yet finished. * * @zh - * 通过相对路径预加载分包中的资源。路径是相对分包文件夹路径的相对路径。调用完后,你仍然需要通过 `Bundle.load` 来完成加载。 - * 就算预加载还没完成,你也可以直接调用 `Bundle.load`。 + * 通过相对路径预加载分包中的资源。路径是相对分包文件夹路径的相对路径。调用完后,你仍然需要通过 [[Bundle.load]] 来完成加载。 + * 就算预加载还没完成,你也可以直接调用 [[Bundle.load]]。 * - * @param paths - Paths of the target asset.The path is relative to bundle folder, extensions must be omitted. - * @param type - Only asset of type will be loaded if this argument is supplied. - * @param onProgress - Callback invoked when progression change. - * @param onProgress.finish - The number of the items that are already completed. - * @param onProgress.total - The total number of the items. - * @param onProgress.item - The finished request item. - * @param onComplete - Callback invoked when the resource loaded. - * @param onComplete.error - The error info or null if loaded successfully. - * @param onComplete.items - The preloaded items. + * @param paths + * @en Paths of the target assets.These paths are relative to the bundle's folder, extension name must be omitted. + * @zh 需要加载的资源的路径。此路径为工程中相对于 bundle 文件夹的相对路径,路径中请不要带扩展名。 + * @param type + * @en Asset type, if this parameter is passed, the asset of the corresponding type will be found in the assets of the corresponding path to finish preloading. + * @zh 资源类型,如果传入此参数,则会在对应路径的资源中找到对应类型的资源完成预加载。 + * @param onProgress + * @en Callback invoked when the preloading progress change. + * @zh 预加载进度发生变化时执行的回调。 + * @param onProgress.finish + * @en The number of request items that have been preloaded. + * @zh 已经完成预加载的资源数量。 + * @param onProgress.total + * @en The number of all request items to be preloaded. + * @zh 所有待预加载的资源数量。 + * @param onProgress.item @en The finished request item. @zh 当前完成的预加载项。 + * @param onComplete @en Callback invoked when all assets preloaded. @zh 所有资源预加载完成后的回调。 + * @param onComplete.error @en Error message during preloading, or null if preloaded successfully. @zh 预加载过程中的错误信息,如果预加载成功则为 null。 + * @param onComplete.items @en The preloaded items. @zh 预加载项。 * * @example * // preload the texture (${project}/assets/resources/textures/background.jpg) from resources @@ -274,15 +296,15 @@ export default class Bundle { * bundle2.load('imgs/cocos', SpriteFrame, (err, spriteFrame) => {}); * */ - public preload (paths: string|string[], type: AssetType|null, onProgress: ProgressCallback|null, onComplete: CompleteCallbackWithData|null): void; - public preload (paths: string|string[], onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; - public preload (paths: string|string[], onComplete?: CompleteCallbackWithData | null): void; - public preload (paths: string|string[], type: AssetType | null, onComplete?: CompleteCallbackWithData | null): void; + public preload (paths: string|string[], type: Constructor|null, onProgress: ((finished: number, total: number, item: RequestItem) => void)|null, onComplete: ((err: Error | null, data: RequestItem[]) => void)|null): void; + public preload (paths: string|string[], onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: RequestItem[]) => void) | null): void; + public preload (paths: string|string[], onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null): void; + public preload (paths: string|string[], type: Constructor | null, onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null): void; public preload ( paths: string|string[], - type?: AssetType | ProgressCallback | CompleteCallbackWithData | null, - onProgress?: ProgressCallback | CompleteCallbackWithData | null, - onComplete?: CompleteCallbackWithData | null, + type?: Constructor | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void) | null, + onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void) | null, + onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null, ) { const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete); cclegacy.assetManager.preloadAny(paths, { __requestType__: RequestType.PATH, type: _type, bundle: this.name }, onProg, onComp); @@ -290,23 +312,28 @@ export default class Bundle { /** * @en - * Load all assets under a folder inside the bundle folder.
+ * Loads all assets under a folder inside the bundle folder.
*
* Note: All asset paths in Creator use forward slashes, paths using backslashes will not work. * * @zh - * 加载目标文件夹中的所有资源, 注意:路径中只能使用斜杠,反斜杠将停止工作 + * 加载目标文件夹中的所有资源, 注意:路径中只能使用斜杠,反斜杠将停止工作。 * - * @param dir - path of the target folder.The path is relative to the bundle folder, extensions must be omitted. - * @param type - Only asset of type will be loaded if this argument is supplied. - * @param onProgress - Callback invoked when progression change. - * @param onProgress.finish - The number of the items that are already completed. - * @param onProgress.total - The total number of the items. - * @param onProgress.item - The latest request item - * @param onComplete - A callback which is called when all assets have been loaded, or an error occurs. - * @param onComplete.error - If one of the asset failed, the complete callback is immediately called with the error. - * If all assets are loaded successfully, error will be null. - * @param onComplete.assets - An array of all loaded assets. + * @param dir @en The path of the target folder. The path is relative to the bundle folder. @zh 目标文件夹路径,此路径为相对于 bundle 文件夹的路径。 + * @param type @en The asset type. Only specify type asset will be loaded if this argument is supplied. @zh 资源类型,如果指定了此参数,则只会加载目标文件夹下此类型的资源。 + * @param onProgress + * @en Callback invoked when the loading progress change. + * @zh 加载进度发生变化时执行的回调。 + * @param onProgress.finish + * @en The number of request items that have been loaded. + * @zh 已经完成加载的资源数量。 + * @param onProgress.total + * @en The number of all request items to be loaded. + * @zh 所有待加载的资源数量。 + * @param onProgress.item @en The finished request item. @zh 当前完成的加载项。 + * @param onComplete @en Callback invoked when all assets loaded. @zh 所有资源加载完成后的回调。 + * @param onComplete.error @en Error message during loading, or null if loaded successfully. @zh 加载过程中的错误信息,如果加载成功则为 null。 + * @param onComplete.assets @en An array of all loaded assets. @zh 完成加载的资源数组。 * * @example * // load all audios (resources/audios/) @@ -325,15 +352,15 @@ export default class Bundle { * bundle2.loadDir('skills', SpriteFrame, null, (err, spriteFrames) => console.log(err)); * */ - public loadDir (dir: string, type: AssetType | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; - public loadDir (dir: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; - public loadDir (dir: string, onComplete?: CompleteCallbackWithData | null): void; - public loadDir (dir: string, type: AssetType | null, onComplete?: CompleteCallbackWithData | null): void; + public loadDir (dir: string, type: Constructor | null, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: T[]) => void) | null): void; + public loadDir (dir: string, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: T[]) => void) | null): void; + public loadDir (dir: string, onComplete?: ((err: Error | null, data: T[]) => void) | null): void; + public loadDir (dir: string, type: Constructor | null, onComplete?: ((err: Error | null, data: T[]) => void) | null): void; public loadDir ( dir: string, - type?: AssetType | ProgressCallback | CompleteCallbackWithData | null, - onProgress?: ProgressCallback | CompleteCallbackWithData | null, - onComplete?: CompleteCallbackWithData | null, + type?: Constructor | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T[]) => void) | null, + onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T[]) => void) | null, + onComplete?: ((err: Error | null, data: T[]) => void) | null, ) { const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete); cclegacy.assetManager.loadAny(dir, { __requestType__: RequestType.DIR, type: _type, bundle: this.name, __outputAsArray__: true }, onProg, onComp); @@ -341,24 +368,29 @@ export default class Bundle { /** * @en - * Preload all assets under a folder inside the bundle folder.
After calling this method, you still need to - * finish loading by calling `Bundle.loadDir`. - * It will be totally fine to call `Bundle.loadDir` at any time even if the preloading is not yet finished + * Preloads all assets under a folder inside the bundle folder.
After calling this method, you still need to + * finish loading by calling [[Bundle.loadDir]]. + * It will be totally fine to call [[Bundle.loadDir]] at any time even if the preloading is not yet finished. * * @zh - * 预加载目标文件夹中的所有资源。调用完后,你仍然需要通过 `Bundle.loadDir` 来完成加载。 - * 就算预加载还没完成,你也可以直接调用 `Bundle.loadDir`。 + * 预加载目标文件夹中的所有资源。调用完后,你仍然需要通过 [[Bundle.loadDir]] 来完成加载。 + * 就算预加载还没完成,你也可以直接调用 [[Bundle.loadDir]]。 * - * @param dir - path of the target folder.The path is relative to the bundle folder, extensions must be omitted. - * @param type - Only asset of type will be preloaded if this argument is supplied. - * @param onProgress - Callback invoked when progression change. - * @param onProgress.finish - The number of the items that are already completed. - * @param onProgress.total - The total number of the items. - * @param onProgress.item - The latest request item - * @param onComplete - A callback which is called when all assets have been loaded, or an error occurs. - * @param onComplete.error - If one of the asset failed, the complete callback is immediately called with the error. - * If all assets are preloaded successfully, error will be null. - * @param onComplete.items - An array of all preloaded items. + * @param dir @en The path of the target folder. The path is relative to the bundle folder. @zh 目标文件夹路径,此路径为相对于 bundle 文件夹的路径。 + * @param type @en The asset type. Only specify type asset will be preloaded if this argument is supplied. @zh 资源类型,如果指定了此参数,则只会预加载目标文件夹下此类型的资源。 + * @param onProgress + * @en Callback invoked when the preloading progress change. + * @zh 预加载进度发生变化时执行的回调。 + * @param onProgress.finish + * @en The number of request items that have been preloaded. + * @zh 已经完成预加载的资源数量。 + * @param onProgress.total + * @en The number of all request items to be preloaded. + * @zh 所有待预加载的资源数量。 + * @param onProgress.item @en The finished request item. @zh 当前完成的预加载项。 + * @param onComplete @en Callback invoked when all assets preloaded. @zh 所有资源预加载完成后的回调。 + * @param onComplete.error @en Error message during preloading, or null if preloaded successfully. @zh 预加载过程中的错误信息,如果预加载成功则为 null。 + * @param onComplete.items @en The preloaded items. @zh 预加载项。 * * @example * // preload all audios (resources/audios/) @@ -377,15 +409,15 @@ export default class Bundle { * // wait for while * bundle2.loadDir('skills', SpriteFrame, (err, spriteFrames) => {}); */ - public preloadDir (dir: string, type: AssetType | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; - public preloadDir (dir: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; - public preloadDir (dir: string, onComplete?: CompleteCallbackWithData | null): void; - public preloadDir (dir: string, type: AssetType | null, onComplete?: CompleteCallbackWithData | null): void; + public preloadDir (dir: string, type: Constructor | null, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: RequestItem[]) => void) | null): void; + public preloadDir (dir: string, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: RequestItem[]) => void) | null): void; + public preloadDir (dir: string, onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null): void; + public preloadDir (dir: string, type: Constructor | null, onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null): void; public preloadDir ( dir: string, - type?: AssetType | ProgressCallback | CompleteCallbackWithData| null, - onProgress?: ProgressCallback | CompleteCallbackWithData| null, - onComplete?: CompleteCallbackWithData| null, + type?: Constructor | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void)| null, + onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void)| null, + onComplete?: ((err: Error | null, data: RequestItem[]) => void)| null, ) { const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete); cclegacy.assetManager.preloadAny(dir, { __requestType__: RequestType.DIR, type: _type, bundle: this.name }, onProg, onComp); @@ -398,31 +430,37 @@ export default class Bundle { * @zh * 通过场景名称加载分包中的场景资源。 * - * @param sceneName - The name of the scene to load. - * @param options - Some optional parameters - * @param onProgress - Callback invoked when progression change. - * @param onProgress.finish - The number of the items that are already completed. - * @param onProgress.total - The total number of the items. - * @param onProgress.item - The latest request item - * @param onComplete - callback, will be called after scene launched. - * @param onComplete.err - The occurred error, null indicetes success - * @param onComplete.sceneAsset - The scene asset + * @param sceneName @en The name of the scene to be loaded. @zh 待加载的场景名称。 + * @param options @en Some optional parameters. @zh 可选参数。 + * @param onProgress + * @en Callback invoked when the loading progress change. + * @zh 加载进度发生变化时执行的回调。 + * @param onProgress.finish + * @en The number of request items that have been loaded. + * @zh 已经完成加载的资源数量。 + * @param onProgress.total + * @en The number of all request items to be loaded. + * @zh 所有待加载的资源数量。 + * @param onProgress.item @en The finished request item. @zh 当前完成的加载项。 + * @param onComplete @en Callback invoked when the scene loaded. @zh 场景加载完成后的回调。 + * @param onComplete.error @en Error message during loading, or null if loaded successfully. @zh 加载过程中的错误信息,如果加载成功则为 null。 + * @param onComplete.sceneAsset @en The scene asset. @zh 加载完成的场景资源。 * * @example * bundle1.loadScene('first', (err, sceneAsset) => director.runScene(sceneAsset)); * */ - public loadScene (sceneName: string, options: IAssetOptions | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; - public loadScene (sceneName: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; - public loadScene (sceneName: string, options: IAssetOptions | null, onComplete?: CompleteCallbackWithData | null): void; - public loadScene (sceneName: string, onComplete?: CompleteCallbackWithData | null): void; + public loadScene (sceneName: string, options: { [key: string]: any, preset?: 'string' } | null, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: SceneAsset) => void) | null): void; + public loadScene (sceneName: string, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: SceneAsset) => void) | null): void; + public loadScene (sceneName: string, options: { [key: string]: any, preset?: 'string' } | null, onComplete?: ((err: Error | null, data: SceneAsset) => void) | null): void; + public loadScene (sceneName: string, onComplete?: ((err: Error | null, data: SceneAsset) => void) | null): void; public loadScene ( sceneName: string, - options?: IAssetOptions | ProgressCallback | CompleteCallbackWithData | null, - onProgress?: ProgressCallback | CompleteCallbackWithData | null, - onComplete?: CompleteCallbackWithData | null, + options?: { [key: string]: any, preset?: 'string' } | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: SceneAsset) => void) | null, + onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: SceneAsset) => void) | null, + onComplete?: ((err: Error | null, data: SceneAsset) => void) | null, ) { - const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters>(options, onProgress, onComplete); + const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<((err: Error | null, data: SceneAsset) => void)>(options, onProgress, onComplete); opts.preset = opts.preset || 'scene'; opts.bundle = this.name; @@ -443,21 +481,27 @@ export default class Bundle { /** * @en * Preload the scene asset within this bundle by its name. After calling this method, you still need to finish loading - * by calling `Bundle.loadScene` or `director.loadScene`.It will be totally fine to call `Bundle.loadDir` at any - * time even if the preloading is not yet finished + * by calling [[Bundle.loadScene]] or [[Director.loadScene]].It will be totally fine to call [[Bundle.loadScene]] at any + * time even if the preloading is not yet finished. * * @zh - * 通过场景名称预加载分包中的场景资源.调用完后,你仍然需要通过 `Bundle.loadScene` 或 `director.loadScene` 来完成加载。 - * 就算预加载还没完成,你也可以直接调用 `Bundle.loadScene` 或 `director.loadScene`。 + * 通过场景名称预加载分包中的场景资源.调用完后,你仍然需要通过 [[Bundle.loadScene]] 或 [[Director.loadScene]] 来完成加载。 + * 就算预加载还没完成,你也可以直接调用 [[Bundle.loadScene]] 或 [[Director.loadScene]]。 * - * @param sceneName - The name of the scene to preload. - * @param options - Some optional parameters - * @param onProgress - callback, will be called when the load progression change. - * @param onProgress.finish - The number of the items that are already completed - * @param onProgress.total - The total number of the items - * @param onProgress.item The latest request item - * @param onComplete - callback, will be called after scene loaded. - * @param onComplete.error - null or the error object. + * @param sceneName @en The name of the scene to be preloaded. @zh 待预加载的场景名称。 + * @param options @en Some optional parameters. @zh 可选参数。 + * @param onProgress + * @en Callback invoked when the preloading progress change. + * @zh 预加载进度发生变化时执行的回调。 + * @param onProgress.finish + * @en The number of request items that have been preloaded. + * @zh 已经完成预加载的资源数量。 + * @param onProgress.total + * @en The number of all request items to be preloaded. + * @zh 所有待预加载的资源数量。 + * @param onProgress.item @en The finished request item. @zh 当前完成的预加载项。 + * @param onComplete @en Callback invoked when the scene preloaded. @zh 场景预加载完成后的回调。 + * @param onComplete.error @en Error message during preloading, or null if preloaded successfully. @zh 预加载过程中的错误信息,如果预加载成功则为 null。 * * @example * bundle1.preloadScene('first'); @@ -465,17 +509,17 @@ export default class Bundle { * bundle1.loadScene('first', (err, scene) => director.runScene(scene)); * */ - public preloadScene (sceneName: string, options: IAssetOptions | null, onProgress: ProgressCallback, onComplete: CompleteCallbackNoData | null): void; - public preloadScene (sceneName: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackNoData | null): void; - public preloadScene (sceneName: string, options: IAssetOptions | null, onComplete?: CompleteCallbackNoData | null): void; - public preloadScene (sceneName: string, onComplete?: CompleteCallbackNoData | null): void; + public preloadScene (sceneName: string, options: { [key: string]: any, preset?: 'string' } | null, onProgress: ((finished: number, total: number, item: RequestItem) => void), onComplete: ((err?: Error | null) => void) | null): void; + public preloadScene (sceneName: string, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err?: Error | null) => void) | null): void; + public preloadScene (sceneName: string, options: { [key: string]: any, preset?: 'string' } | null, onComplete?: ((err?: Error | null) => void) | null): void; + public preloadScene (sceneName: string, onComplete?: ((err?: Error | null) => void) | null): void; public preloadScene ( sceneName: string, - options?: IAssetOptions | ProgressCallback | CompleteCallbackNoData | null, - onProgress?: ProgressCallback | CompleteCallbackNoData | null, - onComplete?: CompleteCallbackNoData | null, + options?: { [key: string]: any, preset?: 'string' } | ((finished: number, total: number, item: RequestItem) => void) | ((err?: Error | null) => void) | null, + onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err?: Error | null) => void) | null, + onComplete?: ((err?: Error | null) => void) | null, ) { - const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters(options, onProgress, onComplete); + const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<((err?: Error | null) => void)>(options, onProgress, onComplete); opts.bundle = this.name; cclegacy.assetManager.preloadAny({ scene: sceneName }, opts, onProg, (err) => { @@ -488,27 +532,28 @@ export default class Bundle { /** * @en - * Get cached asset within this bundle by path and type.
+ * Gets cached asset within this bundle by path and type.
* After you load asset with [[load]] or [[loadDir]], * you can acquire them by passing the path to this API. * - * NOTE:The `path` and `type` parameters passed need to be the same as those passed to `Bundle.load`, - * otherwise it may return some other resources with the same name! + * NOTE:When there are multiple asset with the same name, you can get the specific asset by specifying the type. + * Otherwise the first asset matching that name will be returned. * * @zh * 通过路径与类型获取已缓存资源。在你使用 [[load]] 或者 [[loadDir]] 之后, * 你能通过传路径通过这个 API 获取到这些资源。 * - * 注意:传入的 path 与 type 参数需要与 `Bundle.load` 加载资源时传入的参数一致,否则可能会获取到其他同名资源 + * 注意:当有多个同名的资产时,你可以通过指定类型来获得具体的资产。 + * 否则将返回与该名称相匹配的第一个资产。 * - * @param path - The path of asset - * @param type - Only asset of type will be returned if this argument is supplied. - * @returns - the asset has been cached + * @param path @en The path of asset. @zh 资源的路径。 + * @param type @en The asset type. Only specify type asset will be returned if this argument is supplied. @zh 资源类型,指定后只会返回该类型的资源。 + * @returns @en The asset has been cached. @zh 已缓存的资源。 * * @example * bundle1.get('music/hit', AudioClip); */ - public get (path: string, type?: AssetType | null): T | null { + public get (path: string, type?: Constructor | null): T | null { const info = this.getInfoWithPath(path, type); if (info) { return assets.get(info.uuid) as T || null; @@ -519,27 +564,28 @@ export default class Bundle { /** * @en - * Release the asset loaded by [[load]] or [[loadDir]] - * and it's dependencies. Refer to [[AssetManager.releaseAsset]] for detailed informations. + * Releases the asset loaded by [[load]] or [[loadDir]]. + * and it's dependencies. Refer to [[AssetManager.releaseAsset]] for detailed information. * - * NOTE:The `path` and `type` parameters passed need to be the same as those passed to `Bundle.load`, - * otherwise it may release some other resources with the same name! + * NOTE:When there are multiple asset with the same name, you can specify the asset to be released by specifying the type. + * Otherwise the first resource matching that name will be released. * * @zh * 释放通过 [[load]] 或者 [[loadDir]] 加载的资源。 - * 详细信息请参考 [[AssetManager.releaseAsset]] + * 详细信息请参考 [[AssetManager.releaseAsset]]。 * - * 注意:传入的 path 与 type 参数需要与 `Bundle.load` 加载资源时传入的参数一致,否则可能会释放到其他同名资源 + * 注意:当存在多个资源同名时,可以通过指定类型来指定要释放的资源,否则将释放第一个匹配该名称的资源。 + * - * @param path - The path of asset - * @param type - Only asset of type will be released if this argument is supplied. + * @param path @en The path of asset. @zh 资源的路径。 + * @param type @en The type of asset. @zh 资源的类型。 * * @example * // release a texture which is no longer need * bundle1.release('misc/character/cocos'); * */ - public release (path: string, type?: AssetType | null) { + public release (path: string, type?: Constructor | null) { const asset = this.get(path, type); if (asset) { releaseManager.tryRelease(asset, true); @@ -548,17 +594,16 @@ export default class Bundle { /** * @en - * Release all unused assets within this bundle. Refer to [[AssetManager.releaseAll]] for detailed informations. + * Release all unused assets within this bundle. Refer to [[AssetManager.releaseAll]] for detailed information. * * @zh - * 释放此包中的所有没有用到的资源。详细信息请参考 [[AssetManager.releaseAll]] - * - * @private + * 释放此包中的所有没有用到的资源。详细信息请参考 [[AssetManager.releaseAll]]。 * * @example * // release all unused asset within bundle1 * bundle1.releaseUnusedAssets(); * + * @engineInternal */ public releaseUnusedAssets () { assets.forEach((asset) => { @@ -574,7 +619,7 @@ export default class Bundle { * Release all assets within this bundle. Refer to [[AssetManager.releaseAll]] for detailed information. * * @zh - * 释放此包中的所有资源。详细信息请参考 [[AssetManager.releaseAll]] + * 释放此包中的所有资源。详细信息请参考 [[AssetManager.releaseAll]]。 * * @example * // release all asset within bundle1 @@ -599,10 +644,10 @@ export default class Bundle { /** * @en - * resources is a bundle and controls all asset under assets/resources + * A [[Bundle]] instance to manage all assets in assets/resources. * * @zh - * resources 是一个 bundle,用于管理所有在 assets/resources 下的资源 + * 一个 [[Bundle]] 实例,用于管理所有在 assets/resources 下的资源。 */ export const resources: Bundle = new Bundle(); cclegacy.resources = resources; diff --git a/cocos/asset/asset-manager/cache-manager.ts b/cocos/asset/asset-manager/cache-manager.ts index 78bcc2836f..21e9ef7d93 100644 --- a/cocos/asset/asset-manager/cache-manager.ts +++ b/cocos/asset/asset-manager/cache-manager.ts @@ -27,123 +27,124 @@ import Cache from './cache'; /** * @en * Cache manager is a module which controls all caches downloaded from server in non-web platform, it is a singleton - * All member can be accessed with `assetManager.cacheManager`. + * You can access it via [[AssetManager.cacheManager]]. * * @zh - * 缓存管理器是一个模块,在非 WEB 平台上,用于管理所有从服务器上下载下来的缓存,这是一个单例,所有成员能通过 `assetManager.cacheManager` 访问。 + * 缓存管理器是一个模块,在非 WEB 平台上,用于管理所有从服务器上下载下来的缓存,这是一个单例,你能通过 [[AssetManager.cacheManager]] 访问它。 * */ export default abstract class CacheManager { /** * @en - * The name of cacheDir + * The name of cache directory. * * @zh - * 缓存目录的名称 + * 缓存目录的名称。 */ public abstract cacheDir: string; /** * @en - * Whether or not cache asset into user's storage space, this property only works on mini-game platforms + * Whether to cache file into user's storage space, this property only works on mini-game platforms. * * @zh - * 是否缓存资源到用户存储空间,此属性只在小游戏平台有效 + * 是否缓存文件到用户存储空间,此属性只在小游戏平台有效。 * */ public abstract cacheEnabled: boolean; /** * @en - * Whether or not auto clear cache when storage ran out, this property only works on mini-game platforms + * Whether to clear cache automatically when storage ran out, this property only works on mini-game platforms. * * @zh - * 是否在存储空间满了后自动清理缓存,此属性只在小游戏平台有效 + * 是否在存储空间满了后自动清理缓存,此属性只在小游戏平台有效。 * */ public abstract autoClear: boolean; /** * @en - * The interval between caching resources, this property only works on mini-game platforms, unit: ms + * The interval between caching file, this property only works on mini-game platforms, unit: ms. * * @zh - * 缓存资源的间隔时间,此属性只在小游戏平台有效,单位:毫秒 + * 缓存文件的间隔时间,此属性只在小游戏平台有效,单位:毫秒。 * */ public abstract cacheInterval: number; /** * @en - * The interval between deleting resources, when you use `cleanLRU`, the resources will be deleted as this interval, unit: ms + * The interval between deleting file, when you use `cleanLRU`, the file will be deleted as this interval, unit: ms. * * @zh - * 清理资源的间隔时间,当你使用 `cleanLRU` 时,资源将以此间隔被删除,单位:毫秒 + * 清理资源的间隔时间,当你使用 `cleanLRU` 时,资源将以此间隔被删除,单位:毫秒。 * */ public abstract deleteInterval: number; /** * @en - * List of all cached files + * List of all cached files. * * @zh - * 所有缓存文件列表 + * 所有缓存文件列表。 * */ public abstract cachedFiles: Cache<{ bundle: string, url: string, lastTime: number }>; /** * @en - * Get cached path with origin url + * Gets cached path with origin url. * * @zh - * 通过原始 url 获取缓存后的路径 + * 通过原始 url 获取缓存后的路径。 * - * @param originUrl - * @returns The cached path + * @param originUrl @en The origin url of file. @zh 文件的原始 url。 + * @returns @en The path where the file is cached. @zh 该文件所缓存的路径。 */ public abstract getCache (originUrl: string): string; /** * @en - * Get temporary path with origin url, this method only works on mini-game platforms + * Gets temporary path with origin url, this method only works on mini-game platforms. * * @zh - * 通过原始 url 获取临时文件的路径,此方法只在小游戏平台有效 + * 通过原始 url 获取临时文件的路径,此方法只在小游戏平台有效。 * - * @param originUrl - * @returns The temp path + * @param originUrl @en The origin url of file. @zh 文件的原始 url。 + * @returns @en The temporary path where the file is stored. @zh 该文件所存储的临时路径。 */ public abstract getTemp (originUrl: string): string; /** * @en - * Clear all caches, please use with caution, If necessary, we recommend using it before the game is launched + * Clear all caches, please use with caution, If necessary, we recommend using it before the game is launched. * * @zh - * 清空所有缓存,请谨慎使用,如果必要的话,我们建议在游戏启动之前使用 + * 清空所有缓存,请谨慎使用,如果必要的话,我们建议在游戏启动之前使用。 * */ public abstract clearCache (): void; /** * @en - * Clear part of caches with LRU strategy + * Clear part of caches with LRU strategy. * * @zh - * 使用 LRU 策略清空部分缓存 + * 使用 LRU 策略清空部分缓存。 * */ public abstract clearLRU (): void; /** * @en - * Remove cache with origin url + * Removes cache with origin url. * * @zh - * 通过原始 url 移除缓存 + * 通过原始 url 移除缓存。 * + * @param originUrl @en The origin url to remove from cache. @zh 要从缓存中移除的原始 url。 */ public abstract removeCache (originUrl: string): void; } diff --git a/cocos/asset/asset-manager/cache.ts b/cocos/asset/asset-manager/cache.ts index cd330011bb..87b3f8d990 100644 --- a/cocos/asset/asset-manager/cache.ts +++ b/cocos/asset/asset-manager/cache.ts @@ -24,24 +24,115 @@ import { js } from '../../core'; +/** + * @zh 缓存结构的接口定义,可以用于保存数据。 + * @en Interface definition of a cache structure that can be used to save data. + */ export interface ICache { + /** + * @en + * Adds a Key-Value pair to cache. + * + * @zh + * 增加键值对到缓存中。 + * + * @param key @en The key. @zh 要增加的键值对中的键。 + * @param val @en The value. @zh 要增加的键值对中的值。 + * @returns @en The value. @zh 新增的键值对中的值。 + */ add (key: string, val: T): T; + /** + * @en + * Gets the cached content by key. + * + * @zh + * 通过 key 获取对应的 value。 + * + * @param key @en The key. @zh 要查询的键。 + * @returns @en The corresponding content. @zh 对应键值对中的值。 + */ get (key: string): T | undefined | null; + /** + * @en + * Checks whether or not content exists by key. + * + * @zh + * 通过 Key 判断是否存在对应的内容。 + * + * @param key @en The key. @zh 要查询的键。 + * @returns @en True indicates that content of the key exists. @zh 返回 True 则表明该值存在。 + */ has (key: string): boolean; + /** + * @en + * Removes the cached content by key. + * + * @zh + * 通过 Key 移除对应的内容。 + * + * @param key @en The key. @zh 要移除的键值对中的键。 + * @returns @en The removed content. @zh 移出的键值对中的值。 + */ remove (key: string): T | undefined | null; + + /** + * @en + * Clear all contents. + * + * @zh + * 清除所有内容。 + */ clear (): void; + + /** + * + * @en + * Enumerates all contents and invokes function. + * + * @zh + * 枚举所有内容并执行方法。 + * + * @param func @en Function to be invoked. @zh 待执行的方法。 + * @param func.val @en The value. @zh 传入的键值对中的值。 + * @param func.key @en The corresponding key. @zh 传入的键值对中的键。 + */ forEach (func: (val: T, key: string) => void): void; + /** + * @en + * Enumerates all content to find one element which can fulfill condition. + * + * @zh + * 枚举所有内容,找到一个可以满足条件的元素。 + * + * @param predicate @en The condition function. @zh 条件方法。 + * @returns @en The first content that meets this condition. @zh 第一个符合该条件的内容。 + */ find (predicate: (val: T, key: string) => boolean): T | null; + /** + * @en + * The count of cached content. + * + * @zh + * 缓存数量。 + */ readonly count: number; + + /** + * @en + * Destroy this cache。 + * + * @zh + * 销毁这个 cache. + */ destroy (): void; } /** * @en - * use to cache something + * A data structure used to cache certain content. * * @zh - * 用于缓存某些内容 + * 用于缓存某些内容的数据结构。 * */ export default class Cache implements ICache { @@ -50,12 +141,12 @@ export default class Cache implements ICache { /** * @en - * Create a cache + * Creates a Cache. * * @zh - * 创建一个 cache + * 创建一个 Cache。 * - * @param map - An object used to initialize + * @param map @en An object used to initialize. @zh 用于初始化此缓存的对象。 * */ constructor (map?: Record) { @@ -70,14 +161,14 @@ export default class Cache implements ICache { /** * @en - * Add Key-Value to cache + * Adds a Key-Value pair to cache. * * @zh - * 增加键值对到缓存中 + * 增加键值对到缓存中。 * - * @param key - The key - * @param val - The value - * @returns The value + * @param key @en The key. @zh 要增加的键值对中的键。 + * @param val @en The value. @zh 要增加的键值对中的值。 + * @returns @en The value. @zh 新增的键值对中的值。 * * @example * var cache = new Cache(); @@ -93,13 +184,13 @@ export default class Cache implements ICache { /** * @en - * Get the cached content by key + * Gets the cached content by key. * * @zh - * 通过 key 获取对应的 value + * 通过 key 获取对应的 value。 * - * @param key - The key - * @returns The corresponding content + * @param key @en The key. @zh 要查询的键。 + * @returns @en The corresponding content. @zh 对应键值对中的值。 * * @example * let cache = new Cache(); @@ -112,13 +203,13 @@ export default class Cache implements ICache { /** * @en - * Check whether or not content exists by key + * Checks whether or not content exists by key. * * @zh - * 通过 Key 判断是否存在对应的内容 + * 通过 Key 判断是否存在对应的内容。 * - * @param key - The key - * @returns True indicates that content of the key exists + * @param key @en The key. @zh 要查询的键。 + * @returns @en True indicates that content of the key exists. @zh 返回 True 则表明该值存在。 * * @example * var cache = new Cache(); @@ -131,13 +222,13 @@ export default class Cache implements ICache { /** * @en - * Remove the cached content by key + * Removes the cached content by key. * * @zh - * 通过 Key 移除对应的内容 + * 通过 Key 移除对应的内容。 * - * @param key - The key - * @returns The removed content + * @param key @en The key. @zh 要移除的键值对中的键。 + * @returns @en The removed content. @zh 移出的键值对中的值。 * * @example * var cache = new Cache(); @@ -155,10 +246,10 @@ export default class Cache implements ICache { /** * @en - * Clear all content + * Clear all content. * * @zh - * 清除所有内容 + * 清除所有内容。 * * @example * var cache = new Cache(); @@ -174,14 +265,14 @@ export default class Cache implements ICache { /** * @en - * Enumerate all content and invoke function + * Enumerates all content and invokes function. * * @zh - * 枚举所有内容并执行方法 + * 枚举所有内容并执行方法。 * - * @param func - Function to be invoked - * @param func.val - The value - * @param func.key - The corresponding key + * @param func @en Function to be invoked. @zh 待执行的方法。 + * @param func.val @en The value. @zh 传入的键值对中的值。 + * @param func.key @en The corresponding key. @zh 传入的键值对中的键。 * * @example * var cache = new Cache(); @@ -196,13 +287,13 @@ export default class Cache implements ICache { /** * @en - * Enumerate all content to find one element which can fulfill condition + * Enumerate all content to find one element which can fulfill condition. * * @zh - * 枚举所有内容,找到一个可以满足条件的元素 + * 枚举所有内容,找到一个可以满足条件的元素。 * - * @param predicate - The condition - * @returns content + * @param predicate @en The condition function. @zh 条件方法。 + * @returns @en The first content that meets this condition. @zh 第一个符合该条件的内容。 * * @example * var cache = new Cache(); @@ -220,10 +311,10 @@ export default class Cache implements ICache { /** * @en - * The count of cached content + * The count of cached content. * * @zh - * 缓存数量 + * 缓存数量。 * */ get count (): number { @@ -232,10 +323,10 @@ export default class Cache implements ICache { /** * @en - * Destroy this cache + * Destroy this cache. * * @zh - * 销毁这个 cache + * 销毁这个 cache。 * */ public destroy (): void { diff --git a/cocos/asset/asset-manager/config.ts b/cocos/asset/asset-manager/config.ts index 94244aa993..6f76b0c702 100644 --- a/cocos/asset/asset-manager/config.ts +++ b/cocos/asset/asset-manager/config.ts @@ -26,7 +26,6 @@ import { Asset } from '../assets'; import { js, cclegacy } from '../../core'; import Cache from './cache'; import { decodeUuid, normalize } from './helper'; -import { AssetType } from './shared'; export interface IConfigOption { importBase: string; @@ -45,26 +44,97 @@ export interface IConfigOption { extensionMap: Record; } +/** + * @en Th asset's meta information. Used to obtain information about the asset. + * @zh 资源的元信息。用于获取资源的相关信息。 + */ export interface IAssetInfo { + /** + * @en The uuid of asset. + * @zh 资源的 uuid. + */ uuid: string; + /** + * @en Information about the file where the asset is located. A asset can be in multiple merged files. + * @zh 资源所在文件的相关信息。一个资源可在多个合并文件中。 + */ packs?: IPackInfo[]; + /** + * @en The redirect bundle of this asset. When multiple bundles with different priorities reference to the same asset, + * the asset will be stored in the bundle with the higher priority first, while the other bundles will store a record + * and the `redirect` property of that record will point to the bundle that actually stores the resource. + * @zh 资源所重定向的 bundle。当多个 bundle 引用同一份资源,且优先级不一样时,资源会优先存储在优先级高的 bundle 中, + * 其他 bundle 则会存储一条记录,并且该记录的 redirect 属性将指向真实存储此资源的 bundle。 + */ redirect?: string; + /** + * @en The version of the asset. + * @zh 资源的版本号。 + */ ver?: string; + /** + * @en The version of the native dependency of the asset. + * @zh 资源的原生依赖的版本号。 + */ nativeVer?: string; + /** + * @en The extension of the asset, or 'json' if it is null. + * This property is used to mark assets with special extensions like 'CCON'. + * @zh 资源的原生依赖的版本号。 + */ extension?: string; } -export interface IPackInfo extends IAssetInfo { +/** + * @en Information about the merged files. + * @zh 合并文件的信息。 + */ +export interface IPackInfo { + /** + * @en The unique id of this merged file. + * @zh 此合并文件的唯一 id. + */ + uuid: string; + + /** + * @en The uuid of all the assets contained in this file. + * @zh 此文件中包含的所有资源的 uuid。 + */ packedUuids: string[]; + + /** + * @en The extension of this merged file on the file system, default is 'json'. + * @zh 此合并文件在文件系统上的扩展名,默认为 'json'. + */ ext: string; } +/** + * @en Addressable asset information, you can look up the path of the asset in the project and the type of the asset. + * @zh 可寻址资源的信息,你可以查询到该资源在项目中的路径与资源的类型。 + */ export interface IAddressableInfo extends IAssetInfo { + /** + * @en The relative path of this asset in the project relative to the bundle folder. + * @zh 此资源在项目中相对于 bundle 文件夹的相对路径。 + */ path: string; - ctor: AssetType; + /** + * @en The type of the asset. + * @zh 此资源的类型。 + */ + ctor: Constructor; } +/** + * @en Information about the scene asset. + * @zh 场景资源的相关信息。 + */ export interface ISceneInfo extends IAssetInfo { + /** + * @en The path of the scene asset in the project relative to the bundle folder. + * @zh 场景资源在项目中相对 bundle 文件夹的路径。 + */ url: string; } @@ -199,7 +269,7 @@ export default class Config { } } - public getInfoWithPath (path: string, type?: AssetType | null): IAddressableInfo | null { + public getInfoWithPath (path: string, type?: Constructor | null): IAddressableInfo | null { if (!path) { return null; } @@ -220,7 +290,7 @@ export default class Config { return null; } - public getDirWithPath (path: string, type?: AssetType | null, out?: IAddressableInfo[]): IAddressableInfo[] { + public getDirWithPath (path: string, type?: Constructor | null, out?: IAddressableInfo[]): IAddressableInfo[] { path = normalize(path); if (path[path.length - 1] === '/') { path = path.slice(0, -1); diff --git a/cocos/asset/asset-manager/depend-util.ts b/cocos/asset/asset-manager/depend-util.ts index c1006247ef..63aa625634 100644 --- a/cocos/asset/asset-manager/depend-util.ts +++ b/cocos/asset/asset-manager/depend-util.ts @@ -42,10 +42,10 @@ export interface IDependencies { /** * @en - * Control asset's dependency list, it is a singleton. All member can be accessed with `assetManager.dependUtil` + * Manages asset's dependency list, it is a singleton. You can access it via [[AssetManager.dependUtil]]. * * @zh - * 控制资源的依赖列表,这是一个单例, 所有成员能通过 `assetManager.dependUtil` 访问 + * 管理资源的依赖列表,这是一个单例, 你能通过 [[AssetManager.dependUtil]] 访问它。 * */ export class DependUtil { @@ -53,23 +53,43 @@ export class DependUtil { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _depends: Cache = new Cache(); + private static _instance: DependUtil; + /** + * @en Global singleton for [[DependUtil]]. You can access it via [[AssetManager.dependUtil]]. + * @zh [[DependUtil]] 的全局单例. 你可以通过 [[AssetManager.dependUtil]] 访问. + */ + static get instance () { + if (!this._instance) { + this._instance = new DependUtil(); + } + return this._instance; + } + private constructor () {} + + /** + * @engineInternal + */ public init (): void { this._depends.clear(); } /** * @en - * Get asset's native dependency. For example, Texture's native dependency is image. + * Gets asset's native dependency. For example, ImageAsset's native dependency is image. + * Note: You will need to have loaded this resource to query this information. * * @zh - * 获取资源的原生依赖,例如 Texture 的原生依赖是图片 + * 获取资源的原生依赖,例如 ImageAsset 的原生依赖是图片。 + * 注意:你需要加载过该资源,才能查询此信息。 * - * @param uuid - asset's uuid - * @returns native dependency + * @param uuid @en asset's uuid. @zh 资源的 uuid。 + * @returns @en The native dependency information of this asset. @zh 资源的原生依赖的信息。 * * @example * var dep = dependUtil.getNativeDep('fcmR3XADNLgJ1ByKhqcC5Z'); + * @deprecated Since v3.7, this is an engine internal interface. + * If you want to know the native dependency of the asset, use [[Asset.nativeUrl]] instead. */ public getNativeDep (uuid: string): Record | null { const depend = this._depends.get(uuid); @@ -81,13 +101,15 @@ export class DependUtil { /** * @en - * Get asset's direct referencing non-native dependency list. For example, Material's non-native dependencies are Texture. + * Gets asset's direct referencing dependency list. For example, Material's dependencies are Texture, effect asset etc. + * Note: You will need to have loaded this resource to query this information. * * @zh - * 获取资源直接引用的非原生依赖列表,例如,材质的非原生依赖是 Texture + * 获取资源直接引用的依赖列表,例如,材质的直接依赖资源是 Texture, Effect 等。 + * 注意:你需要加载过该资源,才能查询此信息。 * - * @param uuid - asset's uuid - * @returns direct referencing non-native dependency list + * @param uuid @en asset's uuid. @zh 资源的 uuid。 + * @returns @en The direct referencing dependency asset list. @zh 直接引用的依赖资源列表。 * * @example * var deps = dependUtil.getDeps('fcmR3XADNLgJ1ByKhqcC5Z'); @@ -102,15 +124,17 @@ export class DependUtil { /** * @en - * Get non-native dependency list of the loaded asset, include indirect reference. - * The returned array stores the dependencies with their uuid, after retrieve dependencies, + * Gets dependency list of the loaded asset, include indirect reference. + * Note: You will need to have loaded this resource to query this information. * * @zh - * 获取某个已经加载好的资源的所有非原生依赖资源列表,包括间接引用的资源,并保存在数组中返回。 - * 返回的数组将仅保存依赖资源的 uuid。 + * 获取某个已经加载好的资源的所有依赖资源列表,包括间接引用的资源,并保存在数组中返回。 + * 注意:你需要加载过该资源,才能查询此信息。 * - * @param uuid - The asset's uuid - * @returns non-native dependency list + * @param uuid @en asset's uuid. @zh 资源的 uuid。 + * @returns + * @en The all dependency list including direct reference and indirect reference. + * @zh 所有依赖列表,包括直接引用的与间接引用的。 * * @example * var deps = dependUtil.getDepsRecursively('fcmR3XADNLgJ1ByKhqcC5Z'); @@ -123,13 +147,16 @@ export class DependUtil { return depends; } + /** + * @engineInternal + */ public remove (uuid: string) { this._depends.remove(uuid); } /** * @en - * Extract dependency list from serialized data or asset and then store in cache. + * Extracts dependency list from serialized data or asset and then store in cache. * * @zh * 从序列化数据或资源中提取出依赖列表,并且存储在缓存中。 @@ -143,6 +170,7 @@ export class DependUtil { * var dependencies = parse('fcmR3XADNLgJ1ByKhqcC5Z', file); * }); * + * @engineInternal */ public parse (uuid: string, json: any): IDependencies { let out: IDependencies | null = null; @@ -221,4 +249,4 @@ export class DependUtil { } } -export default new DependUtil(); +export default DependUtil.instance; diff --git a/cocos/asset/asset-manager/deprecated.ts b/cocos/asset/asset-manager/deprecated.ts index d1edb87def..e05b3e8780 100644 --- a/cocos/asset/asset-manager/deprecated.ts +++ b/cocos/asset/asset-manager/deprecated.ts @@ -33,9 +33,10 @@ import downloader from './downloader'; import { getUuidFromURL, transform } from './helper'; import parser from './parser'; import releaseManager from './release-manager'; -import { assets, BuiltinBundleName, bundles, ProgressCallback, CompleteCallback } from './shared'; +import { assets, BuiltinBundleName, bundles } from './shared'; import { parseLoadResArgs, setDefaultProgressCallback } from './utilities'; import factory from './factory'; +import RequestItem from './request-item'; const ImageFmts = ['.png', '.jpg', '.bmp', '.jpeg', '.gif', '.ico', '.tiff', '.webp', '.image', '.pvr', '.pkm', '.astc']; const AudioFmts = ['.mp3', '.ogg', '.wav', '.m4a']; @@ -92,7 +93,7 @@ export class CCLoader { * * @deprecated since v3.0, loader.onProgress is deprecated, please transfer onProgress to API as a parameter */ - public set onProgress (val: ProgressCallback) { + public set onProgress (val: ((finished: number, total: number, item: RequestItem) => void)) { setDefaultProgressCallback(val); } @@ -581,7 +582,7 @@ export class CCLoader { * @param extMap Handlers for corresponding type in a map * @deprecated since v3.0 loader.addDownloadHandlers is deprecated, please use assetManager.downloader.register instead */ - public addDownloadHandlers (extMap: Record void>) { + public addDownloadHandlers (extMap: Record void)) => void>) { const handler = Object.create(null); for (const type in extMap) { const func = extMap[type]; @@ -605,7 +606,7 @@ export class CCLoader { * @param extMap Handlers for corresponding type in a map * @deprecated since v3.0 loader.addLoadHandlers is deprecated, please use assetManager.parser.register instead */ - public addLoadHandlers (extMap: Record void>) { + public addLoadHandlers (extMap: Record void)) => void>) { const handler = Object.create(null); for (const type in extMap) { const func = extMap[type]; @@ -879,7 +880,7 @@ export const AssetLibrary = { * @param {Asset} options.existingAsset - 加载现有资源,此参数仅在编辑器中可用。 * @deprecated since v3.0 AssetLibrary.loadAsset is deprecated, please use assetManager.loadAny instead */ - loadAsset (uuid: string, callback: CompleteCallback, options?) { + loadAsset (uuid: string, callback: ((err: Error | null, data?: any | null) => void), options?) { assetManager.loadAny(uuid, callback); }, }; diff --git a/cocos/asset/asset-manager/download-dom-image.ts b/cocos/asset/asset-manager/download-dom-image.ts index cf94dc4507..d8025f159c 100644 --- a/cocos/asset/asset-manager/download-dom-image.ts +++ b/cocos/asset/asset-manager/download-dom-image.ts @@ -23,18 +23,19 @@ THE SOFTWARE. */ +import { XIAOMI } from 'internal:constants'; import { getError } from '../../core'; import { ccwindow } from '../../core/global-exports'; -import { CompleteCallback, IDownloadParseOptions } from './shared'; export default function downloadDomImage ( url: string, - options: IDownloadParseOptions, - onComplete: CompleteCallback, + options: Record, + onComplete: ((err: Error | null, data?: HTMLImageElement | null) => void), ): HTMLImageElement { const img = new ccwindow.Image(); - if (ccwindow.location.protocol !== 'file:') { + // NOTE: on xiaomi platform, we need to force setting img.crossOrigin as 'anonymous' + if (ccwindow.location.protocol !== 'file:' || XIAOMI) { img.crossOrigin = 'anonymous'; } diff --git a/cocos/asset/asset-manager/download-file.ts b/cocos/asset/asset-manager/download-file.ts index 884999a4f1..a03fbcc978 100644 --- a/cocos/asset/asset-manager/download-file.ts +++ b/cocos/asset/asset-manager/download-file.ts @@ -22,15 +22,13 @@ THE SOFTWARE. */ -import { CompleteCallback, IXHROptions } from './shared'; - type FileProgressCallback = (loaded: number, total: number) => void; export default function downloadFile ( url: string, - options: IXHROptions, + options: Record, onProgress: FileProgressCallback | null | undefined, - onComplete: CompleteCallback, + onComplete: ((err: Error | null, data?: any | null) => void), ): XMLHttpRequest { const xhr = new XMLHttpRequest(); const errInfo = `download failed: ${url}, status: `; diff --git a/cocos/asset/asset-manager/download-script.ts b/cocos/asset/asset-manager/download-script.ts index ed6a576a54..728f723c62 100644 --- a/cocos/asset/asset-manager/download-script.ts +++ b/cocos/asset/asset-manager/download-script.ts @@ -24,7 +24,6 @@ import { getError } from '../../core'; import { ccwindow } from '../../core/global-exports'; -import { CompleteCallback, IBundleOptions } from './shared'; const ccdocument = ccwindow.document; @@ -32,8 +31,8 @@ const downloaded = {}; export default function downloadScript ( url: string, - options: IBundleOptions, - onComplete: CompleteCallback, + options: Record, + onComplete: ((err: Error | null, data?: any | null) => void), ): HTMLScriptElement | null { // no need to load script again if (downloaded[url]) { diff --git a/cocos/asset/asset-manager/downloader.ts b/cocos/asset/asset-manager/downloader.ts index b793ccb30e..86ec94b3d0 100644 --- a/cocos/asset/asset-manager/downloader.ts +++ b/cocos/asset/asset-manager/downloader.ts @@ -28,46 +28,46 @@ import Cache from './cache'; import downloadDomImage from './download-dom-image'; import downloadFile from './download-file'; import downloadScript from './download-script'; -import { CompleteCallback, CompleteCallbackNoData, IBundleOptions, IDownloadParseOptions, files } from './shared'; +import { files } from './shared'; import { retry, RetryFunction, urlAppendTimestamp } from './utilities'; import { IConfigOption } from './config'; import { CCON, parseCCONJson, decodeCCONBinary } from '../../serialization/ccon'; -export type DownloadHandler = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) => void; +export type DownloadHandler = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void; interface IDownloadRequest { id: string; priority: number; url: string; - options: IDownloadParseOptions; - done: CompleteCallback; + options: Record; + done: ((err: Error | null, data?: any | null) => void); handler: DownloadHandler; } const REGEX = /^(?:\w+:\/\/|\.+\/).+/; -const downloadImage = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) => { +const downloadImage = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => { // if createImageBitmap is valid, we can transform blob to ImageBitmap. Otherwise, just use HTMLImageElement to load const func = sys.hasFeature(sys.Feature.IMAGE_BITMAP) && cclegacy.assetManager.allowImageBitmap ? downloadBlob : downloadDomImage; func(url, options, onComplete); }; -const downloadBlob = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) => { +const downloadBlob = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => { options.xhrResponseType = 'blob'; downloadFile(url, options, options.onFileProgress, onComplete); }; -const downloadJson = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback>) => { +const downloadJson = (url: string, options: Record, onComplete: ((err: Error | null, data?: Record | null) => void)) => { options.xhrResponseType = 'json'; downloadFile(url, options, options.onFileProgress, onComplete); }; -const downloadArrayBuffer = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) => { +const downloadArrayBuffer = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => { options.xhrResponseType = 'arraybuffer'; downloadFile(url, options, options.onFileProgress, onComplete); }; -const downloadCCON = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) => { +const downloadCCON = (url: string, options: Record, onComplete: ((err: Error | null, data?: CCON | null) => void)) => { downloadJson(url, options, (err, json) => { if (err) { onComplete(err); @@ -92,7 +92,7 @@ const downloadCCON = (url: string, options: IDownloadParseOptions, onComplete: C }); }; -const downloadCCONB = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) => { +const downloadCCONB = (url: string, options: Record, onComplete: ((err: Error | null, data?: CCON | null) => void)) => { downloadArrayBuffer(url, options, (err, arrayBuffer: ArrayBuffer) => { if (err) { onComplete(err); @@ -107,12 +107,12 @@ const downloadCCONB = (url: string, options: IDownloadParseOptions, onComplete: }); }; -const downloadText = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) => { +const downloadText = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => { options.xhrResponseType = 'text'; downloadFile(url, options, options.onFileProgress, onComplete); }; -const downloadBundle = (nameOrUrl: string, options: IBundleOptions, onComplete: CompleteCallback) => { +const downloadBundle = (nameOrUrl: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => { const bundleName = path.basename(nameOrUrl); let url = nameOrUrl; if (!REGEX.test(url)) { @@ -147,49 +147,50 @@ const downloadBundle = (nameOrUrl: string, options: IBundleOptions, onComplete: /** * @en - * Control all download process, it is a singleton. - * All member can be accessed with `assetManager.downloader`, it can download several types of files: - * 1. Text - * 2. Image - * 3. Audio - * 4. Assets - * 5. Scripts + * Manages all download process, it is a singleton. + * You can access it via [[AssetManager.downloader]], It can download various types of files. * * @zh - * 管理所有下载过程,downloader 是个单例,所有成员能通过 `assetManager.downloader` 访问,它能下载以下几种类型的文件: - * 1. 文本 - * 2. 图片 - * 3. 音频 - * 4. 资源 - * 5. 脚本 + * 管理所有下载过程,downloader 是个单例,你能通过 [[AssetManager.downloader]] 访问它,它能下载各种类型的文件。 * */ export class Downloader { + /** + * @en Global singleton for [[Downloader]]. You can access it via [[AssetManager.downloader]]. + * @zh [[Downloader]] 的全局单例. 你可以通过 [[AssetManager.downloader]] 访问. + */ + public static get instance () { + if (!Downloader._instance) { + Downloader._instance = new Downloader(); + } + return Downloader._instance; + } + /** * @en - * The maximum number of concurrent when downloading + * The maximum number of concurrent when downloading. * * @zh - * 下载时的最大并发数 + * 下载时的最大并发数。 */ public maxConcurrency = 6; /** * @en - * The maximum number of request can be launched per frame when downloading + * The maximum number of request can be launched per frame when downloading. * * @zh - * 下载时每帧可以启动的最大请求数 + * 下载时每帧可以启动的最大请求数。 * */ public maxRequestsPerFrame = 6; /** * @en - * The address of remote server + * The address of remote server. * * @zh - * 远程服务器地址 + * 远程服务器地址。 * */ public get remoteServerAddress () { @@ -198,40 +199,67 @@ export class Downloader { /** * @en - * The max number of retries when fail + * The max number of retries when fail. * * @zh - * 失败重试次数 + * 失败重试次数。 * - * @property maxRetryCount - * @type {Number} */ public maxRetryCount = BUILD ? 3 : 0; + /** + * Whether to automatically add a timestamp after the url. + * This function is mainly used to prevent the browser from using cache in editor mode. + * You don't need to change it at runtime. + * @internal + */ public appendTimeStamp = !!EDITOR; + /** + * @engineInternal + */ public limited = !EDITOR; /** * @en - * Wait for while before another retry, unit: ms + * Wait for while before another retry, unit: ms. * * @zh - * 重试的间隔时间 + * 重试的间隔时间,单位为毫秒。 * */ public retryInterval = 2000; + /** + * Version information of all bundles. + * @engineInternal + */ public bundleVers: Record | null = null; - public remoteBundles: string[] = []; + /** + * Remote bundle list. + * @engineInternal + */ + public remoteBundles: ReadonlyArray = []; + /** + * @deprecated Since v3.7, this is an engine internal interface. You can easily implement the functionality of this API using HTMLImageElement. + */ public downloadDomImage = downloadDomImage; + /** + * @deprecated Since v3.7, this is an engine internal interface. You can easily implement the functionality of this API using HTMLAudioElement. + */ public downloadDomAudio: DownloadHandler | null = null; + /** + * @deprecated Since v3.7, this is an engine internal interface. You can easily implement the functionality of this API using XMLHttpRequest. + */ public downloadFile = downloadFile; + /** + * @deprecated Since v3.7, this is an engine internal interface. You can easily implement the functionality of this API using XMLHttpRequest. + */ public downloadScript = downloadScript; // default handler map @@ -282,7 +310,7 @@ export class Downloader { default: downloadText, }; - private _downloading = new Cache(); + private _downloading = new Cache<((err: Error | null, data?: any | null) => void)[]>(); private _queue: IDownloadRequest[] = []; private _queueDirty = false; // the number of loading thread @@ -295,7 +323,11 @@ export class Downloader { private _checkNextPeriod = false; private _remoteServerAddress = ''; private _maxInterval = 1 / 30; + private static _instance: Downloader; + /** + * @engineInternal + */ public init (remoteServerAddress = '', bundleVers: Record = {}, remoteBundles: string[] = []) { this._downloading.clear(); this._queue.length = 0; @@ -306,16 +338,21 @@ export class Downloader { /** * @en - * Register custom handler if you want to change default behavior or extend downloader to download other format file + * Register custom handler if you want to change default behavior or extend downloader to download other format file. * * @zh - * 当你想修改默认行为或者拓展 downloader 来下载其他格式文件时可以注册自定义的 handler + * 当你想修改默认行为或者拓展 downloader 来下载其他格式文件时可以注册自定义的 handler。 * - * @param type - Extension likes '.jpg' or map likes {'.jpg': jpgHandler, '.png': pngHandler} - * @param handler - handler - * @param handler.url - url - * @param handler.options - some optional parameters will be transferred to handler. - * @param handler.onComplete - callback when finishing downloading + * @param type + * @en Extension name likes '.jpg' or map likes {'.jpg': jpgHandler, '.png': pngHandler}. + * @zh 扩展名,或者形如 {'.jpg': jpgHandler, '.png': pngHandler} 的映射表。 + * @param handler @en Customized handling for this extension. @zh 针对此扩展名的自定义的处理方法。 + * @param handler.url @en The url to be downloaded. @zh 待下载的 url. + * @param handler.options @en Some optional parameters will be transferred to handler. @zh 传递到处理方法的可选参数。 + * @param handler.onComplete + * @en Callback when finishing downloading. You need to call this method manually and pass in the execution result after the custom handler + * is executed. + * @zh 完成下载后的回调。你需要在自定义处理方法执行完后手动调用此方法,并将执行结果传入。 * * @example * downloader.register('.tga', (url, options, onComplete) => onComplete(null, null)); @@ -323,9 +360,12 @@ export class Downloader { * '.ext': (url, options, onComplete) => onComplete(null, null)}); * */ - public register (type: string, handler: DownloadHandler): void; - public register (map: Record): void; - public register (type: string | Record, handler?: DownloadHandler) { + public register (type: string, handler: (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void): void; + public register (map: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void>): void; + public register ( + type: string | Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void>, + handler?: (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void, + ) { if (typeof type === 'object') { js.mixin(this._downloaders, type); } else { @@ -335,29 +375,29 @@ export class Downloader { /** * @en - * Use corresponding handler to download file under limitation + * Use corresponding handler to download file under limitation. * * @zh - * 在限制下使用对应的 handler 来下载文件 + * 在限制下使用对应的 handler 来下载文件。 * - * @param id - The unique id of this download - * @param url - The url should be downloaded - * @param type - The type indicates that which handler should be used to download, such as '.jpg' - * @param options - some optional parameters will be transferred to the corresponding handler. - * @param options.onFileProgress - progressive callback will be transferred to handler. - * @param options.maxRetryCount - How many times should retry when download failed - * @param options.maxConcurrency - The maximum number of concurrent when downloading - * @param options.maxRequestsPerFrame - The maximum number of request can be launched per frame when downloading - * @param options.priority - The priority of this url, default is 0, the greater number is higher priority. - * @param onComplete - callback when finishing downloading - * @param onComplete.err - The occurred error, null indicates success - * @param onComplete.content - The downloaded file + * @param id @en The unique id of this download. @zh 本次下载的唯一 id. + * @param url @en The url should be downloaded. @zh 待下载的 url。 + * @param type @en The type indicates that which handler should be used to download, such as '.jpg'. @zh 要使用的处理方法的类型,例如 '.jpg'。 + * @param options @en Some optional parameters will be transferred to the corresponding handler. @zh 传递到处理方法的一些可选参数。 + * @param options.onFileProgress @en Progressive callback will be transferred to handler. @zh 传递到处理方法的进度回调。 + * @param options.maxRetryCount @en How many times should retry when download failed. @zh 下载失败后的重试数量。 + * @param options.maxConcurrency @en The maximum number of concurrent when downloading. @zh 下载的最大并行数。 + * @param options.maxRequestsPerFrame @en The maximum number of request can be launched per frame when downloading. @zh 每帧能发起的最大请求数量,在下载时。 + * @param options.priority @en The priority of this url, default is 0, the greater number is higher priority. @zh 下载的优先级,值越大优先级越高。 + * @param onComplete @en Callback when finishing downloading. @zh 完成下载后的回调。 + * @param onComplete.err @en The occurred error, null indicates success. @zh 下载过程中出现的错误,如果为 null 则表明下载成功。 + * @param onComplete.content @en The downloaded file. @zh 下载下来的文件内容。 * * @example * download('http://example.com/test.tga', '.tga', { onFileProgress: (loaded, total) => console.log(loaded/total) }, * onComplete: (err) => console.log(err)); */ - public download (id: string, url: string, type: string, options: IDownloadParseOptions, onComplete: CompleteCallback): void { + public download (id: string, url: string, type: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void { // if it is downloaded, don't download again const file = files.get(id); if (file) { @@ -397,7 +437,7 @@ export class Downloader { // refresh this._updateTime(); - const done: CompleteCallback = (err, data) => { + const done: ((err: Error | null, data?: any | null) => void) = (err, data) => { // when finish downloading, update _totalNum this._totalNum--; this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame); @@ -420,7 +460,7 @@ export class Downloader { // when retry finished, invoke callbacks const finale = (err, result) => { if (!err) { files.add(id, result); } - const callbacks = this._downloading.remove(id) as CompleteCallback[]; + const callbacks = this._downloading.remove(id) as ((err: Error | null, data?: any | null) => void)[]; for (let i = 0, l = callbacks.length; i < l; i++) { callbacks[i](err, result); } @@ -431,17 +471,19 @@ export class Downloader { /** * @en Load sub package with name. - * @zh 通过子包名加载子包代码。 - * @param name - Sub package name - * @param completeCallback - Callback invoked when sub package loaded - * @param {Error} completeCallback.error - error information + * @zh 通过子包名加载子包。 + * @param name @en Sub package name. @zh 子包名称。 + * @param completeCallback @en Callback invoked when sub package loaded. @zh 子包加载完成后的回调。 + * @param completeCallback.error @en Error information. Will be null if loaded successfully. @zh 错误信息。如果加载成功则为 null。 * - * @deprecated loader.downloader.loadSubpackage is deprecated, please use AssetManager.loadBundle instead + * @deprecated loader.downloader.loadSubpackage is deprecated, please use AssetManager.loadBundle instead. */ - public loadSubpackage (name: string, completeCallback?: CompleteCallbackNoData) { + public loadSubpackage (name: string, completeCallback?: ((err?: Error | null) => void)) { cclegacy.assetManager.loadBundle(name, null, completeCallback); } + private constructor () {} + private _updateTime () { const now = performance.now(); // use deltaTime as interval @@ -481,7 +523,5 @@ export class Downloader { } } } - -const downloader = new Downloader(); - -export default downloader; +const downloader = Downloader.instance; +export default Downloader.instance; diff --git a/cocos/asset/asset-manager/editor-path-replace.ts b/cocos/asset/asset-manager/editor-path-replace.ts index 3d59343bab..f1fe2b3cf9 100644 --- a/cocos/asset/asset-manager/editor-path-replace.ts +++ b/cocos/asset/asset-manager/editor-path-replace.ts @@ -24,13 +24,13 @@ import { EDITOR, NATIVE, PREVIEW, TEST } from 'internal:constants'; import { assert, Settings, settings } from '../../core'; import { fetchPipeline, pipeline } from './shared'; -import Task, { TaskCompleteCallback } from './task'; +import Task from './task'; declare const Editor: any; if ((EDITOR || PREVIEW) && !TEST) { const cache: {[uuid: string]: string | null} = {}; const resolveMap: { [uuid: string]: Function[] } = {}; - const replaceExtension = (task: Task, done: TaskCompleteCallback) => { + const replaceExtension = (task: Task, done) => { task.output = task.input; (async () => { for (let i = 0; i < task.input.length; i++) { diff --git a/cocos/asset/asset-manager/factory.ts b/cocos/asset/asset-manager/factory.ts index 8ba6311fac..5d77950426 100644 --- a/cocos/asset/asset-manager/factory.ts +++ b/cocos/asset/asset-manager/factory.ts @@ -32,15 +32,14 @@ import Bundle, { resources } from './bundle'; import Cache from './cache'; import { IConfigOption } from './config'; import { - assets, BuiltinBundleName, bundles, CompleteCallback, IRemoteOptions, - IDownloadParseOptions, + assets, BuiltinBundleName, bundles, } from './shared'; import { cache } from './utilities'; import { js } from '../../core'; -export type CreateHandler = (id: string, data: any, options: IDownloadParseOptions, onComplete: CompleteCallback) => void; +export type CreateHandler = (id: string, data: any, options: Record, onComplete: ((err: Error | null, data?: Asset | Bundle | null) => void)) => void; -function createImageAsset (id: string, data: HTMLImageElement, options: IDownloadParseOptions, onComplete: CompleteCallback) { +function createImageAsset (id: string, data: HTMLImageElement, options: Record, onComplete: ((err: Error | null, data?: ImageAsset | null) => void)) { let out: ImageAsset | null = null; let err: Error | null = null; try { @@ -53,33 +52,33 @@ function createImageAsset (id: string, data: HTMLImageElement, options: IDownloa onComplete(err, out); } -function createJsonAsset (id: string, data: Record, options: IDownloadParseOptions, onComplete: CompleteCallback) { +function createJsonAsset (id: string, data: Record, options: Record, onComplete: ((err: Error | null, data?: JsonAsset | null) => void)) { const out = new JsonAsset(); out.json = data; onComplete(null, out); } -function createTextAsset (id: string, data: string, options: IDownloadParseOptions, onComplete: CompleteCallback) { +function createTextAsset (id: string, data: string, options: Record, onComplete: ((err: Error | null, data?: TextAsset | null) => void)) { const out = new TextAsset(); out.text = data; onComplete(null, out); } -function createBufferAsset (id: string, data: ArrayBufferView, options: IDownloadParseOptions, onComplete: CompleteCallback) { +function createBufferAsset (id: string, data: ArrayBufferView, options: Record, onComplete: ((err: Error | null, data?: BufferAsset | null) => void)) { const out = new BufferAsset(); out._nativeUrl = id; out._nativeAsset = data; onComplete(null, out); } -function createAsset (id: string, data: any, options: IDownloadParseOptions, onComplete: CompleteCallback) { +function createAsset (id: string, data: any, options: Record, onComplete: ((err: Error | null, data?: Asset | null) => void)) { const out = new Asset(); out._nativeUrl = id; out._nativeAsset = data; onComplete(null, out); } -function createBundle (id: string, data: IConfigOption, options: IDownloadParseOptions, onComplete: CompleteCallback) { +function createBundle (id: string, data: IConfigOption, options: Record, onComplete: ((err: Error | null, data?: Bundle | null) => void)) { let bundle = bundles.get(data.name); if (!bundle) { bundle = data.name === BuiltinBundleName.RESOURCES ? resources : new Bundle(); @@ -97,7 +96,7 @@ function createBundle (id: string, data: IConfigOption, options: IDownloadParseO } export class Factory { - private _creating = new Cache(); + private _creating = new Cache<((err: Error | null, data?: any | null) => void)[]>(); private _producers: Record = { // Images @@ -147,7 +146,7 @@ export class Factory { } } - public create (id: string, data: any, type: string, options: IRemoteOptions, onComplete: CompleteCallback): void { + public create (id: string, data: any, type: string, options: Record, onComplete: ((err: Error | null, data?: Asset | Bundle | null) => void)): void { const handler = this._producers[type] || this._producers.default; const asset = assets.get(id); if (!options.reloadAsset && asset) { diff --git a/cocos/asset/asset-manager/fetch.ts b/cocos/asset/asset-manager/fetch.ts index a6ccddaa69..e325c1947e 100644 --- a/cocos/asset/asset-manager/fetch.ts +++ b/cocos/asset/asset-manager/fetch.ts @@ -26,11 +26,11 @@ import { Asset } from '../assets'; import { error, cclegacy } from '../../core'; import packManager from './pack-manager'; import RequestItem from './request-item'; -import { assets, CompleteCallbackNoData, fetchPipeline } from './shared'; +import { assets, fetchPipeline } from './shared'; import Task from './task'; import { clear, forEach, getDepends } from './utilities'; -export default function fetch (task: Task, done: CompleteCallbackNoData) { +export default function fetch (task: Task, done: ((err?: Error | null) => void)) { let firstTask = false; if (!task.progress) { task.progress = { finish: 0, total: task.input.length, canInvoke: true }; @@ -58,7 +58,7 @@ export default function fetch (task: Task, done: CompleteCallbackNoData) { packManager.load(item, task.options, (err, data) => { if (err) { - if (!task.isFinish) { + if (!task.isFinished) { if (!cclegacy.assetManager.force || firstTask) { error(err.message, err.stack); progress.canInvoke = false; @@ -70,7 +70,7 @@ export default function fetch (task: Task, done: CompleteCallbackNoData) { } } } - } else if (!task.isFinish) { + } else if (!task.isFinished) { item.file = data; task.output.push(item); if (!item.isNative) { @@ -85,7 +85,7 @@ export default function fetch (task: Task, done: CompleteCallbackNoData) { cb(); }); }, () => { - if (task.isFinish) { + if (task.isFinished) { clear(task, true); task.dispatch('error'); return; diff --git a/cocos/asset/asset-manager/helper.ts b/cocos/asset/asset-manager/helper.ts index a9dd6dca57..a12991b2c8 100644 --- a/cocos/asset/asset-manager/helper.ts +++ b/cocos/asset/asset-manager/helper.ts @@ -23,7 +23,7 @@ */ import { cclegacy, error } from '../../core'; import RequestItem from './request-item'; -import { bundles, Request, IOptions, transformPipeline } from './shared'; +import { bundles, transformPipeline } from './shared'; import Task from './task'; const _uuidRegex = /.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-@]{8,}).*/; @@ -32,13 +32,13 @@ export { default as decodeUuid } from '../../core/utils/decode-uuid'; /** * @en - * Extract uuid from url + * Extracts uuid from url. * * @zh - * 从 url 中提取 uuid + * 从 url 中提取 uuid。 * - * @param url - url - * @returns the uuid parsed from url + * @param url @en The url to be converted. @zh 待转换的 url。 + * @returns @en The uuid extracted from url. @zh url 转换为的 uuid。 * * @example * var url = 'res/import/fc/fc991dd7-0033-4b80-9d41-c8a86a702e59.json'; @@ -54,16 +54,16 @@ export function getUuidFromURL (url: string): string { /** * @en - * Transform uuid to url + * Transforms uuid to url. * * @zh - * 转换 uuid 为 url + * 转换 uuid 为 url。 * - * @param uuid - The uuid of asset - * @param options - Some optional parameters - * @param options.isNative - Indicates whether the path you want is a native resource path - * @param options.nativeExt - Extension of the native resource path, it is required when isNative is true - * @returns url + * @param uuid @en The uuid of asset. @zh 资源的 uuid。 + * @param options @en Some optional parameters. @zh 一些可选参数。 + * @param options.isNative @en Indicates whether the path you want is a native resource path. @zh 需要转换的路径是否是原生资源路径。 + * @param options.nativeExt @en Extension of the native resource path, it is required when isNative is true. @zh 原生资源路径的扩展名,如果 `isNative` 为 true,则需要。 + * @returns @en The url converted from uuid. @zh 从 uuid 转换而来的 url. * * @example * // json path, 'assets/main/import/fc/fc991dd7-0033-4b80-9d41-c8a86a702e59.json'; @@ -90,14 +90,13 @@ export function getUrlWithUuid (uuid: string, options?: { [k: string]: any, isNa /** * @en - * Check if the type of asset is scene + * Checks if the type of asset is scene. * * @zh - * 检查资源类型是否是场景 + * 检查资源类型是否是场景。 * - * @method isScene - * @param {*} asset - asset - * @returns {boolean} - whether or not type is SceneAsset + * @param asset @en The asset to be checked. @zh 待检查的资源。 + * @returns @en Whether or not the asset is a SceneAsset. @zh 此资源是否是场景资源。 * */ export function isScene (asset) { @@ -106,13 +105,13 @@ export function isScene (asset) { /** * @en - * Normalize url, strip './' and '/' + * Normalizes url, strip './' and '/'. * * @zh - * 标准化 url ,去除 './' 和 '/' + * 标准化 url ,去除 './' 和 '/'。 * - * @param url - url - * @returns - The normalized url + * @param url @en The url to be normalized. @zh 待标准化的 url。 + * @returns @en The normalized url. @zh 标准化后的 url。 */ export function normalize (url: string): string { if (url) { @@ -127,7 +126,7 @@ export function normalize (url: string): string { return url; } -export function transform (input: Request, options?: IOptions | null): string | string[] { +export function transform (input: string | string[] | Record | Array>, options?: Record | null): string | string[] { const subTask = Task.create({ input, options }); const urls: string[] = []; try { diff --git a/cocos/asset/asset-manager/load.ts b/cocos/asset/asset-manager/load.ts index e34806028c..898bcfebe2 100644 --- a/cocos/asset/asset-manager/load.ts +++ b/cocos/asset/asset-manager/load.ts @@ -28,7 +28,7 @@ import packManager from './pack-manager'; import parser from './parser'; import { Pipeline } from './pipeline'; import RequestItem from './request-item'; -import { CompleteCallbackNoData, assets, files, parsed, pipeline } from './shared'; +import { assets, files, parsed, pipeline } from './shared'; import Task from './task'; import { cache, checkCircleReference, clear, forEach, gatherAsset, getDepends, setProperties } from './utilities'; import { nativeDependMap, onLoadedInvokedMap } from './depend-maps'; @@ -43,10 +43,10 @@ interface ILoadingRequest { content: Asset; finish: boolean; err?: Error | null; - callbacks: Array<{ done: CompleteCallbackNoData; item: RequestItem }>; + callbacks: Array<{ done: ((err?: Error | null) => void); item: RequestItem }>; } -export default function load (task: Task, done: CompleteCallbackNoData) { +export default function load (task: Task, done: ((err?: Error | null) => void)) { let firstTask = false; if (!task.progress) { task.progress = { finish: 0, total: task.input.length, canInvoke: true }; @@ -66,7 +66,7 @@ export default function load (task: Task, done: CompleteCallbackNoData) { options, progress, onComplete: (err, result) => { - if (err && !task.isFinish) { + if (err && !task.isFinished) { if (!cclegacy.assetManager.force || firstTask) { if (BUILD) { error(err.message, err.stack); @@ -87,7 +87,7 @@ export default function load (task: Task, done: CompleteCallbackNoData) { }, () => { options!.__exclude__ = null; - if (task.isFinish) { + if (task.isFinished) { clear(task, true); task.dispatch('error'); return; @@ -173,7 +173,7 @@ const loadOneAssetPipeline = new Pipeline('loadOneAsset', [ }, ]); -function loadDepends (task: Task, asset: Asset, done: CompleteCallbackNoData) { +function loadDepends (task: Task, asset: Asset, done: ((err?: Error | null) => void)) { const { input: item, progress } = task; const { uuid, id, options, config } = item as RequestItem; const { cacheAsset } = options; diff --git a/cocos/asset/asset-manager/pack-manager.ts b/cocos/asset/asset-manager/pack-manager.ts index b89dc340bc..cf3676d8d9 100644 --- a/cocos/asset/asset-manager/pack-manager.ts +++ b/cocos/asset/asset-manager/pack-manager.ts @@ -30,12 +30,12 @@ import Cache from './cache'; import downloader from './downloader'; import { transform } from './helper'; import RequestItem from './request-item'; -import { CompleteCallback, files, IDownloadParseOptions } from './shared'; +import { files } from './shared'; -export type Unpacker = (packUuid: string[], data: any, options: IDownloadParseOptions, onComplete: CompleteCallback) => void; +export type Unpacker = (packUuid: string[], data: any, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void; interface IUnpackRequest { - onComplete: CompleteCallback; + onComplete: ((err: Error | null, data?: any | null) => void); id: string; } @@ -73,7 +73,7 @@ export class PackManager { * }); * */ - public unpackJson (pack: string[], json: any, options: IDownloadParseOptions, onComplete: CompleteCallback>): void { + public unpackJson (pack: string[], json: any, options: Record, onComplete: ((err: Error | null, data?: Record | null) => void)): void { let out = js.createMap(true); let err: Error | null = null; @@ -170,7 +170,7 @@ export class PackManager { * }); * */ - public unpack (pack: string[], data: any, type: string, options: IDownloadParseOptions, onComplete: CompleteCallback): void { + public unpack (pack: string[], data: any, type: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void { if (!data) { onComplete(new Error('package data is wrong!')); return; @@ -200,7 +200,7 @@ export class PackManager { * packManager.load(requestItem, null, (err, data) => console.log(err)); * */ - public load (item: RequestItem, options: IDownloadParseOptions | null, onComplete: CompleteCallback): void { + public load (item: RequestItem, options: Record | null, onComplete: ((err: Error | null, data?: any | null) => void)): void { // if not in any package, download as uausl if (item.isNative || !item.info || !item.info.packs) { downloader.download(item.id, item.url, item.ext, item.options, onComplete); diff --git a/cocos/asset/asset-manager/parser.ts b/cocos/asset/asset-manager/parser.ts index be212f8429..4982f766cb 100644 --- a/cocos/asset/asset-manager/parser.ts +++ b/cocos/asset/asset-manager/parser.ts @@ -28,22 +28,22 @@ import Cache from './cache'; import deserialize from './deserialize'; import { isScene } from './helper'; import plistParser from './plist-parser'; -import { CompleteCallback, IDownloadParseOptions, files, parsed } from './shared'; +import { files, parsed } from './shared'; import { CCON } from '../../serialization/ccon'; import { Asset } from '../assets'; -export type ParseHandler = (file: any, options: IDownloadParseOptions, onComplete: CompleteCallback) => void; +export type ParseHandler = (file: any, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void; /** * @en - * Parse the downloaded file, it's a singleton, all member can be accessed with `assetManager.parser` + * Parse the downloaded file, it's a singleton, you can access it via [[AssetManager.parser]]. * * @zh - * 解析已下载的文件,parser 是一个单例, 所有成员能通过 `assetManaager.parser` 访问 + * 解析已下载的文件,parser 是一个单例, 你能通过 [[assetManager.parser]] 访问它。 * */ export class Parser { - private _parsing = new Cache(); + private _parsing = new Cache<((err: Error | null, data?: any | null) => void)[]>(); private _parsers: Record = { '.png': this.parseImage, @@ -67,7 +67,20 @@ export class Parser { '.cconb': this.parseImport, }; - public parseImage (file: HTMLImageElement | Blob, options: IDownloadParseOptions, onComplete: CompleteCallback) { + private static _instance: Parser; + + public static get instance () { + if (!this._instance) { + this._instance = new Parser(); + } + return this._instance; + } + private constructor () {} + + /** + * @engineInternal + */ + public parseImage (file: HTMLImageElement | Blob, options: Record, onComplete: ((err: Error | null, data?: HTMLImageElement | ImageBitmap | null) => void)) { if (file instanceof HTMLImageElement) { onComplete(null, file); return; @@ -79,7 +92,10 @@ export class Parser { }); } - public parsePVRTex (file: ArrayBuffer | ArrayBufferView, options: IDownloadParseOptions, onComplete: CompleteCallback) { + /** + * @engineInternal + */ + public parsePVRTex (file: ArrayBuffer | ArrayBufferView, options: Record, onComplete: ((err: Error | null, data?: IMemoryImageSource | null) => void)) { let err: Error | null = null; let out: IMemoryImageSource | null = null; try { @@ -91,7 +107,10 @@ export class Parser { onComplete(err, out); } - public parsePKMTex (file: ArrayBuffer | ArrayBufferView, options: IDownloadParseOptions, onComplete: CompleteCallback) { + /** + * @engineInternal + */ + public parsePKMTex (file: ArrayBuffer | ArrayBufferView, options: Record, onComplete: ((err: Error | null, data?: IMemoryImageSource | null) => void)) { let err: Error | null = null; let out: IMemoryImageSource | null = null; try { @@ -103,7 +122,10 @@ export class Parser { onComplete(err, out); } - public parseASTCTex (file: ArrayBuffer | ArrayBufferView, options: IDownloadParseOptions, onComplete: CompleteCallback) { + /** + * @engineInternal + */ + public parseASTCTex (file: ArrayBuffer | ArrayBufferView, options: Record, onComplete: ((err: Error | null, data?: IMemoryImageSource | null) => void)) { let err: Error | null = null; let out: IMemoryImageSource | null = null; try { @@ -115,14 +137,20 @@ export class Parser { onComplete(err, out); } - public parsePlist (file: string, options: IDownloadParseOptions, onComplete: CompleteCallback) { + /** + * @engineInternal + */ + public parsePlist (file: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) { let err: Error | null = null; const result = plistParser.parse(file); if (!result) { err = new Error('parse failed'); } onComplete(err, result); } - public parseImport (file: Record | CCON, options: IDownloadParseOptions, onComplete: CompleteCallback) { + /** + * @engineInternal + */ + public parseImport (file: Record | CCON, options: Record, onComplete: ((err: Error | null, data?: Asset | null) => void)) { if (!file) { onComplete(new Error(`The json file of asset ${options.__uuid__ as string} is empty or missing`)); return; @@ -137,22 +165,27 @@ export class Parser { onComplete(err, result); } + /** + * @engineInternal + */ public init () { this._parsing.clear(); } /** * @en - * Register custom handler if you want to change default behavior or extend parser to parse other format file + * Register custom handler if you want to change default behavior or extend parser to parse other format file. * * @zh - * 当你想修改默认行为或者拓展 parser 来解析其他格式文件时可以注册自定义的handler + * 当你想修改默认行为或者拓展 parser 来解析其他格式文件时可以注册自定义的 handler。 * - * @param type - Extension likes '.jpg' or map likes {'.jpg': jpgHandler, '.png': pngHandler} - * @param handler - The corresponding handler - * @param handler.file - File - * @param handler.options - Some optional paramter - * @param handler.onComplete - callback when finishing parsing + * @param type + * @en Extension name likes '.jpg' or map likes {'.jpg': jpgHandler, '.png': pngHandler}. + * @zh 形如 '.jpg' 的扩展名或形如 {'.jpg': jpgHandler, '.png': pngHandler} 的映射表。 + * @param handler @en The corresponding handler. @zh 对应扩展名的处理方法。 + * @param handler.file @en The file to be parsed. @zh 待解析的文件。 + * @param handler.options @en Some optional parameters. @zh 一些可选的参数。 + * @param handler.onComplete @en The callback invoked when parsing finished. @zh 完成解析的回调。 * * @example * parser.register('.tga', (file, options, onComplete) => onComplete(null, null)); @@ -160,9 +193,12 @@ export class Parser { * '.ext': (file, options, onComplete) => onComplete(null, null)}); * */ - public register (type: string, handler: ParseHandler): void; - public register (map: Record): void; - public register (type: string | Record, handler?: ParseHandler) { + public register (type: string, handler: (file: any, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void): void; + public register (map: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void>): void; + public register ( + type: string | Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void>, + handler?: (file: any, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void, + ) { if (typeof type === 'object') { js.mixin(this._parsers, type); } else { @@ -172,18 +208,18 @@ export class Parser { /** * @en - * Use corresponding handler to parse file + * Use corresponding handler to parse file. * * @zh - * 使用对应的handler来解析文件 + * 使用对应的 handler 来解析文件。 * - * @param id - The id of file - * @param file - File - * @param type - The corresponding type of file, likes '.jpg'. - * @param options - Some optional parameters will be transferred to the corresponding handler. - * @param onComplete - callback when finishing downloading - * @param onComplete.err - The occurred error, null indicates success - * @param onComplete.content - The parsed file + * @param id @en The id of file. @zh 文件的唯一 id。 + * @param file @en The data of file. @zh 文件的数据。 + * @param type @en The corresponding type of file, likes '.jpg'. @zh 需要使用的解析方法类型。 + * @param options @en Some optional parameters will be transferred to the corresponding handler. @zh 传递到解析方法的额外参数。 + * @param onComplete @en The callback invoked when finishing parsing. @zh 完成解析的回调。 + * @param onComplete.err @en The occurred error, null indicates success. @zh 解析过程中发生的错误,null 表明解析成功。 + * @param onComplete.content @en The parsed data. @zh 解析后的数据。 * * @example * downloader.download('test.jpg', 'test.jpg', '.jpg', {}, (err, file) => { @@ -191,7 +227,7 @@ export class Parser { * }); * */ - public parse (id: string, file: any, type: string, options: IDownloadParseOptions, onComplete: CompleteCallback): void { + public parse (id: string, file: any, type: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void { const parsedAsset = parsed.get(id); if (parsedAsset) { onComplete(null, parsedAsset); @@ -224,4 +260,4 @@ export class Parser { } } -export default new Parser(); +export default Parser.instance; diff --git a/cocos/asset/asset-manager/pipeline.ts b/cocos/asset/asset-manager/pipeline.ts index 79022ae73a..78c19f681d 100644 --- a/cocos/asset/asset-manager/pipeline.ts +++ b/cocos/asset/asset-manager/pipeline.ts @@ -23,19 +23,14 @@ */ import { warnID } from '../../core'; -import { CompleteCallbackNoData } from './shared'; import Task from './task'; -export type IAsyncPipe = (task: Task, done: CompleteCallbackNoData) => void; -export type ISyncPipe = (task: Task) => Error | void; -export type IPipe = IAsyncPipe | ISyncPipe; - /** * @en - * Pipeline can execute the task for some effect. + * The loading pipeline can complete the loading task by executing a series of phases. [[AssetManager]] uses it to load all assets. * * @zh - * 管线能执行任务达到某个效果 + * 加载管线能通过执行一系列阶段来完成加载任务。[[AssetManager]] 使用其来加载所有资源。 * */ export class Pipeline { @@ -43,44 +38,46 @@ export class Pipeline { /** * @en - * The id of pipeline + * The unique id of this pipeline. * * @zh - * 管线的 id + * 管线的唯一 id。 * */ public id: number = Pipeline._pipelineId++; /** * @en - * The name of pipeline + * The name of this pipeline. * * @zh - * 管线的名字 + * 此管线的名称。 * */ public name = ''; /** * @en - * All pipes of pipeline + * All pipes of this pipeline. * * @zh - * 所有的管道 + * 此管线的所有管道。 * */ - public pipes: IPipe[] = []; + public pipes: Array<((task: Task, done: ((err?: Error | null) => void)) => void) | ((task: Task) => Error | void)> = []; /** * @en - * Create a new pipeline + * Creates a new pipeline. * * @zh - * 创建一个管线 + * 创建一个管线。 * - * @param name - The name of pipeline - * @param funcs - The array of pipe, every pipe must be function which take two parameters, - * the first is a `Task` flowed in pipeline, the second is complete callback + * @param name - @en The name of pipeline. @zh 管线的名称。 + * @param funcs + * @en The array of pipes to create pipeline, every pipe must be function which take two parameters, + * the first is a `Task` flowed in pipeline, the second is complete callback. + * @zh 用于创建管线的管道数组,每个管道必须是一个接受两个参数的方法,第一个参数为任务 [[Task]], 第二个参数为完成回调。 * * @example * const pipeline = new Pipeline('download', [ @@ -100,7 +97,7 @@ export class Pipeline { * ]); * */ - constructor (name: string, funcs: IPipe[]) { + constructor (name: string, funcs: Array<((task: Task, done: ((err?: Error | null) => void)) => void) | ((task: Task) => Error | void)>) { this.name = name; for (let i = 0, l = funcs.length; i < l; i++) { this.pipes.push(funcs[i]); @@ -109,16 +106,18 @@ export class Pipeline { /** * @en - * At specific point insert a new pipe to pipeline + * Inserts a new pipe to pipeline at specific point . * * @zh - * 在某个特定的点为管线插入一个新的 pipe + * 在某个特定的点为管线插入一个新的 pipe。 * - * @param func - The new pipe - * @param func.task - The task handled with pipeline will be transferred to this function - * @param func.done - Callback you need to invoke manually when this pipe is finished. if the pipeline is synchronous, callback is unnecessary. - * @param index - The specific point you want to insert at. - * @return pipeline + * @param func @en The new pipe to be inserted. @zh 待插入的管道。 + * @param func.task @en The task handled with pipeline will be transferred to this function. @zh 正在被此管线处理的任务。 + * @param func.done + * @en Callback you need to invoke manually when this pipe is finished. if the pipeline is synchronous, callback is unnecessary. + * @zh 当这个管道完成时,你需要手动调用回调。如果管道是同步的,回调就没有必要。 + * @param index @en The specific point you want to insert at. @zh 要插入进的位置。 + * @return @en Returns the Pipeline itself, which can be used to make chain calls. @zh 返回 Pipeline 本身,可以用于做链式调用。 * * @example * var pipeline = new Pipeline('test', []); @@ -128,7 +127,7 @@ export class Pipeline { * }, 0); * */ - public insert (func: IPipe, index: number): Pipeline { + public insert (func: ((task: Task, done: ((err?: Error | null) => void)) => void) | ((task: Task) => Error | void), index: number): Pipeline { if (index > this.pipes.length) { warnID(4921); return this; @@ -140,15 +139,19 @@ export class Pipeline { /** * @en - * Append a new pipe to the pipeline + * Appends a new pipe to the pipeline. * * @zh - * 添加一个管道到管线中 + * 添加一个管道到管线中。 * - * @param func - The new pipe - * @param func.task - The task handled with pipeline will be transferred to this function - * @param func.done - Callback you need to invoke manually when this pipe is finished. if the pipeline is synchronous, callback is unnecessary. - * @return pipeline + * @param func @en The new pipe to be appended. @zh 要追加的新管道。 + * @param func.task + * @en The task handled with pipeline will be transferred to this function. + * @zh 正在被此管线处理的任务。 + * @param func.done + * @en Callback you need to invoke manually when this pipe is finished. if the pipeline is synchronous, callback is unnecessary. + * @zh 当这个管道完成时,你需要手动调用回调。如果管道是同步的,回调就没有必要。 + * @return @en Returns the Pipeline itself, which can be used to make chain calls. @zh 返回 Pipeline 本身,可以用于做链式调用。 * * @example * var pipeline = new Pipeline('test', []); @@ -158,20 +161,20 @@ export class Pipeline { * }); * */ - public append (func: IPipe): Pipeline { + public append (func: ((task: Task, done: ((err?: Error | null) => void)) => void) | ((task: Task) => Error | void)): Pipeline { this.pipes.push(func); return this; } /** * @en - * Remove pipe which at specific point + * Removes pipe which at specific point. * * @zh - * 移除特定位置的管道 + * 移除特定位置的管道。 * - * @param index - The specific point - * @return pipeline + * @param index @en The specific point. @zh 指定位置的索引。 + * @return @en Returns the Pipeline itself, which can be used to make chain calls. @zh 返回 Pipeline 本身,可以用于做链式调用。 * * @example * var pipeline = new Pipeline('test', (task, done) => { @@ -188,13 +191,13 @@ export class Pipeline { /** * @en - * Execute task synchronously + * Executes task synchronously. * * @zh - * 同步执行任务 + * 同步执行任务。 * - * @param task - The task will be executed - * @returns result + * @param task @en The task will be executed. @zh 要执行的任务。 + * @returns @en The execution result. @zh 执行结果。 * * @example * var pipeline = new Pipeline('sync', [(task) => { @@ -209,12 +212,12 @@ export class Pipeline { public sync (task: Task): any { const pipes = this.pipes; if (pipes.length === 0) { return null; } - task.isFinish = false; + task.isFinished = false; for (let i = 0, l = pipes.length; i < l;) { - const pipe = pipes[i] as ISyncPipe; + const pipe = pipes[i] as ((task: Task) => Error | void); const result = pipe(task); if (result) { - task.isFinish = true; + task.isFinished = true; return result; } i++; @@ -223,18 +226,18 @@ export class Pipeline { task.output = null; } } - task.isFinish = true; + task.isFinished = true; return task.output as unknown; } /** * @en - * Execute task asynchronously + * Executes task asynchronously. * * @zh - * 异步执行任务 + * 异步执行任务。 * - * @param task - The task will be executed + * @param task @en The task will be executed. @zh 待执行的任务。 * * @example * var pipeline = new Pipeline('sync', [(task, done) => { @@ -249,7 +252,7 @@ export class Pipeline { public async (task: Task): void { const pipes = this.pipes; if (pipes.length === 0) { return; } - task.isFinish = false; + task.isFinished = false; this._flow(0, task); } @@ -257,7 +260,7 @@ export class Pipeline { const pipe = this.pipes[index]; pipe(task, (result) => { if (result) { - task.isFinish = true; + task.isFinished = true; task.dispatch('complete', result); } else { index++; @@ -267,7 +270,7 @@ export class Pipeline { task.output = null; this._flow(index, task); } else { - task.isFinish = true; + task.isFinished = true; task.dispatch('complete', result, task.output); } } diff --git a/cocos/asset/asset-manager/preprocess.ts b/cocos/asset/asset-manager/preprocess.ts index 003cc6f2e7..b402a10989 100644 --- a/cocos/asset/asset-manager/preprocess.ts +++ b/cocos/asset/asset-manager/preprocess.ts @@ -22,10 +22,10 @@ THE SOFTWARE. */ -import { CompleteCallbackNoData, RequestType, transformPipeline } from './shared'; +import { RequestType, transformPipeline } from './shared'; import Task from './task'; -export default function preprocess (task: Task, done: CompleteCallbackNoData) { +export default function preprocess (task: Task, done: ((err?: Error | null) => void)) { const options = task.options; const subOptions = Object.create(null); const leftOptions = Object.create(null); diff --git a/cocos/asset/asset-manager/request-item.ts b/cocos/asset/asset-manager/request-item.ts index a2dee831f1..96595ff872 100644 --- a/cocos/asset/asset-manager/request-item.ts +++ b/cocos/asset/asset-manager/request-item.ts @@ -26,19 +26,19 @@ import Config, { IAssetInfo } from './config'; /** * @en - * A collection of information about a request + * A collection of information about a request. * * @zh - * 请求的相关信息集合 + * 请求的相关信息集合。 * */ export default class RequestItem { /** * @en - * The id of request, combined from uuid and isNative + * The id of request, combined from uuid and isNative. * * @zh - * 请求的 id, 由 uuid 和 isNative 组合而成 + * 请求的 id, 由 uuid 和 isNative 组合而成。 */ get id (): string { if (!this._id) { @@ -47,16 +47,19 @@ export default class RequestItem { return this._id; } + /** + * @engineInternal + */ public static MAX_DEAD_NUM = 500; /** * @en - * Create a new request item from pool + * Create a new request item from pool. * * @zh - * 从对象池中创建 requestItem + * 从对象池中创建 requestItem。 * - * @returns requestItem + * @returns @en return a newly created RequestItem. @zh 返回一个刚创建的 `RequestItem`。 * */ public static create (): RequestItem { @@ -74,84 +77,90 @@ export default class RequestItem { /** * @en - * The uuid of request + * The uuid of request. * * @zh - * 请求资源的uuid + * 所请求资源的 uuid。 * */ public uuid = ''; + /** + * @engineInternal only used for L10N asset replacement. + */ public overrideUuid = ''; /** * @en - * The final url of request + * The final url of request. * * @zh - * 请求的最终url + * 请求的最终 url。 * */ public url = ''; /** * @en - * The extension name of asset + * The extension name of asset. * * @zh - * 资源的扩展名 + * 资源的扩展名。 * */ public ext = '.json'; /** * @en - * The content of asset + * The content of asset. * * @zh - * 资源的内容 + * 资源的内容。 * */ public content: any = null; /** * @en - * The file of asset + * The file of asset. * * @zh - * 资源的文件 + * 资源的文件。 * */ public file: any = null; /** * @en - * The information of asset + * The information of asset. * * @zh - * 资源的相关信息 + * 资源的相关信息。 * */ public info: IAssetInfo | null = null; + /** + * @engineInternal + */ public config: Config | null = null; /** * @en - * Whether or not it is native asset + * Whether or not it is native asset. * * @zh - * 资源是否是原生资源 + * 资源是否是原生资源。 * */ public isNative = false; /** * @en - * Custom options + * Custom options. * * @zh - * 自定义参数 + * 自定义参数。 * */ public options: Record = Object.create(null); @@ -160,10 +169,10 @@ export default class RequestItem { /** * @en - * Recycle this for reuse + * Recycle this to be reused. * * @zh - * 回收 requestItem 用于复用 + * 回收 requestItem 用于复用。 * */ public recycle (): void { diff --git a/cocos/asset/asset-manager/shared.ts b/cocos/asset/asset-manager/shared.ts index 33bc4a13b2..bf32743ca8 100644 --- a/cocos/asset/asset-manager/shared.ts +++ b/cocos/asset/asset-manager/shared.ts @@ -27,70 +27,8 @@ import { Asset } from '../assets/asset'; import Bundle from './bundle'; import Cache from './cache'; import { Pipeline } from './pipeline'; -import RequestItem from './request-item'; import WeakCache from './weak-cache'; -export type CompleteCallback = (err: Error | null, data?: T | null) => void; -export type CompleteCallbackNoData = (err?: Error | null) => void; -export type CompleteCallbackWithData = (err: Error | null, data: T) => void; -export type ProgressCallback = (finished: number, total: number, item: RequestItem) => void; -export type Request = string | string[] | IRequest | Array; - -export interface IRequest extends IOptions { - uuid?: string; - url?: string; - path?: string; - dir?: string; - scene?: string; -} - -export interface IOptions extends IBundleOptions, IRemoteOptions { - type?: typeof Asset; - bundle?: string; -} - -export interface IRemoteOptions extends IAssetOptions { - ext?: string; -} - -export interface IXHROptions extends Record { - xhrResponseType?: XMLHttpRequestResponseType; - xhrWithCredentials?: boolean; - xhrTimeout?: number; - xhrHeader?: Record; - xhrMimeType?: string; -} - -export interface IAssetOptions extends INativeAssetOptions { - reloadAsset?: boolean; - cacheAsset?: boolean; -} - -export interface IJsonAssetOptions extends IAssetOptions { - assetId?: string; -} - -export interface IDownloadParseOptions extends IXHROptions { - priority?: number; - audioLoadMode?: number; - onFileProgress?: (loaded: number, total: number) => void; - maxConcurrency?: number; - maxRequestsPerFrame?: number; - maxRetryCount?: number; - cacheEnabled?: boolean; -} - -export interface IBundleOptions extends INativeAssetOptions { - version?: string; - scriptAsyncLoading?: boolean; -} - -export interface INativeAssetOptions extends IDownloadParseOptions { - preset?: string; -} - -export type AssetType = Constructor; - export const assets = EDITOR ? new WeakCache() : new Cache(); export const files = new Cache(); export const parsed = new Cache(); @@ -114,6 +52,14 @@ export enum RequestType { SCENE = 'scene', } +export interface IRequest extends Record { + uuid?: string; + url?: string; + path?: string; + dir?: string; + scene?: string; +} + export const presets: Record> = { default: { diff --git a/cocos/asset/asset-manager/task.ts b/cocos/asset/asset-manager/task.ts index 2fef31571d..8c6032f8dd 100644 --- a/cocos/asset/asset-manager/task.ts +++ b/cocos/asset/asset-manager/task.ts @@ -22,13 +22,10 @@ THE SOFTWARE. */ -export type TaskCompleteCallback = (err: Error | null | undefined, data: any) => void; -export type TaskProgressCallback = (...args: any[]) => void; -export type TaskErrorCallback = (...args: any[]) => void; export interface ITaskOption { - onComplete?: TaskCompleteCallback | null; - onProgress?: TaskProgressCallback | null; - onError?: TaskErrorCallback | null; + onComplete?: ((err: Error | null | undefined, data: any) => void) | null; + onProgress?: ((...args: any[]) => void) | null; + onError?: ((...args: any[]) => void) | null; input: any; progress?: any; options?: Record | null; @@ -36,32 +33,40 @@ export interface ITaskOption { /** * @en - * Task is used to run in the pipeline for some effect + * Tasks are the smallest unit of data running in the pipeline, You can create a task and pass in the input information, + * and then get the output of that task after it has been executed in the pipeline to use. * * @zh - * 任务用于在管线中运行以达成某种效果 + * 任务是在管线中运行的最小数据单位,你可以创建一个任务并传入输入信息,在经过管线执行后获取该任务的输出来使用。 * */ export default class Task { + /** + * @engineInternal + */ public static MAX_DEAD_NUM = 500; /** * @en - * Create a new task from pool + * Create a new task from pool. * * @zh - * 从对象池中创建 task + * 从对象池中创建 task。 * - * @static - * @method create - * @param options - Some optional paramters - * @param options.onComplete - Callback when the task complete, if the pipeline is synchronous, onComplete is unnecessary. - * @param options.onProgress - Continuously callback when the task is runing, if the pipeline is synchronous, onProgress is unnecessary. - * @param options.onError - Callback when something goes wrong, if the pipeline is synchronous, onError is unnecessary. - * @param options.input - Something will be handled with pipeline - * @param options.progress - Progress information, you may need to assign it manually when multiple pipeline share one progress - * @param options.options - Custom parameters - * @returns task + * @param options @en Some optional parameters. @zh 一些可选参数。 + * @param options.onComplete + * @en Callback when the task complete, if the pipeline is synchronous, onComplete is unnecessary. + * @zh 任务完成后的回调,如果流水线是同步的,onComplete 是不必要的。 + * @param options.onProgress + * @en Continuously callback when the task is running, if the pipeline is synchronous, onProgress is unnecessary. + * @zh 在任务运行时持续回调,如果管道是同步的,onProgress 是不必要的。 + * @param options.onError + * @en Callback when something goes wrong, if the pipeline is synchronous, onError is unnecessary. + * @zh 出错时的回调,如果流水线是同步的,onError 是不必要的。 + * @param options.input @en Something will be handled with pipeline. @zh 需要被此管道处理的任务数据。 + * @param options.progress @en Progress information. @zh 进度信息。 + * @param options.options @en Custom parameters. @zh 自定义参数。 + * @returns @en return a newly created task. @zh 返回一个新创建的任务。 * */ public static create (options: ITaskOption): Task { @@ -81,117 +86,138 @@ export default class Task { /** * @en - * The id of task + * The id of task. * * @zh - * 任务id + * 任务 id。 * */ public id: number = Task._taskId++; /** * @en - * The callback when task is completed + * The callback when task is completed. * * @zh - * 完成回调 + * 完成回调。 * */ - public onComplete: TaskCompleteCallback | null = null; + public onComplete: ((err: Error | null | undefined, data: any) => void) | null = null; /** * @en - * The callback of progression + * The callback of progression. * * @zh - * 进度回调 + * 进度回调。 * */ - public onProgress: TaskProgressCallback | null = null; + public onProgress: ((...args: any[]) => void) | null = null; /** * @en - * The callback when something goes wrong + * The callback when something goes wrong. * * @zh - * 错误回调 + * 错误回调。 * */ - public onError: TaskErrorCallback | null = null; + public onError: ((...args: any[]) => void) | null = null; /** * @en - * The source of task + * The source data of task. * * @zh - * 任务的源 + * 任务的源数据。 * */ public source: any = null; /** * @en - * The output of task + * The output of task. * * @zh - * 任务的输出 + * 任务的输出。 */ public output: any = null; /** * @en - * The input of task + * The input of task. * * @zh - * 任务的输入 + * 任务的输入。 * */ public input: any = null; /** * @en - * The progression of task + * The progression of task. * * @zh - * 任务的进度 + * 任务的进度。 * */ public progress: any = null; /** * @en - * Custom options + * Custom options. * * @zh - * 自定义参数 + * 自定义参数。 * */ public options: Record | null = null; /** - * @en - * Whether or not this task is completed - * - * @zh - * 此任务是否已经完成 - * + * @deprecated Typo. Since v3.7, please use [[Task.isFinished]] instead. */ - public isFinish = true; + public get isFinish () { + return this.isFinished; + } + + /** + * @deprecated Typo. Since v3.7, please use [[Task.isFinished]] instead. + */ + public set isFinish (val: boolean) { + this.isFinished = val; + } /** * @en - * Create a new Task + * Whether or not this task is completed. * * @zh - * 创建一个任务 + * 此任务是否已经完成。 * - * @param options - Some optional paramters - * @param options.onComplete - Callback when the task is completed, if the pipeline is synchronous, onComplete is unnecessary. - * @param options.onProgress - Continuously callback when the task is runing, if the pipeline is synchronous, onProgress is unnecessary. - * @param options.onError - Callback when something goes wrong, if the pipeline is synchronous, onError is unnecessary. - * @param options.input - Something will be handled with pipeline - * @param options.progress - Progress information, you may need to assign it manually when multiple pipeline share one progress - * @param options.options - Custom parameters + */ + public isFinished = true; + + /** + * @en + * Create a new Task. + * + * @zh + * 创建一个任务。 + * + * @param options @en Some optional parameters. @zh 一些可选参数。 + * @param options.onComplete + * @en Callback when the task complete, if the pipeline is synchronous, onComplete is unnecessary. + * @zh 任务完成后的回调,如果流水线是同步的,onComplete 是不必要的。 + * @param options.onProgress + * @en Continuously callback when the task is running, if the pipeline is synchronous, onProgress is unnecessary. + * @zh 在任务运行时持续回调,如果管道是同步的,onProgress 是不必要的。 + * @param options.onError + * @en Callback when something goes wrong, if the pipeline is synchronous, onError is unnecessary. + * @zh 出错时的回调,如果流水线是同步的,onError 是不必要的。 + * @param options.input @en Something will be handled with pipeline. @zh 需要被此管道处理的任务数据。 + * @param options.progress @en Progress information. @zh 进度信息。 + * @param options.options @en Custom parameters. @zh 自定义参数。 + * @returns @en return a newly created task. @zh 返回一个新创建的任务。 */ public constructor (options?: ITaskOption) { this.set(options); @@ -199,21 +225,28 @@ export default class Task { /** * @en - * Set parameters of this task + * Set parameters of this task. * * @zh - * 设置任务的参数 + * 设置任务的参数。 * - * @param options - Some optional parameters - * @param options.onComplete - Callback when the task is completed, if the pipeline is synchronous, onComplete is unnecessary. - * @param options.onProgress - Continuously callback when the task is running, if the pipeline is synchronous, onProgress is unnecessary. - * @param options.onError - Callback when something goes wrong, if the pipeline is synchronous, onError is unnecessary. - * @param options.input - Something will be handled with pipeline - * @param options.progress - Progress information, you may need to assign it manually when multiple pipeline share one progress - * @param options.options - Custom parameters + * @param options @en Some optional parameters. @zh 一些可选参数。 + * @param options.onComplete + * @en Callback when the task complete, if the pipeline is synchronous, onComplete is unnecessary. + * @zh 任务完成后的回调,如果流水线是同步的,onComplete 是不必要的。 + * @param options.onProgress + * @en Continuously callback when the task is running, if the pipeline is synchronous, onProgress is unnecessary. + * @zh 在任务运行时持续回调,如果管道是同步的,onProgress 是不必要的。 + * @param options.onError + * @en Callback when something goes wrong, if the pipeline is synchronous, onError is unnecessary. + * @zh 出错时的回调,如果流水线是同步的,onError 是不必要的。 + * @param options.input @en Something will be handled with pipeline. @zh 需要被此管道处理的任务数据。 + * @param options.progress @en Progress information. @zh 进度信息。 + * @param options.options @en Custom parameters. @zh 自定义参数。 + * @returns @en return a newly created task. @zh 返回一个新创建的任务。 * * @example - * var task = new Task(); + * const task = new Task(); * task.set({input: ['test'], onComplete: (err, result) => console.log(err), onProgress: (finish, total) => console.log(finish / total)}); * */ @@ -230,21 +263,21 @@ export default class Task { /** * @en - * Dispatch event + * Dispatch event with any parameter. * * @zh - * 发布事件 + * 分发事件,可以传递任意参数。 * - * @param event - The event name - * @param param1 - Parameter 1 - * @param param2 - Parameter 2 - * @param param3 - Parameter 3 - * @param param4 - Parameter 4 + * @param event @en The event name. @zh 事件名称。 + * @param param1 @en The parameter 1. @zh 参数 1。 + * @param param2 @en The parameter 2. @zh 参数 2。 + * @param param3 @en The parameter 3. @zh 参数 3。 + * @param param4 @en The parameter 4. @zh 参数 4。 * * @example - * var task = Task.create(); - * Task.onComplete = (msg) => console.log(msg); - * Task.dispatch('complete', 'hello world'); + * const task = Task.create(); + * task.onComplete = (msg) => console.log(msg); + * task.dispatch('complete', 'hello world'); * */ public dispatch (event: string, param1?: any, param2?: any, param3?: any, param4?: any): void { @@ -276,10 +309,10 @@ export default class Task { /** * @en - * Recycle this for reuse + * Recycle this task to be reused. * * @zh - * 回收 task 用于复用 + * 回收 task 用于复用。 * */ public recycle (): void { diff --git a/cocos/asset/asset-manager/utilities.ts b/cocos/asset/asset-manager/utilities.ts index 3e6d4f5caf..7fc56dcf6b 100644 --- a/cocos/asset/asset-manager/utilities.ts +++ b/cocos/asset/asset-manager/utilities.ts @@ -30,16 +30,16 @@ import { dependMap, nativeDependMap } from './depend-maps'; import dependUtil from './depend-util'; import { isScene } from './helper'; import RequestItem from './request-item'; -import { assets, AssetType, CompleteCallbackNoData, CompleteCallback, IOptions, ProgressCallback, references } from './shared'; +import { assets, references } from './shared'; import Task from './task'; -let defaultProgressCallback: ProgressCallback | null = null; +let defaultProgressCallback: ((finished: number, total: number, item: RequestItem) => void) | null = null; declare class WeakRef { constructor (obj: any); } -export function setDefaultProgressCallback (onProgress: ProgressCallback) { +export function setDefaultProgressCallback (onProgress: (finished: number, total: number, item: RequestItem) => void) { defaultProgressCallback = onProgress; } @@ -67,9 +67,9 @@ export function urlAppendTimestamp (url: string, append: boolean): string { return url; } -export type RetryFunction = (times: number, done: CompleteCallback) => void; +export type RetryFunction = (times: number, done: ((err: Error | null, data?: any | null) => void)) => void; -export function retry (process: RetryFunction, times: number, wait: number, onComplete: CompleteCallback, index = 0) { +export function retry (process: RetryFunction, times: number, wait: number, onComplete: ((err: Error | null, data?: any | null) => void), index = 0) { process(index, (err, result) => { index++; if (!err || index > times) { @@ -182,7 +182,7 @@ export function gatherAsset (task: Task) { } } -type ForEachFunction = (item: T, done: CompleteCallbackNoData) => void; +type ForEachFunction = (item: T, done: ((err?: Error | null) => void)) => void; export function forEach (array: T[], process: ForEachFunction, onComplete: (errs: Error[]) => void) { let count = 0; @@ -208,20 +208,20 @@ export function forEach (array: T[], process: ForEachFunction, onCom } interface IParameters { - options: IOptions; - onProgress: ProgressCallback | null; + options: Record; + onProgress: ((finished: number, total: number, item: RequestItem) => void) | null; onComplete: T | null; } interface ILoadResArgs { - type: AssetType | null; - onProgress: ProgressCallback | null; + type: Constructor | null; + onProgress: ((finished: number, total: number, item: RequestItem) => void) | null; onComplete: T | null; } export function parseParameters void> ( - options: IOptions | ProgressCallback | T | null | undefined, - onProgress: ProgressCallback | T | null | undefined, + options: Record | ((finished: number, total: number, item: RequestItem) => void) | T | null | undefined, + onProgress: ((finished: number, total: number, item: RequestItem) => void) | T | null | undefined, onComplete: T | null | undefined): IParameters { let optionsOut: any = options; let onProgressOut: any = onProgress; @@ -239,7 +239,7 @@ export function parseParameters void> ( onProgressOut = null; } if (onProgress !== undefined && isCallback) { - onProgressOut = options as ProgressCallback; + onProgressOut = options as ((finished: number, total: number, item: RequestItem) => void); optionsOut = null; } } @@ -248,14 +248,14 @@ export function parseParameters void> ( } export function parseLoadResArgs void> ( - type: AssetType | ProgressCallback | T | null | undefined, - onProgress: ProgressCallback | T | null | undefined, + type: Constructor | ((finished: number, total: number, item: RequestItem) => void) | T | null | undefined, + onProgress: ((finished: number, total: number, item: RequestItem) => void) | T | null | undefined, onComplete: T | null | undefined): ILoadResArgs { let typeOut: any = type; let onProgressOut: any = onProgress; let onCompleteOut: any = onComplete; if (onComplete === undefined) { - const isValidType = js.isChildClassOf(type as AssetType, Asset); + const isValidType = js.isChildClassOf(type as Constructor, Asset); if (onProgress) { onCompleteOut = onProgress as T; if (isValidType) { @@ -267,7 +267,7 @@ export function parseLoadResArgs void> ( typeOut = null; } if (onProgress !== undefined && !isValidType) { - onProgressOut = type as ProgressCallback; + onProgressOut = type as ((finished: number, total: number, item: RequestItem) => void); typeOut = null; } } diff --git a/cocos/asset/assets/asset.ts b/cocos/asset/assets/asset.ts index aedaaa6b93..6455de041a 100644 --- a/cocos/asset/assets/asset.ts +++ b/cocos/asset/assets/asset.ts @@ -76,12 +76,24 @@ export class Asset extends Eventify(CCObject) { public loaded = true; /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + * @en + * The UUID of this asset. + * + * @zh + * 资源的 UUID。 + * + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future, please use [[Asset.uuid]] instead. */ public declare _uuid: string; /** - * @internal + * @en + * Indicates whether this asset is a default asset. + * + * @zh + * 表明此资源是否是默认资源。 + * + * @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances. */ public declare isDefault: boolean; @@ -96,8 +108,14 @@ export class Asset extends Eventify(CCObject) { */ @serializable public _native = ''; + /** - * @internal + * @en + * Path to native dependency. + * @zh + * 原生依赖的路径。 + * + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _nativeUrl = ''; @@ -106,9 +124,9 @@ export class Asset extends Eventify(CCObject) { /** * @en - * Returns the url of this asset's native object, if none it will returns an empty string. + * Returns the url of this asset's native object, will return an empty string if this asset does not have any native dependency. * @zh - * 返回该资源对应的目标平台资源的 URL,如果没有将返回一个空字符串。 + * 返回该资源对应的目标平台资源的 URL,如果此资源没有原生依赖将返回一个空字符串。 * @readOnly */ get nativeUrl () { @@ -131,6 +149,17 @@ export class Asset extends Eventify(CCObject) { return this._nativeUrl; } + /** + * @en + * The UUID of this asset. + * + * @zh + * 资源的 UUID。 + */ + get uuid () { + return this._uuid; + } + /** * @en * The underlying native asset of this asset if one is available.
@@ -188,7 +217,7 @@ export class Asset extends Eventify(CCObject) { * 否则,返回空字符串。
* 子类可能会覆盖此方法。 * @method toString - * @return {String} + * @returns @en String representation of this asset. @zh 此资源的字符串表示。 */ public toString () { return this.nativeUrl; @@ -199,7 +228,7 @@ export class Asset extends Eventify(CCObject) { * 返回一个序列化后的对象 * * @method serialize - * @return {String} + * @returns {String} * @private */ public serialize () { } @@ -234,7 +263,15 @@ export class Asset extends Eventify(CCObject) { public createNode? (callback: CreateNodeCallback): void; /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + * @en + * Get native dependency information. + * + * @zh + * 获取原生依赖信息。 + * + * @returns @en The native dependency information. @zh 原生依赖信息。 + * + * @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances. */ public get _nativeDep () { if (this._native) { @@ -245,10 +282,10 @@ export class Asset extends Eventify(CCObject) { /** * @en - * The number of reference + * Current reference count to this asset. * * @zh - * 引用的数量 + * 当前该资源被引用的数量。 */ public get refCount (): number { return this._ref; @@ -256,12 +293,13 @@ export class Asset extends Eventify(CCObject) { /** * @en - * Add references of asset + * Increase the reference count. This will prevent assets from being automatically recycled. + * When you no longer need to hold the asset, you need to using [[decRef]] to decrease the refCount. * * @zh - * 增加资源的引用 + * 增加资源的引用。这将阻止资源被自动释放。当你不再需要持有该资源时,你需要调用 [[decRef]] 来减少引用计数。 * - * @return itself + * @returns @en The asset itself. @zh 此资源本身。 * */ public addRef (): Asset { @@ -271,12 +309,12 @@ export class Asset extends Eventify(CCObject) { /** * @en - * Reduce references of asset and it will be auto released when refCount equals 0. + * Decrease the reference count and it will be auto released when refCount equals 0. * * @zh - * 减少资源的引用并尝试进行自动释放。 + * 减少资源的引用,如果引用数量为 0,则将自动释放该资源。 * - * @return itself + * @return @en The asset itself. @zh 此资源本身。 * */ public decRef (autoRelease = true): Asset { @@ -289,17 +327,52 @@ export class Asset extends Eventify(CCObject) { return this; } + /** + * @en + * A callback after the asset is loaded that you can use to initialize the asset's internal data. + * + * @zh + * 资源加载后的回调,你可以用于初始化资源的内部数据。 + * + * @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances. + */ public onLoaded () {} + /** + * @en + * Initializes default asset. + * + * @zh + * 初始化为默认资源。 + * + * @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances. + */ public initDefault (uuid?: string) { if (uuid) { this._uuid = uuid; } this.isDefault = true; } + /** + * @en + * Used to verify this asset is an available asset. + * + * @zh + * 用于验证此资源是否为可用资源。 + * + * @returns @zh 是否是可用资源。@en Whether this asset is available or not. + * @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances. + */ public validate (): boolean { return true; } + /** + * @en + * Destroy this asset and its internal data. + * + * @zh + * 销毁此资源以及其内部数据。 + */ public destroy () { debug(getError(12101, this._uuid)); return super.destroy(); diff --git a/cocos/asset/assets/buffer-asset.ts b/cocos/asset/assets/buffer-asset.ts index a293e8301a..c22ac469ba 100644 --- a/cocos/asset/assets/buffer-asset.ts +++ b/cocos/asset/assets/buffer-asset.ts @@ -26,6 +26,13 @@ import { ccclass, override } from 'cc.decorator'; import { assertIsNonNullable, cclegacy } from '../../core'; import { Asset } from './asset'; +/** + * @en + * `BufferAsset` is a kind of assets whose internal data is a section of memory buffer + * that you can access through the [[BufferAsset.buffer]] function. + * @zh + * `BufferAsset` 是一类资产,其内部数据是一段内存缓冲,你可以通过 [[BufferAsset.buffer]] 函数获取其内部数据。 + */ @ccclass('cc.BufferAsset') export class BufferAsset extends Asset { private _buffer: ArrayBuffer | null = null; diff --git a/cocos/asset/assets/effect-asset.ts b/cocos/asset/assets/effect-asset.ts index 018cc78e79..4b58246482 100644 --- a/cocos/asset/assets/effect-asset.ts +++ b/cocos/asset/assets/effect-asset.ts @@ -211,8 +211,10 @@ const legacyBuiltinEffectNames = [ @ccclass('cc.EffectAsset') export class EffectAsset extends Asset { /** - * @en Register the effect asset to the static map + * @en Register the effect asset to the static map. * @zh 将指定 effect 注册到全局管理器。 + * + * @param asset @en The effect asset to be registered. @zh 待注册的 effect asset。 */ public static register (asset: EffectAsset) { EffectAsset._effects[asset.name] = asset; @@ -222,6 +224,8 @@ export class EffectAsset extends Asset { /** * @en Unregister the effect asset from the static map * @zh 将指定 effect 从全局管理器移除。 + * + * @param asset - @en The effect asset to be removed. @zh 待移除的 effect asset。 */ public static remove (asset: EffectAsset | string) { if (typeof asset !== 'string') { @@ -240,8 +244,11 @@ export class EffectAsset extends Asset { } /** - * @en Get the effect asset by the given name. + * @en Gets the effect asset by the given name. * @zh 获取指定名字的 effect 资源。 + * + * @param name - @en The name of effect you want to get. @zh 想要获取的 effect 的名字。 + * @returns @en The effect. @zh 你查询的 effect. */ public static get (name: string) { if (EffectAsset._effects[name]) { return EffectAsset._effects[name]; } @@ -257,14 +264,28 @@ export class EffectAsset extends Asset { } /** - * @en Get all registered effect assets. + * @en Gets all registered effect assets. * @zh 获取所有已注册的 effect 资源。 + * @returns @en All registered effects. @zh 所有已注册的 effect 资源。 */ public static getAll () { return EffectAsset._effects; } + + /** + * @engineInternal + */ protected static _effects: Record = {}; + /** + * @engineInternal + */ public static isLayoutValid (): boolean { return EffectAsset._layoutValid; } + /** + * @engineInternal + */ public static setLayoutValid (): void { EffectAsset._layoutValid = true; } + /** + * @engineInternal + */ protected static _layoutValid = true; /** @@ -291,13 +312,17 @@ export class EffectAsset extends Asset { @editable public combinations: EffectAsset.IPreCompileInfo[] = []; + /** + * @en Whether to hide in editor mode. + * @zh 是否在编辑器内隐藏。 + */ @serializable @editorOnly public hideInEditor = false; /** - * @en The loaded callback which should be invoked by the [[CCLoader]], will automatically register the effect. - * @zh 通过 [[CCLoader]] 加载完成时的回调,将自动注册 effect 资源。 + * @en The loaded callback which should be invoked by the [[AssetManager]], will automatically register the effect. + * @zh 通过 [[AssetManager]] 加载完成时的回调,将自动注册 effect 资源。 */ public onLoaded () { if (cclegacy.rendering && cclegacy.rendering.enableEffectImport) { @@ -310,6 +335,9 @@ export class EffectAsset extends Asset { if (!EDITOR || cclegacy.GAME_VIEW) { cclegacy.game.once(cclegacy.Game.EVENT_RENDERER_INITED, this._precompile, this); } } + /** + * @engineInternal + */ protected _precompile () { if (cclegacy.rendering && cclegacy.rendering.enableEffectImport) { (cclegacy.rendering.programLib as ProgramLibrary).precompileEffect(deviceManager.gfxDevice, this); diff --git a/cocos/asset/assets/image-asset.ts b/cocos/asset/assets/image-asset.ts index b1d42e0f1b..7620011c45 100644 --- a/cocos/asset/assets/image-asset.ts +++ b/cocos/asset/assets/image-asset.ts @@ -24,7 +24,7 @@ // @ts-check import { ccclass, override } from 'cc.decorator'; -import { EDITOR, ALIPAY, XIAOMI, JSB, TEST, BAIDU } from 'internal:constants'; +import { EDITOR, ALIPAY, XIAOMI, JSB, TEST, BAIDU, TAOBAO } from 'internal:constants'; import { Device, Format, FormatFeatureBit, deviceManager } from '../../gfx'; import { Asset } from './asset'; import { PixelFormat } from './asset-enum'; @@ -163,7 +163,7 @@ function fetchImageSource (imageSource: ImageSource) { // 返回该图像源是否是平台提供的图像对象。 function isNativeImage (imageSource: ImageSource): imageSource is (HTMLImageElement | HTMLCanvasElement | ImageBitmap) { - if (ALIPAY || XIAOMI || BAIDU) { + if (ALIPAY || TAOBAO || XIAOMI || BAIDU) { // We're unable to grab the constructors of Alipay native image or canvas object. return !('_data' in imageSource); } @@ -175,8 +175,8 @@ function isNativeImage (imageSource: ImageSource): imageSource is (HTMLImageElem } /** - * @en Image Asset. - * @zh 图像资源。 + * @en Image Asset. The image resource stores the raw data of the image and you can use this resource to create any Texture resource. + * @zh 图像资源。图像资源存储了图像的原始数据,你可以使用此资源来创建任意 [[TextureBase]] 资源。 */ @ccclass('cc.ImageAsset') export class ImageAsset extends Asset { @@ -202,8 +202,8 @@ export class ImageAsset extends Asset { * * * * * ****************************** * * ************************************* - * @param files @zh 压缩纹理数组 @en Compressed Texture Arrays - * @returns out @zh 合并后的压缩纹理数据 @en Merged compressed texture data + * @param files @zh 压缩纹理数组。 @en Compressed Texture Arrays. + * @returns out @zh 合并后的压缩纹理数据。 @en Merged compressed texture data. */ public static mergeCompressedTextureMips (files: ArrayBuffer[] | ArrayBufferView[]) { let out = new Uint8Array(0); @@ -253,8 +253,8 @@ export class ImageAsset extends Asset { } /** - * @param file 解析压缩纹理 - * @param type 压缩纹理类型 + * @param file 解析压缩纹理。 + * @param type 压缩纹理类型。 * @engineInternal */ public static parseCompressedTextures (file: ArrayBuffer | ArrayBufferView, type: number) { @@ -296,13 +296,13 @@ export class ImageAsset extends Asset { } /** - * @zh 解析压缩纹理 - * @param file @zh ccon 文件 - * @param levelIndex @zh 当前 mipmap 层级 - * @param beginOffset @zh 压缩纹理开始时的偏移 - * @param endOffset @zh 压缩纹理结束时的偏移 - * @param type @zh 压缩纹理类型 - * @param out @zh 压缩纹理输出 + * @zh 解析压缩纹理。 + * @param file @zh 压缩纹理原始数据。 + * @param levelIndex @zh 当前 mipmap 层级。 + * @param beginOffset @zh 压缩纹理开始时的偏移。 + * @param endOffset @zh 压缩纹理结束时的偏移。 + * @param type @zh 压缩纹理类型。 + * @param out @zh 压缩纹理输出。 * @engineInternal */ public static parseCompressedTexture (file: ArrayBuffer | ArrayBufferView, levelIndex: number, @@ -323,12 +323,12 @@ export class ImageAsset extends Asset { } /** - * @zh 解析 PVR 格式的压缩纹理 - * @param file @zh ccon 文件 - * @param levelIndex @zh 当前 mipmap 层级 - * @param beginOffset @zh 压缩纹理开始时的偏移 - * @param endOffset @zh 压缩纹理结束时的偏移 - * @param out @zh 压缩纹理输出 + * @zh 解析 PVR 格式的压缩纹理。 + * @param file @zh 压缩纹理原始数据。 + * @param levelIndex @zh 当前 mipmap 层级。 + * @param beginOffset @zh 压缩纹理开始时的偏移。 + * @param endOffset @zh 压缩纹理结束时的偏移。 + * @param out @zh 压缩纹理输出。 * @engineInternal */ public static parsePVRTexture (file: ArrayBuffer | ArrayBufferView, levelIndex: number, @@ -375,12 +375,12 @@ export class ImageAsset extends Asset { } /** - * @zh 解析 PKM 格式的压缩纹理 - * @param file @zh ccon 文件 - * @param levelIndex @zh 当前 mipmap 层级 - * @param beginOffset @zh 压缩纹理开始时的偏移 - * @param endOffset @zh 压缩纹理结束时的偏移 - * @param out @zh 压缩纹理输出 + * @zh 解析 PKM 格式的压缩纹理。 + * @param file @zh 压缩纹理原始数据。 + * @param levelIndex @zh 当前 mipmap 层级。 + * @param beginOffset @zh 压缩纹理开始时的偏移。 + * @param endOffset @zh 压缩纹理结束时的偏移。 + * @param out @zh 压缩纹理输出。 * @engineInternal */ public static parsePKMTexture (file: ArrayBuffer | ArrayBufferView, levelIndex: number, @@ -409,12 +409,12 @@ export class ImageAsset extends Asset { } /** - * @zh 解析 ASTC 格式的压缩纹理 - * @param file @zh ccon 文件 - * @param levelIndex @zh 当前 mipmap 层级 - * @param beginOffset @zh 压缩纹理开始时的偏移 - * @param endOffset @zh 压缩纹理结束时的偏移 - * @param out @zh 压缩纹理输出 + * @zh 解析 ASTC 格式的压缩纹理。 + * @param file @zh 压缩纹理原始数据。 + * @param levelIndex @zh 当前 mipmap 层级。 + * @param beginOffset @zh 压缩纹理开始时的偏移。 + * @param endOffset @zh 压缩纹理结束时的偏移。 + * @param out @zh 压缩纹理输出。 * @engineInternal */ public static parseASTCTexture (file: ArrayBuffer | ArrayBufferView, levelIndex: number, @@ -571,7 +571,7 @@ export class ImageAsset extends Asset { /** * @en Reset the source of the image asset. * @zh 重置此图像资源使用的原始图像源。 - * @param data The new source + * @param data @en The new source. @zh 新的图片数据源。 */ public reset (data: ImageSource) { if (isImageBitmap(data)) { @@ -602,7 +602,7 @@ export class ImageAsset extends Asset { // SERIALIZATION /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + * @engineInternal */ // eslint-disable-next-line consistent-return public _serialize () { @@ -631,7 +631,7 @@ export class ImageAsset extends Asset { } /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + * @engineInternal */ public _deserialize (data: any) { let fmtStr = ''; diff --git a/cocos/asset/assets/json-asset.ts b/cocos/asset/assets/json-asset.ts index f1be660d7b..2afb8edc08 100644 --- a/cocos/asset/assets/json-asset.ts +++ b/cocos/asset/assets/json-asset.ts @@ -39,7 +39,7 @@ export default class JsonAsset extends Asset { */ @serializable @editable - public json: object | null = null; + public json: Record | null = null; } cclegacy.JsonAsset = JsonAsset; diff --git a/cocos/asset/assets/material.ts b/cocos/asset/assets/material.ts index cc829215c5..ef14680e7a 100644 --- a/cocos/asset/assets/material.ts +++ b/cocos/asset/assets/material.ts @@ -98,23 +98,44 @@ export class Material extends Asset { return hash; } + /** + * @engineInternal + */ @type(EffectAsset) protected _effectAsset: EffectAsset | null = null; + /** + * @internal + */ @serializable protected _techIdx = 0; + /** + * @internal + */ @serializable protected _defines: MacroRecord[] = []; + /** + * @internal + */ @serializable protected _states: PassOverrides[] = []; + /** + * @internal + */ @serializable protected _props: Record[] = []; + /** + * @internal + */ protected _passes: Pass[] = []; + /** + * @internal + */ protected _hash = 0; constructor () { @@ -162,16 +183,16 @@ export class Material extends Asset { } /** - * @en The parent material - * @zh 父材质 + * @en The parent material. + * @zh 父材质。 */ get parent (): Material | null { return null; } /** - * @en The owner render component - * @zh 该材质所归属的渲染组件 + * @en The owner render component. + * @zh 该材质所归属的渲染组件。 */ get owner (): Renderer | null { return null; @@ -180,7 +201,7 @@ export class Material extends Asset { /** * @en Initialize this material with the given information. * @zh 根据所给信息初始化这个材质,初始化正常结束后材质即可立即用于渲染。 - * @param info Material description info. + * @param info @en Material description info. @zh 材质描述信息 */ public initialize (info: IMaterialInfo) { if (this._passes.length) { @@ -195,6 +216,12 @@ export class Material extends Asset { this._update(); } + /** + * @en Reset the material with the given information. + * @zh 使用指定的信息重置该材质。 + * + * @param info @en Material description info. @zh 材质描述信息。 + */ public reset (info: IMaterialInfo) { // to be consistent with other assets this.initialize(info); } @@ -219,8 +246,8 @@ export class Material extends Asset { /** * @en Recompile the shader with the specified macro overrides. Allowed only on material instances. * @zh 使用指定预处理宏重新编译当前 pass(数组)中的 shader。只允许对材质实例执行。 - * @param overrides The shader macro override values. - * @param passIdx The pass to apply to. Will apply to all passes if not specified. + * @param overrides @en The shader macro override values. @zh 宏的覆盖值,用于编译不同 Shader 变体。 + * @param passIdx @en The pass to apply to. Will apply to all passes if not specified. @zh 要重编的 pass 索引,如果没有指定,则重编所有 pass。 */ public recompileShaders (overrides: MacroRecord, passIdx?: number) { console.warn(`Shaders in material asset '${this.name}' cannot be modified at runtime, please instantiate the material first.`); @@ -237,8 +264,8 @@ export class Material extends Asset { } /** - * @en Callback function after material is loaded in [[CCLoader]]. Initialize the resources automatically. - * @zh 通过 [[CCLoader]] 加载完成时的回调,将自动初始化材质资源。 + * @en Callback function after material is loaded in [[AssetManager]]. Initialize the resources automatically. + * @zh 通过 [[AssetManager]] 加载完成时的回调,将自动初始化材质资源。 */ public onLoaded () { this._update(); @@ -247,7 +274,7 @@ export class Material extends Asset { /** * @en Reset all the uniforms to the default value specified in [[EffectAsset]]. * @zh 重置材质的所有 uniform 参数数据为 [[EffectAsset]] 中的默认初始值。 - * @param clearPasses Will the rendering data be cleared too? + * @param clearPasses @en Whether to clear the rendering data too. @zh 是否同时清空渲染数据。 */ public resetUniforms (clearPasses = true) { this._props.length = this._passes.length; @@ -266,9 +293,11 @@ export class Material extends Asset { * @zh * 设置材质 uniform 参数的统一入口。
* 注意如果需要每帧更新 uniform,建议使用 [[renderer.Pass.setUniform]] 以获得更好的性能。 - * @param name The target uniform name. - * @param val The target value. - * @param passIdx The pass to apply to. Will apply to all passes if not specified. + * @param name @en The target uniform name. @zh 目标 Uniform 名称。 + * @param val @en The target value. @zh 需要设置的目标值。 + * @param passIdx + * @en The pass to apply to. Will apply to all passes if not specified. + * @zh 设置此属性的 pass 索引,如果没有指定,则会设置此属性到所有 pass 上。 */ public setProperty (name: string, val: MaterialPropertyFull | MaterialPropertyFull[], passIdx?: number) { let success = false; @@ -297,15 +326,18 @@ export class Material extends Asset { /** * @en - * Get the specified uniform value for this material.
+ * Gets the specified uniform value for this material.
* Note that only uniforms set through [[Material.setProperty]] can be acquired here.
* For the complete rendering data, use [[renderer.Pass.getUniform]] instead. * @zh * 获取当前材质的指定 uniform 参数的值。
* 注意只有通过 [[Material.setProperty]] 函数设置的参数才能从此函数取出,
* 如需取出完整的渲染数据,请使用 [[renderer.Pass.getUniform]]。 - * @param name The property or uniform name. - * @param passIdx The target pass index. If not specified, return the first found value in all passes. + * @param name @en The property or uniform name. @zh 属性或 Uniform 的名称。 + * @param passIdx + * @en The target pass index. If not specified, return the first found value in all passes. + * @zh 目标 pass 索引,如果没指定,则返回所有 pass 中第一个找到的值。 + * @return @en The acquired material properties. @zh 获取的材质属性。 */ public getProperty (name: string, passIdx?: number): Readonly { if (passIdx === undefined) { // try get property in all possible passes @@ -326,8 +358,8 @@ export class Material extends Asset { /** * @en Copy the target material, with optional overrides. * @zh 复制目标材质到当前实例,允许提供重载信息。 - * @param mat The material to be copied. - * @param overrides The overriding states on top of the original material. + * @param mat @en The material to be copied. @zh 需要拷贝的原始材质。 + * @param overrides @en The overriding states on top of the original material. @zh 需要在原始材质上覆盖的状态。 */ public copy (mat: Material, overrides?: IMaterialInfo) { this._techIdx = mat._techIdx; @@ -348,6 +380,9 @@ export class Material extends Asset { this._update(); } + /** + * @engineInternal + */ protected _fillInfo (info: IMaterialInfo) { if (info.technique !== undefined) { this._techIdx = info.technique; } if (info.effectAsset) { @@ -359,6 +394,9 @@ export class Material extends Asset { if (info.states) { this._prepareInfo(info.states, this._states); } } + /** + * @engineInternal + */ protected _prepareInfo (patch: Record | Record[], cur: Record[]) { let patchArray = patch; if (!Array.isArray(patchArray)) { // fill all the passes if not specified @@ -370,6 +408,9 @@ export class Material extends Asset { } } + /** + * @engineInternal + */ protected _createPasses () { const tech = this._effectAsset!.techniques[this._techIdx || 0]; if (!tech) { return []; } @@ -394,6 +435,9 @@ export class Material extends Asset { return passes; } + /** + * @engineInternal + */ protected _update (keepProps = true) { if (this._effectAsset) { this._passes = this._createPasses(); @@ -418,6 +462,9 @@ export class Material extends Asset { this._hash = Material.getHash(this); } + /** + * @engineInternal + */ protected _uploadProperty (pass: Pass, name: string, val: MaterialPropertyFull | MaterialPropertyFull[]) { const handle = pass.getHandle(name); if (!handle) { return false; } @@ -448,6 +495,9 @@ export class Material extends Asset { return true; } + /** + * @engineInternal + */ protected _bindTexture (pass: Pass, handle: number, val: MaterialPropertyFull, index?: number) { const binding = Pass.getBindingFromHandle(handle); if (val instanceof Texture) { @@ -463,6 +513,9 @@ export class Material extends Asset { } } + /** + * @engineInternal + */ protected _doDestroy () { if (this._passes && this._passes.length) { for (const pass of this._passes) { diff --git a/cocos/asset/assets/render-texture.ts b/cocos/asset/assets/render-texture.ts index 1761837f37..d18846da0b 100644 --- a/cocos/asset/assets/render-texture.ts +++ b/cocos/asset/assets/render-texture.ts @@ -69,7 +69,7 @@ export class RenderTexture extends TextureBase { /** * @en Initialize the render texture. Using IRenderTextureCreateInfo. * @zh 初始化渲染贴图。设置渲染贴图的名称、尺寸、渲染通道信息。 - * @param info @en The create info of render texture @zh 渲染贴图的创建信息 + * @param info @en The create info of render texture. @zh 渲染贴图的创建信息。 */ public initialize (info: IRenderTextureCreateInfo) { this._name = info.name || ''; @@ -81,7 +81,7 @@ export class RenderTexture extends TextureBase { /** * @en Reset the render texture. User may change the name, size or render pass info of the render texture. * @zh 重新初始化渲染贴图。用户可以更改渲染贴图的名称、尺寸、渲染通道信息。 - * @param info @en The create info of render texture @zh 渲染贴图的创建信息 + * @param info @en The create info of render texture. @zh 渲染贴图的创建信息。 */ public reset (info: IRenderTextureCreateInfo) { // to be consistent with other assets this.initialize(info); @@ -102,10 +102,10 @@ export class RenderTexture extends TextureBase { } /** - * @en Resize the render texture - * @zh 修改渲染贴图的尺寸 - * @param width The pixel width, the range is from 1 to 2048 - * @param height The pixel height, the range is from 1 to 2048 + * @en Resize the render texture. + * @zh 修改渲染贴图的尺寸。 + * @param width @en The pixel width to resize to, the range is from 1 to 2048. @zh 需要调整到的像素宽度,范围为 1-2048。 + * @param height @en The pixel height to resize to, the range is from 1 to 2048. @zh 需要调整到的像素高度,范围为 1-2048。 */ public resize (width: number, height: number) { this._width = Math.floor(clamp(width, 1, 2048)); @@ -139,16 +139,17 @@ export class RenderTexture extends TextureBase { // To be compatible with material property interface /** - * @en Gets the related [[gfx.Texture]] resource, it's also the color attachment for the render window - * @zh 获取渲染贴图的 GFX 资源,同时也是渲染窗口所指向的颜色缓冲贴图资源 + * @en Gets the related [[gfx.Texture]] resource, it's also the color attachment for the render window. + * @zh 获取渲染贴图的 GFX 资源,同时也是渲染窗口所指向的颜色缓冲贴图资源。 + * @return @en The low level gfx texture. @zh 底层的 gfx 贴图。 */ public getGFXTexture (): Texture | null { return this._window && this._window.framebuffer.colorTextures[0]; } /** - * @en Callback function after render texture is loaded in [[CCLoader]]. Initialize the render texture. - * @zh 通过 [[CCLoader]] 加载完成时的回调,初始化渲染贴图。 + * @en Callback function after render texture is loaded in [[AssetManager]]. Initialize the render texture. + * @zh 通过 [[AssetManager]] 加载完成时的回调,初始化渲染贴图。 */ public onLoaded () { this._initWindow(); @@ -157,7 +158,8 @@ export class RenderTexture extends TextureBase { /** * @en Implementation of the render texture initialization. * @zh 初始化渲染贴图的具体实现。 - * @param info @en The create info of render texture @zh 渲染贴图的创建信息 + * @param info @en The create info of render texture. @zh 渲染贴图的创建信息。 + * @engineInternal */ protected _initWindow (info?: IRenderTextureCreateInfo) { const root = cclegacy.director.root as Root; @@ -182,8 +184,9 @@ export class RenderTexture extends TextureBase { /** * @en Initialize the render texture with uuid. The default size is 1x1. - * @zh 初始化渲染贴图。使用uuid进行初始化,贴图的尺寸为 1x1。 - * @param uuid @en asset uuid @zh 资源 uuid + * @zh 初始化渲染贴图。使用 uuid 进行初始化,贴图的尺寸为 1x1。 + * @param uuid @en asset uuid. @zh 资源 uuid。 + * @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances. */ public initDefault (uuid?: string) { super.initDefault(uuid); @@ -194,20 +197,21 @@ export class RenderTexture extends TextureBase { /** * @en Validate the correctness of the render texture. * @zh 验证渲染贴图的正确性。 + * @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances. */ public validate () { return this.width >= 1 && this.width <= 2048 && this.height >= 1 && this.height <= 2048; } /** - * @en Read pixel buffer from render texture @zh 从 render texture 读取像素数据 - * @param x @en The location on x axis @zh 起始位置X轴坐标 - * @param y @en The location on y axis @zh 起始位置Y轴坐标 - * @param width @en The pixel width @zh 像素宽度 - * @param height @en The pixel height @zh 像素高度 - * @param buffer @en The buffer to hold pixel data @zh 像素缓存 + * @en Read pixel buffer from render texture. @zh 从 render texture 读取像素数据。 + * @param x @en The location on x axis. @zh 起始位置X轴坐标。 + * @param y @en The location on y axis. @zh 起始位置Y轴坐标。 + * @param width @en The pixel width. @zh 像素宽度。 + * @param height @en The pixel height. @zh 像素高度。 + * @param buffer @en The buffer to hold pixel data. @zh 像素缓存。 */ - public readPixels (x = 0, y = 0, width?: number, height?: number, buffer?: Uint8Array) : Uint8Array | null { + public readPixels (x = 0, y = 0, width?: number, height?: number, buffer?: Uint8Array): Uint8Array | null { width = width || this.width; height = height || this.height; const gfxTexture = this.getGFXTexture(); diff --git a/cocos/asset/assets/rendering-sub-mesh.ts b/cocos/asset/assets/rendering-sub-mesh.ts index 494abe068b..d0aec9626b 100644 --- a/cocos/asset/assets/rendering-sub-mesh.ts +++ b/cocos/asset/assets/rendering-sub-mesh.ts @@ -37,38 +37,38 @@ import { Mesh } from '../../3d/assets/mesh'; export type IBArray = Uint8Array | Uint16Array | Uint32Array; /** - * @en The interface of geometric information + * @en The interface of geometric information. * @zh 几何信息。 */ export interface IGeometricInfo { /** - * @en Vertex positions + * @en Vertex positions. * @zh 顶点位置。 */ positions: Float32Array; /** - * @en Indices data + * @en Indices data. * @zh 索引数据。 */ indices?: IBArray; /** - * @en Whether the geometry is treated as double sided + * @en Whether the geometry is treated as double sided. * @zh 是否将图元按双面对待。 */ doubleSided?: boolean; /** - * @en The bounding box + * @en The bounding box. * @zh 此几何体的轴对齐包围盒。 */ boundingBox: { max: Vec3 | Readonly; min: Vec3 | Readonly }; } /** - * @en Flat vertex buffer - * @zh 扁平化顶点缓冲区 + * @en Flat vertex buffer. + * @zh 扁平化顶点缓冲区。 */ export interface IFlatBuffer { stride: number; @@ -83,17 +83,17 @@ export interface IFlatBuffer { export class RenderingSubMesh { /** * @en - * mesh object where this sub mesh locates + * mesh object where this sub mesh locates. * @zh - * 子网格所处的网格模型对象 + * 子网格所处的网格模型对象。 */ public mesh?: Mesh; /** * @en - * sub mesh's index in mesh + * sub mesh's index in mesh. * @zh - * 子网格在网格模型中的索引 + * 子网格在网格模型中的索引。 */ public subMeshIdx?: number; @@ -125,14 +125,14 @@ export class RenderingSubMesh { /** * @en - * sub mesh's constructor + * sub mesh's constructor. * @zh - * 子网格构造函数 - * @param vertexBuffers @en vertex buffers @zh 顶点缓冲区数组 - * @param attributes @en vertex attributes @zh 顶点属性数组 - * @param primitiveMode @en primitive mode @zh 图元类型 - * @param indexBuffer @en index buffer @zh 索引缓冲区 - * @param indirectBuffer @en indirect buffer @zh 间接缓冲区 + * 子网格构造函数。 + * @param vertexBuffers @en vertex buffers. @zh 顶点缓冲区数组。 + * @param attributes @en vertex attributes. @zh 顶点属性数组。 + * @param primitiveMode @en primitive mode. @zh 图元类型。 + * @param indexBuffer @en index buffer. @zh 索引缓冲区。 + * @param indirectBuffer @en indirect buffer. @zh 间接缓冲区。 */ constructor ( vertexBuffers: Buffer[], attributes: Attribute[], primitiveMode: PrimitiveMode, @@ -149,31 +149,31 @@ export class RenderingSubMesh { } /** - * @en All vertex attributes used by the sub mesh + * @en All vertex attributes used by the sub mesh. * @zh 所有顶点属性。 */ get attributes () { return this._attributes; } /** - * @en All vertex buffers used by the sub mesh + * @en All vertex buffers used by the sub mesh. * @zh 使用的所有顶点缓冲区。 */ get vertexBuffers () { return this._vertexBuffers; } /** - * @en Index buffer used by the sub mesh + * @en Index buffer used by the sub mesh. * @zh 使用的索引缓冲区,若未使用则无需指定。 */ get indexBuffer () { return this._indexBuffer; } /** - * @en Indirect buffer used by the sub mesh + * @en Indirect buffer used by the sub mesh. * @zh 间接绘制缓冲区。 */ get indirectBuffer () { return this._indirectBuffer; } /** - * @en Primitive mode used by the sub mesh + * @en Primitive mode used by the sub mesh. * @zh 图元类型。 */ get primitiveMode () { return this._primitiveMode; } @@ -234,8 +234,8 @@ export class RenderingSubMesh { public invalidateGeometricInfo () { this._geometricInfo = undefined; } /** - * @en the draw range - * @zh 渲染范围 + * @en the draw range. + * @zh 渲染范围。 */ set drawInfo (info: DrawInfo | null | undefined) { this._drawInfo = info; @@ -246,13 +246,13 @@ export class RenderingSubMesh { } /** - * @en Flatted vertex buffers + * @en Flatted vertex buffers. * @zh 扁平化的顶点缓冲区。 */ get flatBuffers () { return this._flatBuffers; } /** - * @en generate flatted vertex buffers + * @en generate flatted vertex buffers. * @zh 生成扁平化的顶点缓冲区。 */ public genFlatBuffers () { @@ -292,7 +292,7 @@ export class RenderingSubMesh { } /** - * @en The vertex buffer for joint after mapping + * @en The vertex buffer for joint after mapping. * @zh 骨骼索引按映射表处理后的顶点缓冲。 */ get jointMappedBuffers () { @@ -344,14 +344,14 @@ export class RenderingSubMesh { } /** - * @en The input assembler info - * @zh 输入汇集器信息 + * @en The input assembler info. + * @zh 输入汇集器信息。 */ get iaInfo () { return this._iaInfo; } /** - * @en destroy sub mesh - * @zh 销毁子网格 + * @en Destroys sub mesh. + * @zh 销毁子网格。 */ public destroy () { for (let i = 0; i < this.vertexBuffers.length; i++) { diff --git a/cocos/asset/assets/simple-texture.ts b/cocos/asset/assets/simple-texture.ts index 6fc118a9da..dfef7d0295 100644 --- a/cocos/asset/assets/simple-texture.ts +++ b/cocos/asset/assets/simple-texture.ts @@ -59,27 +59,40 @@ function canGenerateMipmap (device: Device, w: number, h: number) { */ @ccclass('cc.SimpleTexture') export class SimpleTexture extends TextureBase { + /** + * @engineInternal + */ protected _gfxTexture: Texture | null = null; + /** + * @engineInternal + */ protected _gfxTextureView: Texture | null = null; private _mipmapLevel = 1; // Cache these data to reduce JSB invoking. private _textureWidth = 0; private _textureHeight = 0; + /** + * @engineInternal + */ protected _baseLevel = 0; + /** + * @engineInternal + */ protected _maxLevel = 1000; /** - * @en The mipmap level of the texture - * @zh 贴图中的 Mipmap 层级数量 + * @en The mipmap level of the texture. + * @zh 贴图中的 Mipmap 层级数量。 */ get mipmapLevel () { return this._mipmapLevel; } /** - * @en The GFX Texture resource + * @en The GFX Texture resource. * @zh 获取此贴图底层的 GFX 贴图对象。 + * @return @en The low level gfx texture. @zh 底层的 GFX 贴图。 */ public getGFXTexture () { return this._gfxTextureView; @@ -103,8 +116,8 @@ export class SimpleTexture extends TextureBase { * @en Update the given level mipmap image. * @zh 更新指定层级范围内的 Mipmap。当 Mipmap 数据发生了改变时应调用此方法提交更改。 * 若指定的层级范围超出了实际已有的层级范围,只有覆盖的那些层级范围会被更新。 - * @param firstLevel First level to be updated - * @param count Mipmap level count to be updated + * @param firstLevel @en First level to be updated. @zh 更新指定层的 mipmap。 + * @param count @en Mipmap level count to be updated。 @zh 指定要更新层的数量。 */ public updateMipmaps (firstLevel = 0, count?: number) { @@ -123,9 +136,9 @@ export class SimpleTexture extends TextureBase { * - 若图像的尺寸与 Mipmap 的尺寸相同,上传后整个 Mipmap 的数据将与图像数据一致; * - 若图像的尺寸小于指定层级 Mipmap 的尺寸(不管是长或宽),则从贴图左上角开始,图像尺寸范围内的 Mipmap 会被更新; * - 若图像的尺寸超出了指定层级 Mipmap 的尺寸(不管是长或宽),都将引起错误。 - * @param source The source image or image data - * @param level Mipmap level to upload the image to - * @param arrayIndex The array index + * @param source @en The source image or image data. @zh 源图像或图像数据。 + * @param level @en Mipmap level to upload the image to. @zh 要上传的 mipmap 层级。 + * @param arrayIndex @en The array index. @zh 要上传的数组索引。 */ public uploadData (source: HTMLCanvasElement | HTMLImageElement | ArrayBufferView | ImageBitmap, level = 0, arrayIndex = 0) { if (!this._gfxTexture || this._mipmapLevel <= level) { @@ -159,6 +172,9 @@ export class SimpleTexture extends TextureBase { } } + /** + * @engineInternal + */ protected _assignImage (image: ImageAsset, level: number, arrayIndex?: number) { const data = image.data; if (!data) { @@ -177,10 +193,16 @@ export class SimpleTexture extends TextureBase { } } + /** + * @engineInternal + */ protected _checkTextureLoaded () { this._textureReady(); } + /** + * @engineInternal + */ protected _textureReady () { this.loaded = true; this.emit('load'); @@ -193,11 +215,16 @@ export class SimpleTexture extends TextureBase { * @zh * 设置此贴图的 mipmap 层级 * @param value The mipmap level. + * @engineInternal + * */ protected _setMipmapLevel (value: number) { this._mipmapLevel = value < 1 ? 1 : value; } + /** + * @engineInternal + */ protected _setMipRange (baseLevel: number, maxLevel: number) { this._baseLevel = baseLevel < 1 ? 0 : baseLevel; this._maxLevel = maxLevel < 1 ? 0 : maxLevel; @@ -206,8 +233,8 @@ export class SimpleTexture extends TextureBase { /** * @en Set mipmap level range for this texture. * @zh 设置当前贴图的 mipmap 范围。 - * @param baseLevel The base mipmap level. - * @param maxLevel The maximum mipmap level. + * @param baseLevel @en The base mipmap level. @zh 最低 mipmap 等级。 + * @param maxLevel @en The maximum mipmap level. @zh 最高 mipmap 等级。 */ public setMipRange (baseLevel: number, maxLevel: number) { assertID(baseLevel <= maxLevel, 3124); @@ -229,6 +256,7 @@ export class SimpleTexture extends TextureBase { * @en This method is override by derived classes to provide GFX texture info. * @zh 这个方法被派生类重写以提供 GFX 纹理信息。 * @param presumed The presumed GFX texture info. + * @engineInternal */ protected _getGfxTextureCreateInfo (presumed: PresumedGFXTextureInfo): TextureInfo | null { return null; @@ -238,11 +266,15 @@ export class SimpleTexture extends TextureBase { * @en This method is overrided by derived classes to provide GFX TextureViewInfo. * @zh 这个方法被派生类重写以提供 GFX 纹理视图信息。 * @param presumed The presumed GFX TextureViewInfo. + * @engineInternal */ protected _getGfxTextureViewCreateInfo (presumed: PresumedGFXTextureViewInfo): TextureViewInfo | null { return null; } + /** + * @engineInternal + */ protected _tryReset () { this._tryDestroyTextureView(); this._tryDestroyTexture(); @@ -259,12 +291,15 @@ export class SimpleTexture extends TextureBase { /** * @en Whether mipmaps are baked convolutional maps. - * @zh mipmaps是否为烘焙出来的卷积图。 + * @zh mipmaps 是否为烘焙出来的卷积图。 */ public isUsingOfflineMipmaps (): boolean { return false; } + /** + * @engineInternal + */ protected _createTexture (device: Device) { if (this._width === 0 || this._height === 0) { return; } let flags = TextureFlagBit.NONE; @@ -291,6 +326,9 @@ export class SimpleTexture extends TextureBase { this._gfxTexture = texture; } + /** + * @engineInternal + */ protected _createTextureView (device: Device): Texture | null { if (!this._gfxTexture) { return null; @@ -309,6 +347,9 @@ export class SimpleTexture extends TextureBase { return device.createTexture(textureViewCreateInfo); } + /** + * @engineInternal + */ protected _tryDestroyTexture () { if (this._gfxTexture) { this._gfxTexture.destroy(); @@ -316,6 +357,9 @@ export class SimpleTexture extends TextureBase { } } + /** + * @engineInternal + */ protected _tryDestroyTextureView () { if (this._gfxTextureView) { this._gfxTextureView.destroy(); diff --git a/cocos/asset/assets/text-asset.ts b/cocos/asset/assets/text-asset.ts index 0d702f7f20..400e76de8a 100644 --- a/cocos/asset/assets/text-asset.ts +++ b/cocos/asset/assets/text-asset.ts @@ -28,7 +28,7 @@ import { Asset } from './asset'; import { cclegacy } from '../../core'; /** - * @en Class for text file. + * @en The asset for text file. * @zh 文本资源。 */ @ccclass('cc.TextAsset') diff --git a/cocos/asset/assets/texture-2d.ts b/cocos/asset/assets/texture-2d.ts index 260deef79e..a908cb023f 100644 --- a/cocos/asset/assets/texture-2d.ts +++ b/cocos/asset/assets/texture-2d.ts @@ -34,45 +34,45 @@ import { js, cclegacy } from '../../core'; const compressedImageAsset: ImageAsset[] = []; /** - * @en The create information for [[Texture2D]] + * @en The create information for [[Texture2D]]. * @zh 用来创建贴图的信息。 */ export interface ITexture2DCreateInfo { /** - * @en The pixel width + * @en The pixel width. * @zh 像素宽度。 */ width: number; /** - * @en The pixel height + * @en The pixel height. * @zh 像素高度。 */ height: number; /** - * @en The pixel format + * @en The pixel format. * @zh 像素格式。 * @default PixelFormat.RGBA8888 */ format?: PixelFormat; /** - * @en The mipmap level count + * @en The mipmap level count. * @zh mipmap 层级。 * @default 1 */ mipmapLevel?: number; /** - * @en The selected base mipmap level + * @en The selected base mipmap level. * @zh 选择使用的最小 mipmap 层级。 * @default 1 */ baseLevel?: number; /** - * @en The selected maximum mipmap level + * @en The selected maximum mipmap level. * @zh 选择使用的最大 mipmap 层级。 * @default 1000 */ @@ -177,6 +177,9 @@ export class Texture2D extends SimpleTexture { @type([ImageAsset]) public _mipmaps: ImageAsset[] = []; + /** + * @engineInternal + */ public initialize () { this.mipmaps = this._mipmaps; } @@ -190,7 +193,7 @@ export class Texture2D extends SimpleTexture { * After reset, the gfx resource will become invalid, you must use [[uploadData]] explicitly to upload the new mipmaps to GPU resources. * @zh 将当前贴图重置为指定尺寸、像素格式以及指定 mipmap 层级。重置后,贴图的像素数据将变为未定义。 * mipmap 图像的数据不会自动更新到贴图中,你必须显式调用 [[uploadData]] 来上传贴图数据。 - * @param info The create information + * @param info @en The create information. @zh 创建贴图的相关信息。 */ public reset (info: ITexture2DCreateInfo) { this._width = info.width; @@ -251,7 +254,7 @@ export class Texture2D extends SimpleTexture { /** * @en If the level 0 mipmap image is a HTML element, then return it, otherwise return null. * @zh 若此贴图 0 级 Mipmap 的图像资源的实际源存在并为 HTML 元素则返回它,否则返回 `null`。 - * @returns HTML element or `null` + * @returns @en HTMLElement or `null`. @zh HTML 元素或者 null。 * @deprecated Please use [[ImageAsset.data]] instead */ public getHtmlElementObj () { @@ -268,9 +271,9 @@ export class Texture2D extends SimpleTexture { } /** - * @en Gets the description of the 2d texture + * @en Gets the description of the 2d texture. * @zh 返回此贴图的描述。 - * @returns The description + * @returns @en The description. @zh 贴图的描述信息。 */ public description () { const url = this._mipmaps[0] ? this._mipmaps[0].url : ''; @@ -280,7 +283,7 @@ export class Texture2D extends SimpleTexture { /** * @en Release used GPU resources. * @zh 释放占用的 GPU 资源。 - * @deprecated please use [[destroy]] instead + * @deprecated please use [[destroy]] instead. */ public releaseTexture () { this.destroy(); @@ -327,6 +330,9 @@ export class Texture2D extends SimpleTexture { } } + /** + * @engineInternal + */ protected _getGfxTextureCreateInfo (presumed: PresumedGFXTextureInfo) { const texInfo = new TextureInfo(TextureType.TEX2D); texInfo.width = this._width; @@ -335,6 +341,9 @@ export class Texture2D extends SimpleTexture { return texInfo; } + /** + * @engineInternal + */ protected _getGfxTextureViewCreateInfo (presumed: PresumedGFXTextureViewInfo) { const texViewInfo = new TextureViewInfo(); texViewInfo.type = TextureType.TEX2D; diff --git a/cocos/asset/assets/texture-base.ts b/cocos/asset/assets/texture-base.ts index 28e9aaaf91..a474b8d7b4 100644 --- a/cocos/asset/assets/texture-base.ts +++ b/cocos/asset/assets/texture-base.ts @@ -50,7 +50,7 @@ export class TextureBase extends Asset { } /** - * @en Pixel width of the texture + * @en Pixel width of the texture. * @zh 此贴图的像素宽度。 */ public get width (): number { @@ -58,7 +58,7 @@ export class TextureBase extends Asset { } /** - * @en Pixel height of the texture + * @en Pixel height of the texture. * @zh 此贴图的像素高度。 */ public get height (): number { @@ -67,47 +67,77 @@ export class TextureBase extends Asset { /** * @en The pixel format enum. - * @zh 像素格式枚举类型 + * @zh 像素格式枚举类型。 */ public static PixelFormat = PixelFormat; /** * @en The wrap mode enum. - * @zh 环绕模式枚举类型 + * @zh 环绕模式枚举类型。 */ public static WrapMode = WrapMode; /** - * @en The texture filter mode enum - * @zh 纹理过滤模式枚举类型 + * @en The texture filter mode enum. + * @zh 纹理过滤模式枚举类型。 */ public static Filter = Filter; + /** + * @engineInternal + */ @serializable protected _format = PixelFormat.RGBA8888; + /** + * @engineInternal + */ @serializable protected _minFilter = Filter.LINEAR; + /** + * @engineInternal + */ @serializable protected _magFilter = Filter.LINEAR; + /** + * @engineInternal + */ @serializable protected _mipFilter = Filter.NONE; + /** + * @engineInternal + */ @serializable protected _wrapS = WrapMode.REPEAT; + /** + * @engineInternal + */ @serializable protected _wrapT = WrapMode.REPEAT; + /** + * @engineInternal + */ @serializable protected _wrapR = WrapMode.REPEAT; + /** + * @engineInternal + */ @serializable protected _anisotropy = 0; + /** + * @engineInternal + */ protected _width = 1; + /** + * @engineInternal + */ protected _height = 1; private _id: string; @@ -127,27 +157,27 @@ export class TextureBase extends Asset { } /** - * @en Gets the id of the texture + * @en Gets the id of the texture. * @zh 获取标识符。 - * @returns The id + * @returns @en The id of this texture. @zh 此贴图的 id。 */ public getId () { return this._id; } /** - * @en Gets the pixel format + * @en Gets the pixel format. * @zh 获取像素格式。 - * @returns The pixel format + * @returns @en The pixel format. @zh 像素格式。 */ public getPixelFormat () { return this._format; } /** - * @en Gets the anisotropy + * @en Gets the anisotropy. * @zh 获取各向异性。 - * @returns The anisotropy + * @returns @en The anisotropy. @zh 各项异性值。 */ public getAnisotropy () { return this._anisotropy; @@ -158,9 +188,9 @@ export class TextureBase extends Asset { * Be noted, if the size of the texture is not power of two, only [[WrapMode.CLAMP_TO_EDGE]] is allowed. * @zh 设置此贴图的缠绕模式。 * 注意,若贴图尺寸不是 2 的整数幂,缠绕模式仅允许 [[WrapMode.CLAMP_TO_EDGE]]。 - * @param wrapS S(U) coordinate wrap mode - * @param wrapT T(V) coordinate wrap mode - * @param wrapR R(W) coordinate wrap mode + * @param wrapS @en S(U) coordinate wrap mode. @zh S(U) 坐标系缠绕模式. + * @param wrapT @en T(V) coordinate wrap mode. @zh T(V) 坐标系缠绕模式. + * @param wrapR @en R(W) coordinate wrap mode. @zh R(W) 坐标系缠绕模式. */ public setWrapMode (wrapS: WrapMode, wrapT: WrapMode, wrapR?: WrapMode) { if (wrapR === undefined) wrapR = wrapS; // wrap modes should be as consistent as possible for performance @@ -178,10 +208,10 @@ export class TextureBase extends Asset { } /** - * @en Sets the texture's filter mode + * @en Sets the texture's filter mode. * @zh 设置此贴图的过滤算法。 - * @param minFilter Filter mode for scale down - * @param magFilter Filter mode for scale up + * @param minFilter @en Filter mode for scale down. @zh 贴图缩小时使用的过滤模式。 + * @param magFilter @en Filter mode for scale up. @zh 贴图放大时使用的过滤模式。 */ public setFilters (minFilter: Filter, magFilter: Filter) { this._minFilter = minFilter; @@ -195,9 +225,9 @@ export class TextureBase extends Asset { } /** - * @en Sets the texture's mip filter - * @zh 设置此贴图的缩小过滤算法。 - * @param mipFilter Filter mode for scale down + * @en Sets the texture's mip filter mode. + * @zh 设置此贴图的多层 mip 过滤算法。 + * @param mipFilter @en Filter mode for multiple mip level. @zh 多层 mip 过滤模式。 */ public setMipFilter (mipFilter: Filter) { this._mipFilter = mipFilter; @@ -209,9 +239,9 @@ export class TextureBase extends Asset { } /** - * @en Sets the texture's anisotropy + * @en Sets the texture's anisotropy. * @zh 设置此贴图的各向异性。 - * @param anisotropy + * @param anisotropy @en The anisotropy to be set. @zh 待设置的各向异性数值。 */ public setAnisotropy (anisotropy: number) { this._anisotropy = anisotropy; diff --git a/cocos/asset/assets/texture-cube.ts b/cocos/asset/assets/texture-cube.ts index 8a8afac52d..110f6fc43d 100644 --- a/cocos/asset/assets/texture-cube.ts +++ b/cocos/asset/assets/texture-cube.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { EDITOR, TEST, WECHAT } from 'internal:constants'; +import { EDITOR, TEST, VIVO, WECHAT } from 'internal:constants'; import { ccclass, serializable } from 'cc.decorator'; import { TextureType, TextureInfo, TextureViewInfo, BufferTextureCopy } from '../../gfx'; import { ImageAsset } from './image-asset'; @@ -168,10 +168,11 @@ export class TextureCube extends SimpleTexture { } /** - * @en Fill mipmaps with convolutional maps. - * @zh 使用卷积图填充mipmaps。 - * @param value All mipmaps of each face of the cube map are stored in the form of atlas + * @en Fill mipmaps for cube map with atlas. + * @zh 使用 atlas 方式排布的图填充到立方体贴图的 mipmaps。 + * @param value @en All mipmaps of each face of the cube map are stored in the form of atlas * and the value contains the atlas of the 6 faces and the layout information of each mipmap layer. + * @zh 立方体贴图六个面的图,其中每张图中的全部 mip 数据都使用 atlas 方式排布 */ set mipmapAtlas (value: ITextureCubeMipmapAtlas | null) { this._mipmapAtlas = value; @@ -189,7 +190,7 @@ export class TextureCube extends SimpleTexture { } //In ios wechat mini-game platform drawImage and getImageData can not get correct data,so upload to gfxTexture than use readPixels to get data //The performance of upload to gfxTexture and readPixels is not good, so only use this way in the ios wechat mini-game platform - if (WECHAT && sys.os === OS.IOS) { + if ((WECHAT && sys.os === OS.IOS) || VIVO) { this._uploadAtlas(); return; } @@ -315,7 +316,7 @@ export class TextureCube extends SimpleTexture { * After reset, the gfx resource will become invalid, you must use [[uploadData]] explicitly to upload the new mipmaps to GPU resources. * @zh 将当前贴图重置为指定尺寸、像素格式以及指定 mipmap 层级。重置后,贴图的像素数据将变为未定义。 * mipmap 图像的数据不会自动更新到贴图中,你必须显式调用 [[uploadData]] 来上传贴图数据。 - * @param info The create information + * @param info @en The create information. @zh 创建贴图的相关信息。 */ public reset (info: ITextureCubeCreateInfo) { this._width = info.width; @@ -329,6 +330,13 @@ export class TextureCube extends SimpleTexture { this._tryReset(); } + /** + * @en Updates the given level mipmap image. + * @zh 更新指定层级范围内的 Mipmap。当 Mipmap 数据发生了改变时应调用此方法提交更改。 + * 若指定的层级范围超出了实际已有的层级范围,只有覆盖的那些层级范围会被更新。 + * @param firstLevel @en First level to be updated. @zh 更新指定层的 mipmap。 + * @param count @en Mipmap level count to be updated。 @zh 指定要更新层的数量。 + */ public updateMipmaps (firstLevel = 0, count?: number) { if (firstLevel >= this._mipmaps.length) { return; @@ -348,7 +356,7 @@ export class TextureCube extends SimpleTexture { } /** - * @en Destroy this texture, clear all mipmaps and release GPU resources + * @en Destroys this texture, clear all mipmaps and release GPU resources * @zh 销毁此贴图,清空所有 Mipmap 并释放占用的 GPU 资源。 */ public destroy () { diff --git a/cocos/audio/audio-downloader.ts b/cocos/audio/audio-downloader.ts index 88f1c34ada..2ace7a2287 100644 --- a/cocos/audio/audio-downloader.ts +++ b/cocos/audio/audio-downloader.ts @@ -25,11 +25,10 @@ import { AudioPlayer } from 'pal/audio'; import { AudioClip, AudioMeta } from './audio-clip'; -import { CompleteCallback, IDownloadParseOptions } from '../asset/asset-manager/shared'; import downloader from '../asset/asset-manager/downloader'; import factory from '../asset/asset-manager/factory'; -export function loadAudioPlayer (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) { +export function loadAudioPlayer (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) { AudioPlayer.load(url, { audioLoadMode: options.audioLoadMode, }).then((player) => { @@ -47,8 +46,8 @@ export function loadAudioPlayer (url: string, options: IDownloadParseOptions, on function createAudioClip (id: string, data: AudioMeta, - options: IDownloadParseOptions, - onComplete: CompleteCallback) { + options: Record, + onComplete: ((err: Error | null, data?: AudioClip | null) => void)) { const out = new AudioClip(); out._nativeUrl = id; out._nativeAsset = data; diff --git a/cocos/core/data/class-stash.ts b/cocos/core/data/class-stash.ts index 181254dea2..477fa71d37 100644 --- a/cocos/core/data/class-stash.ts +++ b/cocos/core/data/class-stash.ts @@ -26,12 +26,12 @@ import { IExposedAttributes } from './utils/attribute-defines'; /** * Class slash stores information collected from decorators. - * Once class decorator entered, class definition begins. It process the stash and remove it. + * Once the class decorator entered, the class definition begins. It processes the stash and removes it. */ export interface ClassStash { /** - * When extract default values under TypeScript environment, - * we have to construct an object of current class and get its member values. + * When extracting default values under the TypeScript environment, + * We have to construct an object of the current class and get its member values. * This field stores the create-once object. */ default?: unknown; @@ -48,7 +48,7 @@ export interface ClassStash { /** * The error properties. - * We record them here to ensure only once error report is given to each property. + * We record them here to ensure only once an error report is given to each property. */ errorProps?: Record; } @@ -85,17 +85,17 @@ export enum PropertyStashInternalFlag { * Indicates this property is reflected using "standalone property decorators" such as * `@editable`, `@visible`, `serializable`. * All standalone property decorators would set this flag; - * non standalone property decorators won't set this flag. + * non-standalone property decorators won't set this flag. */ STANDALONE = 1 << 0, /** - * Indicates this property is visible, if no other explicit visibility decorators(`@visible`s) attached. + * Indicates this property is visible, if no other explicit visibility decorators(`@visible`s) are attached. */ IMPLICIT_VISIBLE = 1 << 1, /** - * Indicates this property is serializable, if no other explicit visibility decorators(`@serializable`s) attached. + * Indicates this property is serializable, if no other explicit visibility decorators(`@serializable`s) are attached. */ IMPLICIT_SERIALIZABLE = 1 << 2, } diff --git a/cocos/core/data/class.ts b/cocos/core/data/class.ts index 91ca1e0b84..aa128718e1 100644 --- a/cocos/core/data/class.ts +++ b/cocos/core/data/class.ts @@ -56,7 +56,7 @@ function pushUnique (array, item) { } } -// both getter and prop must register the name into __props__ array +// both getter and prop must register the name into `__props__` array function appendProp (cls, name) { if (DEV) { // if (!IDENTIFIER_RE.test(name)) { @@ -197,10 +197,10 @@ function define (className, baseClass, options) { window.EditorExtends && window.EditorExtends.Component.addMenu(cls, `hidden:${renderName}/${className}`, -1); } - // Note: `options.ctor` should be same as `cls` except if + // Note: `options.ctor` should be the same as `cls` except if // cc-class is defined by `cc.Class({/* ... */})`. // In such case, `options.ctor` may be `undefined`. - // So we can not use `options.ctor`. Instead we should use `cls` which is the "real" registered cc-class. + // So we can not use `options.ctor`. Instead, we should use `cls` which is the "real" registered cc-class. EditorExtends.emit('class-registered', cls, frame, className); } @@ -243,7 +243,7 @@ function getNewValueTypeCodeJit (value) { // TODO - move escapeForJS, IDENTIFIER_RE, getNewValueTypeCodeJit to misc.js or a new source file -// convert a normal string including newlines, quotes and unicode characters into a string literal +// convert a normal string including newlines, quotes and Unicode characters into a string literal // ready to use in JavaScript source function escapeForJS (s) { return JSON.stringify(s) @@ -358,7 +358,7 @@ CCClass.Attr = attributeUtils; CCClass.attr = attributeUtils.attr; /** - * Returns if the class is a cc-class or is fast defined. + * Returns if the class is a cc-class or is fast-defined. * @param constructor The constructor of the class. * @returns Judge result. * @engineInternal @@ -478,7 +478,9 @@ function parseAttributes (constructor: Function, attributes: PropertyStash, clas if ('default' in attributes) { (attrs || initAttrs())[`${propertyNamePrefix}default`] = attributes.default; } else if (((EDITOR && !window.Build) || TEST) && warnOnNoDefault && !(attributes.get || attributes.set)) { - warnID(3654, className, propertyName); + // TODO: we close this warning for now: + // issue: https://github.com/cocos/3d-tasks/issues/14887 + // warnID(3654, className, propertyName); } const parseSimpleAttribute = (attributeName: keyof IAcceptableAttributes, expectType: string) => { diff --git a/cocos/core/data/custom-serializable.ts b/cocos/core/data/custom-serializable.ts index 1ae7850bac..7eb64aa802 100644 --- a/cocos/core/data/custom-serializable.ts +++ b/cocos/core/data/custom-serializable.ts @@ -38,7 +38,7 @@ export const deserializeTag = Symbol('[[Deserialize]]'); export interface SerializationInput { /** - * Reads a property from input. + * Reads a property from the input. * @param name Property name. * @returns The property's value, after deserialized. */ @@ -76,19 +76,17 @@ export interface SerializationOutput { export type SerializationContext = { /** - * The main serializing asset or root node in the scene/prefab passed to serialization procedure. + * The main serializing asset or root node in the scene/prefab passed to the serialization procedure. */ root: unknown; - /** * True if the serialization procedure is targeting CCON. */ toCCON: boolean; - /** * Customized arguments passed to serialization procedure. */ - customArguments: Record + customArguments: Record; }; /** @@ -108,7 +106,7 @@ export interface CustomSerializable { } /** - * Enables the custom serialize/deserialize method only if the (de)serialize procedure is targeting CCON. + * Enables the custom to serialize/deserialize method only if the (de)serialize procedure is targeting CCON. * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ export const enableIfCCON: MethodDecorator = ( diff --git a/cocos/core/data/decorators/component.ts b/cocos/core/data/decorators/component.ts index 6f5469acad..0b80f1a5f0 100644 --- a/cocos/core/data/decorators/component.ts +++ b/cocos/core/data/decorators/component.ts @@ -28,7 +28,7 @@ import { makeEditorClassDecoratorFn, makeSmartEditorClassDecorator, emptySmartCl /** * @en Declare that the current component relies on another type of component. - * If the required component doesn't exist, the engine will create a new empty instance of the required component and add to the node. + * If the required component doesn't exist, the engine will create a new empty instance of the required component and add it to the node. * @zh 为声明为 CCClass 的组件添加依赖的其它组件。当组件添加到节点上时,如果依赖的组件不存在,引擎将会自动将依赖组件添加到同一个节点,防止脚本出错。该设置在运行时同样有效。 * @param requiredComponent The required component type * @example @@ -46,10 +46,10 @@ import { makeEditorClassDecoratorFn, makeSmartEditorClassDecorator, emptySmartCl export const requireComponent: (requiredComponent: Function | Function[]) => ClassDecorator = makeEditorClassDecoratorFn('requireComponent'); /** - * @en Set the component priority, it decides at which order the life cycle functions of components will be invoked. Smaller priority get invoked before larger priority. + * @en Set the component priority, it decides at which order the life cycle functions of components will be invoked. Smaller priority gets invoked before larger priority. * This will affect `onLoad`, `onEnable`, `start`, `update` and `lateUpdate`, but `onDisable` and `onDestroy` won't be affected. * @zh 设置脚本生命周期方法调用的优先级。优先级小于 0 的组件将会优先执行,优先级大于 0 的组件将会延后执行。优先级仅会影响 onLoad, onEnable, start, update 和 lateUpdate,而 onDisable 和 onDestroy 不受影响。 - * @param priority - The execution order of life cycle methods for Component. Smaller priority get invoked before larger priority. + * @param priority - The execution order of life cycle methods for Component. Smaller priority gets invoked before larger priority. * @example * ```ts * import { _decorator, Component } from 'cc'; @@ -65,7 +65,7 @@ export const requireComponent: (requiredComponent: Function | Function[]) => Cla export const executionOrder: (priority: number) => ClassDecorator = makeEditorClassDecoratorFn('executionOrder'); /** - * @en Forbid add multiple instances of the component to the same node. + * @en Forbid adds multiple instances of the component to the same node. * @zh 防止多个相同类型(或子类型)的组件被添加到同一个节点。 * @example * ```ts @@ -83,4 +83,4 @@ export const disallowMultiple: ClassDecorator & ((yes?: boolean) => ClassDecorat export const allowReplicated: ClassDecorator = (ctor) => { CCClass.Attr.setClassAttr(ctor, 'replicated', 'visible', true); -} +}; diff --git a/cocos/core/data/decorators/editable.ts b/cocos/core/data/decorators/editable.ts index f22c10cd8a..98a528cf2c 100644 --- a/cocos/core/data/decorators/editable.ts +++ b/cocos/core/data/decorators/editable.ts @@ -30,7 +30,7 @@ import { PropertyStash, PropertyStashInternalFlag } from '../class-stash'; import { LegacyPropertyDecorator, emptyDecorator, makeSmartEditorClassDecorator, makeEditorClassDecoratorFn, emptySmartClassDecorator, emptyDecoratorFn } from './utils'; /** - * @en Makes a CCClass that inherit from component execute in edit mode.
+ * @en Makes a CCClass that inherits from component execute in edit mode.
* By default, all components are only executed in play mode,
* which means they will not have their callback functions executed while the Editor is in edit mode.
* @zh 允许继承自 Component 的 CCClass 在编辑器里执行。
@@ -52,7 +52,7 @@ export const executeInEditMode: ClassDecorator & ((yes?: boolean) => ClassDecora /** * @en Add the current component to the specific menu path in `Add Component` selector of the inspector panel * @zh 将当前组件添加到组件菜单中,方便用户查找。例如 "Rendering/CameraCtrl"。 - * @param path - The path is the menu represented like a pathname. For example the menu could be "Rendering/CameraCtrl". + * @param path - The path is the menu represented like a pathname. For example, the menu could be "Rendering/CameraCtrl". * @example * ```ts * import { _decorator, Component } from 'cc'; @@ -69,7 +69,7 @@ export const menu: (path: string) => ClassDecorator = DEV ? makeEditorClassDe /** * @en When [[_decorator.executeInEditMode]] is set, - * this decorator will make the editor running in high FPS mode when a node with the component is focused + * This decorator will make the editor run in high FPS mode when a node with the component is focused * @zh 当指定了 [[_decorator.executeInEditMode]] 以后,playOnFocus 可以在选中当前组件所在的节点时,提高编辑器的场景刷新频率到 60 FPS,否则场景就只会在必要的时候进行重绘。 * @example * ```ts @@ -89,7 +89,7 @@ export const playOnFocus: ClassDecorator & ((yes?: boolean) => ClassDecorator) = /** * @en Use a customized inspector page in the **inspector** * @zh 自定义当前组件在 **属性检查器** 中渲染时所用的 UI 页面描述。 - * @param url The url of the page definition in js + * @param url The URL of the page definition in js * @example * ```ts * import { _decorator, Component } from 'cc'; @@ -124,10 +124,10 @@ export const inspector: (url: string) => ClassDecorator = DEV ? makeEditorCla export const icon: (url: string) => ClassDecorator = DEV ? makeEditorClassDecoratorFn('icon') : emptyDecoratorFn; /** - * @en Define the help documentation url, - * if given, the component section in the **Inspector** will have a help documentation icon reference to the web page given. + * @en Define the help documentation URL, + * if given, the component section in the **Inspector** will have a help documentation icon refers to the web page given. * @zh 指定当前组件的帮助文档的 url,设置过后,在 **属性检查器** 中就会出现一个帮助图标,用户点击将打开指定的网页。 - * @param url The url of the help documentation + * @param url The URL of the help documentation * @example * ```ts * import { _decorator, Component } from 'cc'; @@ -170,7 +170,7 @@ export const visible: (condition: boolean | (() => boolean)) => LegacyPropertyDe /** * @en - * Sets the property to be read only in editor. + * Sets the property to be read-only in the editor. * @zh * 设置该属性在编辑器中仅是可读的。 */ @@ -180,7 +180,7 @@ export const readOnly: LegacyPropertyDecorator = !DEV /** * @en - * Sets the display name of the property in editor. + * Sets the display name of the property in the editor. * @zh * 设置该属性在编辑器中的显示名称。 * @param text 显示名称。 @@ -215,7 +215,7 @@ export const group: (options: NonNullable) => Legac /** * @en - * Sets the allowed range of the property in editor. + * Sets the allowed range of the property in the editor. * @zh * 设置该属性在编辑器中允许设置的范围。 * @param values 范围。 @@ -227,7 +227,7 @@ export const range: (values: [number, number, number] | [number, number]) => Leg /** * @en - * Sets the allowed min value of the property in editor. + * Sets the allowed min value of the property in the editor. * @zh * 设置该属性在编辑器中允许的最小值。 * @param value 最小值。 @@ -238,7 +238,7 @@ export const rangeMin: (value: number) => LegacyPropertyDecorator = !DEV /** * @en - * Sets the allowed max value of the property in editor. + * Sets the allowed max value of the property in the editor. * @zh * 设置该属性在编辑器中允许的最大值。 * @param value 最大值。 @@ -249,7 +249,7 @@ export const rangeMax: (value: number) => LegacyPropertyDecorator = !DEV /** * @en - * Sets the step of the property in editor. + * Sets the step of the property in the editor. * @zh * 设置该属性在编辑器中的步进值。 * @param value 步进值。 @@ -261,7 +261,7 @@ export const rangeStep: (value: number) => LegacyPropertyDecorator = !DEV /** * @en - * Enable a slider be given to coordinate the property in editor. + * Enable a slider to be given to coordinate the property in the editor. * @zh * 允许在编辑器中提供滑动条来调节值 * @engineInternal @@ -272,7 +272,7 @@ export const slide: LegacyPropertyDecorator = !DEV /** * @en - * Sets the display order of the property in editor. + * Sets the display order of the property in the editor. * @zh * 设置该属性在编辑器中的显示顺序。 * @param order 显示顺序。 @@ -284,7 +284,7 @@ export const displayOrder: (order: number) => LegacyPropertyDecorator = !DEV /** * @en - * Sets the unit of the property in editor. + * Sets the unit of the property in the editor. * @zh * 设置该属性在编辑器中的计量单位。 * @param name 计量单位的名称。 @@ -299,7 +299,7 @@ export const unit: (name: /** * @en - * Sets to convert the value into radian before feed it to the property in editor. + * Sets to convert the value into radian before feeding it to the property in the editor. * @zh * 设置在编辑器中赋值该属性前将值先转换为弧度制。 */ @@ -319,7 +319,7 @@ export const multiline: LegacyPropertyDecorator = !DEV /** * @en - * Sets the property so that it does not interop with the animation parts in editor. + * Sets the property so that it does not interop with the animation parts in the editor. * @zh * 设置该属性不参与编辑器中动画相关的交互。 * @engineInternal diff --git a/cocos/core/data/decorators/property.ts b/cocos/core/data/decorators/property.ts index 61610a3d78..2257095766 100644 --- a/cocos/core/data/decorators/property.ts +++ b/cocos/core/data/decorators/property.ts @@ -120,7 +120,7 @@ function getDefaultFromInitializer (initializer: Initializer) { // string boolean number function undefined null return value; } else { - // The default attribute will not be used in ES6 constructor actually, + // The default attribute will not be used in the ES6 constructor actually, // so we don't need to simplify into `{}` or `[]` or vec2 completely. return initializer; } @@ -246,19 +246,24 @@ function setDefaultValue ( propertyStash: PropertyStash, classConstructor: new () => T, propertyKey: PropertyKey, - descriptorOrInitializer: BabelPropertyDecoratorDescriptor | Initializer | undefined, + descriptorOrInitializer: BabelPropertyDecoratorDescriptor | Initializer | undefined | null, ) { - if (descriptorOrInitializer) { + if (descriptorOrInitializer !== undefined) { if (typeof descriptorOrInitializer === 'function') { propertyStash.default = getDefaultFromInitializer(descriptorOrInitializer); + } else if (descriptorOrInitializer === null) { + // For some decorated properties we haven't specified the default value, then the initializer should be null. + // We fall back to the behavior of v3.6.3, where we don't specify the default value automatically. + // propertyStash.default = undefined; } else if (descriptorOrInitializer.initializer) { - // In case of Babel, if an initializer is given for class field. + // In the case of Babel, if an initializer is given for a class field. // That initializer is passed to `descriptor.initializer`. propertyStash.default = getDefaultFromInitializer(descriptorOrInitializer.initializer); } } else { - // In case of TypeScript, we can not directly capture the initializer. + // In the case of TypeScript, we can not directly capture the initializer. // We have to be hacking to extract the value. + // We should fall back to the TypeScript case only when `descriptorOrInitializer` is undefined. const actualDefaultValues = classStash.default || (classStash.default = extractActualDefaultValues(classConstructor)); // eslint-disable-next-line no-prototype-builtins if ((actualDefaultValues as any).hasOwnProperty(propertyKey)) { diff --git a/cocos/core/data/decorators/serializable.ts b/cocos/core/data/decorators/serializable.ts index 678683c582..93f522f465 100644 --- a/cocos/core/data/decorators/serializable.ts +++ b/cocos/core/data/decorators/serializable.ts @@ -29,7 +29,7 @@ import { PropertyStash, PropertyStashInternalFlag } from '../class-stash'; import { getOrCreateSerializationMetadata } from '../serialization-metadata'; /** - * True if serialization feature is enabled in current environment. + * True if the serialization feature is enabled in the current environment. * @engineInternal */ const WITH_SERIALIZATION = EDITOR || TEST; @@ -72,9 +72,9 @@ function setImplicitSerializable (propertyStash: PropertyStash) { /** * @en * Marks the target class as "uniquely referenced" which means, in the aspect of serialization, - * no more than one objects should reference to same instance of that class. + * no more than one object should reference the same instance of that class. * When serializing references to objects of such class, - * they're treated as different object even they point to actually the same. + * they're treated as different objects even if they point to actually the same. * While deserializing, these two references would point two distinct objects. * For example: * ```ts diff --git a/cocos/core/data/decorators/utils.ts b/cocos/core/data/decorators/utils.ts index 1b7cddcb2b..0f8a229523 100644 --- a/cocos/core/data/decorators/utils.ts +++ b/cocos/core/data/decorators/utils.ts @@ -33,14 +33,16 @@ export type BabelPropertyDecoratorDescriptor = PropertyDescriptor & { initialize /** * @en - * The signature compatible with both TypeScript legacy decorator and Babel legacy decorator. - * The third argument is `descriptor` in Babel case. - * For some engine internal optimized deocorators, the third argument is initializer. + * The signature is compatible with both the TypeScript legacy decorator and the Babel legacy decorator. + * The third argument is `descriptor` in the Babel case. + * For some engine internally optimized decorators, the third argument is the initializer. * @zh * 该签名同时兼容 TypeScript legacy 装饰器以及 Babel legacy 装饰器。 * 第三个参数在 Babel 情况下,会传入 descriptor。对于一些被优化的引擎内部装饰器,会传入 initializer。 */ -export type LegacyPropertyDecorator = (target: Record, propertyKey: string | symbol, descriptorOrInitializer?: BabelPropertyDecoratorDescriptor | Initializer) => void; +export type LegacyPropertyDecorator = ( + target: Record, propertyKey: string | symbol, descriptorOrInitializer?: BabelPropertyDecoratorDescriptor | Initializer | null, +) => void; /** * @en @@ -52,7 +54,7 @@ export const emptyDecorator: ClassDecorator & LegacyPropertyDecorator = () => {} /** * @en - * A function which ignore all arguments and return the `emptyDecorator`. + * A function that ignores all arguments and returns the `emptyDecorator`. * @zh * 一个忽略所有参数并且返回 `emptyDecorator` 的函数。 */ @@ -73,7 +75,7 @@ export const emptySmartClassDecorator = makeSmartClassDecorator(() => {}); * - `@x` * - `@x(arg0)` * - * and forward both the decorated class and the `arg0` (in first form, `arg0` is forward as `undefined`) to + * and forward both the decorated class and the `arg0` (in the first form, `arg0` is forwarded as `undefined`) to * `decorate`. * @zh * 创建一个智能类装饰器,它能正确地处理以下形式的装饰器语法: @@ -111,7 +113,7 @@ function writeEditorClassProperty (constructor: AnyFunction, propertyNam /** * @en - * Make a function which accept an argument value and return a class decorator. + * Make a function that accepts an argument value and returns a class decorator. * The decorator sets the editor property `propertyName`, on the decorated class, into that argument value. * @zh * 创建一个函数,该函数接受一个参数值并返回一个类装饰器。 diff --git a/cocos/core/data/editor-extendable.ts b/cocos/core/data/editor-extendable.ts index 9a2fbb520b..38a8cf6f59 100644 --- a/cocos/core/data/editor-extendable.ts +++ b/cocos/core/data/editor-extendable.ts @@ -31,10 +31,10 @@ import { assertIsTrue } from './utils/asserts'; // Functions and classes exposed from this module are useful to // make a class to be `EditorExtendableObject`. // -// These helpers are used internally, don't expose them to user. +// These helpers are used internally, don't expose them to the user. /** - * Creates a mixin class which inherits from specific base class and implements the `EditorExtendableObject` interface. + * Creates a mixin class that inherits from the specific base class and implements the `EditorExtendableObject` interface. * @param Base The base class. * @param className Assign an optional cc class name. If the base class is not cc class, this param is required. * @returns The mixin class. diff --git a/cocos/core/data/editor-extras-tag.ts b/cocos/core/data/editor-extras-tag.ts index 27081d7165..4a06478d65 100644 --- a/cocos/core/data/editor-extras-tag.ts +++ b/cocos/core/data/editor-extras-tag.ts @@ -23,12 +23,12 @@ */ /** - * Tag to visit editor extras of an object. Never concern about its value please. + * Tag to visit editor extras of an object. Never be concerned about its value, please. */ export const editorExtrasTag = '__editorExtras__'; /** - * Engine classes with this kind of signatures are integrated with editor extendability. + * Engine classes with this kind of signature are integrated with editor extendability. * @internal */ export interface EditorExtendableObject { @@ -37,10 +37,10 @@ export interface EditorExtendableObject { * The editor extras on this object. * * BE CAREFUL: this property is currently governed by Cocos Creator Editor. - * Its definition is not visible and is unknown to both engine code or users codes, - * they SHALL NOT operates it. + * Its definition is not visible and is unknown to both engine code and users codes, + * they SHALL NOT operate it. * - * You should use editor extras tag to visit this property. + * You should use the editor extras tag to visit this property. * @example * ```ts * import { editorExtrasTag } from 'cc'; diff --git a/cocos/core/data/utils/attribute.ts b/cocos/core/data/utils/attribute.ts index e39b2e0f3d..5316d4196e 100644 --- a/cocos/core/data/utils/attribute.ts +++ b/cocos/core/data/utils/attribute.ts @@ -68,7 +68,7 @@ export function createAttrs (subclass: any) { * Tag the class with any meta attributes, then return all current attributes assigned to it. * This function holds only the attributes, not their implementations. * @param constructor The class or instance. If instance, the attribute will be dynamic and only available for the specified instance. - * @param propertyName The name of property or function, used to retrieve the attributes. + * @param propertyName The name of the property or function, used to retrieve the attributes. * @private */ export function attr (constructor: any, propertyName: string): { [attributeName: string]: any; } { @@ -84,7 +84,7 @@ export function attr (constructor: any, propertyName: string): { [attributeName: } /** - * Returns a readonly meta object. + * Returns a read-only meta-object. */ export function getClassAttrs (constructor: any) { return (constructor.hasOwnProperty('__attrs__') && constructor.__attrs__) || createAttrs(constructor); @@ -111,14 +111,14 @@ export class PrimitiveType { /** * @en - * Indicates that the editor should treats this property or array element as a Integer value. + * Indicates that the editor should treat this property or array element as an Integer value. * @zh * 指定编辑器以整数形式对待该属性或数组元素。 * @example * ```ts * import { CCInteger, _decorator } from "cc"; * - * // in class definition: + * // in the class definition: * * @_decorator.property({type: CCInteger}) * count = 0; @@ -133,14 +133,14 @@ legacyCC.CCInteger = CCInteger; /** * @en - * Indicates that the editor should treats this property or array element as a Float value. + * Indicates that the editor should treat this property or array element as a Float value. * @zh * 指定编辑器以浮点数形式对待该属性或数组元素。 * @example * ```ts * import { CCFloat, _decorator } from "cc"; * - * // in class definition: + * // in the class definition: * * @_decorator.property({type: CCFloat}) * x = 0; @@ -162,14 +162,14 @@ if (EDITOR) { /** * @en - * Indicates that the editor should treats this property or array element as a Boolean value. + * Indicates that the editor should treat this property or array element as a Boolean value. * @zh * 指定编辑器以布尔值形式对待该属性或数组元素。 * * @example * ```ts * import { CCBoolean, _decorator } from "cc"; - * // in class definition + * // in the class definition * @_decorator.property({type: CCBoolean}) * isTrue = false; * @@ -183,14 +183,14 @@ legacyCC.CCBoolean = CCBoolean; /** * @en - * Indicates that the editor should treats this property or array element as a String value. + * Indicates that the editor should treat this property or array element as a String value. * @zh * 指定编辑器以字符串形式对待该属性或数组元素。 * @example * ```ts * import { CCString, _decorator } from "cc"; * - * // in class definition + * // in the class definition * * @_decorator.property({type: CCString}) * name = ''; diff --git a/cocos/core/data/utils/compact-value-type-array.ts b/cocos/core/data/utils/compact-value-type-array.ts index 8f85ee0f32..54f41685fc 100644 --- a/cocos/core/data/utils/compact-value-type-array.ts +++ b/cocos/core/data/utils/compact-value-type-array.ts @@ -65,7 +65,7 @@ export class CompactValueTypeArray { public static ElementType = ElementType; /** - * Offset into buffer, in bytes. + * Offset into the buffer, in bytes. */ @serializable private _byteOffset = 0; diff --git a/cocos/core/data/utils/extends-enum.ts b/cocos/core/data/utils/extends-enum.ts index 00cfbca3e9..546ed14c86 100644 --- a/cocos/core/data/utils/extends-enum.ts +++ b/cocos/core/data/utils/extends-enum.ts @@ -31,10 +31,10 @@ import { errorID } from '../../platform/debug'; * 此函数的行为等价于返回了一个新的枚举,其成员囊括了所有源枚举的成员。 * 这些枚举的成员必须各不相同(包括成员名和值),否则行为是未定义的。 * @en - * Combine arbitray number of enumerations. - * It behaves like an enumeration having members that is a combination of members of the source enumerations + * Combine an arbitrary number of enumerations. + * It behaves like an enumeration having members that are a combination of members of the source enumerations * is returned. - * These enumerations shall have non-overlaped member names or member values. + * These enumerations shall have non-overlapped member names or member values. * If not, the behavior is undefined. * @example * ```ts diff --git a/cocos/core/math/mat3.ts b/cocos/core/math/mat3.ts index df313dd4f6..b37fe90684 100644 --- a/cocos/core/math/mat3.ts +++ b/cocos/core/math/mat3.ts @@ -26,7 +26,7 @@ import { CCClass } from '../data/class'; import { ValueType } from '../value-types/value-type'; import { Quat } from './quat'; import { IMat3Like, IMat4Like, IQuatLike, IVec2Like, IVec3Like } from './type-define'; -import { EPSILON } from './utils'; +import { EPSILON, HALF_PI } from './utils'; import { Vec3 } from './vec3'; import { legacyCC } from '../global-exports'; @@ -623,6 +623,41 @@ export class Mat3 extends ValueType { ); } + /** + * @en Convert Matrix to euler angle, resulting angle y, z in the range of [-PI, PI], + * x in the range of [-PI/2, PI/2], the rotation order is YXZ. + * @zh 将矩阵转换成欧拉角, 返回角度 y,z 在 [-PI, PI] 区间内, x 在 [-PI/2, PI/2] 区间内,旋转顺序为 YXZ. + */ + public static toEuler (matrix: Mat3, v: Vec3): boolean { + //a[col][row] + const a00 = matrix.m00; const a01 = matrix.m01; const a02 = matrix.m02; + const a10 = matrix.m03; const a11 = matrix.m04; const a12 = matrix.m05; + const a20 = matrix.m06; const a21 = matrix.m07; const a22 = matrix.m08; + + // from http://www.geometrictools.com/Documentation/EulerAngles.pdf + // YXZ order + if (a21 < 0.999) { + if (a21 > -0.999) { + v.x = Math.asin(-a21); + v.y = Math.atan2(a20, a22); + v.z = Math.atan2(a01, a11); + return true; + } else { + // Not unique. YA - ZA = atan2(r01,r00) + v.x = HALF_PI; + v.y = Math.atan2(a10, a00); + v.z = 0.0; + return false; + } + } else { + // Not unique. YA + ZA = atan2(-r01,r00) + v.x = -HALF_PI; + v.y = Math.atan2(-a10, a00); + v.z = 0.0; + return false; + } + } + /** * @en Value at column 0 row 0 of the matrix. * @zh 矩阵第 0 列第 0 行的元素。 diff --git a/cocos/core/math/mat4.ts b/cocos/core/math/mat4.ts index c6ce34c867..cc1d6cc455 100644 --- a/cocos/core/math/mat4.ts +++ b/cocos/core/math/mat4.ts @@ -2024,7 +2024,7 @@ export class Mat4 extends ValueType { out.x = Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02); out.y = Math.sqrt(m04 * m04 + m05 * m05 + m06 * m06); out.z = Math.sqrt(m08 * m08 + m09 * m09 + m10 * m10); - // account for refections + // account for reflections if (Mat3.determinant(m3_1) < 0) { out.x *= -1; } return out; } @@ -2035,36 +2035,27 @@ export class Mat4 extends ValueType { * @param out Vector to receive rotation component */ public getRotation (out: Quat) { - const trace = this.m00 + this.m05 + this.m10; - let S = 0; - - if (trace > 0) { - S = Math.sqrt(trace + 1.0) * 2; - out.w = 0.25 * S; - out.x = (this.m06 - this.m09) / S; - out.y = (this.m08 - this.m02) / S; - out.z = (this.m01 - this.m04) / S; - } else if ((this.m00 > this.m05) && (this.m00 > this.m10)) { - S = Math.sqrt(1.0 + this.m00 - this.m05 - this.m10) * 2; - out.w = (this.m06 - this.m09) / S; - out.x = 0.25 * S; - out.y = (this.m01 + this.m04) / S; - out.z = (this.m08 + this.m02) / S; - } else if (this.m05 > this.m10) { - S = Math.sqrt(1.0 + this.m05 - this.m00 - this.m10) * 2; - out.w = (this.m08 - this.m02) / S; - out.x = (this.m01 + this.m04) / S; - out.y = 0.25 * S; - out.z = (this.m06 + this.m09) / S; - } else { - S = Math.sqrt(1.0 + this.m10 - this.m00 - this.m05) * 2; - out.w = (this.m01 - this.m04) / S; - out.x = (this.m08 + this.m02) / S; - out.y = (this.m06 + this.m09) / S; - out.z = 0.25 * S; + // Extract rotation matrix first + const sx = Vec3.set(v3_1, this.m00, this.m01, this.m02).length(); + const sy = Vec3.set(v3_1, this.m04, this.m05, this.m06).length(); + const sz = Vec3.set(v3_1, this.m08, this.m09, this.m10).length(); + m3_1.m00 = this.m00 / sx; + m3_1.m01 = this.m01 / sx; + m3_1.m02 = this.m02 / sx; + m3_1.m03 = this.m04 / sy; + m3_1.m04 = this.m05 / sy; + m3_1.m05 = this.m06 / sy; + m3_1.m06 = this.m08 / sz; + m3_1.m07 = this.m09 / sz; + m3_1.m08 = this.m10 / sz; + const det = Mat3.determinant(m3_1); + if (det < 0) { + m3_1.m00 *= -1; + m3_1.m01 *= -1; + m3_1.m02 *= -1; } - return out; + return Quat.fromMat3(out, m3_1); } /** diff --git a/cocos/core/math/quat.ts b/cocos/core/math/quat.ts index 3332737bdc..208a62c8ea 100644 --- a/cocos/core/math/quat.ts +++ b/cocos/core/math/quat.ts @@ -396,8 +396,8 @@ export class Quat extends ValueType { } /** - * @en Normalize the given quaternion - * @zh 归一化四元数 + * @en Normalize the given quaternion, returns a zero quaternion if input is a zero quaternion. + * @zh 归一化四元数,输入零四元数将会返回零四元数。 */ public static normalize (out: Out, a: Out) { let len = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w; @@ -407,6 +407,11 @@ export class Quat extends ValueType { out.y = a.y * len; out.z = a.z * len; out.w = a.w * len; + } else { + out.x = 0; + out.y = 0; + out.z = 0; + out.w = 0; } return out; } @@ -452,43 +457,43 @@ export class Quat extends ValueType { * @en Calculates the quaternion with the three-dimensional transform matrix, considering no scale included in the matrix * @zh 根据三维矩阵信息计算四元数,默认输入矩阵不含有缩放信息 */ - public static fromMat3 (out: Out, m: Mat3) { + public static fromMat3 (out: Out, m: Mat3) { const { - m00, m03, m06, - m01, m04, m07, - m02, m05, m08, + m00, m03: m01, m06: m02, + m01: m10, m04: m11, m07: m12, + m02: m20, m05: m21, m08: m22, } = m; - const trace = m00 + m04 + m08; + const trace = m00 + m11 + m22; if (trace > 0) { const s = 0.5 / Math.sqrt(trace + 1.0); out.w = 0.25 / s; - out.x = (m05 - m07) * s; - out.y = (m06 - m02) * s; - out.z = (m01 - m03) * s; - } else if ((m00 > m04) && (m00 > m08)) { - const s = 2.0 * Math.sqrt(1.0 + m00 - m04 - m08); + out.x = (m21 - m12) * s; + out.y = (m02 - m20) * s; + out.z = (m10 - m01) * s; + } else if ((m00 > m11) && (m00 > m22)) { + const s = 0.5 / Math.sqrt(1.0 + m00 - m11 - m22); - out.w = (m05 - m07) / s; - out.x = 0.25 * s; - out.y = (m03 + m01) / s; - out.z = (m06 + m02) / s; - } else if (m04 > m08) { - const s = 2.0 * Math.sqrt(1.0 + m04 - m00 - m08); + out.w = (m21 - m12) * s; + out.x = 0.25 / s; + out.y = (m01 + m10) * s; + out.z = (m02 + m20) * s; + } else if (m11 > m22) { + const s = 0.5 / Math.sqrt(1.0 + m11 - m00 - m22); - out.w = (m06 - m02) / s; - out.x = (m03 + m01) / s; - out.y = 0.25 * s; - out.z = (m07 + m05) / s; + out.w = (m02 - m20) * s; + out.x = (m01 + m10) * s; + out.y = 0.25 / s; + out.z = (m12 + m21) * s; } else { - const s = 2.0 * Math.sqrt(1.0 + m08 - m00 - m04); + const s = 0.5 / Math.sqrt(1.0 + m22 - m00 - m11); - out.w = (m01 - m03) / s; - out.x = (m06 + m02) / s; - out.y = (m07 + m05) / s; - out.z = 0.25 * s; + out.w = (m10 - m01) * s; + out.x = (m02 + m20) * s; + out.y = (m12 + m21) * s; + out.z = 0.25 / s; } return out; @@ -613,6 +618,18 @@ export class Quat extends ValueType { return out; } + /** + * @en Converts the quaternion to euler angles, result angle y, z in the range of [-180, 180], x in the range of [-90, 90], the rotation order is YXZ + * @zh 根据四元数计算欧拉角,返回角度 yz 在 [-180, 180], x 在 [-90, 90],旋转顺序为 YXZ + */ + public static toEulerInYXZOrder (out: Vec3, q: IQuatLike) { + Mat3.fromQuat(m3_1, q); + Mat3.toEuler(m3_1, out); + out.x = toDegree(out.x); + out.y = toDegree(out.y); + out.z = toDegree(out.z); + } + /** * @en Converts quaternion to an array * @zh 四元数转数组 diff --git a/cocos/core/math/utils.ts b/cocos/core/math/utils.ts index bab7e54a67..68e7ff491a 100644 --- a/cocos/core/math/utils.ts +++ b/cocos/core/math/utils.ts @@ -31,6 +31,9 @@ const _d2r = Math.PI / 180.0; const _r2d = 180.0 / Math.PI; +export const HALF_PI = Math.PI * 0.5; +export const TWO_PI = Math.PI * 2.0; + export const EPSILON = 0.000001; /** diff --git a/cocos/core/math/vec2.ts b/cocos/core/math/vec2.ts index 0dbbf6df6c..2b1eddedff 100644 --- a/cocos/core/math/vec2.ts +++ b/cocos/core/math/vec2.ts @@ -265,8 +265,8 @@ export class Vec2 extends ValueType { } /** - * @en Sets the normalized vector to the out vector - * @zh 归一化向量 + * @en Sets the normalized vector to the out vector, returns a zero vector if input is a zero vector. + * @zh 归一化向量,输入零向量将会返回零向量。 */ public static normalize (out: Out, a: Vec2Like) { const x = a.x; @@ -276,6 +276,9 @@ export class Vec2 extends ValueType { len = 1 / Math.sqrt(len); out.x = x * len; out.y = y * len; + } else { + out.x = 0; + out.y = 0; } return out; } @@ -301,7 +304,7 @@ export class Vec2 extends ValueType { */ public static cross (out: Vec3, a: Out, b: Out): Vec3; - public static cross (out: IVec2Like | Vec3, a: IVec2Like, b?: IVec2Like) : number | Vec3 { + public static cross (out: IVec2Like | Vec3, a: IVec2Like, b?: IVec2Like): number | Vec3 { if (out instanceof Vec3) { out.x = out.y = 0; out.z = a.x * b!.y - a.y * b!.x; @@ -412,19 +415,20 @@ export class Vec2 extends ValueType { } /** - * @en Calculates the radian angle between two vectors - * @zh 求两向量夹角弧度 + * @en Calculates the radian angle between two vectors, returns zero if either vector is a zero vector. + * @zh 求两向量夹角弧度,任意一个向量是零向量则返回零。 */ public static angle (a: Out, b: Out) { - Vec2.normalize(v2_1, a); - Vec2.normalize(v2_2, b); - const cosine = Vec2.dot(v2_1, v2_2); - if (cosine > 1.0) { - return 0; - } - if (cosine < -1.0) { - return Math.PI; + const magSqr1 = a.x * a.x + a.y * a.y; + const magSqr2 = b.x * b.x + b.y * b.y; + + if (magSqr1 === 0 || magSqr2 === 0) { + return 0.0; } + + const dot = a.x * b.x + a.y * b.y; + let cosine = dot / (Math.sqrt(magSqr1 * magSqr2)); + cosine = clamp(cosine, -1.0, 1.0); return Math.acos(cosine); } @@ -751,24 +755,23 @@ export class Vec2 extends ValueType { } /** - * @en Calculates radian angle between two vectors - * @zh 获取当前向量和指定向量之间的角度。 - * @param other specified vector - * @return The angle between the current vector and the specified vector (in radians); if there are zero vectors in the current vector and the specified vector, 0 is returned. + * @en Calculates radian angle between two vectors, returns zero if either vector is a zero vector. + * @zh 获取当前向量和指定向量之间的角度,任意一个向量是零向量则返回零。 + * @param other specified vector. + * @return The angle between the current vector and the specified vector. */ public angle (other: Vec2) { const magSqr1 = this.lengthSqr(); const magSqr2 = other.lengthSqr(); if (magSqr1 === 0 || magSqr2 === 0) { - console.warn('Can\'t get angle between zero vector'); return 0.0; } const dot = this.dot(other); - let theta = dot / (Math.sqrt(magSqr1 * magSqr2)); - theta = clamp(theta, -1.0, 1.0); - return Math.acos(theta); + let cosine = dot / (Math.sqrt(magSqr1 * magSqr2)); + cosine = clamp(cosine, -1.0, 1.0); + return Math.acos(cosine); } /** diff --git a/cocos/core/math/vec3.ts b/cocos/core/math/vec3.ts index f7d264f7e4..f22bd7e2f4 100644 --- a/cocos/core/math/vec3.ts +++ b/cocos/core/math/vec3.ts @@ -305,8 +305,8 @@ export class Vec3 extends ValueType { } /** - * @en Sets the normalized vector to the out vector - * @zh 归一化向量 + * @en Sets the normalized vector to the out vector, returns a zero vector if input is a zero vector. + * @zh 归一化向量,输入零向量将会返回零向量。 */ public static normalize (out: Out, a: IVec3Like) { const x = a.x; @@ -319,6 +319,10 @@ export class Vec3 extends ValueType { out.x = x * len; out.y = y * len; out.z = z * len; + } else { + out.x = 0; + out.y = 0; + out.z = 0; } return out; } @@ -699,15 +703,16 @@ export class Vec3 extends ValueType { * @zh 求两向量夹角弧度 */ public static angle (a: IVec3Like, b: IVec3Like) { - Vec3.normalize(v3_1, a); - Vec3.normalize(v3_2, b); - const cosine = Vec3.dot(v3_1, v3_2); - if (cosine > 1.0) { - return 0; - } - if (cosine < -1.0) { - return Math.PI; + const magSqr1 = a.x * a.x + a.y * a.y + a.z * a.z; + const magSqr2 = b.x * b.x + b.y * b.y + b.z * b.z; + + if (magSqr1 === 0 || magSqr2 === 0) { + return 0.0; } + + const dot = a.x * b.x + a.y * b.y + a.z * b.z; + let cosine = dot / (Math.sqrt(magSqr1 * magSqr2)); + cosine = clamp(cosine, -1.0, 1.0); return Math.acos(cosine); } @@ -1088,6 +1093,7 @@ export class Vec3 extends ValueType { this.y = y * len; this.z = z * len; } + return this; } @@ -1109,9 +1115,6 @@ export class Vec3 extends ValueType { } } -const v3_1 = new Vec3(); -const v3_2 = new Vec3(); - CCClass.fastDefine('cc.Vec3', Vec3, { x: 0, y: 0, z: 0 }); legacyCC.Vec3 = Vec3; diff --git a/cocos/core/math/vec4.ts b/cocos/core/math/vec4.ts index 1613801978..d614300d02 100644 --- a/cocos/core/math/vec4.ts +++ b/cocos/core/math/vec4.ts @@ -313,8 +313,8 @@ export class Vec4 extends ValueType { } /** - * @en Sets the normalized vector to the out vector - * @zh 归一化向量 + * @en Sets the normalized vector to the out vector, returns a zero vector if input is a zero vector. + * @zh 归一化向量,输入零向量将会返回零向量。 */ public static normalize (out: Out, a: Out) { const x = a.x; @@ -328,6 +328,11 @@ export class Vec4 extends ValueType { out.y = y * len; out.z = z * len; out.w = w * len; + } else { + out.x = 0; + out.y = 0; + out.z = 0; + out.w = 0; } return out; } diff --git a/cocos/core/memop/container-manager.ts b/cocos/core/memop/container-manager.ts deleted file mode 100644 index da4787152b..0000000000 --- a/cocos/core/memop/container-manager.ts +++ /dev/null @@ -1,85 +0,0 @@ -/* - Copyright (c) 2021-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 { fastRemoveAt } from '../utils/array'; -import { ScalableContainer } from './scalable-container'; - -/** - * @en ContainerManager is a sequence container that stores ScalableContainers. - * It will shrink all managed ScalableContainer in a fixed interval. - */ -class ContainerManager { - private _pools: ScalableContainer[] = []; - private _lastShrinkPassed = 0; - /** - * @en Shrink interval in seconds. - */ - public shrinkTimeSpan = 5; - - /** - * @en Add a ScalableContainer. Will add the same ScalableContainer instance once. - * @param pool @en The ScalableContainer to add. - */ - addContainer (pool: ScalableContainer) { - if (pool._poolHandle !== -1) return; - pool._poolHandle = this._pools.length; - this._pools.push(pool); - } - - /** - * @en Remove a ScalableContainer. - * @param pool @en The ScalableContainer to remove. - */ - removeContainer (pool: ScalableContainer) { - if (pool._poolHandle === -1) return; - this._pools[this._pools.length - 1]._poolHandle = pool._poolHandle; - fastRemoveAt(this._pools, pool._poolHandle); - pool._poolHandle = -1; - } - - /** - * @en Try to shrink all managed ScalableContainers. - */ - tryShrink () { - for (let i = 0; i < this._pools.length; i++) { - this._pools[i].tryShrink(); - } - } - - /** - * @en An update function invoked every frame. - * @param dt @en Delta time of frame interval in secondes. - */ - update (dt: number) { - this._lastShrinkPassed += dt; - if (this._lastShrinkPassed > this.shrinkTimeSpan) { - this.tryShrink(); - this._lastShrinkPassed -= this.shrinkTimeSpan; - } - } -} - -/** - * @en A global ContainerManager instance. - */ -export const containerManager = new ContainerManager(); diff --git a/cocos/core/memop/scalable-container.ts b/cocos/core/memop/scalable-container.ts index 913f708de0..44e9c3451d 100644 --- a/cocos/core/memop/scalable-container.ts +++ b/cocos/core/memop/scalable-container.ts @@ -21,8 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - -import { containerManager } from './container-manager'; +import { fastRemoveAt } from '../utils/array'; export abstract class ScalableContainer { /** @@ -30,12 +29,72 @@ export abstract class ScalableContainer { */ public _poolHandle = -1; constructor () { - containerManager.addContainer(this); + scalableContainerManager.addContainer(this); } abstract tryShrink (): void; destroy () { - containerManager.removeContainer(this); + scalableContainerManager.removeContainer(this); } } + +/** + * @en ScalableContainerManager is a sequence container that stores ScalableContainers. + * It will shrink all managed ScalableContainer in a fixed interval. + */ +class ScalableContainerManager { + private _pools: ScalableContainer[] = []; + private _lastShrinkPassed = 0; + /** + * @en Shrink interval in seconds. + */ + public shrinkTimeSpan = 5; + + /** + * @en Add a ScalableContainer. Will add the same ScalableContainer instance once. + * @param pool @en The ScalableContainer to add. + */ + addContainer (pool: ScalableContainer) { + if (pool._poolHandle !== -1) return; + pool._poolHandle = this._pools.length; + this._pools.push(pool); + } + + /** + * @en Remove a ScalableContainer. + * @param pool @en The ScalableContainer to remove. + */ + removeContainer (pool: ScalableContainer) { + if (pool._poolHandle === -1) return; + this._pools[this._pools.length - 1]._poolHandle = pool._poolHandle; + fastRemoveAt(this._pools, pool._poolHandle); + pool._poolHandle = -1; + } + + /** + * @en Try to shrink all managed ScalableContainers. + */ + tryShrink () { + for (let i = 0; i < this._pools.length; i++) { + this._pools[i].tryShrink(); + } + } + + /** + * @en An update function invoked every frame. + * @param dt @en Delta time of frame interval in secondes. + */ + update (dt: number) { + this._lastShrinkPassed += dt; + if (this._lastShrinkPassed > this.shrinkTimeSpan) { + this.tryShrink(); + this._lastShrinkPassed -= this.shrinkTimeSpan; + } + } +} + +/** + * @en A global ScalableContainerManager instance. + */ +export const scalableContainerManager = new ScalableContainerManager(); diff --git a/cocos/core/value-types/bitmask.ts b/cocos/core/value-types/bitmask.ts index 0aacda28e9..24fa654792 100644 --- a/cocos/core/value-types/bitmask.ts +++ b/cocos/core/value-types/bitmask.ts @@ -3,23 +3,23 @@ http://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. + 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 { EDITOR, TEST } from 'internal:constants'; @@ -29,13 +29,33 @@ import { errorID } from '../platform/debug'; /** * @en - * Define an BitMask type. + * Defines a BitMask type. The editor will display different inspector depending on this data type. It may define some properties to the object. + * The keys of new properties are the integer type values, and the values are corresponding keys. See the example below. + * keys. * @zh - * 定义一个位掩码类型。 + * 定义一个位掩码类型。编辑器会根据这个数据类型显示不同的显示界面。它可能会在对象添加新属性。新属性的 key 是原来的整型 value,value 是对应的 key。参考下面的例子。 * @param obj * @en A JavaScript literal object containing BitMask names and values. * @zh 包含 BitMask 名称和值的 JavaScript 文字对象。 - * @return @en The defined BitMask type @zh 定义的位掩码类型。 + * @returns @en The defined BitMask type @zh 定义的位掩码类型。 + * @example + * ```ts + * // `type1` and `type2` are single-selected. + * let obj = { + * type1: 0, + * type2: 1 << 2, + * } + * + * // `type1` and `type2` are multiple-selected. + * // New properties are added to obj, obj now is + * // { + * // type1: 0, + * // type2: 1<< 2, + * // 0: type1, + * // 4: type2 + * // } + * BitMask(obj); + * ``` */ export function BitMask (obj: T): T { if ('__bitmask__' in obj) { @@ -69,8 +89,19 @@ export function BitMask (obj: T): T { return obj; } +/** + * @en Checks if an object is BitMask. @zh 检查一个对象是否是 BitMask。 + * @param BitMaskType @en The object to check. @zh 待检查对象。 + * @returns @en True if it is a BitMask, false else. + * @zh 如果是 BitMask,返回 true;否则返回 false。 + */ BitMask.isBitMask = (BitMaskType) => BitMaskType && BitMaskType.hasOwnProperty('__bitmask__'); +/** + * + * @param BitMaskDef + * @returns @en A sorted array with integer values. @zh 存储整型属性值的数组。该数组已排序。 + */ BitMask.getList = (BitMaskDef) => { if (BitMaskDef.__bitmask__) { return BitMaskDef.__bitmask__; @@ -88,6 +119,12 @@ BitMask.getList = (BitMaskDef) => { return bitlist; }; +/** + * @en Similar to [[BitMask]], but it doesn't add properties to the object. + * @zh 和 [[BitMask]] 类似功能,但不会往对象添加属性。 + * @param bitmaskx @en An object to make BitMask type. @zh 要标记为 BitMask 类型的对象。 + * @returns @en The passed in object. @zh 传入的对象。 + */ export function ccbitmask (bitmaskx) { if ('__bitmask__' in bitmaskx) { return; diff --git a/cocos/game/director.ts b/cocos/game/director.ts index 58db1a5051..0c49e4af73 100644 --- a/cocos/game/director.ts +++ b/cocos/game/director.ts @@ -35,7 +35,7 @@ import { Root } from '../root'; import { Node, Scene } from '../scene-graph'; import { ComponentScheduler } from '../scene-graph/component-scheduler'; import NodeActivator from '../scene-graph/node-activator'; -import { containerManager } from '../core/memop/container-manager'; +import { scalableContainerManager } from '../core/memop/scalable-container'; import { uiRendererManager } from '../2d/framework/ui-renderer-manager'; import { assetManager } from '../asset/asset-manager'; import { deviceManager } from '../gfx'; @@ -732,7 +732,7 @@ export class Director extends EventTarget { Node.resetHasChangedFlags(); Node.clearNodeArray(); - containerManager.update(dt); + scalableContainerManager.update(dt); this.emit(Director.EVENT_END_FRAME); this._totalFrames++; } diff --git a/cocos/game/game.ts b/cocos/game/game.ts index 3a69606cdd..ee79c7d4f8 100644 --- a/cocos/game/game.ts +++ b/cocos/game/game.ts @@ -31,14 +31,13 @@ import { ConfigOrientation } from 'pal/screen-adapter'; import assetManager, { IAssetManagerOptions } from '../asset/asset-manager/asset-manager'; import { EventTarget, AsyncDelegate, sys, macro, VERSION, cclegacy, screen, Settings, settings, assert, garbageCollectionManager, DebugMode, warn, log, _resetDebugSetting } from '../core'; import { input } from '../input'; -import { deviceManager } from '../gfx'; +import { deviceManager, LegacyRenderMode } from '../gfx'; import { SplashScreen } from './splash-screen'; import { RenderPipeline } from '../rendering'; import { Layers, Node } from '../scene-graph'; import { builtinResMgr } from '../asset/asset-manager/builtin-res-mgr'; import { Director, director } from './director'; import { bindingMappingInfo } from '../rendering/define'; -import { IBundleOptions } from '../asset/asset-manager/shared'; import { ICustomJointTextureLayout } from '../3d/skeletal-animation/skeletal-animation-utils'; import { IPhysicsConfig } from '../physics/framework/physics-config'; import { effectSettings } from '../core/effect-settings'; @@ -174,7 +173,7 @@ export interface IGameConfig { * 是否让游戏外框对齐到屏幕上,目前只在 web 平台生效 * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.SCREEN: { 'exactFitScreen': true }}``` to set this. */ - exactFitScreen: boolean, + exactFitScreen?: boolean, } /** @@ -752,6 +751,9 @@ export class Game extends EventTarget { screen.init(); garbageCollectionManager.init(); deviceManager.init(this.canvas, bindingMappingInfo); + if (macro.CUSTOM_PIPELINE_NAME === '') { + cclegacy.rendering = undefined; + } assetManager.init(); builtinResMgr.init(); Layers.init(); @@ -770,12 +772,17 @@ export class Game extends EventTarget { this.emit(Game.EVENT_PRE_SUBSYSTEM_INIT); return this.onPreSubsystemInitDelegate.dispatch(); }) - .then(() => effectSettings.init(config.effectSettingsPath)) + .then(() => effectSettings.init(settings.querySettings(Settings.Category.RENDERING, 'effectSettingsPath') as string)) .then(() => { // initialize custom render pipeline if (!cclegacy.rendering || !cclegacy.rendering.enableEffectImport) { return; } + const renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode'); + if (renderMode === LegacyRenderMode.HEADLESS) { + cclegacy.rendering.init(deviceManager.gfxDevice, null); + return; + } const data = effectSettings.data; if (data === null) { console.error('Effect settings not found, effects will not be imported.'); @@ -945,7 +952,7 @@ export class Game extends EventTarget { const preloadBundles = settings.querySettings<{ bundle: string, version: string }[]>(Settings.Category.ASSETS, 'preloadBundles'); if (!preloadBundles) return Promise.resolve([]); return Promise.all(preloadBundles.map(({ bundle, version }) => new Promise((resolve, reject) => { - const opts: IBundleOptions = {}; + const opts: Record = {}; if (version) opts.version = version; assetManager.loadBundle(bundle, opts, (err) => { if (err) { diff --git a/cocos/gfx/base/device.ts b/cocos/gfx/base/device.ts index 7291fe2120..3ccf22f4c0 100644 --- a/cocos/gfx/base/device.ts +++ b/cocos/gfx/base/device.ts @@ -27,7 +27,8 @@ import { CommandBufferInfo, BufferInfo, BufferViewInfo, TextureInfo, TextureViewInfo, SamplerInfo, DescriptorSetInfo, ShaderInfo, InputAssemblerInfo, RenderPassInfo, FramebufferInfo, DescriptorSetLayoutInfo, PipelineLayoutInfo, QueueInfo, BufferTextureCopy, DeviceInfo, DeviceCaps, GeneralBarrierInfo, TextureBarrierInfo, BufferBarrierInfo, - SwapchainInfo, BindingMappingInfo, Format, FormatFeature, TextureType, TextureUsageBit, TextureFlagBit, Offset, Extent, SampleCount, TextureSubresLayers, + SwapchainInfo, BindingMappingInfo, Format, FormatFeature, TextureType, TextureUsageBit, + TextureFlagBit, Offset, Extent, SampleCount, TextureSubresLayers, } from './define'; import { Buffer } from './buffer'; import { CommandBuffer } from './command-buffer'; @@ -354,11 +355,10 @@ export abstract class Device { } export class DefaultResource { - private _texture2D : Texture | null = null; - private _texture3D : Texture | null = null; - private _textureCube : Texture | null = null; - private _texture1DArray : Texture | null = null; - private _texture2DArray : Texture | null = null; + private _texture2D: Texture | null = null; + private _texture3D: Texture | null = null; + private _textureCube: Texture | null = null; + private _texture2DArray: Texture | null = null; constructor (device: Device) { const bufferSize = 64; @@ -412,20 +412,6 @@ export class DefaultResource { const copyRegion = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(2, 2, 2), new TextureSubresLayers(0, 0, 1)); device.copyBuffersToTexture([buffer], this._texture3D, [copyRegion]); } - if (device.capabilities.maxArrayTextureLayers >= 2) { - this._texture1DArray = device.createTexture(new TextureInfo( - TextureType.TEX1D_ARRAY, - TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, - Format.RGBA8, - 1, 1, - TextureFlagBit.NONE, - 2, - )); - const copyRegion = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(1, 1, 1), new TextureSubresLayers(0, 0, 1)); - device.copyBuffersToTexture([buffer], this._texture1DArray, [copyRegion]); - copyRegion.texSubres.baseArrayLayer = 1; - device.copyBuffersToTexture([buffer], this._texture1DArray, [copyRegion]); - } if (device.capabilities.maxArrayTextureLayers >= 2) { this._texture2DArray = device.createTexture(new TextureInfo( TextureType.TEX2D_ARRAY, @@ -442,12 +428,11 @@ export class DefaultResource { } } - public getTexture (type : TextureType) { + public getTexture (type: TextureType) { switch (type) { case TextureType.TEX2D: return this._texture2D; case TextureType.TEX3D: return this._texture3D; case TextureType.CUBE: return this._textureCube; - case TextureType.TEX1D_ARRAY: return this._texture1DArray; case TextureType.TEX2D_ARRAY: return this._texture2DArray; default: return null; } diff --git a/cocos/gi/light-probe/light-probe.ts b/cocos/gi/light-probe/light-probe.ts index 650f5a824a..9ea470a210 100644 --- a/cocos/gi/light-probe/light-probe.ts +++ b/cocos/gi/light-probe/light-probe.ts @@ -150,7 +150,7 @@ export class LightProbesData { return tetIndex; } - private hasCoefficients () { + public hasCoefficients () { return !this.empty() && this._probes[0].coefficients.length !== 0; } diff --git a/cocos/misc/camera-component.ts b/cocos/misc/camera-component.ts index c69a319ad8..98071e802f 100644 --- a/cocos/misc/camera-component.ts +++ b/cocos/misc/camera-component.ts @@ -24,7 +24,7 @@ */ import { EDITOR } from 'internal:constants'; -import { ccclass, help, executeInEditMode, menu, tooltip, displayOrder, type, serializable, visible } from 'cc.decorator'; +import { ccclass, help, executeInEditMode, menu, tooltip, displayOrder, type, serializable, visible, range, rangeMin } from 'cc.decorator'; import { RenderTexture } from '../asset/assets/render-texture'; import { UITransform } from '../2d/framework'; import { Component } from '../scene-graph'; @@ -41,23 +41,42 @@ import { ClearFlagBit } from '../gfx'; const _temp_vec3_1 = new Vec3(); -/** - * @en The projection type. - * @zh 投影类型。 - */ const ProjectionType = Enum(CameraProjection); const FOVAxis = Enum(CameraFOVAxis); const Aperture = Enum(CameraAperture); const Shutter = Enum(CameraShutter); const ISO = Enum(CameraISO); +/** + * @en Clear screen flag enumeration of the camera. + * @zh 相机的清屏标记枚举。 + */ export const ClearFlag = Enum({ + /** + * @en Clear the screen with [[SceneGlobals.skybox]], will clear the depth and stencil buffer at the same time. + * @zh 使用指定天空盒 [[SceneGlobals.skybox]] 清屏,会同时清理深度和蒙版缓冲。 + */ SKYBOX: SKYBOX_FLAG | ClearFlagBit.DEPTH_STENCIL, + /** + * @en Clear the screen with the given [[Camera.clearColor]], will clear the depth and stencil buffer at the same time. + * @zh 使用指定的相机清屏颜色 [[Camera.clearColor]] 来清屏,会同时清理将深度和蒙版缓冲。 + */ SOLID_COLOR: ClearFlagBit.ALL, + /** + * @en Only clear the depth and stencil buffer while keeping the color buffer intact. Often used in UI camera. + * @zh 只清理深度和蒙版缓冲,同时保留颜色缓冲不变。常用于 UI 相机。 + */ DEPTH_ONLY: ClearFlagBit.DEPTH_STENCIL, + /** + * @en Don't clear anything and continue rendering. + * @zh 不清理任何内容就开始渲染,适合多 Camera 叠加渲染。 + */ DONT_CLEAR: ClearFlagBit.NONE, }); +/** + * @internal + */ export declare namespace Camera { export type ProjectionType = EnumAlias; export type FOVAxis = EnumAlias; @@ -170,6 +189,7 @@ export class Camera extends Component { * @zh 相机的渲染优先级,值越小越优先渲染。 */ @displayOrder(0) + @range([0, 65535, 1]) @tooltip('i18n:camera.priority') get priority () { return this._priority; @@ -311,6 +331,7 @@ export class Camera extends Component { @visible(function (this: Camera) { return this._projection === ProjectionType.PERSPECTIVE; }) + @range([1, 180, 1]) @tooltip('i18n:camera.fov') get fov () { return this._fov; @@ -329,6 +350,7 @@ export class Camera extends Component { @visible(function (this: Camera) { return this._projection === ProjectionType.ORTHO; }) + @rangeMin(1) @tooltip('i18n:camera.ortho_height') get orthoHeight () { return this._orthoHeight; @@ -344,6 +366,7 @@ export class Camera extends Component { * @zh 相机的近裁剪距离,应在可接受范围内尽量取最大。 */ @displayOrder(10) + @rangeMin(0) @tooltip('i18n:camera.near') get near () { return this._near; @@ -359,6 +382,7 @@ export class Camera extends Component { * @zh 相机的远裁剪距离,应在可接受范围内尽量取最小。 */ @displayOrder(11) + @rangeMin(0) @tooltip('i18n:camera.far') get far () { return this._far; @@ -489,6 +513,9 @@ export class Camera extends Component { } } + /** + * @internal + */ get cameraType () { return this._cameraType; } @@ -503,6 +530,9 @@ export class Camera extends Component { } } + /** + * @internal + */ get trackingType () { return this._trackingType; } diff --git a/cocos/particle/animator/color-overtime.ts b/cocos/particle/animator/color-overtime.ts index 53d63832fb..b14aa8b8d9 100644 --- a/cocos/particle/animator/color-overtime.ts +++ b/cocos/particle/animator/color-overtime.ts @@ -31,11 +31,18 @@ import { isGradientTwoValues } from '../particle-general-function'; const COLOR_OVERTIME_RAND_OFFSET = ModuleRandSeed.COLOR; +/** + * @en + * This module will modify particle color over life time. You can set the color gradient to see how it changes. + * @zh + * 本模块用于在粒子生命周期内对颜色进行改变,可以修改模块下的颜色渐变条来查看粒子颜色渐变效果。 + */ @ccclass('cc.ColorOvertimeModule') export default class ColorOvertimeModule extends ParticleModuleBase { @serializable _enable = false; /** + * @en Enable or disable this module. * @zh 是否启用。 */ @displayOrder(0) @@ -51,7 +58,8 @@ export default class ColorOvertimeModule extends ParticleModuleBase { } /** - * @zh 颜色随时间变化的参数,各个 key 之间线性差值变化。 + * @en Change color over life time. Evaluate by key interpolation. + * @zh 颜色随时间变化的参数,各个 key 之间线性插值变化。 */ @type(GradientRange) @serializable @@ -59,6 +67,12 @@ export default class ColorOvertimeModule extends ParticleModuleBase { public color = new GradientRange(); public name = PARTICLE_MODULE_NAME.COLOR; + /** + * @en Apply color animation to particle. + * @zh 作用颜色变换到粒子上。 + * @param particle @en Particle to animate. @zh 模块需要更新的粒子。 + * @internal + */ public animate (particle: Particle) { particle.color.set(particle.startColor); const rand = isGradientTwoValues(this.color) ? pseudoRandom(particle.randomSeed + COLOR_OVERTIME_RAND_OFFSET) : 0; diff --git a/cocos/particle/animator/curve-range.ts b/cocos/particle/animator/curve-range.ts index b18ea5d007..59b4bce740 100644 --- a/cocos/particle/animator/curve-range.ts +++ b/cocos/particle/animator/curve-range.ts @@ -24,7 +24,7 @@ import { ccclass } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; -import { lerp, RealCurve, CCClass, geometry, Enum } from '../../core'; +import { lerp, RealCurve, CCClass, geometry, Enum, approx, EPSILON } from '../../core'; import { PixelFormat, Filter, WrapMode } from '../../asset/assets/asset-enum'; import { Texture2D, ImageAsset } from '../../asset/assets'; @@ -37,6 +37,21 @@ const SerializableTable = [ ['mode', 'constantMin', 'constantMax', 'multiplier'], ] as const; +/** + * @en + * This curve has 4 modes: + * Constant means this curve only have the constant value all the time. + * Tow Constants means this curve value will generated by the interpolation of these 2 constant values. + * Curve means the curve value will generated by one RealCurve. + * A RealCurve has many key frames, so the value will be generated by interpolation of key frames. + * Two Curves has two RealCurve, so the value is generated by the interpolation of these 2 curves. + * @zh + * 曲线控件包含四种模式: + * 常值,表示曲线的值从头到尾都是一个常量。 + * 双常值,表示曲线的值是从两个常量进行插值。 + * 曲线,包含一个 RealCurve 曲线值,从 RealCurve 取得关键帧进行插值得到。 + * 双曲线,包含两个 RealCurve 曲线,首先对每个曲线进行关键帧插值计算,然后再对算出的两个曲线值进行插值得到最终的数值。 + */ export const Mode = Enum({ Constant: 0, Curve: 1, @@ -44,14 +59,30 @@ export const Mode = Enum({ TwoConstants: 3, }); // TODO: can not remove ccclass for now, we need ccclass specified deserialization to handle deserialization of RealCurve + +/** + * @en + * CurveRange is a data structure which contains some constants or curves. + * Calculate the value by its mode and particle system will use it to change particle attribute associated with it. + * Refer [[CurveRange.Mode]] to see the detail of calculation mode. + * @zh + * CurveRange 是一类数据结构,其包含了多个常数值或曲线值,计算时其将根据计算模式计算最终值,粒子系统使用此数据结构对所有的粒子的属性进行修改。 + * 详细的计算模式请参考 [[CurveRange.Mode]] 的解释。 + */ @ccclass('cc.CurveRange') export default class CurveRange { + /** + * @en The curve mode. See [[Mode]]. + * @zh 曲线类型 [[Mode]]。 + */ public static Mode = Mode; /** - * @zh 当mode为Curve时,spline创建1个RealCurve,当mode为TwoCurves时,splineMax创建1个RealCurve,splineMin创建一个RealCurve + * @en Spline will create a RealCurve when mode is curve. The mode of curve range, see [[Mode]]. + * A RealCurve will be created for each spline(SplineMin & SplineMax) when mode is TwoCurves. + * @zh 当mode为Curve时,spline创建1个RealCurve,当mode为TwoCurves时,splineMax创建1个RealCurve,splineMin创建一个RealCurve。 */ - set mode (mode:number) { + set mode (mode: number) { this._mode = mode; switch (mode) { case Mode.Constant: @@ -73,22 +104,26 @@ export default class CurveRange { return this._mode; } /** - * @zh 当mode为Curve时,使用的曲线。 + * @en The spline used when mode is Mode.Curve. + * @zh 当 mode 为Curve时,使用的曲线。 */ - public declare spline:RealCurve; + public declare spline: RealCurve; /** - * @zh 当mode为TwoCurves时,使用的曲线下限。 + * @en The min spline when mode is Mode.TwoCurves. + * @zh 当 mode 为TwoCurves时,使用的曲线下限。 */ - public declare splineMin:RealCurve; + public declare splineMin: RealCurve; /** - * @zh 当mode为TwoCurves时,使用的曲线上限。 + * @en Max spline when mode is TwoCurves. + * @zh 当 mode 为TwoCurves时,使用的曲线上限。 */ - public declare splineMax:RealCurve; + public declare splineMax: RealCurve; /** - * @zh 当mode为Curve时,使用的曲线。 + * @en Gets/Sets the curve when use curve mode. + * @zh 当 mode 为 Curve 时,使用的曲线。 * @deprecated Since V3.3. Use `spline` instead. */ get curve () { @@ -101,7 +136,8 @@ export default class CurveRange { } /** - * @zh 当mode为TwoCurves时,使用的曲线下限。 + * @en Get/Set min curve when use TwoCurves mode. + * @zh 当 mode 为 TwoCurves 时,使用的曲线下限。 * @deprecated Since V3.3. Use `splineMin` instead. */ get curveMin () { @@ -114,7 +150,8 @@ export default class CurveRange { } /** - * @zh 当mode为TwoCurves时,使用的曲线上限。 + * @en Gets/Sets max curve when use TwoCurves mode. + * @zh 当 mode 为 TwoCurves 时,使用的曲线上限。 * @deprecated Since V3.3. Use `splineMax` instead. */ get curveMax () { @@ -127,27 +164,32 @@ export default class CurveRange { } /** - * @zh 当mode为Constant时,曲线的值。 + * @en Constant value when use constant mode. + * @zh 当 mode 为 Constant 时,曲线的值。 */ public constant = 0; /** - * @zh 当mode为TwoConstants时,曲线的上限。 + * @en Constant min value when use TwoConstants mode. + * @zh 当 mode 为 TwoConstants 时,曲线的下限。 */ public constantMin = 0; /** - * @zh 当mode为TwoConstants时,曲线的下限。 + * @en Constant max value when use TwoConstants mode. + * @zh 当 mode 为 TwoConstants 时,曲线的上限。 */ public constantMax = 0; /** + * @en Mulitplier used to evaluate spline. * @zh 应用于曲线插值的系数。 */ public multiplier = 1; /** - * @zh 曲线类型[[Mode]]。 + * @en Curve mode to use. + * @zh 曲线类型 [[Mode]]。 */ private _mode = Mode.Constant; @@ -161,8 +203,17 @@ export default class CurveRange { } } + /** + * @en Calculate curve value. + * @zh 计算曲线数值。 + * @param time @en Normalized time to interpolate. @zh 用于插值的归一化时间。 + * @param rndRatio @en Interpolation ratio when mode is TwoCurves or TwoConstants. + * Particle attribute will pass in a random number to get a random result. + * @zh 当模式为双曲线或双常数时,使用的插值比例,通常粒子系统会传入一个随机数以获得一个随机结果。 + * @returns @en Curve value. @zh 曲线的值。 + */ public evaluate (time: number, rndRatio: number) { - switch (this.mode) { + switch (this._mode) { default: case Mode.Constant: return this.constant; @@ -175,8 +226,13 @@ export default class CurveRange { } } + /** + * @en Gets the max value this curve can reach. + * @zh 获得曲线能达到的最大值。 + * @returns @en Max value of this curve @zh 曲线能达到的最大值 + */ public getMax (): number { - switch (this.mode) { + switch (this._mode) { default: case Mode.Constant: return this.constant; @@ -189,12 +245,26 @@ export default class CurveRange { } } + public isZero (): boolean { + switch (this._mode) { + default: + case Mode.Constant: + return approx(this.constant, 0.0, EPSILON); + case Mode.Curve: + return approx(this.multiplier, 0.0, EPSILON); + case Mode.TwoConstants: + return approx(Math.max(Math.abs(this.constantMax), Math.abs(this.constantMin)), 0.0, EPSILON); + case Mode.TwoCurves: + return approx(this.multiplier, 0.0, EPSILON); + } + } + /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onBeforeSerialize (props) { // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return SerializableTable[this.mode]; + return SerializableTable[this._mode]; } private declare _curve: geometry.AnimationCurve | undefined; @@ -286,7 +356,7 @@ function updateTexture (tex: Texture2D | null, data, width, height): Texture2D { return tex; } -export function packCurveRangeZ (tex: Texture2D | null, data: Float32Array | null, samples:number, cr: CurveRange, discrete?: boolean) { +export function packCurveRangeZ (tex: Texture2D | null, data: Float32Array | null, samples: number, cr: CurveRange, discrete?: boolean) { const height = evaluateHeight(cr); const len = samples * height * 4; if (data === null || data.length !== len) { @@ -313,7 +383,7 @@ export function packCurveRangeZ (tex: Texture2D | null, data: Float32Array | nul } return { texture: updateTexture(tex, data, samples, height), texdata: data }; } -export function packCurveRangeN (tex: Texture2D | null, data: Float32Array | null, samples:number, cr: CurveRange, discrete?: boolean) { +export function packCurveRangeN (tex: Texture2D | null, data: Float32Array | null, samples: number, cr: CurveRange, discrete?: boolean) { const height = evaluateHeight(cr); const len = samples * height * 4; if (data === null || data.length !== len) { diff --git a/cocos/particle/animator/force-overtime.ts b/cocos/particle/animator/force-overtime.ts index ee94021b48..91d5fd875f 100644 --- a/cocos/particle/animator/force-overtime.ts +++ b/cocos/particle/animator/force-overtime.ts @@ -34,11 +34,20 @@ const FORCE_OVERTIME_RAND_OFFSET = ModuleRandSeed.FORCE; const _temp_v3 = new Vec3(); +/** + * @en + * This module will apply force to particle over life time. + * Force on every axis is curve so you can modify these curves to see how it animate. + * @zh + * 本模块用于在粒子生命周期内对粒子施加外力。 + * 每个轴上的受力大小都是可以用曲线来进行编辑,修改曲线就能够看到粒子受力变化的效果了。 + */ @ccclass('cc.ForceOvertimeModule') export default class ForceOvertimeModule extends ParticleModuleBase { @serializable _enable = false; /** + * @en Enable this module or not. * @zh 是否启用。 */ @displayOrder(0) @@ -54,6 +63,7 @@ export default class ForceOvertimeModule extends ParticleModuleBase { } /** + * @en Force on the X axis. * @zh X 轴方向上的加速度分量。 */ @type(CurveRange) @@ -63,6 +73,7 @@ export default class ForceOvertimeModule extends ParticleModuleBase { public x = new CurveRange(); /** + * @en Force on the Y axis. * @zh Y 轴方向上的加速度分量。 */ @type(CurveRange) @@ -72,6 +83,7 @@ export default class ForceOvertimeModule extends ParticleModuleBase { public y = new CurveRange(); /** + * @en Force on the Z axis. * @zh Z 轴方向上的加速度分量。 */ @type(CurveRange) @@ -81,6 +93,7 @@ export default class ForceOvertimeModule extends ParticleModuleBase { public z = new CurveRange(); /** + * @en Force calculation coordinate. See [[Space]]. * @zh 加速度计算时采用的坐标系 [[Space]]。 */ @type(Space) @@ -103,10 +116,24 @@ export default class ForceOvertimeModule extends ParticleModuleBase { this.needUpdate = true; } + /** + * @en Update force module calculate transform. + * @zh 更新模块,计算坐标变换。 + * @param space @en Force module update space. @zh 模块更新空间。 + * @param worldTransform @en Particle system world transform. @zh 粒子系统的世界变换矩阵。 + * @internal + */ public update (space, worldTransform) { this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation); } + /** + * @en Apply force to particle. + * @zh 作用力到粒子上。 + * @param p @en Particle to animate. @zh 模块需要更新的粒子。 + * @param dt @en Update interval time. @zh 粒子系统更新的间隔时间。 + * @internal + */ public animate (p: Particle, dt) { const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; const randX = isCurveTwoValues(this.x) ? pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET) : 0; diff --git a/cocos/particle/animator/gradient-range.ts b/cocos/particle/animator/gradient-range.ts index 89eed4b1ce..c4b3f5c299 100644 --- a/cocos/particle/animator/gradient-range.ts +++ b/cocos/particle/animator/gradient-range.ts @@ -37,6 +37,22 @@ const SerializableTable = EDITOR && [ ['_mode', 'gradient'], ]; +/** + * @en + * Gradinet is a component to calculate color value. It contains 5 modes: + * Color is just the color value all the time. + * Two Colors has 2 color values to interpolate the color value. + * Gradient value is generated by many color keys interpolation. + * Two Gradients has 2 gradients. The value is calculated by interpolation of the 2 gradients value. + * Random Color has one gradient. The value is get from color keys of the gradient randomly. + * @zh + * 渐变曲线是用来计算颜色值的控件,它包含五种模式: + * 单色从头到尾只返回一种颜色值。 + * 双色包含两个颜色值,返回两种颜色之间的插值。 + * 渐变曲线包含许多颜色帧,返回颜色帧之间的插值。 + * 双渐变曲线包含两个渐变曲线,对两个渐变曲线返回的颜色值再进行插值。 + * 随机颜色包含一个颜色曲线,从曲线中随机获取颜色值。 + */ const Mode = Enum({ Color: 0, Gradient: 1, @@ -45,10 +61,20 @@ const Mode = Enum({ RandomColor: 4, }); +/** + * @en + * GradientRange is a data structure which contains some constant colors or gradients. + * Calculate the color by its mode and particle system will use it to change particle attribute associated with it. + * Refer [[GradientRange.Mode]] to see the detail of calculation mode. + * @zh + * GradientRange 是一类数据结构,其包含了多个常数颜色或渐变色,计算时其将根据计算模式计算最终颜色,粒子系统使用此数据结构对所有的粒子的属性进行修改。 + * 详细的计算模式请参考 [[GradientRange.Mode]] 的解释。 + */ @ccclass('cc.GradientRange') export default class GradientRange { /** - * @zh 渐变色类型 [[Mode]]。 + * @en Gets/Sets color gradient mode to use. See [[Mode]]. + * @zh 使用的渐变色类型 参考 [[Mode]]。 */ @type(Mode) get mode () { @@ -69,43 +95,53 @@ export default class GradientRange { this._mode = m; } + /** + * @en The gradient mode. See [[Mode]]. + * @zh 渐变色类型 参考 [[Mode]]。 + */ public static Mode = Mode; /** - * @zh 当mode为Color时的颜色。 + * @en Color value when use color mode. + * @zh 当 mode 为 Color 时的颜色。 */ @serializable @editable public color = Color.WHITE.clone(); /** - * @zh 当mode为TwoColors时的颜色下限。 + * @en Min color value when use TwoColors mode. + * @zh 当 mode 为 TwoColors 时的颜色下限。 */ @serializable @editable public colorMin = Color.WHITE.clone(); /** - * @zh 当mode为TwoColors时的颜色上限。 + * @en Max color value when use TwoColors mode. + * @zh 当 mode 为 TwoColors 时的颜色上限。 */ @serializable @editable public colorMax = Color.WHITE.clone(); /** - * @zh 当mode为Gradient时的颜色渐变。 + * @en Gradient value when use gradient mode. + * @zh 当 mode 为 Gradient 时的颜色渐变。 */ @type(Gradient) public gradient = new Gradient(); /** + * @en Gradient min value when use TwoGradients. * @zh 当mode为TwoGradients时的颜色渐变下限。 */ @type(Gradient) public gradientMin = new Gradient(); /** - * @zh 当mode为TwoGradients时的颜色渐变上限。 + * @en Gradient max value when use TwoGradients. + * @zh 当 mode 为 TwoGradients 时的颜色渐变上限。 */ @type(Gradient) public gradientMax = new Gradient(); @@ -115,6 +151,15 @@ export default class GradientRange { private _color = Color.WHITE.clone(); + /** + * @en Calculate gradient value. + * @zh 计算颜色渐变曲线数值。 + * @param time @en Normalized time to interpolate. @zh 用于插值的归一化时间。 + * @param rndRatio @en Interpolation ratio when mode is TwoColors or TwoGradients. + * Particle attribute will pass in a random number to get a random result. + * @zh 当模式为双色或双渐变色时,使用的插值比例,通常粒子系统会传入一个随机数以获得一个随机结果。 + * @returns @en Gradient value. @zh 颜色渐变曲线的值。 + */ public evaluate (time: number, rndRatio: number) { switch (this._mode) { case Mode.Color: diff --git a/cocos/particle/animator/gradient.ts b/cocos/particle/animator/gradient.ts index d50482b6f1..acb5d1468d 100644 --- a/cocos/particle/animator/gradient.ts +++ b/cocos/particle/animator/gradient.ts @@ -72,7 +72,21 @@ CCClass.fastDefine('cc.AlphaKey', AlphaKey, { CCClass.Attr.setClassAttr(AlphaKey, 'alpha', 'visible', true); CCClass.Attr.setClassAttr(AlphaKey, 'time', 'visible', true); +/** + * @en Gradient is a component that has a lot of color keys and alpha keys to get the interpolated color value. + * @zh 渐变曲线控件包含了颜色关键帧和透明度关键帧,在关键帧中进行插值渐变返回最终的颜色值。 + */ export default class Gradient { + /** + * @en + * There are 2 kind of mode: + * Blend just interpolate the nearest 2 colors from keys. + * Fixed get the nearest color from keys without interpolate. + * @zh + * 这个控件包含了两种取色模式: + * 混合模式对取到的最近两个颜色帧进行插值计算。 + * 固定模式直接取最近的颜色帧返回,不进行插值。 + */ public static Mode = Mode; /** * @en Array of color key. @@ -96,11 +110,21 @@ export default class Gradient { this._color = Color.WHITE.clone(); } + /** + * @en Set color keys array and alpha keys array. + * @zh 设置颜色和透明度的关键帧列表。 + * @param colorKeys @en Array of color keys @zh 颜色关键帧列表 + * @param alphaKeys @en Array of alpha keys @zh 透明度关键帧列表 + */ public setKeys (colorKeys: ColorKey[], alphaKeys: AlphaKey[]) { this.colorKeys = colorKeys; this.alphaKeys = alphaKeys; } + /** + * @en Sort color keys and alpha keys. + * @zh 对颜色和透明度的关键帧进行排序。 + */ public sortKeys () { if (this.colorKeys.length > 1) { this.colorKeys.sort((a, b) => a.time - b.time); @@ -110,12 +134,23 @@ export default class Gradient { } } + /** + * @en Interpolate color and alpha from color and alpha keys. + * @zh 根据颜色列表插值计算颜色和透明度。 + * @param time @en Normalized time to interpolate. @zh 用于插值的归一化时间。 + * @returns @en Interpolated color value. @zh 插值过后的颜色值。 + */ public evaluate (time: number) { this.getRGB(time); this._color._set_a_unsafe(this.getAlpha(time)!); return this._color; } + /** + * @en Generates a random color and alpha. + * @zh 随机生成颜色和透明度。 + * @returns @en Randomized color. @zh 随机生成的颜色。 + */ public randomColor () { const c = this.colorKeys[Math.trunc(Math.random() * this.colorKeys.length)]; const a = this.alphaKeys[Math.trunc(Math.random() * this.alphaKeys.length)]; diff --git a/cocos/particle/animator/limit-velocity-overtime.ts b/cocos/particle/animator/limit-velocity-overtime.ts index 4991785d2f..f7d7f6f012 100644 --- a/cocos/particle/animator/limit-velocity-overtime.ts +++ b/cocos/particle/animator/limit-velocity-overtime.ts @@ -34,11 +34,22 @@ const LIMIT_VELOCITY_RAND_OFFSET = ModuleRandSeed.LIMIT; const _temp_v3 = new Vec3(); const _temp_v3_1 = new Vec3(); +/** + * @en + * This module will damping particle velocity to the limit value over life time. + * Open the separateAxes option you can damping the particle velocity on XYZ axis + * Limit value on every axis is curve so you can modify these curves to see how it animate. + * @zh + * 本模块用于在粒子生命周期内对速度进行衰减,速度每次衰减比例为 dampen 持续衰减到极限速度。 + * 打开 separateAxes 就能够修改粒子在三个轴方向的极限速度大小。 + * 每个轴上的粒子极限速度大小都是可以用曲线来进行编辑,修改曲线就能够看到粒子大小变化的效果了。 + */ @ccclass('cc.LimitVelocityOvertimeModule') export default class LimitVelocityOvertimeModule extends ParticleModuleBase { @serializable _enable = false; /** + * @en Enable this module or not. * @zh 是否启用。 */ @displayOrder(0) @@ -54,6 +65,7 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { } /** + * @en Limit velocity on X axis. * @zh X 轴方向上的速度下限。 */ @type(CurveRange) @@ -66,6 +78,7 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { public limitX = new CurveRange(); /** + * @en Limit velocity on Y axis. * @zh Y 轴方向上的速度下限。 */ @type(CurveRange) @@ -78,6 +91,7 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { public limitY = new CurveRange(); /** + * @en Limit velocity on Z axis. * @zh Z 轴方向上的速度下限。 */ @type(CurveRange) @@ -90,6 +104,7 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { public limitZ = new CurveRange(); /** + * @en Velocity limit. * @zh 速度下限。 */ @type(CurveRange) @@ -102,7 +117,8 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { public limit = new CurveRange(); /** - * @zh 当前速度与速度下限的插值。 + * @en Dampen velocity percent every time. + * @zh 速度每次衰减的比例。 */ @serializable @displayOrder(7) @@ -110,6 +126,7 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { public dampen = 3; /** + * @en Limit velocity on separate axis. * @zh 是否三个轴分开限制。 */ @serializable @@ -118,6 +135,7 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { public separateAxes = false; /** + * @en Space used to calculate limit velocity. * @zh 计算速度下限时采用的坐标系 [[Space]]。 */ @type(Space) @@ -141,10 +159,24 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { this.needUpdate = true; } + /** + * @en Update limit velocity module calculate transform. + * @zh 更新模块,计算坐标变换。 + * @param space @en Limit velocity module update space @zh 模块更新空间 + * @param worldTransform @en Particle system world transform @zh 粒子系统的世界变换矩阵 + * @internal + */ public update (space: number, worldTransform: Mat4) { this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation); } + /** + * @en Apply limit velocity to particle. + * @zh 作用速度衰减到粒子上。 + * @param p @en Particle to animate @zh 模块需要更新的粒子 + * @param dt @en Update interval time @zh 粒子系统更新的间隔时间 + * @internal + */ public animate (p: Particle, dt: number) { const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; const dampedVel = _temp_v3; diff --git a/cocos/particle/animator/noise-module.ts b/cocos/particle/animator/noise-module.ts index 5b3e60d23b..cfce15415a 100644 --- a/cocos/particle/animator/noise-module.ts +++ b/cocos/particle/animator/noise-module.ts @@ -26,13 +26,20 @@ import { CCFloat, CCInteger, _decorator, Vec3 } from '../../core'; import { ParticleNoise } from '../noise'; import { Particle, PARTICLE_MODULE_NAME, ParticleModuleBase } from '../particle'; -const { ccclass, serializable, displayOrder, type, range, slide, rangeStep, visible } = _decorator; +const { ccclass, serializable, displayOrder, type, range, slide, visible } = _decorator; +/** + * @en + * Adding noise to your particles is a simple and effective way to create interesting patterns and effects. + * @zh + * 为粒子添加噪声是创建有趣方案和效果的简单有效方法。 + */ @ccclass('cc.NoiseModule') export class NoiseModule extends ParticleModuleBase { @serializable _enable = false; /** + * @en Enable this module or not. * @zh 是否启用。 */ @displayOrder(0) @@ -47,6 +54,10 @@ export class NoiseModule extends ParticleModuleBase { this.target.enableModule(this.name, val, this); } + /** + * @en Strength on X axis. + * @zh X 轴上的强度大小。 + */ @type(CCFloat) @range([0, 100]) @displayOrder(16) @@ -60,6 +71,10 @@ export class NoiseModule extends ParticleModuleBase { @serializable private _strengthX = 10; + /** + * @en Strength on Y axis. + * @zh Y 轴上的强度大小。 + */ @type(CCFloat) @range([0, 100]) @displayOrder(16) @@ -73,6 +88,10 @@ export class NoiseModule extends ParticleModuleBase { @serializable private _strengthY = 10; + /** + * @en Strength on Z axis. + * @zh Z 轴上的强度大小。 + */ @type(CCFloat) @range([0, 100]) @displayOrder(16) @@ -86,6 +105,10 @@ export class NoiseModule extends ParticleModuleBase { @serializable private _strengthZ = 10; + /** + * @en Noise texture roll speed on X axis. + * @zh X 轴上的噪声图滚动速度。 + */ @type(CCFloat) @range([0, 100]) @slide @@ -99,6 +122,10 @@ export class NoiseModule extends ParticleModuleBase { @serializable private _noiseSpeedX = 0; + /** + * @en Noise texture roll speed on Y axis. + * @zh Y 轴上的噪声图滚动速度。 + */ @type(CCFloat) @range([0, 100]) @displayOrder(16) @@ -112,6 +139,10 @@ export class NoiseModule extends ParticleModuleBase { @serializable private _noiseSpeedY = 0; + /** + * @en Noise texture roll speed on Z axis. + * @zh Z 轴上的噪声图滚动速度。 + */ @type(CCFloat) @range([0, 100]) @displayOrder(16) @@ -125,9 +156,12 @@ export class NoiseModule extends ParticleModuleBase { @serializable private _noiseSpeedZ = 0; + /** + * @en Noise frequency. + * @zh 噪声图频率。 + */ @type(CCFloat) - @range([0, 100]) - @rangeStep(0.1) + @range([0, 100, 0.1]) @displayOrder(16) @slide get noiseFrequency () { @@ -139,10 +173,13 @@ export class NoiseModule extends ParticleModuleBase { @serializable private _noiseFrequency = 1; + /** + * @en Remap the final noise X axis values into a different range. + * @zh 噪声值映射到 X 轴的不同范围。 + */ @visible(false) @type(CCFloat) - @range([0, 1]) - @rangeStep(0.1) + @range([0, 1, 0.1]) @displayOrder(16) @slide get remapX () { @@ -154,10 +191,13 @@ export class NoiseModule extends ParticleModuleBase { @serializable private _remapX = 0; + /** + * @en Remap the final noise Y axis values into a different range. + * @zh 噪声值映射到 Y 轴的不同范围。 + */ @visible(false) @type(CCFloat) - @range([0, 1]) - @rangeStep(0.1) + @range([0, 1, 0.1]) @displayOrder(16) @slide get remapY () { @@ -169,10 +209,13 @@ export class NoiseModule extends ParticleModuleBase { @serializable private _remapY = 0; + /** + * @en Remap the final noise Z axis values into a different range. + * @zh 噪声值映射到 Z 轴的不同范围。 + */ @visible(false) @type(CCFloat) - @range([0, 1]) - @rangeStep(0.1) + @range([0, 1, 0.1]) @displayOrder(16) @slide get remapZ () { @@ -184,9 +227,12 @@ export class NoiseModule extends ParticleModuleBase { @serializable private _remapZ = 0; + /** + * @en Specify how many layers of overlapping noise are combined to produce the final noise values. + * @zh 指定组合多少层重叠噪声来产生最终噪声值。 + */ @type(CCInteger) - @range([1, 4]) - @rangeStep(1) + @range([1, 4, 1]) @displayOrder(16) @slide get octaves () { @@ -198,11 +244,14 @@ export class NoiseModule extends ParticleModuleBase { @serializable private _octaves = 1; + /** + * @en For each additional noise layer, reduce the strength by this proportion. + * @zh 对于每个附加的噪声层,按此比例降低强度。 + */ // eslint-disable-next-line func-names @visible(function (this: NoiseModule) { return this._octaves > 1; }) @type(CCFloat) - @range([0, 1]) - @rangeStep(0.1) + @range([0, 1, 0.1]) @displayOrder(16) get octaveMultiplier () { return this._octaveMultiplier; @@ -213,11 +262,14 @@ export class NoiseModule extends ParticleModuleBase { @serializable private _octaveMultiplier = 0.5; + /** + * @en For each additional noise layer, adjust the frequency by this multiplier. + * @zh 对于每个附加的噪声层,按此乘数调整频率。 + */ // eslint-disable-next-line func-names @visible(function (this: NoiseModule) { return this._octaves > 1; }) @type(CCFloat) - @range([1, 4]) - @rangeStep(0.1) + @range([1, 4, 0.1]) @displayOrder(16) get octaveScale () { return this._octaveScale; @@ -234,6 +286,13 @@ export class NoiseModule extends ParticleModuleBase { private samplePosition: Vec3 = new Vec3(); + /** + * @en Apply noise effect to particle. + * @zh 作用噪声效果到粒子上。 + * @param particle @en Particle to animate @zh 模块需要更新的粒子 + * @param dt @en Update interval time @zh 粒子系统更新的间隔时间 + * @internal + */ public animate (particle: Particle, dt: number) { this.noise.setTime(particle.particleSystem.time); this.noise.setSpeed(this.noiseSpeedX, this.noiseSpeedY, this.noiseSpeedZ); @@ -252,6 +311,14 @@ export class NoiseModule extends ParticleModuleBase { Vec3.add(particle.position, particle.position, noisePosition.multiplyScalar(dt)); } + /** + * @en Gets the preview of noise texture. + * @zh 获取噪声图预览。 + * @param out @en Noise texture pixels array @zh 噪声图像素数组 + * @param ps @en Particle system @zh 噪声图作用的粒子系统 + * @param width @en Texture width @zh 噪声图宽度 + * @param height @en Texture height @zh 噪声图高度 + */ public getNoisePreview (out: number[], ps, width: number, height: number) { this.noise.setTime(ps.time); this.noise.setSpeed(this.noiseSpeedX, this.noiseSpeedY, this.noiseSpeedZ); diff --git a/cocos/particle/animator/rotation-overtime.ts b/cocos/particle/animator/rotation-overtime.ts index 0d2e87bb61..474b388d1d 100644 --- a/cocos/particle/animator/rotation-overtime.ts +++ b/cocos/particle/animator/rotation-overtime.ts @@ -32,11 +32,22 @@ import { isCurveTwoValues } from '../particle-general-function'; const ROTATION_OVERTIME_RAND_OFFSET = ModuleRandSeed.ROTATION; +/** + * @en + * This module will apply rotation to particle over life time. + * Open the separateAxes option you can change the rotation on XYZ axis + * Rotation on every axis is curve so you can modify these curves to see how it animate. + * @zh + * 本模块用于在粒子生命周期内对粒子施加旋转角速度。 + * 打开 separateAxes 就能够修改粒子在三个轴方向的旋转角速度大小。 + * 每个轴上的旋转角速度都是可以用曲线来进行编辑,修改曲线就能够看到粒子受力变化的效果了。 + */ @ccclass('cc.RotationOvertimeModule') export default class RotationOvertimeModule extends ParticleModuleBase { @serializable _enable = false; /** + * @en Enable this module or not. * @zh 是否启用。 */ @displayOrder(0) @@ -55,7 +66,8 @@ export default class RotationOvertimeModule extends ParticleModuleBase { private _separateAxes = false; /** - * @zh 是否三个轴分开设定旋转(暂不支持)。 + * @en Rotation around separate axis. + * @zh 是否三个轴分开设定旋转。 */ @displayOrder(1) @tooltip('i18n:rotationOvertimeModule.separateAxes') @@ -68,6 +80,7 @@ export default class RotationOvertimeModule extends ParticleModuleBase { } /** + * @en Angle around X axis. * @zh 绕 X 轴设定旋转。 */ @type(CurveRange) @@ -79,6 +92,7 @@ export default class RotationOvertimeModule extends ParticleModuleBase { public x = new CurveRange(); /** + * @en Angle around Y axis. * @zh 绕 Y 轴设定旋转。 */ @type(CurveRange) @@ -90,6 +104,7 @@ export default class RotationOvertimeModule extends ParticleModuleBase { public y = new CurveRange(); /** + * @en Angle around Z axis. * @zh 绕 Z 轴设定旋转。 */ @type(CurveRange) @@ -121,6 +136,13 @@ export default class RotationOvertimeModule extends ParticleModuleBase { } } + /** + * @en Apply rotation to particle. + * @zh 作用旋转到粒子上。 + * @param p @en Particle to animate @zh 模块需要更新的粒子 + * @param dt @en Update interval time @zh 粒子系统更新的间隔时间 + * @internal + */ public animate (p: Particle, dt: number) { const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; const randZ = isCurveTwoValues(this.z) ? pseudoRandom(p.randomSeed + ROTATION_OVERTIME_RAND_OFFSET) : 0; diff --git a/cocos/particle/animator/size-overtime.ts b/cocos/particle/animator/size-overtime.ts index d499a9e235..ced2a24b73 100644 --- a/cocos/particle/animator/size-overtime.ts +++ b/cocos/particle/animator/size-overtime.ts @@ -31,11 +31,22 @@ import { isCurveTwoValues } from '../particle-general-function'; const SIZE_OVERTIME_RAND_OFFSET = ModuleRandSeed.SIZE; +/** + * @en + * This module will modify particle size over life time. + * Open the separateAxes option you can change the particle size on XYZ axis (Size on Z axis is invalid for billboard particle) + * Size on every axis is curve so you can modify these curves to see how it animate. + * @zh + * 本模块用于在粒子生命周期内对大小进行改变。 + * 打开 separateAxes 就能够修改粒子在三个轴方向的大小(z轴大小对公告板粒子无效) + * 每个轴上的粒子大小都是可以用曲线来进行编辑,修改曲线就能够看到粒子大小变化的效果了。 + */ @ccclass('cc.SizeOvertimeModule') export default class SizeOvertimeModule extends ParticleModuleBase { @serializable _enable = false; /** + * @en Enable this module or not. * @zh 是否启用。 */ @displayOrder(0) @@ -51,6 +62,7 @@ export default class SizeOvertimeModule extends ParticleModuleBase { } /** + * @en Different size on separate axis. * @zh 决定是否在每个轴上独立控制粒子大小。 */ @serializable @@ -59,6 +71,7 @@ export default class SizeOvertimeModule extends ParticleModuleBase { public separateAxes = false; /** + * @en Curve to modify particle size. * @zh 定义一条曲线来决定粒子在其生命周期中的大小变化。 */ @type(CurveRange) @@ -70,6 +83,7 @@ export default class SizeOvertimeModule extends ParticleModuleBase { public size = new CurveRange(); /** + * @en Curve to modify particle size on X axis. * @zh 定义一条曲线来决定粒子在其生命周期中 X 轴方向上的大小变化。 */ @type(CurveRange) @@ -81,6 +95,7 @@ export default class SizeOvertimeModule extends ParticleModuleBase { public x = new CurveRange(); /** + * @en Curve to modify particle size on Y axis. * @zh 定义一条曲线来决定粒子在其生命周期中 Y 轴方向上的大小变化。 */ @type(CurveRange) @@ -92,6 +107,7 @@ export default class SizeOvertimeModule extends ParticleModuleBase { public y = new CurveRange(); /** + * @en Curve to modify particle size on Z axis. * @zh 定义一条曲线来决定粒子在其生命周期中 Z 轴方向上的大小变化。 */ @type(CurveRange) @@ -104,6 +120,13 @@ export default class SizeOvertimeModule extends ParticleModuleBase { public name = PARTICLE_MODULE_NAME.SIZE; + /** + * @en Apply size animation to particle. + * @zh 应用大小变换到粒子上。 + * @param particle @en Particle to animate @zh 模块需要更新的粒子 + * @param dt @en Update interval time @zh 粒子系统更新的间隔时间 + * @internal + */ public animate (particle: Particle, dt: number) { if (!this.separateAxes) { const rand = isCurveTwoValues(this.size) ? pseudoRandom(particle.randomSeed + SIZE_OVERTIME_RAND_OFFSET) : 0; diff --git a/cocos/particle/animator/texture-animation.ts b/cocos/particle/animator/texture-animation.ts index b3efbff3f7..aa5f1696d7 100644 --- a/cocos/particle/animator/texture-animation.ts +++ b/cocos/particle/animator/texture-animation.ts @@ -32,7 +32,8 @@ import { isCurveTwoValues } from '../particle-general-function'; const TEXTURE_ANIMATION_RAND_OFFSET = ModuleRandSeed.TEXTURE; /** - * 粒子贴图动画类型。 + * @en Texture animation type. + * @zh 粒子贴图动画类型。 * @enum textureAnimationModule.Mode */ const Mode = Enum({ @@ -48,21 +49,30 @@ const Mode = Enum({ }); /** - * 贴图动画的播放方式。 + * @en Mode to play texture animation. + * @zh 贴图动画的播放方式。 * @enum textureAnimationModule.Animation */ const Animation = Enum({ /** - * 播放贴图中的所有帧。 + * @en Play whole sheet of texture. + * @zh 播放贴图中的所有帧。 */ WholeSheet: 0, /** - * 播放贴图中的其中一行动画。 + * @en Play just one row of texture. + * @zh 播放贴图中的其中一行动画。 */ SingleRow: 1, }); +/** + * @en + * Use this module to play frame animation of the particle texture. + * @zh + * 这个模块用于播放粒子纹理带的纹理帧动画。 + */ @ccclass('cc.TextureAnimationModule') export default class TextureAnimationModule extends ParticleModuleBase { @serializable @@ -75,6 +85,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { private _numTilesY = 0; /** + * @en Enable this module or not. * @zh 是否启用。 */ @displayOrder(0) @@ -94,6 +105,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { private _mode = Mode.Grid; /** + * @en Set texture animation [[Mode]] (only support Grid mode). * @zh 设定粒子贴图动画的类型(暂只支持 Grid 模式)[[Mode]]。 */ @type(Mode) @@ -110,6 +122,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { } /** + * @en Tile count on X axis. * @zh X 方向动画帧数。 */ @displayOrder(2) @@ -126,6 +139,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { } /** + * @en Tile count on Y axis. * @zh Y 方向动画帧数。 */ @displayOrder(3) @@ -142,6 +156,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { } /** + * @en Texture animation type. See [[Animation]]. * @zh 动画播放方式 [[Animation]]。 */ @type(Animation) @@ -151,6 +166,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { public animation = Animation.WholeSheet; /** + * @en Curve to control texture animation speed. * @zh 一个周期内动画播放的帧与时间变化曲线。 */ @type(CurveRange) @@ -161,6 +177,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { public frameOverTime = new CurveRange(); /** + * @en Texture animation frame start to play. * @zh 从第几帧开始播放,时间为整个粒子系统的生命周期。 */ @type(CurveRange) @@ -171,6 +188,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { public startFrame = new CurveRange(); /** + * @en Animation cycle count per particle life. * @zh 一个生命周期内播放循环的次数。 */ @serializable @@ -215,6 +233,8 @@ export default class TextureAnimationModule extends ParticleModuleBase { } /** + * @en Get random row from texture to generate animation.
+ * This option is available when [[Animation]] type is SingleRow. * @zh 随机从动画贴图中选择一行以生成动画。
* 此选项仅在动画播放方式为 SingleRow 时生效。 */ @@ -224,6 +244,8 @@ export default class TextureAnimationModule extends ParticleModuleBase { public randomRow = false; /** + * @en Generate animation from specific row in texture.
+ * This option is available when [[Animation]] type is SingleRow and randomRow option is disabled. * @zh 从动画贴图中选择特定行以生成动画。
* 此选项仅在动画播放方式为 SingleRow 时且禁用 randomRow 时可用。 */ @@ -234,10 +256,23 @@ export default class TextureAnimationModule extends ParticleModuleBase { public name = PARTICLE_MODULE_NAME.TEXTURE; + /** + * @en Init start row to particle. + * @zh 给粒子创建初始行属性。 + * @param p @en Particle to set start row. @zh 设置初始行属性的粒子。 + * @internal + */ public init (p: Particle) { p.startRow = Math.floor(Math.random() * this.numTilesY); } + /** + * @en Apply texture animation to particle. + * @zh 应用贴图动画到粒子。 + * @param p @en Particle to animate. @zh 模块需要更新的粒子。 + * @param dt @en Update interval time. @zh 粒子系统更新的间隔时间。 + * @internal + */ public animate (p: Particle, dt: number) { const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; const randStart = isCurveTwoValues(this.startFrame) ? pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET) : 0; diff --git a/cocos/particle/animator/velocity-overtime.ts b/cocos/particle/animator/velocity-overtime.ts index d08d6f9a1b..9d3103a970 100644 --- a/cocos/particle/animator/velocity-overtime.ts +++ b/cocos/particle/animator/velocity-overtime.ts @@ -35,11 +35,22 @@ const VELOCITY_Z_OVERTIME_RAND_OFFSET = ModuleRandSeed.VELOCITY_Z; const _temp_v3 = new Vec3(); +/** + * @en + * This module will modify particle velocity over life time. + * Open the separateAxes option you can change the velocity on XYZ axis. + * Velocity on every axis is curve so you can modify these curves to see how it animate. + * @zh + * 本模块用于在粒子生命周期内改变粒子的速度。 + * 打开 separateAxes 就能够修改粒子在三个轴方向的速度大小。 + * 每个轴上的速度大小都是可以用曲线来进行编辑,修改曲线就能够看到粒子速度变化的效果了。 + */ @ccclass('cc.VelocityOvertimeModule') export default class VelocityOvertimeModule extends ParticleModuleBase { @serializable _enable = false; /** + * @en Enable this module or not. * @zh 是否启用。 */ @displayOrder(0) @@ -55,6 +66,7 @@ export default class VelocityOvertimeModule extends ParticleModuleBase { } /** + * @en Velocity on X axis. * @zh X 轴方向上的速度分量。 */ @type(CurveRange) @@ -64,6 +76,7 @@ export default class VelocityOvertimeModule extends ParticleModuleBase { public x = new CurveRange(); /** + * @en Velocity on Y axis. * @zh Y 轴方向上的速度分量。 */ @type(CurveRange) @@ -73,6 +86,7 @@ export default class VelocityOvertimeModule extends ParticleModuleBase { public y = new CurveRange(); /** + * @en Velocity on Z axis. * @zh Z 轴方向上的速度分量。 */ @type(CurveRange) @@ -82,6 +96,7 @@ export default class VelocityOvertimeModule extends ParticleModuleBase { public z = new CurveRange(); /** + * @en Speed modifier (available for CPU particle). * @zh 速度修正系数(只支持 CPU 粒子)。 */ @type(CurveRange) @@ -91,6 +106,7 @@ export default class VelocityOvertimeModule extends ParticleModuleBase { public speedModifier = new CurveRange(); /** + * @en Velocity [[Space]] used to calculate particle velocity. * @zh 速度计算时采用的坐标系[[Space]]。 */ @type(Space) @@ -111,10 +127,24 @@ export default class VelocityOvertimeModule extends ParticleModuleBase { this.needUpdate = true; } + /** + * @en Update velocity overtime module calculate transform. + * @zh 更新模块,计算坐标变换。 + * @param space @en Velocity overtime module update space @zh 模块更新空间 + * @param worldTransform @en Particle system world transform @zh 粒子系统的世界变换矩阵 + * @internal + */ public update (space: number, worldTransform: Mat4) { this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation); } + /** + * @en Apply velocity animation to particle. + * @zh 作用速度变换到粒子上。 + * @param p @en Particle to animate @zh 模块需要更新的粒子 + * @param dt @en Update interval time @zh 粒子系统更新的间隔时间 + * @internal + */ public animate (p: Particle, dt: number) { const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; const randX = isCurveTwoValues(this.x) ? pseudoRandom(p.randomSeed ^ VELOCITY_X_OVERTIME_RAND_OFFSET) : 0; diff --git a/cocos/particle/burst.ts b/cocos/particle/burst.ts index 42f078422e..83fe0c666d 100644 --- a/cocos/particle/burst.ts +++ b/cocos/particle/burst.ts @@ -26,13 +26,20 @@ import { ccclass, type, serializable, editable, range } from 'cc.decorator'; import { repeat } from '../core/math'; import CurveRange from './animator/curve-range'; +/** + * @en + * A burst is a particle emission event, where a number of particles are all emitted at the same time + * @zh + * Burst 是粒子的一种发射事件,触发时很多粒子将会同时喷出 + */ @ccclass('cc.Burst') export default class Burst { @serializable private _time = 0; /** - * @zh 粒子系统开始运行到触发此次 Brust 的时间。 + * @en The time from particle system start until this burst triggered. + * @zh 粒子系统开始运行到触发此次 Brust 的时间。 */ @editable get time () { @@ -48,6 +55,7 @@ export default class Burst { private _repeatCount = 1; /** + * @en Burst trigger count. * @zh Burst 的触发次数。 */ @editable @@ -61,6 +69,7 @@ export default class Burst { } /** + * @en Trigger interval count. * @zh 每次触发的间隔时间。 */ @serializable @@ -68,11 +77,12 @@ export default class Burst { public repeatInterval = 1; /** + * @en Burst particle count. * @zh 发射的粒子的数量。 */ @type(CurveRange) @serializable - @range([0, Number.POSITIVE_INFINITY]) + @range([0, Number.POSITIVE_INFINITY, 1]) public count: CurveRange = new CurveRange(); private _remainingCount: number; @@ -83,6 +93,13 @@ export default class Burst { this._curTime = 0.0; } + /** + * @en Update burst trigger + * @zh 更新触发事件 + * @param psys @en Particle system to burst. @zh 要触发的粒子系统。 + * @param dt @en Update interval time. @zh 粒子系统更新的间隔时间。 + * @internal + */ public update (psys, dt: number) { if (this._remainingCount === 0) { this._remainingCount = this._repeatCount; @@ -100,11 +117,21 @@ export default class Burst { } } + /** + * @en Reset remaining burst count and burst time to zero. + * @zh 重置触发时间和留存的触发次数为零。 + */ public reset () { this._remainingCount = 0; this._curTime = 0.0; } + /** + * @en Get the max particle count this burst trigger. + * @zh 获取最大的触发粒子数量。 + * @param psys @en Particle system to burst. @zh 要触发的粒子系统。 + * @returns @en burst max particle count. @zh 一次最多触发的粒子个数。 + */ public getMaxCount (psys) { return this.count.getMax() * Math.min(Math.ceil(psys.duration / this.repeatInterval), this.repeatCount); } diff --git a/cocos/particle/emitter/shape-module.ts b/cocos/particle/emitter/shape-module.ts index be5e08bc18..26afbad824 100644 --- a/cocos/particle/emitter/shape-module.ts +++ b/cocos/particle/emitter/shape-module.ts @@ -45,9 +45,23 @@ function getShapeTypeEnumName (enumValue: number): keyof typeof ShapeType { return enumName as keyof typeof ShapeType; } +/** + * @en + * This module defines the the volume or surface from which particles can be emitted, and the direction of the start velocity. + * The Shape property defines the shape of the emission volume, and the rest of the module properties vary depending on the Shape you choose. + * All shapes have properties that define their dimensions, such as the Radius property. + * To edit these, drag the handles on the wireframe emitter shape in the Scene view. + * The choice of shape affects the region from which particles can be emitted, but also the initial direction of the particles. + * @zh + * 本模块定义一个发射体或发射面,粒子将会从它进行发射,并且定义了粒子发射的初始方向和初始速度。 + * 形状属性定义粒子系统的发射体,剩下的属性依赖于选择的形状。 + * 所有形状都具有定义其大小的属性,例如 Radius 属性。要编辑这些属性,请在视图中拖动线框发射器形状上的控制柄。 + * 形状的选择会影响可发射粒子的区域,但也会影响粒子的初始方向。 + */ @ccclass('cc.ShapeModule') export default class ShapeModule { /** + * @en Emitter position. * @zh 粒子发射器位置。 */ @displayOrder(13) @@ -61,6 +75,7 @@ export default class ShapeModule { } /** + * @en Emitter rotation. * @zh 粒子发射器旋转角度。 */ @displayOrder(14) @@ -74,6 +89,7 @@ export default class ShapeModule { } /** + * @en Emitter size scale. * @zh 粒子发射器缩放比例。 */ @displayOrder(15) @@ -87,6 +103,7 @@ export default class ShapeModule { } /** + * @en Particles will be emitted in an arc if shape is Cone or Circle. * @zh 粒子发射器在一个扇形范围内发射。 */ @displayOrder(6) @@ -105,6 +122,8 @@ export default class ShapeModule { } /** + * @en The angle of the Cone. + * Define how the cone opening and closing. * @zh 圆锥的轴与母线的夹角。 * 决定圆锥发射器的开合程度。 */ @@ -126,6 +145,7 @@ export default class ShapeModule { @serializable private _enable = false; /** + * @en Enable this module or not. * @zh 是否启用。 */ @displayOrder(0) @@ -138,6 +158,7 @@ export default class ShapeModule { } /** + * @en Emitter [[ShapeType]]. * @zh 粒子发射器类型 [[ShapeType]]。 * * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. @@ -178,6 +199,7 @@ export default class ShapeModule { } /** + * @en Particles emitted from which part of the shape [[EmitLocation]] (Box Cone Sphere Hemisphere). * @zh 粒子从发射器哪个部位发射 [[EmitLocation]]。 */ @type(EmitLocation) @@ -192,6 +214,7 @@ export default class ShapeModule { public emitFrom = EmitLocation.Volume; /** + * @en Align particle with particle direction. * @zh 根据粒子的初始方向决定粒子的移动方向。 */ @serializable @@ -200,6 +223,7 @@ export default class ShapeModule { public alignToDirection = false; /** + * @en Particle direction random amount. * @zh 粒子生成方向随机设定。 */ @serializable @@ -208,6 +232,7 @@ export default class ShapeModule { public randomDirectionAmount = 0; /** + * @en Blend particle directions towards a spherical direction, where they travel outwards from the center of their transform. * @zh 表示当前发射方向与当前位置到结点中心连线方向的插值。 */ @serializable @@ -216,6 +241,7 @@ export default class ShapeModule { public sphericalDirectionAmount = 0; /** + * @en Particle position random amount. * @zh 粒子生成位置随机设定(设定此值为非 0 会使粒子生成位置超出生成器大小范围)。 */ @serializable @@ -224,6 +250,7 @@ export default class ShapeModule { public randomPositionAmount = 0; /** + * @en Emition radius (available for Circle Cone Sphere Hemisphere). * @zh 粒子发射器半径。 */ @serializable @@ -237,6 +264,10 @@ export default class ShapeModule { public radius = 1; /** + * @en Emit position in shape (available for Circle Cone Sphere Hemisphere): + * - 0 Emit from surface; + * - 1 Emit from volume center; + * - 0 to 1 Emit within surface and volume center. * @zh 粒子发射器发射位置(对 Box 类型的发射器无效): * - 0 表示从表面发射; * - 1 表示从中心发射; @@ -253,6 +284,7 @@ export default class ShapeModule { public radiusThickness = 1; /** + * @en Arc mode for Cone and Circle shape. * @zh 粒子在扇形范围内的发射方式 [[ArcMode]]。 */ @type(ArcMode) @@ -267,6 +299,7 @@ export default class ShapeModule { public arcMode = ArcMode.Random; /** + * @en Control arc spread for Cone and circle shape. * @zh 控制可能产生粒子的弧周围的离散间隔。 */ @visible(function noArc (this: ShapeModule) { return this.arcMode !== ArcMode.Random; }) // Bug fix: Hide this input when arcMode is random @@ -281,6 +314,7 @@ export default class ShapeModule { public arcSpread = 0; /** + * @en Emit speed around arc (available for Cone and Circle). * @zh 粒子沿圆周发射的速度。 */ @type(CurveRange) @@ -297,6 +331,7 @@ export default class ShapeModule { public arcSpeed = new CurveRange(); /** + * @en The length from Cone bottom to top. * @zh 圆锥顶部截面距离底部的轴长。 * 决定圆锥发射器的高度。 */ @@ -311,6 +346,7 @@ export default class ShapeModule { public length = 5; /** + * @en Shape thickness for box shape. * @zh 粒子发射器发射位置(针对 Box 类型的粒子发射器)。 */ @serializable @@ -352,12 +388,24 @@ export default class ShapeModule { this.totalAngle = 0; } + /** + * @en Apply particle system to this shape and create shape transform matrix. + * @zh 把发射形状应用到粒子系统,并且创建发射形状变换矩阵。 + * @param ps @en Emit shape applied to which Particle system. @zh 使用发射形状的粒子系统。 + * @internal + */ public onInit (ps: ParticleSystem) { this.particleSystem = ps; this.constructMat(); this.lastTime = this.particleSystem._time; } + /** + * @en Emit particle by this shape. + * @zh 通过这个形状发射粒子。 + * @param p @en Particle emitted. @zh 发射出来的粒子。 + * @internal + */ public emit (p) { switch (this.shapeType) { case ShapeType.Box: diff --git a/cocos/particle/noise.ts b/cocos/particle/noise.ts index 0e78272567..fd42921d23 100644 --- a/cocos/particle/noise.ts +++ b/cocos/particle/noise.ts @@ -24,6 +24,10 @@ import { Vec2, Vec3 } from '../core/math'; +/** + * @en Noise generation class. + * @zh 此类生成噪声纹理。 + */ export class ParticleNoise { private permutation: 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, @@ -40,12 +44,22 @@ export class ParticleNoise { 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180, ]; - constructor (permutation ? : number[]) { + constructor (permutation?: number[]) { if (permutation) { this.permutation = permutation; } } + /** + * @en Noise generation function. + * @zh 噪声生成函数。 + * @param x @en Relative X coordinate. @zh 纹理坐标在 X 轴的偏移量。 + * @param y @en Relative Y coordinate. @zh 纹理坐标在 Y 轴的偏移量。 + * @param z @en Relative Z coordinate. @zh 纹理坐标在 Z 轴的偏移量。 + * @param min @en Min pixel value. @zh 像素最小值。 + * @param max @en Max pixel value. @zh 像素最大值。 + * @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]; } @@ -105,34 +119,83 @@ export class ParticleNoise { private result: Vec3 = new Vec3(); private mixOut: Vec2 = new Vec2(); + /** + * @en Set texture rolling speed. + * @zh 设置纹理滚动速度。 + * @param x @en X axis roll speed. @zh X 轴滚动速度。 + * @param y @en Y axis roll speed. @zh Y 轴滚动速度。 + * @param z @en Z axis roll speed. @zh Z 轴滚动速度。 + */ public setSpeed (x, y, z) { this.noiseSpeed.set(x, y, z); } + /** + * @en Set noise frequency. + * @zh 设置生成的噪声频率。 + * @param f @en Noise texture frequency. @zh 噪声频率。 + */ public setFrequency (f) { this.noiseFrequency = f; } + /** + * @zh 将最终噪声值重新映射到不同的范围。 + * @en The curve that describes how the final noise values are transformed. + * @param x @en X value transformed. @zh X 轴上噪声值的偏移。 + * @param y @en Y value transformed. @zh Y 轴上噪声值的偏移。 + * @param z @en Z value transformed. @zh Z 轴上噪声值的偏移。 + * @deprecated since v3.6.0 + */ public setAbs (x, y, z) { this.noiseAbs.set(x, y, z); } + /** + * @en Set noise amplititude. + * @zh 设置噪声强度。 + * @param x @en Noise amplititude on X axis. @zh X 轴上的噪声强度。 + * @param y @en Noise amplititude on Y axis. @zh Y 轴上的噪声强度。 + * @param z @en Noise amplititude on Z axis. @zh Z 轴上的噪声强度。 + */ public setAmplititude (x, y, z) { this.noiseAmplitude.set(x, y, z); } + /** + * @en Specify how many layers of overlapping noise are combined to produce the final noise values. + * @zh 指定组合多少层重叠噪声来产生最终噪声值。 + * @param x @en Layer count. @zh 噪声层数。 + * @param y @en For each additional noise layer, reduce the strength by this proportion. @zh 每一层的噪声强度衰减比例。 + * @param z @en For each additional noise layer, adjust the frequency by this multiplier. @zh 对于每个附加的噪声层,按此乘数调整频率。 + */ public setOctaves (x, y, z) { this.octaves.set(x, y, z); } + /** + * @en Set update interval time. + * @zh 设置更新间隔时间。 + * @param t @en Update interval time. @zh 更新的间隔时间。 + */ public setTime (t) { this.dt = t; } + /** + * @en Set noise texture sample point. + * @zh 设置噪声纹理的采样点。 + * @param p @en Sample point of noise texture. @zh 噪声纹理采样点。 + */ public setSamplePoint (p: Vec3) { this.point.set(p); } + /** + * @en Get the sample pixel. + * @zh 获取采样的像素。 + * @returns @en The sample result. @zh 纹理采样结果。 + */ public getResult (): Vec3 { return this.result; } @@ -162,6 +225,10 @@ export class ParticleNoise { out.y = this.getNoise(point.y, point.z, point.x, time, offSpeed, noiseFrequency, octaves); } + /** + * @en Sample pixel from noise texture. + * @zh 从噪声纹理采样像素。 + */ public getNoiseParticle () { this.accSpeed.set(this.noiseSpeed.x * this.dt, this.noiseSpeed.y * this.dt, this.noiseSpeed.z * this.dt); @@ -176,6 +243,13 @@ export class ParticleNoise { this.result.set(sampX * this.noiseAmplitude.x, sampY * this.noiseAmplitude.y, sampZ * this.noiseAmplitude.z); } + /** + * @en Generate noise texture preview. + * @zh 生成噪声纹理的预览。 + * @param out @en Noise pixel array. @zh 噪声像素 RGB 数组。 + * @param width @en Texture width. @zh 纹理宽度。 + * @param height @en Texture height. @zh 纹理高度。 + */ public getPreview (out: number[], width: number, height: number) { for (let h = 0; h < height; ++h) { for (let w = 0; w < width; ++w) { diff --git a/cocos/particle/particle-system.ts b/cocos/particle/particle-system.ts index b6e55255aa..7f65b61d31 100644 --- a/cocos/particle/particle-system.ts +++ b/cocos/particle/particle-system.ts @@ -57,6 +57,16 @@ const _world_rol = new Quat(); const superMaterials = Object.getOwnPropertyDescriptor(Renderer.prototype, 'sharedMaterials')!; +/** + * @en + * Particle system component, which can make many effects such as smoke and fire. + * Include some interesting modules and components such as Velocity Overtime, Force Overtime, Trail and Noise. + * You can open these modules to see how the particles animate. + * @zh + * 粒子系统能够用来制作许多特效,例如 烟雾和火焰。 + * 包含一些有趣的模块,例如 速度模块,受力模块,拖尾模块和噪声模块。 + * 打开这些模块可以看到粒子如何进行变化。 + */ @ccclass('cc.ParticleSystem') @help('i18n:cc.ParticleSystem') @menu('Effects/ParticleSystem') @@ -64,10 +74,10 @@ const superMaterials = Object.getOwnPropertyDescriptor(Renderer.prototype, 'shar @executeInEditMode export class ParticleSystem extends ModelRenderer { /** - * @en Maximum particle capacity to generate + * @en Maximum particle capacity to generate. * @zh 粒子系统能生成的最大粒子数量。 */ - @range([0, Number.POSITIVE_INFINITY]) + @range([0, Number.POSITIVE_INFINITY, 1]) @displayOrder(1) @tooltip('i18n:particle_system.capacity') public get capacity () { @@ -84,7 +94,7 @@ export class ParticleSystem extends ModelRenderer { } /** - * @en The initial color of the particle + * @en The initial color of the particle. * @zh 粒子初始颜色。 */ @type(GradientRange) @@ -93,19 +103,27 @@ export class ParticleSystem extends ModelRenderer { @tooltip('i18n:particle_system.startColor') public startColor = new GradientRange(); + /** + * @en The space of particle scaling. + * @zh 计算粒子缩放的空间。 + */ @type(Space) @serializable @displayOrder(9) @tooltip('i18n:particle_system.scaleSpace') public scaleSpace = Space.Local; + /** + * @en Whether to modify particle size on XYZ axis. + * @zh 是否需要修改粒子在三个轴上的大小。 + */ @serializable @displayOrder(10) @tooltip('i18n:particle_system.startSize3D') public startSize3D = false; /** - * @en The initial X size of the particle + * @en The initial X size of the particle. * @zh 粒子初始x轴方向大小。 */ @formerlySerializedAs('startSize') @@ -116,7 +134,7 @@ export class ParticleSystem extends ModelRenderer { public startSizeX = new CurveRange(); /** - * @en The initial Y size of the particle + * @en The initial Y size of the particle. * @zh 粒子初始y轴方向大小。 */ @type(CurveRange) @@ -128,7 +146,7 @@ export class ParticleSystem extends ModelRenderer { public startSizeY = new CurveRange(); /** - * @en The initial Z size of the particle + * @en The initial Z size of the particle. * @zh 粒子初始z轴方向大小。 */ @type(CurveRange) @@ -140,7 +158,7 @@ export class ParticleSystem extends ModelRenderer { public startSizeZ = new CurveRange(); /** - * @en The initial velocity of the particle + * @en The initial velocity of the particle. * @zh 粒子初始速度。 */ @type(CurveRange) @@ -149,13 +167,17 @@ export class ParticleSystem extends ModelRenderer { @tooltip('i18n:particle_system.startSpeed') public startSpeed = new CurveRange(); + /** + * @en Whether to modify particle rotation on XYZ axis. + * @zh 是否需要修改粒子在三个轴上的旋转。 + */ @serializable @displayOrder(12) @tooltip('i18n:particle_system.startRotation3D') public startRotation3D = false; /** - * @en The initial rotation angle of the particle on X axis + * @en The initial rotation angle of the particle on X axis. * @zh 粒子初始x轴旋转角度。 */ @type(CurveRange) @@ -168,7 +190,7 @@ export class ParticleSystem extends ModelRenderer { public startRotationX = new CurveRange(); /** - * @en The initial rotation angle of the particle on Y axis + * @en The initial rotation angle of the particle on Y axis. * @zh 粒子初始y轴旋转角度。 */ @type(CurveRange) @@ -181,7 +203,7 @@ export class ParticleSystem extends ModelRenderer { public startRotationY = new CurveRange(); /** - * @en The initial rotation angle of the particle on Z axis + * @en The initial rotation angle of the particle on Z axis. * @zh 粒子初始z轴旋转角度。 */ @type(CurveRange) @@ -190,11 +212,10 @@ export class ParticleSystem extends ModelRenderer { @radian @displayOrder(12) @tooltip('i18n:particle_system.startRotationZ') - @visible(function (this: ParticleSystem): boolean { return this.startRotation3D; }) public startRotationZ = new CurveRange(); /** - * @en The time delay to start emission after the particle system starts running + * @en The time delay to start emission after the particle system starts running. * @zh 粒子系统开始运行后,延迟粒子发射的时间。 */ @type(CurveRange) @@ -205,7 +226,7 @@ export class ParticleSystem extends ModelRenderer { public startDelay = new CurveRange(); /** - * @en Particle life time + * @en Particle life time. * @zh 粒子生命周期。 */ @type(CurveRange) @@ -216,7 +237,7 @@ export class ParticleSystem extends ModelRenderer { public startLifetime = new CurveRange(); /** - * @en Particle system duration time + * @en Particle system duration time. * @zh 粒子系统运行时间。 */ @serializable @@ -234,7 +255,7 @@ export class ParticleSystem extends ModelRenderer { public loop = true; /** - * @en Play one round before start this particle system + * @en Play one round before start this particle system. * @zh 选中之后,粒子系统会以已播放完一轮之后的状态开始播放(仅当循环播放启用时有效)。 */ @displayOrder(3) @@ -251,7 +272,7 @@ export class ParticleSystem extends ModelRenderer { } /** - * @en The simulation space of the particle system, it could be world, local or custom + * @en The simulation space of the particle system, it could be world, local or custom. * @zh 选择粒子系统所在的坐标系[[Space]]。
*/ @type(Space) @@ -273,7 +294,7 @@ export class ParticleSystem extends ModelRenderer { } /** - * @en The simulation speed of the particle system + * @en The simulation speed of the particle system. * @zh 控制整个粒子系统的更新速度。 */ @serializable @@ -282,7 +303,7 @@ export class ParticleSystem extends ModelRenderer { public simulationSpeed = 1.0; /** - * @en Automatically start playing after particle system initialized + * @en Automatically start playing after particle system initialized. * @zh 粒子系统加载后是否自动开始播放。 */ @serializable @@ -291,7 +312,7 @@ export class ParticleSystem extends ModelRenderer { public playOnAwake = true; /** - * @en The gravity of the particle system + * @en The gravity of the particle system. * @zh 粒子受重力影响的重力系数。 */ @type(CurveRange) @@ -302,7 +323,7 @@ export class ParticleSystem extends ModelRenderer { // emission module /** - * @en The value curve of emission rate over time + * @en The value curve of emission rate over time. * @zh 随时间推移发射的粒子数的变化曲线。 */ @type(CurveRange) @@ -313,7 +334,7 @@ export class ParticleSystem extends ModelRenderer { public rateOverTime = new CurveRange(); /** - * @en The value curve of emission rate over distance + * @en The value curve of emission rate over distance. * @zh 每移动单位距离发射的粒子数的变化曲线。 */ @type(CurveRange) @@ -324,7 +345,7 @@ export class ParticleSystem extends ModelRenderer { public rateOverDistance = new CurveRange(); /** - * @en Burst triggers of the particle system + * @en Burst triggers of the particle system. * @zh 设定在指定时间发射指定数量的粒子的 burst 的数量。 */ @type([Burst]) @@ -334,7 +355,8 @@ export class ParticleSystem extends ModelRenderer { public bursts: Burst[] = []; /** - * @en Enable particle culling switch. Open it to enable particle culling. If enabled will generate emitter bounding box and emitters outside the frustum will be culled. + * @en Enable particle culling switch. Open it to enable particle culling. + * If enabled will generate emitter bounding box and emitters outside the frustum will be culled. * @zh 粒子剔除开关,如果打开将会生成一个发射器包围盒,包围盒在相机外发射器将被剔除。 */ @type(CCBoolean) @@ -375,6 +397,10 @@ export class ParticleSystem extends ModelRenderer { @serializable _cullingMode = CullingMode.Pause; + /** + * @en Emitter culling mode. + * @zh 发射器的各种剔除模式。 + */ public static CullingMode = CullingMode; /** @@ -484,7 +510,7 @@ export class ParticleSystem extends ModelRenderer { @type(ColorOverLifetimeModule) _colorOverLifetimeModule: ColorOverLifetimeModule | null = null; /** - * @en The module controlling particles' color over life time + * @en The module controlling particle's color over life time. * @zh 颜色控制模块。 */ @type(ColorOverLifetimeModule) @@ -509,7 +535,7 @@ export class ParticleSystem extends ModelRenderer { @type(ShapeModule) _shapeModule: ShapeModule | null = null; /** - * @en The module controlling emitter's shape + * @en The module controlling emitter's shape. * @zh 粒子发射器模块。 */ @type(ShapeModule) @@ -534,7 +560,7 @@ export class ParticleSystem extends ModelRenderer { @type(SizeOvertimeModule) _sizeOvertimeModule: SizeOvertimeModule | null = null; /** - * @en The module controlling particles' size over time + * @en The module controlling particle's size over time. * @zh 粒子大小模块。 */ @type(SizeOvertimeModule) @@ -559,7 +585,7 @@ export class ParticleSystem extends ModelRenderer { @type(VelocityOvertimeModule) _velocityOvertimeModule: VelocityOvertimeModule | null = null; /** - * @en The module controlling particles' velocity over time + * @en The module controlling particle's velocity over time. * @zh 粒子速度模块。 */ @type(VelocityOvertimeModule) @@ -584,7 +610,7 @@ export class ParticleSystem extends ModelRenderer { @type(ForceOvertimeModule) _forceOvertimeModule: ForceOvertimeModule | null = null; /** - * @en The module controlling the force applied to particles over time + * @en The module controlling the force applied to particles over time. * @zh 粒子加速度模块。 */ @type(ForceOvertimeModule) @@ -610,7 +636,7 @@ export class ParticleSystem extends ModelRenderer { _limitVelocityOvertimeModule: LimitVelocityOvertimeModule | null = null; /** - * @en The module which limits the velocity applied to particles over time, only supported in CPU particle system + * @en The module which limits the velocity applied to particles over time, only supported in CPU particle system. * @zh 粒子限制速度模块(只支持 CPU 粒子)。 */ @type(LimitVelocityOvertimeModule) @@ -635,7 +661,7 @@ export class ParticleSystem extends ModelRenderer { @type(RotationOvertimeModule) _rotationOvertimeModule: RotationOvertimeModule | null = null; /** - * @en The module controlling the rotation of particles over time + * @en The module controlling the rotation of particles over time. * @zh 粒子旋转模块。 */ @type(RotationOvertimeModule) @@ -660,7 +686,7 @@ export class ParticleSystem extends ModelRenderer { @type(TextureAnimationModule) _textureAnimationModule: TextureAnimationModule | null = null; /** - * @en The module controlling the texture animation of particles + * @en The module controlling the texture animation of particles. * @zh 贴图动画模块。 */ @type(TextureAnimationModule) @@ -682,11 +708,15 @@ export class ParticleSystem extends ModelRenderer { } // noise module + /** + * @en Noise module which can add some interesting effects. + * @zh 噪声模块能够增加许多有趣的特效。 + */ @type(NoiseModule) private _noiseModule: NoiseModule | null = null; /** - * @en The module controlling noise map applied to the particles, only supported in CPU particle system - * @zh 噪声动画模块。 + * @en The module controlling noise map applied to the particles, only supported in CPU particle system. + * @zh 噪声动画模块,仅支持 CPU 粒子。 */ @type(NoiseModule) @displayOrder(24) @@ -710,7 +740,7 @@ export class ParticleSystem extends ModelRenderer { @type(TrailModule) _trailModule: TrailModule | null = null; /** - * @en The module controlling the trail module + * @en The module controlling the trail module. * @zh 粒子轨迹模块。 */ @type(TrailModule) @@ -731,6 +761,10 @@ export class ParticleSystem extends ModelRenderer { } // particle system renderer + /** + * @en Particle system renderer (CPU or GPU). + * @zh 粒子系统渲染器(CPU 还是 GPU)。 + */ @type(ParticleSystemRenderer) @serializable @displayOrder(26) @@ -775,6 +809,10 @@ export class ParticleSystem extends ModelRenderer { @serializable private _simulationSpace = Space.Local; + /** + * @en Particle update processor (update every particle). + * @zh 粒子更新器(负责更新每个粒子)。 + */ public processor: IParticleSystemRenderer = null!; constructor () { @@ -879,6 +917,10 @@ export class ParticleSystem extends ModelRenderer { } } + /** + * @en Bind module to particle processor. + * @zh 把模块绑定到粒子更新函数上。 + */ public bindModule () { if (this._colorOverLifetimeModule) this._colorOverLifetimeModule.bindTarget(this.processor); if (this._sizeOvertimeModule) this._sizeOvertimeModule.bindTarget(this.processor); @@ -896,7 +938,7 @@ export class ParticleSystem extends ModelRenderer { // } /** - * @en play particle system + * @en Play particle system. * @zh 播放粒子效果。 */ public play () { @@ -930,7 +972,7 @@ export class ParticleSystem extends ModelRenderer { } /** - * @en pause particle system + * @en Pause particle system. * @zh 暂停播放粒子效果。 */ public pause () { @@ -954,7 +996,7 @@ export class ParticleSystem extends ModelRenderer { } /** - * @en stop particle system + * @en Stop particle system. * @zh 停止播放粒子。 */ public stop () { @@ -998,8 +1040,8 @@ export class ParticleSystem extends ModelRenderer { } /** - * @en Get current particle capacity - * @zh 获取当前粒子数量 + * @en Get current particle capacity. + * @zh 获取当前粒子数量。 */ public getParticleCount () { return this.processor.getParticleCount(); @@ -1012,6 +1054,9 @@ export class ParticleSystem extends ModelRenderer { Vec2.set(this._customData1, x, y); } + /** + * @ignore + */ public setCustomData2 (x, y) { Vec2.set(this._customData2, x, y); } @@ -1135,7 +1180,7 @@ export class ParticleSystem extends ModelRenderer { let culled = true; if (cameraLst !== undefined && this._boundingBox) { for (let i = 0; i < cameraLst.length; ++i) { - const camera:Camera = cameraLst[i]; + const camera: Camera = cameraLst[i]; const visibility = camera.visibility; if ((visibility & this.node.layer) === this.node.layer) { if (EDITOR && !cclegacy.GAME_VIEW) { @@ -1469,18 +1514,34 @@ export class ParticleSystem extends ModelRenderer { return this._isPlaying; } + /** + * @en Query particle system is paused or not. + * @zh 获取粒子系统当前是否已经暂停运行。 + */ get isPaused () { return this._isPaused; } + /** + * @en Query particle system is stopped or not. + * @zh 获取粒子系统当前是否已经停止。 + */ get isStopped () { return this._isStopped; } + /** + * @en Query particle system is emitting or not. + * @zh 获取粒子系统当前是否还在发射。 + */ get isEmitting () { return this._isEmitting; } + /** + * @en Query particle system simulation time. + * @zh 获取粒子系统运行时间。 + */ get time () { return this._time; } @@ -1493,6 +1554,13 @@ export class ParticleSystem extends ModelRenderer { return this.dataCulling ? props.filter((p) => !PARTICLE_MODULE_PROPERTY.includes(p) || (this[p] && this[p].enable)) : props; } + /** + * @en Gets the preview of noise texture. + * @zh 获取噪声图预览。 + * @param width @en Noise texture width @zh 噪声图宽度 + * @param height @en Noise texture height @zh 噪声图高度 + * @returns @en Noise texture RGB pixel array @zh 噪声图 RGB 纹理数组 + */ public getNoisePreview (width: number, height: number): number[] { const out: number[] = []; if (this.processor) { diff --git a/cocos/particle/particle-utils.ts b/cocos/particle/particle-utils.ts index da90cc9b06..e2781a74b9 100644 --- a/cocos/particle/particle-utils.ts +++ b/cocos/particle/particle-utils.ts @@ -30,10 +30,14 @@ import { ParticleSystem } from './particle-system'; import CurveRange from './animator/curve-range'; import GradientRange from './animator/gradient-range'; +/** + * @en Contains some util functions for particle system. Such as create and destroy particle system. + * @zh 该类包含一些粒子系统的工具函数,例如创建和销毁粒子系统。 + */ export class ParticleUtils { /** - * @en instantiate particle system from prefab - * @zh 从 prefab 实例化粒子系统 + * @en Instantiate particle system from prefab. + * @zh 从 prefab 实例化粒子系统。 */ public static instantiate (prefab) { if (!this.registeredSceneEvent) { @@ -47,6 +51,11 @@ export class ParticleUtils { return this.particleSystemPool.get(prefab._uuid)!.alloc(); } + /** + * @en Destroy particle system prefab. + * @zh 销毁创建出来的粒子系统prefab。 + * @param prefab @en Particle system prefab to destroy. @zh 要销毁的粒子系统prefab。 + */ public static destroy (prefab) { if (this.particleSystemPool.has(prefab._prefab.asset._uuid)) { this.stop(prefab); @@ -54,12 +63,22 @@ export class ParticleUtils { } } + /** + * @en Play particle system. + * @zh 播放粒子系统。 + * @param rootNode @en Root node contains the particle system. @zh 包含粒子系统的根节点。 + */ public static play (rootNode: Node) { for (const ps of rootNode.getComponentsInChildren(ParticleSystem)) { (ps).play(); } } + /** + * @en Stop particle system. + * @zh 停止播放粒子系统。 + * @param rootNode @en Root node contains the particle system. @zh 包含粒子系统的根节点。 + */ public static stop (rootNode: Node) { for (const ps of rootNode.getComponentsInChildren(ParticleSystem)) { (ps).stop(); diff --git a/cocos/particle/renderer/particle-system-renderer-cpu.ts b/cocos/particle/renderer/particle-system-renderer-cpu.ts index 3e128edb23..ee123ed1e1 100644 --- a/cocos/particle/renderer/particle-system-renderer-cpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-cpu.ts @@ -368,16 +368,19 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas trailModule.update(); } - if (ps.simulationSpace === Space.Local) { - const r: Quat = ps.node.getRotation(); - Mat4.fromQuat(this._localMat, r); - this._localMat.transpose(); // just consider rotation, use transpose as invert - } + const useGravity = !ps.gravityModifier.isZero(); + if (useGravity) { + if (ps.simulationSpace === Space.Local) { + const r: Quat = ps.node.getRotation(); + Mat4.fromQuat(this._localMat, r); + this._localMat.transpose(); // just consider rotation, use transpose as invert + } - if (ps.node.parent) { - const r: Quat = ps.node.parent.getWorldRotation(); - Mat4.fromQuat(_tempParentInverse, r); - _tempParentInverse.transpose(); + if (ps.node.parent) { + const r: Quat = ps.node.parent.getWorldRotation(); + Mat4.fromQuat(_tempParentInverse, r); + _tempParentInverse.transpose(); + } } for (let i = 0; i < this._particles!.length; ++i) { @@ -395,7 +398,6 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } // apply gravity when both the mode is not Constant and the value is not 0. - const useGravity = (ps.gravityModifier.mode !== Mode.Constant || ps.gravityModifier.constant !== 0); if (useGravity) { const rand = isCurveTwoValues(ps.gravityModifier) ? pseudoRandom(p.randomSeed) : 0; if (ps.simulationSpace === Space.Local) { diff --git a/cocos/physics-2d/box2d/physics-contact.ts b/cocos/physics-2d/box2d/physics-contact.ts index a9c0f554d0..9c145f7ec9 100644 --- a/cocos/physics-2d/box2d/physics-contact.ts +++ b/cocos/physics-2d/box2d/physics-contact.ts @@ -23,16 +23,13 @@ */ import b2 from '@cocos/box2d'; +import { b2Contact } from '@cocos/box2d/src/box2d'; import { Vec2 } from '../../core'; import { PHYSICS_2D_PTM_RATIO } from '../framework/physics-types'; import { Collider2D, Contact2DType, PhysicsSystem2D } from '../framework'; import { b2Shape2D } from './shapes/shape-2d'; import { IPhysics2DContact, IPhysics2DImpulse, IPhysics2DManifoldPoint, IPhysics2DWorldManifold } from '../spec/i-physics-contact'; -export type b2ContactExtends = b2.Contact & { - m_userData: any -} - const pools: PhysicsContact[] = []; // temp world manifold @@ -67,40 +64,29 @@ const impulse: IPhysics2DImpulse = { }; export class PhysicsContact implements IPhysics2DContact { - static get (b2contact: b2ContactExtends) { - let c = pools.pop(); - - if (!c) { - c = new PhysicsContact(); - } - - c.init(b2contact); - return c; + public constructor (b2contact: b2Contact) { + this.ref = 1; + this.init(b2contact); } - static put (b2contact: b2ContactExtends) { - const c: PhysicsContact = b2contact.m_userData as PhysicsContact; - if (!c) return; + public ref = 0; + public status = Contact2DType.None; - pools.push(c); - c.reset(); - } + public colliderA: Collider2D | null = null; + public colliderB: Collider2D | null = null; - colliderA: Collider2D | null = null; - colliderB: Collider2D | null = null; - - disabled = false; - disabledOnce = false; + public disabled = false; + public disabledOnce = false; private _impulse: b2.ContactImpulse | null = null; private _inverted = false; - private _b2contact: b2ContactExtends | null = null; + private _b2contact: b2Contact | null = null; _setImpulse (impulse: b2.ContactImpulse | null) { this._impulse = impulse; } - init (b2contact: b2ContactExtends) { + private init (b2contact) { this.colliderA = (b2contact.m_fixtureA.m_userData as b2Shape2D).collider; this.colliderB = (b2contact.m_fixtureB.m_userData as b2Shape2D).collider; this.disabled = false; @@ -110,7 +96,6 @@ export class PhysicsContact implements IPhysics2DContact { this._inverted = false; this._b2contact = b2contact; - b2contact.m_userData = this; } reset () { @@ -122,8 +107,6 @@ export class PhysicsContact implements IPhysics2DContact { this.colliderB = null; this.disabled = false; this._impulse = null; - - this._b2contact!.m_userData = null; this._b2contact = null; } @@ -210,47 +193,6 @@ export class PhysicsContact implements IPhysics2DContact { return impulse; } - emit (contactType) { - let func; - switch (contactType) { - case Contact2DType.BEGIN_CONTACT: - func = 'onBeginContact'; - break; - case Contact2DType.END_CONTACT: - func = 'onEndContact'; - break; - case Contact2DType.PRE_SOLVE: - func = 'onPreSolve'; - break; - case Contact2DType.POST_SOLVE: - func = 'onPostSolve'; - break; - } - - const colliderA = this.colliderA; - const colliderB = this.colliderB; - - const bodyA = colliderA!.body; - const bodyB = colliderB!.body; - - if (bodyA!.enabledContactListener) { - colliderA?.emit(contactType, colliderA, colliderB, this); - } - - if (bodyB!.enabledContactListener) { - colliderB?.emit(contactType, colliderB, colliderA, this); - } - - if (bodyA!.enabledContactListener || bodyB!.enabledContactListener) { - PhysicsSystem2D.instance.emit(contactType, colliderA, colliderB, this); - } - - if (this.disabled || this.disabledOnce) { - this.setEnabled(false); - this.disabledOnce = false; - } - } - setEnabled (value) { this._b2contact!.SetEnabled(value); } diff --git a/cocos/physics-2d/box2d/physics-world.ts b/cocos/physics-2d/box2d/physics-world.ts index 73c4551517..f07abd246a 100644 --- a/cocos/physics-2d/box2d/physics-world.ts +++ b/cocos/physics-2d/box2d/physics-world.ts @@ -35,8 +35,7 @@ import { b2RigidBody2D } from './rigid-body'; import { PhysicsContactListener } from './platform/physics-contact-listener'; import { PhysicsAABBQueryCallback } from './platform/physics-aabb-query-callback'; import { PhysicsRayCastCallback } from './platform/physics-ray-cast-callback'; -import { PhysicsContact, b2ContactExtends } from './physics-contact'; -import { Contact2DType, Collider2D, RaycastResult2D } from '../framework'; +import { Collider2D, RaycastResult2D } from '../framework'; import { b2Shape2D } from './shapes/shape-2d'; import { PhysicsDebugDraw } from './platform/physics-debug-draw'; import { Node, find, Layers } from '../../scene-graph'; @@ -76,12 +75,7 @@ export class b2PhysicsWorld implements IPhysicsWorld { //tempBodyDef.position.Set(480 / PHYSICS_2D_PTM_RATIO, 320 / PHYSICS_2D_PTM_RATIO);//temporary this._physicsGroundBody = this._world.CreateBody(tempBodyDef); const listener = new PhysicsContactListener(); - listener.setBeginContact(this._onBeginContact); - listener.setEndContact(this._onEndContact); - listener.setPreSolve(this._onPreSolve); - listener.setPostSolve(this._onPostSolve); this._world.SetContactListener(listener); - this._contactListener = listener; this._aabbQueryCallback = new PhysicsAABBQueryCallback(); @@ -328,13 +322,6 @@ export class b2PhysicsWorld implements IPhysicsWorld { } } - registerContactFixture (fixture: b2.Fixture) { - this._contactListener.registerContactFixture(fixture); - } - unregisterContactFixture (fixture: b2.Fixture) { - this._contactListener.unregisterContactFixture(fixture); - } - testPoint (point: Vec2): readonly Collider2D[] { const x = tempVec2_1.x = point.x / PHYSICS_2D_PTM_RATIO; const y = tempVec2_1.y = point.y / PHYSICS_2D_PTM_RATIO; @@ -391,39 +378,7 @@ export class b2PhysicsWorld implements IPhysicsWorld { this._world.DrawDebugData(); } - _onBeginContact (b2contact: b2ContactExtends) { - const c = PhysicsContact.get(b2contact); - c.emit(Contact2DType.BEGIN_CONTACT); - } - - _onEndContact (b2contact: b2ContactExtends) { - const c = b2contact.m_userData as PhysicsContact; - if (!c) { - return; - } - c.emit(Contact2DType.END_CONTACT); - - PhysicsContact.put(b2contact); - } - - _onPreSolve (b2contact: b2ContactExtends) { - const c = b2contact.m_userData as PhysicsContact; - if (!c) { - return; - } - - c.emit(Contact2DType.PRE_SOLVE); - } - - _onPostSolve (b2contact: b2ContactExtends, impulse: b2.ContactImpulse) { - const c: PhysicsContact = b2contact.m_userData as PhysicsContact; - if (!c) { - return; - } - - // impulse only survive during post sole callback - c._setImpulse(impulse); - c.emit(Contact2DType.POST_SOLVE); - c._setImpulse(null); + finalizeContactEvent () { + this._contactListener.finalizeContactEvent(); } } diff --git a/cocos/physics-2d/box2d/platform/physics-contact-listener.ts b/cocos/physics-2d/box2d/platform/physics-contact-listener.ts index 4e5279f60b..4c64093095 100644 --- a/cocos/physics-2d/box2d/platform/physics-contact-listener.ts +++ b/cocos/physics-2d/box2d/platform/physics-contact-listener.ts @@ -23,71 +23,117 @@ */ import b2 from '@cocos/box2d'; -import { js } from '../../../core'; +import { assert, js } from '../../../core'; +import { fastRemove } from '../../../core/utils/array'; +import { Contact2DType, PhysicsSystem2D } from '../../framework'; +import { PhysicsContact } from '../physics-contact'; +import { b2Shape2D } from '../shapes/shape-2d'; export class PhysicsContactListener extends b2.ContactListener { - _contactFixtures: b2.Fixture[] = []; + static readonly _contactMap = new Map(); - _BeginContact: Function | null = null; - _EndContact: Function | null = null; - _PreSolve: Function | null = null; - _PostSolve: Function | null = null; - - setBeginContact (cb) { - this._BeginContact = cb; - } - - setEndContact (cb) { - this._EndContact = cb; - } - - setPreSolve (cb) { - this._PreSolve = cb; - } - - setPostSolve (cb) { - this._PostSolve = cb; + private getContactKey (contact: b2.Contact) { + const colliderA = (contact.m_fixtureA.m_userData as b2Shape2D).collider; + const colliderB = (contact.m_fixtureB.m_userData as b2Shape2D).collider; + let key = colliderA.uuid + colliderB.uuid; + if (colliderA.uuid > colliderB.uuid) { + key = colliderB.uuid + colliderA.uuid; + } + return key; } BeginContact (contact: b2.Contact) { - if (!this._BeginContact) return; + const key = this.getContactKey(contact); - const fixtureA = contact.GetFixtureA(); - const fixtureB = contact.GetFixtureB(); - const fixtures = this._contactFixtures; - - (contact as any)._shouldReport = false; - - if (fixtures.indexOf(fixtureA) !== -1 || fixtures.indexOf(fixtureB) !== -1) { - (contact as any)._shouldReport = true; // for quick check whether this contact should report - this._BeginContact(contact); + if (PhysicsContactListener._contactMap.has(key)) { + const retContact = PhysicsContactListener._contactMap.get(key)!; + retContact.ref++; + //console.log(' collision++', key, 'current ref is:', retContact.ref); + if (retContact.status === Contact2DType.END_CONTACT) { + retContact.status = Contact2DType.STAY_CONTACT; + //console.log(' set as stay'); + } else if (retContact.status !== Contact2DType.STAY_CONTACT) { + retContact.status = Contact2DType.BEGIN_CONTACT; + //console.log(' set as enter'); + } + } else { + //console.log(' new collision', key, 'current ref is:', 1); + const retCollision = new PhysicsContact(contact); + PhysicsContactListener._contactMap.set(key, retCollision); + retCollision.status = Contact2DType.BEGIN_CONTACT; } } EndContact (contact: b2.Contact) { - if (this._EndContact && (contact as any)._shouldReport) { - (contact as any)._shouldReport = false; - this._EndContact(contact); + const key = this.getContactKey(contact); + + const retContact = PhysicsContactListener._contactMap.get(key); + assert(retContact); + + retContact.ref--; + //console.log(' collision--', key, 'current ref is:', retCollision.ref); + if (retContact.ref <= 0) { + //console.log(' set as exit'); + retContact.status = Contact2DType.END_CONTACT; } } PreSolve (contact: b2.Contact, oldManifold: b2.Manifold) { - if (this._PreSolve && (contact as any)._shouldReport) { - this._PreSolve(contact, oldManifold); - } } PostSolve (contact: b2.Contact, impulse: b2.ContactImpulse) { - if (this._PostSolve && (contact as any)._shouldReport) { - this._PostSolve(contact, impulse); + } + + public finalizeContactEvent () { + PhysicsContactListener._contactMap.forEach((contact: PhysicsContact, key: string) => { + //console.log('forEach', key, collision); + if (contact.status === Contact2DType.END_CONTACT) { + PhysicsContactListener._contactMap.delete(key); + //console.log(' report end collision', key, 'current ref is:', contact.ref); + this.emit(Contact2DType.END_CONTACT, contact); + } else if (contact.status === Contact2DType.BEGIN_CONTACT) { + contact.status = Contact2DType.STAY_CONTACT; + //console.log(' report enter collision', key, 'current ref is:', contact.ref); + this.emit(Contact2DType.BEGIN_CONTACT, contact); + } else if (contact.status === Contact2DType.STAY_CONTACT) { + //console.log(' report stay collision', key, 'current ref is:', contact.ref); + this.emit(Contact2DType.STAY_CONTACT, contact); + } + }); + } + + private emit (contactType, contact: PhysicsContact) { + const colliderA = contact.colliderA; + const colliderB = contact.colliderB; + if (!colliderA || !colliderB) { + return; + } + + const bodyA = colliderA.body; + const bodyB = colliderB.body; + //if rigid body doesn't exist, collider will be added to groundRigidbody automatically, + //hence it should emit event + if ((bodyA && !bodyA.enabledInHierarchy) || (bodyB && !bodyB.enabledInHierarchy) || (!bodyA && !bodyB)) { + return; + } + + //bodyA exists and enabledContactListner, or bodyA doesn't exist + if ((bodyA && bodyA.enabledContactListener) || (!bodyA)) { + colliderA?.emit(contactType, colliderA, colliderB, contact); + } + + //bodyB exists and enabledContactListner, or bodyB doesn't exist + if ((bodyB && bodyB.enabledContactListener) || (!bodyB)) { + colliderB?.emit(contactType, colliderB, colliderA, contact); + } + + if ((bodyA && bodyA.enabledContactListener) || (bodyB && bodyB.enabledContactListener) || !bodyA || !bodyB) { + PhysicsSystem2D.instance.emit(contactType, colliderA, colliderB, contact); + } + + if (contact.disabled || contact.disabledOnce) { + contact.setEnabled(false); + contact.disabledOnce = false; } } - - registerContactFixture (fixture) { - this._contactFixtures.push(fixture); - } - - unregisterContactFixture (fixture) { - js.array.remove(this._contactFixtures, fixture); - } } diff --git a/cocos/physics-2d/box2d/rigid-body.ts b/cocos/physics-2d/box2d/rigid-body.ts index 99ab775597..8d3ec48fcd 100644 --- a/cocos/physics-2d/box2d/rigid-body.ts +++ b/cocos/physics-2d/box2d/rigid-body.ts @@ -27,7 +27,7 @@ import { IRigidBody2D } from '../spec/i-rigid-body'; import { RigidBody2D } from '../framework/components/rigid-body-2d'; import { PhysicsSystem2D } from '../framework/physics-system'; import { b2PhysicsWorld } from './physics-world'; -import { Vec2, toRadian, Vec3, Quat, IVec2Like, toDegree } from '../../core'; +import { Vec2, toRadian, Vec3, Quat, IVec2Like, toDegree, TWO_PI, HALF_PI } from '../../core'; import { PHYSICS_2D_PTM_RATIO, ERigidBody2DType } from '../framework/physics-types'; import { Node } from '../../scene-graph/node'; @@ -132,8 +132,21 @@ export class b2RigidBody2D implements IRigidBody2D { tempVec2_1.y = (this._animatedPos.y - b2Pos.y) * timeStep; b2body.SetLinearVelocity(tempVec2_1); - const b2Rotation = b2body.GetAngle(); - b2body.SetAngularVelocity((this._animatedAngle - b2Rotation) * timeStep); + //convert b2Rotation to [-PI~PI], which is the same as this._animatedAngle + let b2Rotation = b2body.GetAngle() % (TWO_PI); + if (b2Rotation > Math.PI) { + b2Rotation -= TWO_PI; + } + + //calculate angular velocity + let angularVelocity = (this._animatedAngle - b2Rotation) * timeStep; + if (this._animatedAngle < -HALF_PI && b2Rotation > HALF_PI) { //ccw, crossing PI + angularVelocity = (this._animatedAngle + TWO_PI - b2Rotation) * timeStep; + } if (this._animatedAngle > HALF_PI && b2Rotation < -HALF_PI) { //cw, crossing PI + angularVelocity = (this._animatedAngle - TWO_PI - b2Rotation) * timeStep; + } + + b2body.SetAngularVelocity(angularVelocity); } syncSceneToPhysics () { @@ -171,7 +184,7 @@ export class b2RigidBody2D implements IRigidBody2D { const rot = this._rigidBody.node.worldRotation; const euler = tempVec3; - Quat.toEuler(euler, rot); + Quat.toEulerInYXZOrder(euler, rot); const rotation = toRadian(euler.z); const bodyType = this._rigidBody.type; diff --git a/cocos/physics-2d/box2d/shapes/box-shape-2d.ts b/cocos/physics-2d/box2d/shapes/box-shape-2d.ts index 4c3b539559..b2bef265a6 100644 --- a/cocos/physics-2d/box2d/shapes/box-shape-2d.ts +++ b/cocos/physics-2d/box2d/shapes/box-shape-2d.ts @@ -54,7 +54,7 @@ export class b2BoxShape extends b2Shape2D implements IBoxShape { return wps; } - _createShapes (scaleX: number, scaleY: number) { + _createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number) { scaleX = Math.abs(scaleX); scaleY = Math.abs(scaleY); @@ -62,8 +62,8 @@ export class b2BoxShape extends b2Shape2D implements IBoxShape { const width = comp.size.width / 2 / PHYSICS_2D_PTM_RATIO * scaleX; const height = comp.size.height / 2 / PHYSICS_2D_PTM_RATIO * scaleY; - const offsetX = comp.offset.x / PHYSICS_2D_PTM_RATIO * scaleX; - const offsetY = comp.offset.y / PHYSICS_2D_PTM_RATIO * scaleY; + const offsetX = (relativePositionX + comp.offset.x * scaleX) / PHYSICS_2D_PTM_RATIO; + const offsetY = (relativePositionY + comp.offset.y * scaleY) / PHYSICS_2D_PTM_RATIO; const shape = new b2.PolygonShape(); shape.SetAsBox(width, height, new b2.Vec2(offsetX, offsetY), 0); diff --git a/cocos/physics-2d/box2d/shapes/circle-shape-2d.ts b/cocos/physics-2d/box2d/shapes/circle-shape-2d.ts index 6ac3a84a17..1c453ba3cb 100644 --- a/cocos/physics-2d/box2d/shapes/circle-shape-2d.ts +++ b/cocos/physics-2d/box2d/shapes/circle-shape-2d.ts @@ -40,14 +40,14 @@ export class b2CircleShape extends b2Shape2D implements ICircleShape { return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO); } - _createShapes (scaleX: number, scaleY: number) { + _createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number) { scaleX = Math.abs(scaleX); scaleY = Math.abs(scaleY); const comp = this.collider as CircleCollider2D; - const offsetX = comp.offset.x / PHYSICS_2D_PTM_RATIO * scaleX; - const offsetY = comp.offset.y / PHYSICS_2D_PTM_RATIO * scaleY; + const offsetX = (relativePositionX + comp.offset.x * scaleX) / PHYSICS_2D_PTM_RATIO; + const offsetY = (relativePositionY + comp.offset.y * scaleY) / PHYSICS_2D_PTM_RATIO; const shape = new b2.CircleShape(); shape.m_radius = comp.radius / PHYSICS_2D_PTM_RATIO * scaleX; diff --git a/cocos/physics-2d/box2d/shapes/polygon-shape-2d.ts b/cocos/physics-2d/box2d/shapes/polygon-shape-2d.ts index 47c3cbbc3f..6a9a4e4b4a 100644 --- a/cocos/physics-2d/box2d/shapes/polygon-shape-2d.ts +++ b/cocos/physics-2d/box2d/shapes/polygon-shape-2d.ts @@ -49,7 +49,7 @@ export class b2PolygonShape extends b2Shape2D implements IPolygonShape { return this._worldPoints; } - _createShapes (scaleX: number, scaleY: number) { + _createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number) { const shapes: b2.PolygonShape[] = []; const comp = this.collider as PolygonCollider2D; @@ -79,8 +79,8 @@ export class b2PolygonShape extends b2Shape2D implements IPolygonShape { shape = new b2.PolygonShape(); } const p = poly[j]; - const x = (p.x + offset.x) / PHYSICS_2D_PTM_RATIO * scaleX; - const y = (p.y + offset.y) / PHYSICS_2D_PTM_RATIO * scaleY; + const x = (relativePositionX + (p.x + offset.x) * scaleX) / PHYSICS_2D_PTM_RATIO; + const y = (relativePositionY + (p.y + offset.y) * scaleY) / PHYSICS_2D_PTM_RATIO; const v = new b2.Vec2(x, y); vertices.push(v); diff --git a/cocos/physics-2d/box2d/shapes/shape-2d.ts b/cocos/physics-2d/box2d/shapes/shape-2d.ts index a0e804bc44..91bd0b4463 100644 --- a/cocos/physics-2d/box2d/shapes/shape-2d.ts +++ b/cocos/physics-2d/box2d/shapes/shape-2d.ts @@ -22,11 +22,11 @@ THE SOFTWARE. */ -import b2 from '@cocos/box2d'; +import b2, { Vec2 } from '@cocos/box2d'; import { IBaseShape } from '../../spec/i-physics-shape'; import { Collider2D, PhysicsSystem2D, RigidBody2D, PHYSICS_2D_PTM_RATIO } from '../../../../exports/physics-2d-framework'; -import { Rect } from '../../../core'; +import { Rect, Vec3 } from '../../../core'; import { b2PhysicsWorld } from '../physics-world'; import { PhysicsGroup } from '../../../physics/framework/physics-enum'; @@ -34,7 +34,11 @@ const tempFilter = new b2.Filter(); function getFilter (shape: b2Shape2D) { const comp = shape.collider; - tempFilter.categoryBits = comp.group === PhysicsGroup.DEFAULT ? comp.body!.group : comp.group; + if (comp.body) { + tempFilter.categoryBits = comp.group === PhysicsGroup.DEFAULT ? comp.body.group : comp.group; + } else { + tempFilter.categoryBits = comp.group; + } tempFilter.maskBits = PhysicsSystem2D.instance.collisionMatrix[tempFilter.categoryBits]; return tempFilter; } @@ -133,7 +137,8 @@ export class b2Shape2D implements IBaseShape { return this._fixtures.indexOf(fixture); } - _createShapes (scaleX: number, scaleY: number): b2.Shape[] { + //relativePositionX/Y : relative Position from shape to rigid body + _createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): b2.Shape[] { return []; } @@ -141,16 +146,21 @@ export class b2Shape2D implements IBaseShape { if (this._inited) return; const comp = this.collider; + const scale = comp.node.worldScale; + // relative Position from shape to rigid body + let relativePosition = Vec3.ZERO; const body = comp.getComponent(RigidBody2D); - if (!body) return; - const innerBody = body.impl?.impl as b2.Body; - if (!innerBody) return; + //if rigid body is not attached to the same node of collider, this b2.shape is attached + // to the groundRigidBody(pos zero, rot zero) + if (body && body.impl && body.impl.impl) { + this._body = body.impl.impl as b2.Body; + } else { + this._body = (PhysicsSystem2D.instance.physicsWorld as b2PhysicsWorld).groundBodyImpl; + relativePosition = comp.node.worldPosition; + } - const node = body.node; - const scale = node.worldScale; - - const shapes = scale.x === 0 && scale.y === 0 ? [] : this._createShapes(scale.x, scale.y); + const shapes = scale.x === 0 && scale.y === 0 ? [] : this._createShapes(scale.x, scale.y, relativePosition.x, relativePosition.y); const filter = getFilter(this); @@ -167,19 +177,13 @@ export class b2Shape2D implements IBaseShape { filter, }; - const fixture = innerBody.CreateFixture(fixDef); + const fixture = this._body.CreateFixture(fixDef); fixture.m_userData = this; - if (body.enabledContactListener) { - (PhysicsSystem2D.instance.physicsWorld as b2PhysicsWorld).registerContactFixture(fixture); - } - this._shapes.push(shape); this._fixtures.push(fixture); } - this._body = innerBody; - this._inited = true; } @@ -191,9 +195,6 @@ export class b2Shape2D implements IBaseShape { for (let i = fixtures.length - 1; i >= 0; i--) { const fixture = fixtures[i]; - fixture.m_userData = null; - - (PhysicsSystem2D.instance.physicsWorld as b2PhysicsWorld).unregisterContactFixture(fixture); if (body) { body.DestroyFixture(fixture); diff --git a/cocos/physics-2d/builtin/builtin-world.ts b/cocos/physics-2d/builtin/builtin-world.ts index f09c266b1e..d1429b976a 100644 --- a/cocos/physics-2d/builtin/builtin-world.ts +++ b/cocos/physics-2d/builtin/builtin-world.ts @@ -260,4 +260,7 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld { raycast (p1: IVec2Like, p2: IVec2Like, type: ERaycast2DType): RaycastResult2D[] { return []; } + finalizeContactEvent () { + + } } diff --git a/cocos/physics-2d/framework/components/colliders/box-collider-2d.ts b/cocos/physics-2d/framework/components/colliders/box-collider-2d.ts index 54ebcdb3a4..f044fa0a19 100644 --- a/cocos/physics-2d/framework/components/colliders/box-collider-2d.ts +++ b/cocos/physics-2d/framework/components/colliders/box-collider-2d.ts @@ -26,20 +26,23 @@ import { Vec2, Size, _decorator } from '../../../../core'; import { Collider2D } from './collider-2d'; import { ECollider2DType } from '../../physics-types'; import { IBoxShape } from '../../../spec/i-physics-shape'; +import { help, serializable, tooltip, type } from '../../../../core/data/decorators'; const { ccclass, menu, property } = _decorator; @ccclass('cc.BoxCollider2D') +@help('i18n:cc.BoxCollider2D') @menu('Physics2D/Colliders/BoxCollider2D') export class BoxCollider2D extends Collider2D { - @property + @serializable private _size = new Size(1, 1); /** * @en Box size. * @zh 包围盒大小。 */ - @property + @type(Size) + @tooltip('i18n:physics2d.collider.size') get size () { return this._size; } diff --git a/cocos/physics-2d/framework/components/colliders/circle-collider-2d.ts b/cocos/physics-2d/framework/components/colliders/circle-collider-2d.ts index 001a6cd434..22699791e7 100644 --- a/cocos/physics-2d/framework/components/colliders/circle-collider-2d.ts +++ b/cocos/physics-2d/framework/components/colliders/circle-collider-2d.ts @@ -22,24 +22,27 @@ THE SOFTWARE. */ -import { Vec2, _decorator } from '../../../../core'; +import { CCFloat, Vec2, _decorator } from '../../../../core'; import { Collider2D } from './collider-2d'; import { ECollider2DType } from '../../physics-types'; import { ICircleShape } from '../../../spec/i-physics-shape'; +import { help, serializable, tooltip, type } from '../../../../core/data/decorators'; const { ccclass, menu, property } = _decorator; @ccclass('cc.CircleCollider2D') +@help('i18n:cc.CircleCollider2D') @menu('Physics2D/Colliders/CircleCollider2D') export class CircleCollider2D extends Collider2D { - @property + @serializable private _radius = 1; /** * @en Circle radius. * @zh 圆形半径。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.collider.radius') get radius () { return this._radius; } diff --git a/cocos/physics-2d/framework/components/colliders/collider-2d.ts b/cocos/physics-2d/framework/components/colliders/collider-2d.ts index 4fd1401a3c..daf3e4db72 100644 --- a/cocos/physics-2d/framework/components/colliders/collider-2d.ts +++ b/cocos/physics-2d/framework/components/colliders/collider-2d.ts @@ -24,12 +24,12 @@ import { EDITOR } from 'internal:constants'; -import { Vec2, Rect, _decorator, Eventify, cclegacy } from '../../../../core'; +import { Vec2, Rect, _decorator, Eventify, cclegacy, tooltip, CCInteger, serializable, CCFloat, CCBoolean, warnID } from '../../../../core'; import { PhysicsGroup } from '../../../../physics/framework/physics-enum'; import { RigidBody2D } from '../rigid-body-2d'; import { createShape } from '../../physics-selector'; -import { ECollider2DType } from '../../physics-types'; +import { Contact2DType, ECollider2DType } from '../../physics-types'; import { IBaseShape } from '../../../spec/i-physics-shape'; import { Component } from '../../../../scene-graph'; @@ -38,12 +38,15 @@ const { ccclass, editable, property, type } = _decorator; @ccclass('cc.Collider2D') export class Collider2D extends Eventify(Component) { @editable + @tooltip('i18n:physics2d.collider.editing') editing = false; /** * @en Tag. If a node has several collider components, you can judge which type of collider is collided according to the tag. * @zh 标签。当一个节点上有多个碰撞组件时,在发生碰撞后,可以使用此标签来判断是节点上的哪个碰撞组件被碰撞了。 */ - @property + @type(CCFloat) + @serializable + @tooltip('i18n:physics2d.collider.tag') tag = 0; /** @@ -53,6 +56,7 @@ export class Collider2D extends Eventify(Component) { * 获取或设置分组。 */ @type(PhysicsGroup) + @tooltip('i18n:physics2d.collider.group') public get group (): number { return this._group; } @@ -67,7 +71,8 @@ export class Collider2D extends Eventify(Component) { * @en The density. * @zh 密度。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.collider.density') get density () { return this._density; } @@ -81,7 +86,8 @@ export class Collider2D extends Eventify(Component) { * @zh * 一个传感器类型的碰撞体会产生碰撞回调,但是不会发生物理碰撞效果。 */ - @property + @type(CCBoolean) + @tooltip('i18n:physics2d.collider.sensor') get sensor () { return this._sensor; } @@ -95,7 +101,8 @@ export class Collider2D extends Eventify(Component) { * @zh * 摩擦系数,取值一般在 [0, 1] 之间。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.collider.friction') get friction () { return this._friction; } @@ -109,7 +116,8 @@ export class Collider2D extends Eventify(Component) { * @zh * 弹性系数,取值一般在 [0, 1]之间。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.collider.restitution') get restitution () { return this._restitution; } @@ -120,7 +128,8 @@ export class Collider2D extends Eventify(Component) { * @en Position offset * @zh 位置偏移量 */ - @property + @type(Vec2) + @tooltip('i18n:physics2d.collider.offset') get offset () { return this._offset; } @@ -203,21 +212,28 @@ export class Collider2D extends Eventify(Component) { return new Rect(); } + public on void>(type: string, callback: TFunction, thisArg?: any, once?: boolean): typeof callback { + if (type === Contact2DType.PRE_SOLVE || type === Contact2DType.POST_SOLVE) { + warnID(16002, type, '3.7.1'); + } + return super.on(type, callback, thisArg, once); + } + // protected properties protected _shape: IBaseShape | null = null; protected _body: RigidBody2D | null = null; - @property + @serializable protected _group = PhysicsGroup.DEFAULT; - @property + @serializable protected _density = 1.0; - @property + @serializable protected _sensor = false; - @property + @serializable protected _friction = 0.2; - @property + @serializable protected _restitution = 0; - @property + @serializable protected _offset = new Vec2(); } diff --git a/cocos/physics-2d/framework/components/colliders/polygon-collider-2d.ts b/cocos/physics-2d/framework/components/colliders/polygon-collider-2d.ts index 0e870af309..3a6385178e 100644 --- a/cocos/physics-2d/framework/components/colliders/polygon-collider-2d.ts +++ b/cocos/physics-2d/framework/components/colliders/polygon-collider-2d.ts @@ -22,27 +22,32 @@ THE SOFTWARE. */ -import { Vec2, _decorator } from '../../../../core'; +import { CCFloat, Vec2, _decorator } from '../../../../core'; import { Collider2D } from './collider-2d'; import { ECollider2DType } from '../../physics-types'; import { IPolygonShape } from '../../../spec/i-physics-shape'; +import { displayOrder, help, serializable, tooltip, type } from '../../../../core/data/decorators'; const { ccclass, menu, property } = _decorator; @ccclass('cc.PolygonCollider2D') +@help('i18n:cc.PolygonCollider2D') @menu('Physics2D/Colliders/PolygonCollider2D') export class PolygonCollider2D extends Collider2D { - @property({ serializable: false, displayOrder: 0 }) + @type(CCFloat) + @displayOrder(0) + @tooltip('i18n:physics2d.collider.threshold') threshold = 1; - @property + @serializable private _points = [new Vec2(-1, -1), new Vec2(1, -1), new Vec2(1, 1), new Vec2(-1, 1)]; /** * @en Polygon points. * @zh 多边形顶点数组。 */ - @property({ type: Vec2 }) + @type([Vec2]) + @tooltip('i18n:physics2d.collider.points') get points () { return this._points; } diff --git a/cocos/physics-2d/framework/components/joints/distance-joint-2d.ts b/cocos/physics-2d/framework/components/joints/distance-joint-2d.ts index c01d29a100..625bc0c253 100644 --- a/cocos/physics-2d/framework/components/joints/distance-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/distance-joint-2d.ts @@ -25,11 +25,13 @@ import { Joint2D } from './joint-2d'; import { IDistanceJoint } from '../../../spec/i-physics-joint'; import { EJoint2DType } from '../../physics-types'; -import { Vec3, _decorator } from '../../../../core'; +import { CCBoolean, CCFloat, Vec3, _decorator } from '../../../../core'; +import { help, serializable, tooltip, type } from '../../../../core/data/decorators'; const { ccclass, menu, property } = _decorator; @ccclass('cc.DistanceJoint2D') +@help('i18n:cc.Joint2D') @menu('Physics2D/Joints/DistanceJoint2D') export class DistanceJoint2D extends Joint2D { TYPE = EJoint2DType.DISTANCE; @@ -40,7 +42,8 @@ export class DistanceJoint2D extends Joint2D { * @zh * 最大长度。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.maxLength') get maxLength () { if (this._autoCalcDistance) { if (this.connectedBody) { @@ -64,7 +67,8 @@ export class DistanceJoint2D extends Joint2D { * @zh * 自动计算关节连接的两个刚体间的距离。 */ - @property + @type(CCBoolean) + @tooltip('i18n:physics2d.joint.autoCalcDistance') get autoCalcDistance () { return this._autoCalcDistance; } @@ -74,8 +78,9 @@ export class DistanceJoint2D extends Joint2D { /// private properties - @property + @serializable private _maxLength = 5; - @property + + @serializable private _autoCalcDistance = true; } diff --git a/cocos/physics-2d/framework/components/joints/fixed-joint-2d.ts b/cocos/physics-2d/framework/components/joints/fixed-joint-2d.ts index c6ea0edb97..96a44ebdf7 100644 --- a/cocos/physics-2d/framework/components/joints/fixed-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/fixed-joint-2d.ts @@ -23,13 +23,15 @@ */ import { Joint2D } from './joint-2d'; -import { _decorator } from '../../../../core'; +import { CCFloat, _decorator } from '../../../../core'; import { IFixedJoint } from '../../../spec/i-physics-joint'; import { EJoint2DType } from '../../physics-types'; +import { help, serializable, tooltip, type } from '../../../../core/data/decorators'; const { ccclass, menu, property } = _decorator; @ccclass('cc.FixedJoint2D') +@help('i18n:cc.Joint2D') @menu('Physics2D/Joints/FixedJoint2D') export class FixedJoint2D extends Joint2D { TYPE = EJoint2DType.FIXED; @@ -40,7 +42,8 @@ export class FixedJoint2D extends Joint2D { * @zh * 弹性系数。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.frequency') get frequency (): number { return this._frequency; } @@ -57,7 +60,8 @@ export class FixedJoint2D extends Joint2D { * @zh * 阻尼,表示关节变形后,恢复到初始状态受到的阻力。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.dampingRatio') get dampingRatio (): number { return this._dampingRatio; } @@ -70,8 +74,9 @@ export class FixedJoint2D extends Joint2D { /// private properties - @property + @serializable private _frequency = 0.7; - @property + + @serializable private _dampingRatio = 0.5; } diff --git a/cocos/physics-2d/framework/components/joints/hinge-joint-2d.ts b/cocos/physics-2d/framework/components/joints/hinge-joint-2d.ts index a6a488c125..b359515fcd 100644 --- a/cocos/physics-2d/framework/components/joints/hinge-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/hinge-joint-2d.ts @@ -23,13 +23,15 @@ */ import { Joint2D } from './joint-2d'; -import { _decorator } from '../../../../core'; +import { CCBoolean, CCFloat, _decorator } from '../../../../core'; import { IHingeJoint } from '../../../spec/i-physics-joint'; import { EJoint2DType } from '../../physics-types'; +import { help, serializable, tooltip, type } from '../../../../core/data/decorators'; const { ccclass, menu, property } = _decorator; @ccclass('cc.HingeJoint2D') +@help('i18n:cc.Joint2D') @menu('Physics2D/Joints/HingeJoint2D') export class HingeJoint2D extends Joint2D { TYPE = EJoint2DType.HINGE; @@ -40,7 +42,8 @@ export class HingeJoint2D extends Joint2D { * @zh * 是否开启关节的限制? */ - @property + @type(CCBoolean) + @tooltip('i18n:physics2d.joint.enableLimit') get enableLimit (): boolean { return this._enableLimit; } @@ -54,7 +57,8 @@ export class HingeJoint2D extends Joint2D { * @zh * 角度的最低限制。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.lowerAngle') get lowerAngle (): number { return this._lowerAngle; } @@ -71,7 +75,8 @@ export class HingeJoint2D extends Joint2D { * @zh * 角度的最高限制。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.upperAngle') get upperAngle (): number { return this._upperAngle; } @@ -88,7 +93,8 @@ export class HingeJoint2D extends Joint2D { * @zh * 是否开启关节马达? */ - @property + @type(CCBoolean) + @tooltip('i18n:physics2d.joint.enableMotor') get enableMotor (): boolean { return this._enableMotor; } @@ -105,7 +111,8 @@ export class HingeJoint2D extends Joint2D { * @zh * 可以施加到刚体的最大扭矩。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.maxMotorTorque') get maxMotorTorque (): number { return this._maxMotorTorque; } @@ -122,7 +129,8 @@ export class HingeJoint2D extends Joint2D { * @zh * 期望的马达速度。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.motorSpeed') get motorSpeed (): number { return this._motorSpeed; } @@ -135,16 +143,21 @@ export class HingeJoint2D extends Joint2D { /// private properties - @property + @serializable private _enableLimit = false; - @property + + @serializable private _lowerAngle = 0; - @property + + @serializable private _upperAngle = 0; - @property + + @serializable private _enableMotor = false; - @property + + @serializable private _maxMotorTorque = 1000; - @property + + @serializable private _motorSpeed = 0; } diff --git a/cocos/physics-2d/framework/components/joints/joint-2d.ts b/cocos/physics-2d/framework/components/joints/joint-2d.ts index d55997020a..b90a364c10 100644 --- a/cocos/physics-2d/framework/components/joints/joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/joint-2d.ts @@ -23,7 +23,7 @@ */ import { EDITOR } from 'internal:constants'; -import { Vec2, _decorator, cclegacy } from '../../../../core'; +import { Vec2, _decorator, cclegacy, tooltip, serializable, CCBoolean } from '../../../../core'; import { RigidBody2D } from '../rigid-body-2d'; import { IJoint2D } from '../../../spec/i-physics-joint'; import { EJoint2DType } from '../../physics-types'; @@ -40,7 +40,9 @@ export class Joint2D extends Component { * @zh * 在自身刚体的本地空间中,Joint2D的位置。 */ - @property + @type(Vec2) + @serializable + @tooltip('i18n:physics2d.joint.anchor') anchor = new Vec2(); /** @@ -49,7 +51,9 @@ export class Joint2D extends Component { * @zh * 在连接刚体的本地空间中,Joint2D的位置。 */ - @property + @type(Vec2) + @serializable + @tooltip('i18n:physics2d.joint.connectedAnchor') connectedAnchor = new Vec2(); /** @@ -58,7 +62,9 @@ export class Joint2D extends Component { * @zh * 关节连接的两刚体之间是否开启碰撞。 */ - @property + @type(CCBoolean) + @serializable + @tooltip('i18n:physics2d.joint.collideConnected') collideConnected = false; /** @@ -68,6 +74,8 @@ export class Joint2D extends Component { * 关节连接的刚体,为空时表示连接到位于世界原点的静态刚体。 */ @type(RigidBody2D) + @serializable + @tooltip('i18n:physics2d.joint.connectedBody') connectedBody: RigidBody2D | null = null; /** diff --git a/cocos/physics-2d/framework/components/joints/mouse-joint-2d.ts b/cocos/physics-2d/framework/components/joints/mouse-joint-2d.ts index 3636e5b064..0ed1424f3f 100644 --- a/cocos/physics-2d/framework/components/joints/mouse-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/mouse-joint-2d.ts @@ -25,11 +25,13 @@ import { Joint2D } from './joint-2d'; import { IMouseJoint } from '../../../spec/i-physics-joint'; import { EJoint2DType } from '../../physics-types'; -import { Vec2, _decorator } from '../../../../core'; +import { CCFloat, Vec2, _decorator } from '../../../../core'; +import { help, serializable, tooltip, type } from '../../../../core/data/decorators'; const { ccclass, menu, property } = _decorator; @ccclass('cc.MouseJoint2D') +@help('i18n:cc.Joint2D') @menu('Physics2D/Joints/MouseJoint2D') export class MouseJoint2D extends Joint2D { TYPE = EJoint2DType.MOUSE; @@ -50,7 +52,8 @@ export class MouseJoint2D extends Joint2D { * @zh * 弹簧系数。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.frequency') get frequency (): number { return this._frequency; } @@ -67,7 +70,8 @@ export class MouseJoint2D extends Joint2D { * @zh * 阻尼,表示关节变形后,恢复到初始状态受到的阻力。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.dampingRatio') get dampingRatio (): number { return this._dampingRatio; } @@ -84,7 +88,8 @@ export class MouseJoint2D extends Joint2D { * @zh * 最大阻力值。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.maxForce') get maxForce (): number { return this._maxForce; } @@ -99,11 +104,14 @@ export class MouseJoint2D extends Joint2D { this._joint!.update!(dt); } - @property + @serializable private _maxForce = 1000; - @property + + @serializable private _dampingRatio = 0.7; - @property + + @serializable private _frequency = 5; + private _target = new Vec2(); } diff --git a/cocos/physics-2d/framework/components/joints/relative-joint-2d.ts b/cocos/physics-2d/framework/components/joints/relative-joint-2d.ts index 7096b45208..1d0845efc0 100644 --- a/cocos/physics-2d/framework/components/joints/relative-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/relative-joint-2d.ts @@ -25,7 +25,8 @@ import { Joint2D } from './joint-2d'; import { IRelativeJoint } from '../../../spec/i-physics-joint'; import { EJoint2DType } from '../../physics-types'; -import { Vec3, Vec2, IVec2Like, Quat, _decorator } from '../../../../core'; +import { Vec3, Vec2, IVec2Like, Quat, _decorator, CCFloat, CCBoolean } from '../../../../core'; +import { help, serializable, tooltip, type } from '../../../../core/data/decorators'; const tempVec3_1 = new Vec3(); const tempVec3_2 = new Vec3(); @@ -33,6 +34,7 @@ const tempVec3_2 = new Vec3(); const { ccclass, menu, property } = _decorator; @ccclass('cc.RelativeJoint2D') +@help('i18n:cc.Joint2D') @menu('Physics2D/Joints/RelativeJoint2D') export class RelativeJoint2D extends Joint2D { TYPE = EJoint2DType.RELATIVE; @@ -43,7 +45,8 @@ export class RelativeJoint2D extends Joint2D { * @zh * 可以应用于刚体的最大的力值。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.maxForce') get maxForce (): number { return this._maxForce; } @@ -60,7 +63,8 @@ export class RelativeJoint2D extends Joint2D { * @zh * 可以应用于刚体的最大扭矩值。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.maxTorque') get maxTorque (): number { return this._maxTorque; } @@ -77,7 +81,8 @@ export class RelativeJoint2D extends Joint2D { * @zh * 位置矫正系数,范围为 [0, 1]。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.correctionFactor') get correctionFactor (): number { return this._correctionFactor; } @@ -94,7 +99,8 @@ export class RelativeJoint2D extends Joint2D { * @zh * 关节另一端的刚体相对于起始端刚体的位置偏移量。 */ - @property + @type(Vec2) + @tooltip('i18n:physics2d.joint.linearOffset') get linearOffset (): Vec2 { if (this._autoCalcOffset) { if (this.connectedBody) { @@ -120,7 +126,8 @@ export class RelativeJoint2D extends Joint2D { * @zh * 关节另一端的刚体相对于起始端刚体的角度偏移量。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.angularOffset') get angularOffset (): number { if (this._autoCalcOffset) { Quat.toEuler(tempVec3_1, this.node.worldRotation); @@ -146,7 +153,8 @@ export class RelativeJoint2D extends Joint2D { * @zh * 自动计算关节连接的两个刚体间的 angularOffset 和 linearOffset。 */ - @property + @type(CCBoolean) + @tooltip('i18n:physics2d.joint.autoCalcOffset') get autoCalcOffset (): boolean { return this._autoCalcOffset; } @@ -156,16 +164,21 @@ export class RelativeJoint2D extends Joint2D { /// private properties - @property + @serializable private _maxForce = 5; - @property + + @serializable private _maxTorque = 0.7; - @property + + @serializable private _correctionFactor = 0.3; - @property + + @serializable private _angularOffset = 0; - @property + + @serializable private _linearOffset = new Vec2(); - @property + + @serializable private _autoCalcOffset = true; } diff --git a/cocos/physics-2d/framework/components/joints/slider-joint-2d.ts b/cocos/physics-2d/framework/components/joints/slider-joint-2d.ts index 3e304cd2c5..35364eb2d1 100644 --- a/cocos/physics-2d/framework/components/joints/slider-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/slider-joint-2d.ts @@ -25,12 +25,14 @@ import { Joint2D } from './joint-2d'; import { ISliderJoint } from '../../../spec/i-physics-joint'; import { EJoint2DType } from '../../physics-types'; -import { Vec2, IVec2Like, toDegree, _decorator } from '../../../../core'; +import { Vec2, IVec2Like, toDegree, _decorator, CCFloat, CCBoolean } from '../../../../core'; +import { help, serializable, tooltip, type } from '../../../../core/data/decorators'; const tempVec2 = new Vec2(); const { ccclass, menu, property } = _decorator; @ccclass('cc.SliderJoint2D') +@help('i18n:cc.Joint2D') @menu('Physics2D/Joints/SliderJoint2D') export class SliderJoint2D extends Joint2D { TYPE = EJoint2DType.SLIDER; @@ -39,7 +41,8 @@ export class SliderJoint2D extends Joint2D { * @en Slide direction. * @zh 滑动的方向。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.angle') get angle (): number { if (this._autoCalcAngle) { if (this.connectedBody) { @@ -59,7 +62,8 @@ export class SliderJoint2D extends Joint2D { * @en Auto calculate slide direction according to the slide direction. * @zh 根据连接的两个刚体自动计算滑动方向。 */ - @property + @type(CCBoolean) + @tooltip('i18n:physics2d.joint.autoCalcAngle') get autoCalcAngle (): boolean { return this._autoCalcAngle; } @@ -73,7 +77,8 @@ export class SliderJoint2D extends Joint2D { * @zh * 是否开启关节马达? */ - @property + @type(CCBoolean) + @tooltip('i18n:physics2d.joint.enableMotor') get enableMotor (): boolean { return this._enableMotor; } @@ -87,7 +92,8 @@ export class SliderJoint2D extends Joint2D { * @zh * 可以施加到刚体的最大力。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.maxMotorForce') get maxMotorForce (): number { return this._maxMotorForce; } @@ -104,7 +110,8 @@ export class SliderJoint2D extends Joint2D { * @zh * 期望的马达速度。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.motorSpeed') get motorSpeed (): number { return this._motorSpeed; } @@ -121,7 +128,8 @@ export class SliderJoint2D extends Joint2D { * @zh * 是否开启关节的距离限制? */ - @property + @type(CCBoolean) + @tooltip('i18n:physics2d.joint.enableLimit') get enableLimit (): boolean { return this._enableLimit; } @@ -135,7 +143,8 @@ export class SliderJoint2D extends Joint2D { * @zh * 刚体能够移动的最小值。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.lowerLimit') get lowerLimit (): number { return this._lowerLimit; } @@ -152,7 +161,8 @@ export class SliderJoint2D extends Joint2D { * @zh * 刚体能够移动的最大值。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.upperLimit') get upperLimit (): number { return this._upperLimit; } @@ -165,20 +175,27 @@ export class SliderJoint2D extends Joint2D { /// private properties - @property + @serializable private _angle = 0; - @property + + @serializable private _autoCalcAngle = true; - @property + + @serializable private _enableMotor = false; - @property + + @serializable private _maxMotorForce = 1000; - @property + + @serializable private _motorSpeed = 1000; - @property + + @serializable private _enableLimit = false; - @property + + @serializable private _lowerLimit = 0; - @property + + @serializable private _upperLimit = 0; } diff --git a/cocos/physics-2d/framework/components/joints/spring-joint-2d.ts b/cocos/physics-2d/framework/components/joints/spring-joint-2d.ts index 0bc326e6b7..232bdcef97 100644 --- a/cocos/physics-2d/framework/components/joints/spring-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/spring-joint-2d.ts @@ -25,11 +25,13 @@ import { Joint2D } from './joint-2d'; import { ISpringJoint } from '../../../spec/i-physics-joint'; import { EJoint2DType } from '../../physics-types'; -import { Vec3, _decorator } from '../../../../core'; +import { CCBoolean, CCFloat, Vec3, _decorator } from '../../../../core'; +import { help, serializable, tooltip, type } from '../../../../core/data/decorators'; const { ccclass, property, menu } = _decorator; @ccclass('cc.SpringJoint2D') +@help('i18n:cc.Joint2D') @menu('Physics2D/Joints/SpringJoint2D') export class SpringJoint2D extends Joint2D { TYPE = EJoint2DType.SPRING; @@ -40,7 +42,8 @@ export class SpringJoint2D extends Joint2D { * @zh * 弹性系数。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.frequency') get frequency () { return this._frequency; } @@ -57,7 +60,8 @@ export class SpringJoint2D extends Joint2D { * @zh * 阻尼,表示关节变形后,恢复到初始状态受到的阻力。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.dampingRatio') get dampingRatio () { return this._dampingRatio; } @@ -74,7 +78,8 @@ export class SpringJoint2D extends Joint2D { * @zh * 关节两端的距离。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.distance') get distance () { if (this._autoCalcDistance) { if (this.connectedBody) { @@ -98,7 +103,8 @@ export class SpringJoint2D extends Joint2D { * @zh * 自动计算关节连接的两个刚体间的距离。 */ - @property + @type(CCBoolean) + @tooltip('i18n:physics2d.joint.autoCalcDistance') get autoCalcDistance () { return this._autoCalcDistance; } @@ -108,12 +114,15 @@ export class SpringJoint2D extends Joint2D { /// private properties - @property + @serializable private _frequency = 5; - @property + + @serializable private _dampingRatio = 0.7; - @property + + @serializable private _distance = 10; - @property + + @serializable private _autoCalcDistance = true; } diff --git a/cocos/physics-2d/framework/components/joints/wheel-joint-2d.ts b/cocos/physics-2d/framework/components/joints/wheel-joint-2d.ts index 8f5b5abbbf..eb352c681a 100644 --- a/cocos/physics-2d/framework/components/joints/wheel-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/wheel-joint-2d.ts @@ -23,13 +23,15 @@ */ import { Joint2D } from './joint-2d'; -import { _decorator } from '../../../../core'; +import { CCBoolean, CCFloat, _decorator } from '../../../../core'; import { IWheelJoint } from '../../../spec/i-physics-joint'; import { EJoint2DType } from '../../physics-types'; +import { help, serializable, tooltip, type } from '../../../../core/data/decorators'; const { ccclass, menu, property } = _decorator; @ccclass('cc.WheelJoint2D') +@help('i18n:cc.Joint2D') @menu('Physics2D/Joints/WheelJoint2D') export class WheelJoint2D extends Joint2D { TYPE = EJoint2DType.WHEEL; @@ -38,7 +40,8 @@ export class WheelJoint2D extends Joint2D { * @en Wheel susspension direction. * @zh 轮子震动方向。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.angle') get angle (): number { return this._angle; } @@ -52,7 +55,8 @@ export class WheelJoint2D extends Joint2D { * @zh * 是否开启关节马达? */ - @property + @type(CCBoolean) + @tooltip('i18n:physics2d.joint.enableMotor') get enableMotor (): boolean { return this._enableMotor; } @@ -69,7 +73,8 @@ export class WheelJoint2D extends Joint2D { * @zh * 可以施加到刚体的最大扭矩。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.maxMotorTorque') get maxMotorTorque (): number { return this._maxMotorTorque; } @@ -86,7 +91,8 @@ export class WheelJoint2D extends Joint2D { * @zh * 期望的马达速度。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.motorSpeed') get motorSpeed (): number { return this._motorSpeed; } @@ -103,7 +109,8 @@ export class WheelJoint2D extends Joint2D { * @zh * 弹性系数。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.frequency') get frequency (): number { return this._frequency; } @@ -120,7 +127,8 @@ export class WheelJoint2D extends Joint2D { * @zh * 阻尼,表示关节变形后,恢复到初始状态受到的阻力。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.joint.dampingRatio') get dampingRatio (): number { return this._dampingRatio; } @@ -133,16 +141,21 @@ export class WheelJoint2D extends Joint2D { /// private properties - @property + @serializable private _angle = 90; - @property + + @serializable private _enableMotor = false; - @property + + @serializable private _maxMotorTorque = 1000; - @property + + @serializable private _motorSpeed = 0; - @property + + @serializable private _frequency = 5; - @property + + @serializable private _dampingRatio = 0.7; } diff --git a/cocos/physics-2d/framework/components/rigid-body-2d.ts b/cocos/physics-2d/framework/components/rigid-body-2d.ts index 670d9c16a0..f46cf49022 100644 --- a/cocos/physics-2d/framework/components/rigid-body-2d.ts +++ b/cocos/physics-2d/framework/components/rigid-body-2d.ts @@ -24,15 +24,17 @@ import { EDITOR } from 'internal:constants'; import { IRigidBody2D } from '../../spec/i-rigid-body'; -import { _decorator, Vec2, IVec2Like, cclegacy } from '../../../core'; +import { _decorator, Vec2, IVec2Like, cclegacy, CCBoolean, CCFloat } from '../../../core'; import { ERigidBody2DType } from '../physics-types'; import { createRigidBody } from '../physics-selector'; import { PhysicsGroup } from '../../../physics/framework/physics-enum'; import { Component } from '../../../scene-graph'; +import { help, serializable, tooltip } from '../../../core/data/decorators'; const { property, type, menu, ccclass } = _decorator; @ccclass('cc.RigidBody2D') +@help('i18n:cc.RigidBody2D') @menu('Physics2D/RigidBody2D') export class RigidBody2D extends Component { /** @@ -42,6 +44,7 @@ export class RigidBody2D extends Component { * 获取或设置分组。 */ @type(PhysicsGroup) + @tooltip('i18n:physics2d.rigidbody.group') public get group (): number { return this._group; } @@ -49,7 +52,9 @@ export class RigidBody2D extends Component { this._group = v; } - @property + @type(CCBoolean) + @serializable + @tooltip('i18n:physics2d.rigidbody.enabledContactListener') enabledContactListener = false; /** @@ -65,7 +70,9 @@ export class RigidBody2D extends Component { * - 所有刚体都被禁止从 运动刚体 和 静态刚体 中穿过。此选项只关注于 动态刚体。 * - 应该尽量少的使用此选项,因为它会增加程序处理时间。 */ - @property + @type(CCBoolean) + @serializable + @tooltip('i18n:physics2d.rigidbody.bullet') bullet = false; /** @@ -75,6 +82,7 @@ export class RigidBody2D extends Component { * 刚体类型: Static, Kinematic, Dynamic or Animated. */ @type(ERigidBody2DType) + @tooltip('i18n:physics2d.rigidbody.type') get type (): ERigidBody2DType { return this._type; } @@ -97,7 +105,8 @@ export class RigidBody2D extends Component { * 如果此刚体永远都不应该进入睡眠,那么设置这个属性为 false。 * 需要注意这将使 CPU 占用率提高。 */ - @property + @type(CCBoolean) + @tooltip('i18n:physics2d.rigidbody.allowSleep') get allowSleep (): boolean { return this._allowSleep; } @@ -114,7 +123,8 @@ export class RigidBody2D extends Component { * @zh * 缩放应用在此刚体上的重力值。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.rigidbody.gravityScale') get gravityScale (): number { return this._gravityScale; } @@ -133,7 +143,8 @@ export class RigidBody2D extends Component { * @zh * Linear damping 用于衰减刚体的线性速度。衰减系数可以大于 1,但是当衰减系数比较大的时候,衰减的效果会变得比较敏感。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.rigidbody.linearDamping') get linearDamping (): number { return this._linearDamping; } @@ -152,7 +163,8 @@ export class RigidBody2D extends Component { * @zh * Angular damping 用于衰减刚体的角速度。衰减系数可以大于 1,但是当衰减系数比较大的时候,衰减的效果会变得比较敏感。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.rigidbody.angularDamping') get angularDamping (): number { return this._angularDamping; } @@ -169,7 +181,8 @@ export class RigidBody2D extends Component { * @zh * 刚体在世界坐标下的线性速度。 */ - @property + @type(Vec2) + @tooltip('i18n:physics2d.rigidbody.linearVelocity') get linearVelocity (): Vec2 { if (this._body) { this._body.getLinearVelocity(this._linearVelocity); @@ -189,7 +202,8 @@ export class RigidBody2D extends Component { * @zh * 刚体的角速度。 */ - @property + @type(CCFloat) + @tooltip('i18n:physics2d.rigidbody.angularVelocity') get angularVelocity (): number { if (this._body) { this._angularVelocity = this._body.getAngularVelocity(); @@ -209,7 +223,8 @@ export class RigidBody2D extends Component { * @zh * 是否禁止此刚体进行旋转。 */ - @property + @type(CCBoolean) + @tooltip('i18n:physics2d.rigidbody.fixedRotation') get fixedRotation (): boolean { return this._fixedRotation; } @@ -226,7 +241,9 @@ export class RigidBody2D extends Component { * @zh * 是否在初始化时唤醒此刚体。 */ - @property + @type(CCBoolean) + @serializable + @tooltip('i18n:physics2d.rigidbody.awakeOnLoad') awakeOnLoad = true; // /** @@ -555,22 +572,30 @@ export class RigidBody2D extends Component { return this._body; } - @property + @serializable private _group = PhysicsGroup.DEFAULT; - @property + + @serializable private _type = ERigidBody2DType.Dynamic; - @property + + @serializable private _allowSleep = true; - @property + + @serializable private _gravityScale = 1; - @property + + @serializable private _linearDamping = 0; - @property + + @serializable private _angularDamping = 0; - @property + + @serializable private _linearVelocity = new Vec2(); - @property + + @serializable private _angularVelocity = 0; - @property + + @serializable private _fixedRotation = false; } diff --git a/cocos/physics-2d/framework/physics-selector.ts b/cocos/physics-2d/framework/physics-selector.ts index 50954568f3..124e6122f4 100644 --- a/cocos/physics-2d/framework/physics-selector.ts +++ b/cocos/physics-2d/framework/physics-selector.ts @@ -164,6 +164,7 @@ const ENTIRE_WORLD: IPhysicsWorld = { testPoint: FUNC, testAABB: FUNC, drawDebug: FUNC, + finalizeContactEvent: FUNC, }; export function checkPhysicsModule (obj: any) { diff --git a/cocos/physics-2d/framework/physics-system.ts b/cocos/physics-2d/framework/physics-system.ts index 2d8d8a6b06..e5ae6f4f47 100644 --- a/cocos/physics-2d/framework/physics-system.ts +++ b/cocos/physics-2d/framework/physics-system.ts @@ -23,13 +23,13 @@ */ import { EDITOR } from 'internal:constants'; -import { System, Vec2, IVec2Like, Rect, Eventify, Enum, Settings, settings, cclegacy } from '../../core'; +import { System, Vec2, IVec2Like, Rect, Eventify, Enum, Settings, settings, cclegacy, warnID } from '../../core'; import { createPhysicsWorld, selector, IPhysicsSelector } from './physics-selector'; import { DelayEvent } from './physics-internal-types'; import { ICollisionMatrix } from '../../physics/framework/physics-config'; import { CollisionMatrix } from '../../physics/framework/collision-matrix'; -import { ERaycast2DType, RaycastResult2D, PHYSICS_2D_PTM_RATIO, PhysicsGroup } from './physics-types'; +import { ERaycast2DType, RaycastResult2D, PHYSICS_2D_PTM_RATIO, PhysicsGroup, Contact2DType } from './physics-types'; import { Collider2D } from './components/colliders/collider-2d'; import { director, Director } from '../../game'; @@ -300,6 +300,8 @@ export class PhysicsSystem2D extends Eventify(System) { this.physicsWorld.syncPhysicsToScene(); + this.physicsWorld.finalizeContactEvent(); + if (this.debugDrawFlags) { this.physicsWorld.drawDebug(); } @@ -373,6 +375,13 @@ export class PhysicsSystem2D extends Eventify(System) { testAABB (rect: Rect): readonly Collider2D[] { return this.physicsWorld.testAABB(rect); } + + public on void>(type: string, callback: TFunction, thisArg?: any, once?: boolean): typeof callback { + if (type === Contact2DType.PRE_SOLVE || type === Contact2DType.POST_SOLVE) { + warnID(16002, type, '3.7.1'); + } + return super.on(type, callback, thisArg, once); + } } function initPhysicsSystem () { diff --git a/cocos/physics-2d/framework/physics-types.ts b/cocos/physics-2d/framework/physics-types.ts index f8b2dccdf2..426d121565 100644 --- a/cocos/physics-2d/framework/physics-types.ts +++ b/cocos/physics-2d/framework/physics-types.ts @@ -130,8 +130,19 @@ export enum ERaycast2DType { export const Contact2DType = { None: 'none-contact', BEGIN_CONTACT: 'begin-contact', + STAY_CONTACT: 'stay-contact', END_CONTACT: 'end-contact', + + /** + * @deprecated Since v3.7.1, PhysicsSystem2D doesn't directly emit the contact events emitted by box2d. + * If you need this event, try to modify the relevant engine code(mainly PhysicsContactListener). + */ PRE_SOLVE: 'pre-solve', + + /** + * @deprecated Since v3.7.1, PhysicsSystem2D doesn't directly emit the contact events emitted by box2d. + * If you need this event, try to modify the relevant engine code(mainly PhysicsContactListener). + */ POST_SOLVE: 'post-solve', }; diff --git a/cocos/physics-2d/spec/i-physics-world.ts b/cocos/physics-2d/spec/i-physics-world.ts index 1d5c9753f3..7109c439c8 100644 --- a/cocos/physics-2d/spec/i-physics-world.ts +++ b/cocos/physics-2d/spec/i-physics-world.ts @@ -38,4 +38,5 @@ export interface IPhysicsWorld { testPoint (p: Vec2): readonly Collider2D[]; testAABB (rect: Rect): readonly Collider2D[]; drawDebug (): void; + finalizeContactEvent(): void } diff --git a/cocos/render-scene/core/render-scene.ts b/cocos/render-scene/core/render-scene.ts index d3e129e144..ad198d1e29 100644 --- a/cocos/render-scene/core/render-scene.ts +++ b/cocos/render-scene/core/render-scene.ts @@ -523,26 +523,13 @@ export class RenderScene { } } -class ModelInfo { - /** - * @zh model 所属的 LOD 层级 - * @en LOD level of the model。 - */ - ownerLodLevel = -1; - lodGroup: LODGroup = null!; - /** - * @zh model 能被看到的相机列表 - * @en List of cameras that model can be seen. - */ - visibleCameras: Map = new Map(); -} - class LODInfo { /** * @zh 当前使用哪一级的 LOD, -1 表示没有层级被使用 * @en Which level of LOD is currently in use, -1 means no levels are used */ usedLevel = -1; + lastUsedLevel = -1; transformDirty = true; } @@ -599,6 +586,7 @@ class LodStateCache { for (const visibleCamera of this._lodStateInCamera) { visibleCamera[1].delete(lodGroup); } + this._levelModels.delete(lodGroup); } removeModel (model: Model) { @@ -609,31 +597,42 @@ class LodStateCache { // Update list of visible cameras on _modelsInLODGroup and update lod usage level under specified camera. updateLodState () { - //insert vecAddedLodGroup's model into modelsByAnyLODGroup + // insert vecAddedLodGroup's model into modelsByAnyLODGroup for (const addedLodGroup of this._newAddedLodGroupVec) { + let levelModels = this._levelModels.get(addedLodGroup); + if (!levelModels) { + levelModels = new Map>(); + this._levelModels.set(addedLodGroup, levelModels); + } for (let index = 0; index < addedLodGroup.lodCount; index++) { + let lodModels = levelModels.get(index); + if (!lodModels) { + lodModels = new Array(); + } const lod = addedLodGroup.lodDataArray[index]; for (const model of lod.models) { let modelInfo = this._modelsInLODGroup.get(model); if (!modelInfo) { - modelInfo = new ModelInfo(); + modelInfo = new Map(); } - modelInfo.ownerLodLevel = index; - modelInfo.lodGroup = addedLodGroup; this._modelsInLODGroup.set(model, modelInfo); + lodModels.push(model); } + levelModels.set(index, lodModels); } } this._newAddedLodGroupVec.length = 0; - //update current visible lod index & model's visible cameras list + // update current visible lod index & model's visible cameras list for (const lodGroup of this._renderScene.lodGroups) { if (lodGroup.enabled) { const lodLevels = lodGroup.getLockedLODLevels(); const count = lodLevels.length; - // count > 0, indicating that the user force to use certain layers of lod + // count > 0, indicating that the user force to use certain layers of + // lod if (count > 0) { - //Update the dirty flag to make it easier to update the visible index of lod after lifting the forced use of lod. + // Update the dirty flag to make it easier to update the visible + // index of lod after lifting the forced use of lod. if (lodGroup.node.hasChangedFlags > 0) { for (const visibleCamera of this._lodStateInCamera) { let lodInfo = visibleCamera[1].get(lodGroup); @@ -644,26 +643,33 @@ class LodStateCache { lodInfo.transformDirty = true; } } - //Update the visible camera list of all models on lodGroup when the visible level changes. + // Update the visible camera list of all models on lodGroup when the + // visible level changes. if (lodGroup.isLockLevelChanged()) { lodGroup.resetLockChangeFlag(); - for (let index = 0; index < lodGroup.lodCount; index++) { - const lod = lodGroup.lodDataArray[index]; - for (const model of lod.models) { - const modelInfo = this._modelsInLODGroup.get(model); - if (!modelInfo) { - continue; - } - modelInfo.visibleCameras.clear(); - if (model.node && model.node.active) { - for (const visibleIndex of lodLevels) { - if (modelInfo.ownerLodLevel === visibleIndex) { - for (const visibleCamera of this._lodStateInCamera) { - modelInfo.visibleCameras.set(visibleCamera[0], true); - } - break; - } + + const lodModels = this._levelModels.get(lodGroup); + if (lodModels) { + lodModels.forEach((vecArray, index) => { + vecArray.forEach((model) => { + const modelInfo = this._modelsInLODGroup.get(model); + if (modelInfo) { + modelInfo.clear(); } + }); + }); + + for (const visibleIndex of lodLevels) { + const vecModels = lodModels.get(visibleIndex); + if (vecModels) { + vecModels.forEach((model) => { + const modelInfo = this._modelsInLODGroup.get(model); + if (modelInfo && model.node && model.node.active) { + for (const visibleCamera of this._lodStateInCamera) { + modelInfo.set(visibleCamera[0], true); + } + } + }); } } } @@ -671,7 +677,7 @@ class LodStateCache { continue; } - //Normal Process, no LOD is forced. + // Normal Process, no LOD is forced. let hasUpdated = false; for (const visibleCamera of this._lodStateInCamera) { let lodInfo = visibleCamera[1].get(lodGroup); @@ -681,48 +687,74 @@ class LodStateCache { } const cameraChangeFlags = visibleCamera[0].node.hasChangedFlags; const lodChangeFlags = lodGroup.node.hasChangedFlags; - // Changes in the camera matrix or changes in the matrix of the node where lodGroup is located or - // the transformDirty marker is true, etc. All need to recalculate the visible level of LOD. + // Changes in the camera matrix or changes in the matrix of the node + // where lodGroup is located or the transformDirty marker is true, + // etc. All need to recalculate the visible level of LOD. if (cameraChangeFlags > 0 || lodChangeFlags > 0 || lodInfo.transformDirty) { if (lodInfo.transformDirty) { lodInfo.transformDirty = false; } const index = lodGroup.getVisibleLODLevel(visibleCamera[0]); if (index !== lodInfo.usedLevel) { + lodInfo.lastUsedLevel = lodInfo.usedLevel; lodInfo.usedLevel = index; hasUpdated = true; } } } - //The LOD of the last frame is forced to be used, the list of visible cameras of modelInfo needs to be updated. + const lodModels = this._levelModels.get(lodGroup); + if (!lodModels) { + continue; + } + + // The LOD of the last frame is forced to be used, the list of visible + // cameras of modelInfo needs to be updated. if (lodGroup.isLockLevelChanged()) { lodGroup.resetLockChangeFlag(); - hasUpdated = true; - } - //Update the visible camera list of all models on lodGroup. - if (hasUpdated) { - for (let index = 0; index < lodGroup.lodCount; index++) { - const lod = lodGroup.lodDataArray[index]; - for (const model of lod.models) { + + lodModels.forEach((vecArray, index) => { + vecArray.forEach((model) => { const modelInfo = this._modelsInLODGroup.get(model); if (modelInfo) { - modelInfo.visibleCameras.clear(); - if (model.node && model.node.active) { - this._lodStateInCamera.forEach((lodMap, camera) => { - let visibleLevel = -1; - const lodInfo = lodMap.get(lodGroup); - if (lodInfo) { - visibleLevel = lodInfo.usedLevel; - } - if (modelInfo.ownerLodLevel === visibleLevel) { - modelInfo.visibleCameras.set(camera, true); - } - }); - } + modelInfo.clear(); + } + }); + }); + hasUpdated = true; + } else if (hasUpdated) { + this._lodStateInCamera.forEach((lodState, camera) => { + const lodInfo = lodState.get(lodGroup); + if (lodInfo && lodInfo.usedLevel !== lodInfo.lastUsedLevel) { + const vecModels = lodModels.get(lodInfo.lastUsedLevel); + if (vecModels) { + vecModels.forEach((model) => { + const modelInfo = this._modelsInLODGroup.get(model); + if (modelInfo) { + modelInfo.clear(); + } + }); } } - } + }); + } + + if (hasUpdated) { + this._lodStateInCamera.forEach((lodState, camera) => { + const lodInfo = lodState.get(lodGroup); + if (lodInfo) { + const usedLevel = lodInfo.usedLevel; + const vecModels = lodModels.get(usedLevel); + if (vecModels) { + vecModels.forEach((model) => { + const modelInfo = this._modelsInLODGroup.get(model); + if (modelInfo && model.node && model.node.active) { + modelInfo.set(camera, true); + } + }); + } + } + }); } } } @@ -734,10 +766,11 @@ class LodStateCache { return false; } - return !modelInfo.visibleCameras.has(camera); + return !modelInfo.has(camera); } clearCache () { + this._levelModels.clear(); this._modelsInLODGroup.clear(); this._lodStateInCamera.clear(); this._newAddedLodGroupVec.length = 0; @@ -751,10 +784,11 @@ class LodStateCache { private _renderScene: RenderScene = null!; /** - * @zh LOD使用的model集合;包含每个LODGroup的每一级LOD - * @en The collection of models used by LOD; Each LOD of each LODGroup. + * @zh LOD使用的model集合以及每个model当前能被看到的相机列表;包含每个LODGroup的每一级LOD + * @en The set of models used by the LOD and the list of cameras that each models can currently be seen, + * contains each level of LOD for each LODGroup. */ - private _modelsInLODGroup: Map = new Map(); + private _modelsInLODGroup: Map> = new Map>(); /** * @zh 指定相机下,LODGroup使用哪一级的LOD @@ -767,4 +801,6 @@ class LodStateCache { * @en The lodgroup added in the previous frame. */ private _newAddedLodGroupVec: Array = new Array(); + + private _levelModels: Map>> = new Map>>(); } diff --git a/cocos/render-scene/scene/camera.ts b/cocos/render-scene/scene/camera.ts index 4f6b5fd71c..c5305b3e90 100644 --- a/cocos/render-scene/scene/camera.ts +++ b/cocos/render-scene/scene/camera.ts @@ -30,42 +30,145 @@ import { RenderScene } from '../core/render-scene'; import { RenderWindow } from '../core/render-window'; import { GeometryRenderer } from '../../rendering/geometry-renderer'; +/** + * @en The enumeration type for the fixed axis of the camera. + * The field of view along the corresponding axis would be fixed regardless of screen aspect changes. + * @zh 相机视角的锁定轴向枚举,在对应轴上不会跟随屏幕长宽比例变化。 + */ export enum CameraFOVAxis { + /** + * @en Vertically fixed camera + * @zh 在垂直轴向上锁定的相机 + */ VERTICAL, + /** + * @en Horizontally fixed camera + * @zh 在水平轴向上锁定的相机 + */ HORIZONTAL, } +/** + * @en The projection type enumeration of the camera. + * @zh 相机的投影类型枚举。 + */ export enum CameraProjection { + /** + * @en Orthogonal projection type + * @zh 正交投影类型 + */ ORTHO, + /** + * @en Perspective projection type + * @zh 透视投影类型 + */ PERSPECTIVE, } +/** + * @en The aperture enumeration of the camera, represent in f-number. + * The smaller the value is, the bigger the aperture is, and more light it can capture, but less depth it supports. + * @zh 相机的快门枚举,使用 f 值来表示。f 值越小,光圈就越大,进光量也越大,景深越浅。 + */ export enum CameraAperture { + /** + * f/1.8 + */ F1_8, + /** + * f/2.0 + */ F2_0, + /** + * f/2.2 + */ F2_2, + /** + * f/2.5 + */ F2_5, + /** + * f/2.8 + */ F2_8, + /** + * f/3.2 + */ F3_2, + /** + * f/3.5 + */ F3_5, + /** + * f/4.0 + */ F4_0, + /** + * f/4.5 + */ F4_5, + /** + * f/5.0 + */ F5_0, + /** + * f/5.6 + */ F5_6, + /** + * f/6.3 + */ F6_3, + /** + * f/7.1 + */ F7_1, + /** + * f/8 + */ F8_0, + /** + * f/9 + */ F9_0, + /** + * f/10 + */ F10_0, + /** + * f/11 + */ F11_0, + /** + * f/13 + */ F13_0, + /** + * f/14 + */ F14_0, + /** + * f/16 + */ F16_0, + /** + * f/18 + */ F18_0, + /** + * f/20 + */ F20_0, + /** + * f/22 + */ F22_0, } +/** + * @en The ISO enumeration of the camera, lower ISO means the camera is less sensitive to light. + * @zh 相机感光度枚举,越低的 ISO 数值表示相机对光更加不敏感。 + */ export enum CameraISO { ISO100, ISO200, @@ -73,41 +176,151 @@ export enum CameraISO { ISO800, } +/** + * @en Camera shutter enumeration, the value represents the speed of the shutter. + * @zh 相机快门枚举,枚举值表示快门速度。 + */ export enum CameraShutter { + /** + * 1 second + */ D1, + /** + * 1/2 second + */ D2, + /** + * 1/4 second + */ D4, + /** + * 1/8 second + */ D8, + /** + * 1/15 second + */ D15, + /** + * 1/30 second + */ D30, + /** + * 1/60 second + */ D60, + /** + * 1/125 second + */ D125, + /** + * 1/250 second + */ D250, + /** + * 1/500 second + */ D500, + /** + * 1/1000 second + */ D1000, + /** + * 1/2000 second + */ D2000, + /** + * 1/4000 second + */ D4000, } +/** + * @en The type of the camera, mainly for marking different camera usage in XR, it determines the camera's viewport and parameters. + * @zh 相机类型,主要服务于标记 XR 中的不同相机用途,影响渲染的视口和对应的参数。 + */ export enum CameraType { + /** + * @en Default camera type + * @zh 默认相机类型 + */ DEFAULT = -1, + /** + * @en If a camera is set to be left eye, it will be used to render the left eye screen, + * otherwise, the left eye screen will be rendered using adjusted parameters based on XR main camera. + * @zh 如果设置了左眼相机,则在绘制左眼屏幕时使用,否则,就根据 XR 主相机的参数来计算左眼参数。 + */ LEFT_EYE = 0, + /** + * @en If a camera is set to be right eye, it will be used to render the right eye screen, + * otherwise, the right eye screen will be rendered using adjusted parameters based on XR main camera. + * @zh 如果设置了右眼相机,则在绘制右眼屏幕时使用,否则,就根据 XR 主相机的参数来计算左眼参数。 + */ RIGHT_EYE = 1, + /** + * @en The main camera, it could be used to calculate the parameters for both left eye and the right eye cameras. + * It could be converted from the default 3d camera. + * @zh XR 主相机,可以通过默认相机转换,也可以手动创建新的 XR 相机,可以计算出左右两个相机的相对参数。 + */ MAIN = 2, } +/** + * @en The spatial tracking signal type used by the camera in XR. + * @zh 相机使用的 XR 空间定位追踪信号类型。 + */ export enum TrackingType { + /** + * @en Camera without signal tracking in XR device. + * @zh 无追踪相机,不对 XR 设备的信号进行追踪。 + */ NO_TRACKING = 0, + /** + * @en Camera tracking position and rotation signals from XR device. + * @zh 相机追踪 XR 设备移动位置和旋转角度信号。 + */ POSITION_AND_ROTATION = 1, + /** + * @en Camera only tracking position signals from XR device. + * @zh 相机只追踪 XR 设备位置信号。 + */ POSITION = 2, + /** + * @en Camera only tracking rotation signals from XR device. + * @zh 相机只追踪 XR 设备旋转角度信号。 + */ ROTATION = 3, } +/** + * @en The usage of the camera, it's an engine internal marker enumeration. + * @zh 相机的用途枚举,这是引擎内部使用的标记枚举。 + */ export enum CameraUsage { + /** + * @en Camera used in editor + * @zh 编辑器下使用的相机 + */ EDITOR, + /** + * @en Camera used in editor's game view. + * @zh 编辑器 GameView 视图下使用的相机。 + */ GAME_VIEW, + /** + * @en Camera used in editor's scene view. + * @zh 编辑器场景编辑器视图下使用的相机。 + */ SCENE_VIEW, + /** + * @en Camera used in editor's camera preview window. + * @zh 编辑器预览小窗视图下使用的相机。 + */ PREVIEW, + /** + * @en Camera used in game, normally user created cameras are all GAME type. + * @zh 游戏视图下使用的相机,一般情况下用户创建的相机都是 GAME 类型。 + */ GAME = 100, } @@ -116,16 +329,58 @@ const SHUTTERS: number[] = [1.0, 1.0 / 2.0, 1.0 / 4.0, 1.0 / 8.0, 1.0 / 15.0, 1. 1.0 / 250.0, 1.0 / 500.0, 1.0 / 1000.0, 1.0 / 2000.0, 1.0 / 4000.0]; const ISOS: number[] = [100.0, 200.0, 400.0, 800.0]; +/** + * @en The camera creation information struct + * @zh 用来创建相机的结构体 + */ export interface ICameraInfo { + /** + * @en The name of the camera. + * @zh 相机命名。 + */ name: string; + /** + * @en The node which the camera is attached to. + * @zh 相机挂载的节点。 + */ node: Node; - projection: number; + /** + * @en The projection type of the camera. + * @zh 相机的投影类型。 + */ + projection: CameraProjection; + /** + * @en The id of the target display, if absent, it will be rendered on the default one. + * @zh 相机的目标屏幕,如果缺省,将会使用默认屏幕。 + */ targetDisplay?: number; + /** + * @en The target render window of the camera, is absent, the camera won't be rendered. + * @zh 相机的目标渲染窗口,如果缺省,该相机不会执行渲染流程。 + */ window?: RenderWindow | null; + /** + * @en Render priority of the camera. Cameras with higher depth are rendered after cameras with lower depth. + * @zh 相机的渲染优先级,值越小越优先渲染。 + */ priority: number; + /** + * @internal + */ pipeline?: string; + /** + * @en The type of the camera, mainly for marking different camera usage in XR, it determines the camera's viewport and parameters. + * @zh 相机类型,主要服务于标记 XR 中的不同相机用途,影响渲染的视口和对应的参数。 + */ cameraType?: CameraType; + /** + * @en The spatial tracking signal type used by the camera in XR. + * @zh 相机使用的 XR 空间定位追踪信号类型。 + */ trackingType?: TrackingType; + /** + * @internal + */ usage?: CameraUsage; } @@ -351,7 +606,7 @@ export class Camera { * @en Clearing flags of the camera, specifies which part of the framebuffer will be actually cleared every frame. * @zh 相机的缓冲清除标志位,指定帧缓冲的哪部分要每帧清除。 */ - get clearFlag () : ClearFlags { + get clearFlag (): ClearFlags { return this._clearFlag; } set clearFlag (flag: ClearFlags) { @@ -376,7 +631,7 @@ export class Camera { * @en Clearing depth of the camera. * @zh 相机的深度缓冲默认值。 */ - get clearDepth () : number { + get clearDepth (): number { return this._clearDepth; } set clearDepth (depth: number) { @@ -387,7 +642,7 @@ export class Camera { * @en Clearing stencil of the camera. * @zh 相机的模板缓冲默认值。 */ - get clearStencil () : number { + get clearStencil (): number { return this._clearStencil; } set clearStencil (stencil: number) { @@ -853,7 +1108,7 @@ export class Camera { return this._geometryRenderer; } - get cameraType () : CameraType { + get cameraType (): CameraType { return this._cameraType; } @@ -861,7 +1116,7 @@ export class Camera { this._cameraType = type; } - get trackingType () : TrackingType { + get trackingType (): TrackingType { return this._trackingType; } @@ -869,7 +1124,7 @@ export class Camera { this._trackingType = type; } - get cameraUsage () : CameraUsage { + get cameraUsage (): CameraUsage { return this._usage; } diff --git a/cocos/render-scene/scene/lod-group.ts b/cocos/render-scene/scene/lod-group.ts index 70f346ef8a..5d85721088 100644 --- a/cocos/render-scene/scene/lod-group.ts +++ b/cocos/render-scene/scene/lod-group.ts @@ -114,6 +114,18 @@ export class LODGroup { } lockLODLevels (lockLev: number[]) { + if (lockLev.length !== this._lockedLODLevelVec.length) { + this._isLockLevelChanged = true; + } else { + const size = lockLev.length; + let index = 0; + for (; index < size; index++) { + if (lockLev[index] !== this._lockedLODLevelVec[index]) { + this._isLockLevelChanged = true; + break; + } + } + } this._lockedLODLevelVec = lockLev; } diff --git a/cocos/render-scene/scene/model.ts b/cocos/render-scene/scene/model.ts index b0728b747c..8b2c081809 100644 --- a/cocos/render-scene/scene/model.ts +++ b/cocos/render-scene/scene/model.ts @@ -55,10 +55,15 @@ const stationaryLightMapPatches: IMacroPatch[] = [ { name: 'CC_USE_LIGHTMAP', value: 2 }, ]; +const highpLightMapPatches: IMacroPatch[] = [ + { name: 'CC_LIGHT_MAP_VERSION', value: 2 }, +]; + const lightProbePatches: IMacroPatch[] = [ { name: 'CC_USE_LIGHT_PROBE', value: true }, ]; const CC_USE_REFLECTION_PROBE = 'CC_USE_REFLECTION_PROBE'; +const CC_RECEIVE_DIRECTIONAL_LIGHT = 'CC_RECEIVE_DIRECTIONAL_LIGHT'; export enum ModelType { DEFAULT, SKINNING, @@ -237,11 +242,23 @@ export class Model { this._castShadow = val; } + /** + * @en Gets or sets receive direction Light. + * @zh 获取或者设置接收平行光光照。 + */ + get receiveDirLight (): boolean { + return this._receiveDirLight; + } + set receiveDirLight (val) { + this._receiveDirLight = val; + this.onMacroPatchesStateChanged(); + } + /** * @en The node to which the model belongs * @zh 模型所在的节点 */ - get node () : Node { + get node (): Node { return this._node; } @@ -253,7 +270,7 @@ export class Model { * @en Model's transform * @zh 模型的变换 */ - get transform () : Node { + get transform (): Node { return this._transform; } @@ -268,7 +285,7 @@ export class Model { * @zh 模型的可见性标志 * 模型的可见性标志与 [[Node.layer]] 不同,它会在剔除阶段与 [[Camera.visibility]] 进行比较 */ - get visFlags () : number { + get visFlags (): number { return this._visFlags; } @@ -280,7 +297,7 @@ export class Model { * @en Whether the model is enabled in the render scene so that it will be rendered * @zh 模型是否在渲染场景中启用并被渲染 */ - get enabled () : boolean { + get enabled (): boolean { return this._enabled; } @@ -292,7 +309,7 @@ export class Model { * @en Rendering priority in the transparent queue of model. * @zh Model 在透明队列中的渲染排序优先级 */ - get priority () : number { + get priority (): number { return this._priority; } @@ -460,6 +477,12 @@ export class Model { */ protected _castShadow = false; + /** + * @en Is received direction Light. + * @zh 是否接收平行光光照。 + */ + protected _receiveDirLight = true; + /** * @en Shadow bias * @zh 阴影偏移 @@ -971,6 +994,11 @@ export class Model { const lightmapPathes = stationary ? stationaryLightMapPatches : staticLightMapPatches; patches = patches ? patches.concat(lightmapPathes) : lightmapPathes; + + // use highp lightmap + if (this.node.scene.globals.bakedWithHighpLightmap) { + patches = patches.concat(highpLightMapPatches); + } } if (this._useLightProbe) { patches = patches ? patches.concat(lightProbePatches) : lightProbePatches; @@ -979,6 +1007,10 @@ export class Model { { name: CC_USE_REFLECTION_PROBE, value: this._reflectionProbeType }, ]; patches = patches ? patches.concat(reflectionProbePatches) : reflectionProbePatches; + const receiveDirLightPatches: IMacroPatch[] = [ + { name: CC_RECEIVE_DIRECTIONAL_LIGHT, value: this._receiveDirLight }, + ]; + patches = patches ? patches.concat(receiveDirLightPatches) : receiveDirLightPatches; return patches; } diff --git a/cocos/rendering/custom/builtin-pipelines.ts b/cocos/rendering/custom/builtin-pipelines.ts index 54a71b9eed..b2d12a1ae8 100644 --- a/cocos/rendering/custom/builtin-pipelines.ts +++ b/cocos/rendering/custom/builtin-pipelines.ts @@ -23,9 +23,11 @@ */ import { EDITOR } from 'internal:constants'; -import { Camera } from '../../render-scene/scene'; +import { Camera, CameraUsage } from '../../render-scene/scene'; import { Pipeline, PipelineBuilder } from './pipeline'; -import { buildForwardPass, buildGBufferPass, buildLightingPass, buildPostprocessPass, buildReflectionProbePasss } from './define'; +import { buildForwardPass, buildGBufferPass, buildLightingPass, buildPostprocessPass, + buildReflectionProbePasss, buildUIPass } from './define'; +import { isUICamera } from './utils'; export class ForwardPipelineBuilder implements PipelineBuilder { public setup (cameras: Camera[], ppl: Pipeline): void { @@ -50,16 +52,23 @@ export class DeferredPipelineBuilder implements PipelineBuilder { if (!camera.scene) { continue; } - if (EDITOR) { + const isGameView = camera.cameraUsage === CameraUsage.GAME + || camera.cameraUsage === CameraUsage.GAME_VIEW; + if (!isGameView) { buildForwardPass(camera, ppl, false); continue; } + if (!isUICamera(camera)) { // GBuffer Pass - const gBufferInfo = buildGBufferPass(camera, ppl); - // Lighting Pass - const lightInfo = buildLightingPass(camera, ppl, gBufferInfo); - // Postprocess - buildPostprocessPass(camera, ppl, lightInfo.rtName); + const gBufferInfo = buildGBufferPass(camera, ppl); + // Lighting Pass + const lightInfo = buildLightingPass(camera, ppl, gBufferInfo); + // Postprocess + buildPostprocessPass(camera, ppl, lightInfo.rtName); + continue; + } + // render ui + buildUIPass(camera, ppl); } } } diff --git a/cocos/rendering/custom/custom-pipeline.ts b/cocos/rendering/custom/custom-pipeline.ts index 3563449efc..66605e74fe 100644 --- a/cocos/rendering/custom/custom-pipeline.ts +++ b/cocos/rendering/custom/custom-pipeline.ts @@ -24,8 +24,10 @@ import { Camera, CameraUsage } from '../../render-scene/scene'; import { buildFxaaPass, buildBloomPass as buildBloomPasses, buildForwardPass, - buildNativeDeferredPipeline, buildNativeForwardPass, buildPostprocessPass, AntiAliasing } from './define'; + buildNativeDeferredPipeline, buildNativeForwardPass, buildPostprocessPass, + AntiAliasing, buildUIPass } from './define'; import { Pipeline, PipelineBuilder } from './pipeline'; +import { isUICamera } from './utils'; export class CustomPipelineBuilder implements PipelineBuilder { public setup (cameras: Camera[], ppl: Pipeline): void { @@ -36,17 +38,25 @@ export class CustomPipelineBuilder implements PipelineBuilder { } const isGameView = camera.cameraUsage === CameraUsage.GAME || camera.cameraUsage === CameraUsage.GAME_VIEW; - // forward pass - const forwardInfo = buildForwardPass(camera, ppl, isGameView); if (!isGameView) { + // forward pass + buildForwardPass(camera, ppl, isGameView); continue; } - // fxaa pass - const fxaaInfo = buildFxaaPass(camera, ppl, forwardInfo.rtName); - // bloom passes - const bloomInfo = buildBloomPasses(camera, ppl, fxaaInfo.rtName); - // Present Pass - buildPostprocessPass(camera, ppl, bloomInfo.rtName, AntiAliasing.NONE); + // TODO: There is currently no effective way to judge the ui camera. Let’s do this first. + if (!isUICamera(camera)) { + // forward pass + const forwardInfo = buildForwardPass(camera, ppl, isGameView); + // fxaa pass + const fxaaInfo = buildFxaaPass(camera, ppl, forwardInfo.rtName); + // bloom passes + const bloomInfo = buildBloomPasses(camera, ppl, fxaaInfo.rtName); + // Present Pass + buildPostprocessPass(camera, ppl, bloomInfo.rtName, AntiAliasing.NONE); + continue; + } + // render ui + buildUIPass(camera, ppl); } } } diff --git a/cocos/rendering/custom/define.ts b/cocos/rendering/custom/define.ts index f1975e9179..50bcc3ee8d 100644 --- a/cocos/rendering/custom/define.ts +++ b/cocos/rendering/custom/define.ts @@ -27,14 +27,15 @@ import { BufferInfo, Buffer, BufferUsageBit, ClearFlagBit, Color, DescriptorSet, import { Camera, CSMLevel, DirectionalLight, Light, LightType, ReflectionProbe, ShadowType, SKYBOX_FLAG, SpotLight } from '../../render-scene/scene'; import { supportsR32FloatTexture } from '../define'; import { Pipeline } from './pipeline'; -import { AccessType, AttachmentType, ComputeView, LightInfo, QueueHint, RasterView, ResourceResidency, SceneFlags } from './types'; -import { Vec4, macro, geometry, toRadian, cclegacy } from '../../core'; +import { AccessType, AttachmentType, ComputeView, LightInfo, QueueHint, RasterView, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; +import { Vec4, macro, geometry, toRadian, cclegacy, assert } from '../../core'; import { Material } from '../../asset/assets'; -import { SRGBToLinear } from '../pipeline-funcs'; +import { getProfilerCamera, SRGBToLinear } from '../pipeline-funcs'; import { RenderWindow } from '../../render-scene/core/render-window'; import { RenderData } from './render-graph'; import { WebPipeline } from './web-pipeline'; import { DescriptorSetData } from './layout-graph'; +import { legacyCC } from '../../core/global-exports'; // Anti-aliasing type, other types will be gradually added in the future export enum AntiAliasing { @@ -481,7 +482,7 @@ export function buildPostprocessPass (camera: Camera, const postprocessPassRTName = `postprocessPassRTName${cameraID}`; const postprocessPassDS = `postprocessPassDS${cameraID}`; if (!ppl.containsResource(postprocessPassRTName)) { - ppl.addRenderTexture(postprocessPassRTName, Format.RGBA8, width, height, camera.window); + ppl.addRenderTexture(postprocessPassRTName, Format.BGRA8, width, height, camera.window); ppl.addDepthStencil(postprocessPassDS, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); } ppl.updateRenderWindow(postprocessPassRTName, camera.window); @@ -518,7 +519,10 @@ export function buildPostprocessPass (camera: Camera, postInfo.postMaterial, 0, SceneFlags.NONE, ); postprocessPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), - SceneFlags.UI | SceneFlags.PROFILER); + SceneFlags.UI); + if (getProfilerCamera() === camera) { + postprocessPass.showStatistics = true; + } return { rtName: postprocessPassRTName, dsName: postprocessPassDS }; } @@ -536,7 +540,7 @@ export function buildForwardPass (camera: Camera, const forwardPassDSName = `dsForwardPassDS${cameraName}`; if (!ppl.containsResource(forwardPassRTName)) { if (!isOffScreen) { - ppl.addRenderTexture(forwardPassRTName, Format.RGBA8, width, height, camera.window); + ppl.addRenderTexture(forwardPassRTName, Format.BGRA8, width, height, camera.window); } else { ppl.addRenderTarget(forwardPassRTName, Format.RGBA16F, width, height, ResourceResidency.MANAGED); } @@ -544,6 +548,7 @@ export function buildForwardPass (camera: Camera, } if (!isOffScreen) { ppl.updateRenderWindow(forwardPassRTName, camera.window); + ppl.updateDepthStencil(forwardPassDSName, width, height); } else { ppl.updateRenderTarget(forwardPassRTName, width, height); ppl.updateDepthStencil(forwardPassDSName, width, height); @@ -553,13 +558,13 @@ export function buildForwardPass (camera: Camera, forwardPass.setViewport(new Viewport(area.x, area.y, width, height)); for (const dirShadowName of cameraInfo.mainLightShadowNames) { if (ppl.containsResource(dirShadowName)) { - const computeView = new ComputeView(); + const computeView = new ComputeView('cc_shadowMap'); forwardPass.addComputeView(dirShadowName, computeView); } } for (const spotShadowName of cameraInfo.spotLightShadowNames) { if (ppl.containsResource(spotShadowName)) { - const computeView = new ComputeView(); + const computeView = new ComputeView('cc_spotShadowMap'); forwardPass.addComputeView(spotShadowName, computeView); } } @@ -584,7 +589,8 @@ export function buildForwardPass (camera: Camera, | SceneFlags.DEFAULT_LIGHTING | SceneFlags.DRAW_INSTANCING); let sceneFlags = SceneFlags.TRANSPARENT_OBJECT | SceneFlags.GEOMETRY; if (!isOffScreen) { - sceneFlags |= SceneFlags.UI | SceneFlags.PROFILER; + sceneFlags |= SceneFlags.UI; + forwardPass.showStatistics = true; } forwardPass .addQueue(QueueHint.RENDER_TRANSPARENT) @@ -871,13 +877,13 @@ export function buildLightingPass (camera: Camera, ppl: Pipeline, gBuffer: GBuff lightingPass.setViewport(new Viewport(area.x, area.y, width, height)); for (const dirShadowName of cameraInfo.mainLightShadowNames) { if (ppl.containsResource(dirShadowName)) { - const computeView = new ComputeView(); + const computeView = new ComputeView('cc_shadowMap'); lightingPass.addComputeView(dirShadowName, computeView); } } for (const spotShadowName of cameraInfo.spotLightShadowNames) { if (ppl.containsResource(spotShadowName)) { - const computeView = new ComputeView(); + const computeView = new ComputeView('cc_spotShadowMap'); lightingPass.addComputeView(spotShadowName, computeView); } } @@ -915,8 +921,8 @@ export function buildLightingPass (camera: Camera, ppl: Pipeline, gBuffer: GBuff camera, lightingInfo.deferredLightingMaterial, 0, SceneFlags.VOLUMETRIC_LIGHTING, ); - lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), - SceneFlags.TRANSPARENT_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.GEOMETRY); + // lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), + // SceneFlags.TRANSPARENT_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.GEOMETRY); return { rtName: deferredLightingPassRTName, dsName: deferredLightingPassDS }; } @@ -942,6 +948,48 @@ function getClearFlags (attachment: AttachmentType, clearFlag: ClearFlagBit, loa } } +export function buildUIPass (camera: Camera, + ppl: Pipeline) { + const cameraID = getCameraUniqueID(camera); + const cameraName = `Camera${cameraID}`; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + + const dsUIAndProfilerPassRTName = `dsUIAndProfilerPassColor${cameraName}`; + const dsUIAndProfilerPassDSName = `dsUIAndProfilerPassDS${cameraName}`; + if (!ppl.containsResource(dsUIAndProfilerPassRTName)) { + ppl.addRenderTexture(dsUIAndProfilerPassRTName, Format.BGRA8, width, height, camera.window); + ppl.addDepthStencil(dsUIAndProfilerPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); + } + ppl.updateRenderWindow(dsUIAndProfilerPassRTName, camera.window); + ppl.updateDepthStencil(dsUIAndProfilerPassDSName, width, height); + const uIAndProfilerPass = ppl.addRasterPass(width, height, 'default'); + uIAndProfilerPass.name = `CameraUIAndProfilerPass${cameraID}`; + uIAndProfilerPass.setViewport(new Viewport(area.x, area.y, width, height)); + const passView = new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), + StoreOp.STORE, + camera.clearFlag, + new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w)); + const passDSView = new RasterView('_', + AccessType.WRITE, AttachmentType.DEPTH_STENCIL, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), + StoreOp.STORE, + camera.clearFlag, + new Color(camera.clearDepth, camera.clearStencil, 0, 0)); + uIAndProfilerPass.addRasterView(dsUIAndProfilerPassRTName, passView); + uIAndProfilerPass.addRasterView(dsUIAndProfilerPassDSName, passDSView); + const sceneFlags = SceneFlags.UI; + uIAndProfilerPass + .addQueue(QueueHint.RENDER_TRANSPARENT) + .addSceneOfCamera(camera, new LightInfo(), sceneFlags); + if (getProfilerCamera() === camera) { + uIAndProfilerPass.showStatistics = true; + } +} + export function buildNativeForwardPass (camera: Camera, ppl: Pipeline) { const cameraID = getCameraUniqueID(camera); const cameraName = `Camera${cameraID}`; @@ -998,8 +1046,8 @@ export function buildNativeForwardPass (camera: Camera, ppl: Pipeline) { forwardPass .addQueue(QueueHint.RENDER_TRANSPARENT) .addSceneOfCamera(camera, new LightInfo(), - SceneFlags.UI - | SceneFlags.PROFILER); + SceneFlags.UI); + forwardPass.showStatistics = true; } export function buildNativeDeferredPipeline (camera: Camera, ppl: Pipeline) { @@ -1106,11 +1154,11 @@ function bindDescValue (desc: DescriptorSet, binding: number, value) { } } -function bindGlobalDesc (pipeline: Pipeline, binding: number, value) { - bindDescValue(pipeline.descriptorSet, binding, value); +function bindGlobalDesc (desc: DescriptorSet, binding: number, value) { + bindDescValue(desc, binding, value); } -function getDescBinding (descId, descData: DescriptorSetData): number { +export function getDescBinding (descId, descData: DescriptorSetData): number { const layoutData = descData; // find descriptor binding for (const block of layoutData.descriptorSetLayoutData.descriptorBlocks) { @@ -1147,15 +1195,17 @@ export function getDescBindingFromName (bindingName: string) { return -1; } -function applyGlobalDescBinding (pipeline: Pipeline, data: RenderData, isUpdate = false) { +function applyGlobalDescBinding (data: RenderData, layout: string, isUpdate = false) { const constants = data.constants; const samplers = data.samplers; const textures = data.textures; const device = cclegacy.director.root.device; - const currPip = pipeline as WebPipeline; + const descriptorSetData = getDescriptorSetDataFromLayout(layout)!; + const descriptorSet = descriptorSetData.descriptorSet!; for (const [key, value] of constants) { - const bindId = getDescBinding(key, currPip.globalDescriptorSetData); - let buffer = pipeline.descriptorSet.getBuffer(bindId); + const bindId = getDescBinding(key, descriptorSetData); + if (bindId === -1) { continue; } + let buffer = descriptorSet.getBuffer(bindId); let haveBuff = true; if (!buffer && !isUpdate) { buffer = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, @@ -1165,28 +1215,81 @@ function applyGlobalDescBinding (pipeline: Pipeline, data: RenderData, isUpdate haveBuff = false; } if (isUpdate) buffer.update(new Float32Array(value)); - if (!haveBuff) bindGlobalDesc(pipeline, bindId, buffer); + if (!haveBuff) bindGlobalDesc(descriptorSet, bindId, buffer); } for (const [key, value] of textures) { - const bindId = getDescBinding(key, currPip.globalDescriptorSetData); - const tex = pipeline.descriptorSet.getTexture(bindId); + const bindId = getDescBinding(key, descriptorSetData); + if (bindId === -1) { continue; } + const tex = descriptorSet.getTexture(bindId); if (!tex || isUpdate) { - bindGlobalDesc(pipeline, bindId, value); + bindGlobalDesc(descriptorSet, bindId, value); } } for (const [key, value] of samplers) { - const bindId = getDescBinding(key, currPip.globalDescriptorSetData); - const sampler = pipeline.descriptorSet.getSampler(bindId); + const bindId = getDescBinding(key, descriptorSetData); + if (bindId === -1) { continue; } + const sampler = descriptorSet.getSampler(bindId); if (!sampler || isUpdate) { - bindGlobalDesc(pipeline, bindId, value); + bindGlobalDesc(descriptorSet, bindId, value); } } } - -export function initGlobalDescBinding (pipeline: Pipeline, data: RenderData) { - applyGlobalDescBinding(pipeline, data); +const layouts: Map = new Map(); +export function getDescriptorSetDataFromLayout (layoutName: string) { + const descLayout = layouts.get(layoutName); + if (descLayout) { + return descLayout; + } + const webPip = cclegacy.director.root.pipeline as WebPipeline; + const stageId = webPip.layoutGraph.locateChild(webPip.layoutGraph.nullVertex(), layoutName); + assert(stageId !== 0xFFFFFFFF); + const layout = webPip.layoutGraph.getLayout(stageId); + const layoutData = layout.descriptorSets.get(UpdateFrequency.PER_PASS); + layouts.set(layoutName, layoutData!); + return layoutData; } -export function updateGlobalDescBinding (pipeline: Pipeline, data: RenderData) { - applyGlobalDescBinding(pipeline, data, true); +export function getDescriptorSetDataFromLayoutId (id: number) { + const webPip = cclegacy.director.root.pipeline as WebPipeline; + const layout = webPip.layoutGraph.getLayout(id); + const layoutData = layout.descriptorSets.get(UpdateFrequency.PER_PASS); + return layoutData; +} + +export function initGlobalDescBinding (data: RenderData, layoutName = 'default') { + applyGlobalDescBinding(data, layoutName); +} + +export function updateGlobalDescBinding (data: RenderData, layoutName = 'default') { + applyGlobalDescBinding(data, layoutName, true); +} + +export function mergeSrcToTargetDesc (fromDesc, toDesc, isForce = false) { + fromDesc.update(); + const fromGpuDesc = fromDesc.gpuDescriptorSet; + const toGpuDesc = toDesc.gpuDescriptorSet; + const extResId: number[] = []; + if (isForce) { + toGpuDesc.gpuDescriptors = fromGpuDesc.gpuDescriptors; + toGpuDesc.descriptorIndices = fromGpuDesc.descriptorIndices; + return extResId; + } + for (let i = 0; i < toGpuDesc.gpuDescriptors.length; i++) { + const fromRes = fromGpuDesc.gpuDescriptors[i]; + if (!fromRes) continue; + const currRes = toGpuDesc.gpuDescriptors[i]; + if (!currRes.gpuBuffer && fromRes.gpuBuffer) { + currRes.gpuBuffer = fromRes.gpuBuffer; + extResId.push(i); + } else if ('gpuTextureView' in currRes && !currRes.gpuTextureView) { + currRes.gpuTextureView = fromRes.gpuTextureView; + currRes.gpuSampler = fromRes.gpuSampler; + extResId.push(i); + } else if ('gpuTexture' in currRes && !currRes.gpuTexture) { + currRes.gpuTexture = fromRes.gpuTexture; + currRes.gpuSampler = fromRes.gpuSampler; + extResId.push(i); + } + } + return extResId; } diff --git a/cocos/rendering/custom/effect.ts b/cocos/rendering/custom/effect.ts index a1e5856069..d038ce3e66 100644 --- a/cocos/rendering/custom/effect.ts +++ b/cocos/rendering/custom/effect.ts @@ -22,231 +22,7 @@ THE SOFTWARE. */ -import { EffectAsset } from '../../asset/assets'; -import { CollectVisitor, WebDescriptorHierarchy } from './web-descriptor-hierarchy'; -// eslint-disable-next-line max-len -import { DescriptorBlockData, DescriptorDB, LayoutGraph, LayoutGraphData, LayoutGraphValue, ShaderProgramData } from './layout-graph'; -import { LayoutGraphBuilder, Pipeline } from './pipeline'; -import { ShaderStageFlagBit, Type, UniformBlock } from '../../gfx'; -import { Descriptor, DescriptorBlock, DescriptorBlockFlattened, DescriptorBlockIndex, DescriptorTypeOrder, - ParameterType, UpdateFrequency } from './types'; -import { depthFirstSearch, GraphColor, MutableVertexPropertyMap } from './graph'; -import { SetIndex } from '../define'; - -function descriptorBlock2Flattened (block: DescriptorBlock, flattened: DescriptorBlockFlattened): void { - block.descriptors.forEach((value, key) => { - const name: string = key; - const d: Descriptor = value; - flattened.descriptorNames.push(name); - flattened.descriptors.push(d); - }); - block.uniformBlocks.forEach((value, key) => { - const name: string = key; - const u: UniformBlock = value; - flattened.uniformBlockNames.push(name); - flattened.uniformBlocks.push(u); - }); - flattened.count = block.count; - flattened.capacity = block.capacity; -} - -export function buildLayoutGraphDataImpl (graph: LayoutGraph, lgData: LayoutGraphBuilder) { - for (const v of graph.vertices()) { - const db: DescriptorDB = graph.getDescriptors(v); - let vid = 0; - if (graph.id(v) === LayoutGraphValue.RenderStage) { - vid = lgData.addRenderStage(graph.getName(v)); - } - if (graph.id(v) === LayoutGraphValue.RenderPhase) { - vid = lgData.addRenderPhase(graph.getName(v), graph.getParent(v)); - const phase = graph.getRenderPhase(vid); - for (const shaderName of phase.shaders) { - lgData.addShader(shaderName, vid); - } - } - - db.blocks.forEach((value, key) => { - const index: DescriptorBlockIndex = JSON.parse(key) as DescriptorBlockIndex; - const block: DescriptorBlock = value; - const flattened = new DescriptorBlockFlattened(); - descriptorBlock2Flattened(block, flattened); - if (block.capacity > 0) { - lgData.addDescriptorBlock(vid, index, flattened); - } - for (let i = 0; i < flattened.uniformBlockNames.length; ++i) { - lgData.addUniformBlock(vid, index, flattened.uniformBlockNames[i], flattened.uniformBlocks[i]); - } - }); - } -} - -enum BloomStage { - PREFILTER, - DOWNSAMPLE, - UPSAMPLE, - COMBINE -} - -function buildBloomDownSample (lg, idx: number) { - const bloomDownsampleID = lg.addRenderStage(`bloom-downsample${idx}`, BloomStage.DOWNSAMPLE); - lg.addRenderPhase('Queue', bloomDownsampleID); - const bloomDownsampleDescriptors = lg.layoutGraph.getDescriptors(bloomDownsampleID); - - const bloomDownsampleUniformBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, - DescriptorTypeOrder.UNIFORM_BUFFER, - ShaderStageFlagBit.ALL, - bloomDownsampleDescriptors); - const bloomDownsampleUBO: UniformBlock = lg.getUniformBlock(SetIndex.MATERIAL, - 0, 'BloomUBO', bloomDownsampleUniformBlock); - lg.setUniform(bloomDownsampleUBO, 'texSize', Type.FLOAT4, 1); - lg.setDescriptor(bloomDownsampleUniformBlock, 'BloomUBO', Type.UNKNOWN); - - const bloomDownsamplePassBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, - DescriptorTypeOrder.SAMPLER_TEXTURE, - ShaderStageFlagBit.FRAGMENT, - bloomDownsampleDescriptors); - lg.setDescriptor(bloomDownsamplePassBlock, 'bloomTexture', Type.SAMPLER2D); - lg.merge(bloomDownsampleDescriptors); - lg.mergeDescriptors(bloomDownsampleID); -} - -function buildBloomUpSample (lg, idx: number) { - const bloomUpsampleID = lg.addRenderStage(`bloom-upsample${idx}`, BloomStage.UPSAMPLE); - lg.addRenderPhase('Queue', bloomUpsampleID); - const bloomUpsampleDescriptors = lg.layoutGraph.getDescriptors(bloomUpsampleID); - - const bloomUpsampleUniformBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, - DescriptorTypeOrder.UNIFORM_BUFFER, - ShaderStageFlagBit.ALL, - bloomUpsampleDescriptors); - const bloomUpsampleUBO: UniformBlock = lg.getUniformBlock(SetIndex.MATERIAL, - 0, 'BloomUBO', bloomUpsampleUniformBlock); - lg.setUniform(bloomUpsampleUBO, 'texSize', Type.FLOAT4, 1); - lg.setDescriptor(bloomUpsampleUniformBlock, 'BloomUBO', Type.UNKNOWN); - - const bloomUpsamplePassBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, - DescriptorTypeOrder.SAMPLER_TEXTURE, - ShaderStageFlagBit.FRAGMENT, - bloomUpsampleDescriptors); - lg.setDescriptor(bloomUpsamplePassBlock, 'bloomTexture', Type.SAMPLER2D); - lg.merge(bloomUpsampleDescriptors); - lg.mergeDescriptors(bloomUpsampleID); -} - -export function buildForwardLayout (ppl: Pipeline) { - const lg = new WebDescriptorHierarchy(); - - const defaultID = lg.addGlobal('default', true, true, true, true, true, true, true, true); - lg.mergeDescriptors(defaultID); - // 1.=== Bloom prefilter === - const bloomPrefilterID = lg.addRenderStage('bloom-prefilter', BloomStage.PREFILTER); - lg.addRenderPhase('Queue', bloomPrefilterID); - const bloomPrefilterDescriptors = lg.layoutGraph.getDescriptors(bloomPrefilterID); - // unifom - const bloomPrefilterUniformBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, - DescriptorTypeOrder.UNIFORM_BUFFER, - ShaderStageFlagBit.ALL, - bloomPrefilterDescriptors); - const bloomPrefilterUBO: UniformBlock = lg.getUniformBlock(SetIndex.MATERIAL, - 0, 'BloomUBO', bloomPrefilterUniformBlock); - lg.setUniform(bloomPrefilterUBO, 'texSize', Type.FLOAT4, 1); - lg.setDescriptor(bloomPrefilterUniformBlock, 'BloomUBO', Type.UNKNOWN); - // texture - const bloomPrefilterPassBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, - DescriptorTypeOrder.SAMPLER_TEXTURE, - ShaderStageFlagBit.FRAGMENT, - bloomPrefilterDescriptors); - lg.setDescriptor(bloomPrefilterPassBlock, 'outputResultMap', Type.SAMPLER2D); - lg.merge(bloomPrefilterDescriptors); - lg.mergeDescriptors(bloomPrefilterID); - // 2.=== Bloom downsample === - buildBloomDownSample(lg, 0); - buildBloomDownSample(lg, 1); - // 3.=== Bloom upsample === - buildBloomUpSample(lg, 0); - buildBloomUpSample(lg, 1); - // 4.=== Bloom combine === - const bloomCombineSampleID = lg.addRenderStage('bloom-combine', BloomStage.COMBINE); - lg.addRenderPhase('Queue', bloomCombineSampleID); - const bloomCombineSampleDescriptors = lg.layoutGraph.getDescriptors(bloomCombineSampleID); - - const bloomCombinesampleUniformBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, - DescriptorTypeOrder.UNIFORM_BUFFER, - ShaderStageFlagBit.ALL, - bloomCombineSampleDescriptors); - const bloomCombinesampleUBO: UniformBlock = lg.getUniformBlock(SetIndex.MATERIAL, - 0, 'BloomUBO', bloomCombinesampleUniformBlock); - lg.setUniform(bloomCombinesampleUBO, 'texSize', Type.FLOAT4, 1); - lg.setDescriptor(bloomCombinesampleUniformBlock, 'BloomUBO', Type.UNKNOWN); - - const bloomCombineSamplePassBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, - DescriptorTypeOrder.SAMPLER_TEXTURE, - ShaderStageFlagBit.FRAGMENT, - bloomCombineSampleDescriptors); - lg.setDescriptor(bloomCombineSamplePassBlock, 'outputResultMap', Type.SAMPLER2D); - const bloomCombineSamplePassBlock2 = lg.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, - DescriptorTypeOrder.SAMPLER_TEXTURE, - ShaderStageFlagBit.FRAGMENT, - bloomCombineSampleDescriptors); - lg.setDescriptor(bloomCombineSamplePassBlock2, 'bloomTexture', Type.SAMPLER2D); - lg.merge(bloomCombineSampleDescriptors); - lg.mergeDescriptors(bloomCombineSampleID); - // 5.=== Postprocess === - const postPassID = lg.addRenderStage('post-process', DeferredStage.POST); - const postDescriptors = lg.layoutGraph.getDescriptors(postPassID); - const postPassBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, - DescriptorTypeOrder.SAMPLER_TEXTURE, - ShaderStageFlagBit.FRAGMENT, - postDescriptors); - - lg.setDescriptor(postPassBlock, 'outputResultMap', Type.SAMPLER2D); - lg.merge(postDescriptors); - lg.mergeDescriptors(postPassID); - - // 6.=== FxaaHQ === - const fxaaID = lg.addRenderStage('fxaa', 1); - lg.addRenderPhase('Queue', fxaaID); - const fxaaDescriptors = lg.layoutGraph.getDescriptors(fxaaID); - // unifom - const fxaaUniformBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, - DescriptorTypeOrder.UNIFORM_BUFFER, - ShaderStageFlagBit.ALL, - fxaaDescriptors); - const fxaaUBO: UniformBlock = lg.getUniformBlock(SetIndex.MATERIAL, - 0, 'fxaaUBO', fxaaUniformBlock); - lg.setUniform(fxaaUBO, 'texSize', Type.FLOAT4, 1); - lg.setDescriptor(fxaaUniformBlock, 'fxaaUBO', Type.UNKNOWN); - // texture - const fxaaPassBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, - DescriptorTypeOrder.SAMPLER_TEXTURE, - ShaderStageFlagBit.FRAGMENT, - fxaaDescriptors); - lg.setDescriptor(fxaaPassBlock, 'sceneColorMap', Type.SAMPLER2D); - lg.merge(fxaaDescriptors); - lg.mergeDescriptors(fxaaID); - - const builder = ppl.layoutGraphBuilder; - builder.clear(); - buildLayoutGraphDataImpl(lg.layoutGraph, builder); -} - -enum DeferredStage { - GEOMETRY, - LIGHTING, - POST -} +import { GraphColor, MutableVertexPropertyMap } from './graph'; export class VectorGraphColorMap implements MutableVertexPropertyMap { constructor (sz: number) { @@ -260,137 +36,3 @@ export class VectorGraphColorMap implements MutableVertexPropertyMap } readonly colors: Array; } - -export function buildDeferredLayout (ppl: Pipeline) { - const lg = new WebDescriptorHierarchy(); - const defaultID = lg.addGlobal('default', true, true, true, true, true, true, true, true); - lg.mergeDescriptors(defaultID); - const geometryPassID = lg.addRenderStage('Geometry', DeferredStage.GEOMETRY); - const lightingPassID = lg.addRenderStage('deferred-lighting', DeferredStage.LIGHTING); - const postPassID = lg.addRenderStage('post-process', DeferredStage.POST); - - const geometryQueueID = lg.addRenderPhase('Queue', geometryPassID); - const lightingQueueID = lg.addRenderPhase('Queue', lightingPassID); - const postQueueID = lg.addRenderPhase('Queue', postPassID); - - const lightingDescriptors = lg.layoutGraph.getDescriptors(lightingQueueID); - - const lightingPassBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, - DescriptorTypeOrder.SAMPLER_TEXTURE, - ShaderStageFlagBit.FRAGMENT, - lightingDescriptors); - - lg.setDescriptor(lightingPassBlock, 'gbuffer_albedoMap', Type.FLOAT4); - lg.setDescriptor(lightingPassBlock, 'gbuffer_normalMap', Type.FLOAT4); - lg.setDescriptor(lightingPassBlock, 'gbuffer_emissiveMap', Type.FLOAT4); - lg.setDescriptor(lightingPassBlock, 'depth_stencil', Type.FLOAT4); - - const visitor = new CollectVisitor(); - const colorMap = new VectorGraphColorMap(lg.layoutGraph.numVertices()); - depthFirstSearch(lg.layoutGraph, visitor, colorMap); - - lg.mergeDescriptors(lightingPassID); - // Postprocess - const postDescriptors = lg.layoutGraph.getDescriptors(postPassID); - - const postPassBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, - DescriptorTypeOrder.SAMPLER_TEXTURE, - ShaderStageFlagBit.FRAGMENT, - postDescriptors); - - lg.setDescriptor(postPassBlock, 'outputResultMap', Type.FLOAT4); - lg.merge(postDescriptors); - - lg.mergeDescriptors(postPassID); - if (visitor.error) { - console.log(visitor.error); - } - - const builder = ppl.layoutGraphBuilder; - builder.clear(); - buildLayoutGraphDataImpl(lg.layoutGraph, builder); -} - -function applyBinding (lg: Readonly, - descId: number, - srcBlock: EffectAsset.IBlockInfo | EffectAsset.IBufferInfo | EffectAsset.ISamplerTextureInfo | EffectAsset.ISamplerInfo, - dstBlock: DescriptorBlockData) { - if (lg.attributeIndex.get(srcBlock.name) === descId) { - srcBlock.stageFlags = dstBlock.visibility; - srcBlock.binding = dstBlock.offset; - } -} - -function updateShaderBinding (lg: Readonly, - shaderData: Readonly, - shader: EffectAsset.IShaderInfo) { - for (const pair of shaderData.layout.descriptorSets) { - const updateFrequency = pair[0]; - if (updateFrequency === UpdateFrequency.PER_BATCH - || updateFrequency === UpdateFrequency.PER_INSTANCE) { - continue; - } - const descData = pair[1]; - for (const descBlock of descData.descriptorSetLayoutData.descriptorBlocks) { - for (let j = 0; j < descBlock.descriptors.length; ++j) { - const descData = descBlock.descriptors[j]; - const descriptorId = descData.descriptorID; - for (const block of shader.blocks) { - applyBinding(lg, descriptorId, block, descBlock); - } - for (const buff of shader.buffers) { - applyBinding(lg, descriptorId, buff, descBlock); - } - for (const img of shader.images) { - applyBinding(lg, descriptorId, img, descBlock); - } - for (const samplerTex of shader.samplerTextures) { - applyBinding(lg, descriptorId, samplerTex, descBlock); - } - for (const sampler of shader.samplers) { - applyBinding(lg, descriptorId, sampler, descBlock); - } - for (const tex of shader.textures) { - applyBinding(lg, descriptorId, tex, descBlock); - } - for (const subpassInput of shader.subpassInputs) { - applyBinding(lg, descriptorId, subpassInput, descBlock); - } - } - } - } -} - -export function replacePerBatchOrInstanceShaderInfo (lg: LayoutGraphData, - asset: EffectAsset, stageName: string) { - const stageID = lg.locateChild(lg.nullVertex(), stageName); - let phaseName; - for (let i = 0; i < asset.techniques.length; ++i) { - const tech = asset.techniques[i]; - for (let j = 0; j < tech.passes.length; ++j) { - const pass = tech.passes[j]; - const passPhase = pass.phase; - if (phaseName && phaseName === `${stageName}_` && !passPhase) { - continue; - } - if (passPhase === undefined) { - phaseName = `${stageName}_`; - } else if (typeof passPhase === 'number') { - phaseName = passPhase.toString(); - } else { - phaseName = passPhase; - } - const phaseID = lg.locateChild(stageID, phaseName); - if (phaseID === 0xFFFFFFFF) { continue; } - const phaseData = lg.getRenderPhase(phaseID); - const shaderID = phaseData.shaderIndex.get(pass.program); - const shader = asset.shaders.find((val) => val.name === pass.program)!; - if (shaderID) { - const shaderData = phaseData.shaderPrograms[shaderID]; - updateShaderBinding(lg, shaderData, shader); - } - } - } -} diff --git a/cocos/rendering/custom/executor.ts b/cocos/rendering/custom/executor.ts index 11289c2df4..8bf8d0af77 100644 --- a/cocos/rendering/custom/executor.ts +++ b/cocos/rendering/custom/executor.ts @@ -58,13 +58,14 @@ import { WebSceneVisitor } from './web-scene-visitor'; import { stringify } from './utils'; import { RenderAdditiveLightQueue } from '../render-additive-light-queue'; import { RenderShadowMapBatchedQueue } from '../render-shadow-map-batched-queue'; -import { renderProfiler } from '../pipeline-funcs'; import { PlanarShadowQueue } from '../planar-shadow-queue'; import { DefaultVisitor, depthFirstSearch, ReferenceGraphView } from './graph'; import { VectorGraphColorMap } from './effect'; -import { getDescBindingFromName, getRenderArea, updateGlobalDescBinding } from './define'; +import { getDescBindingFromName, getDescriptorSetDataFromLayout, getDescriptorSetDataFromLayoutId, getRenderArea, mergeSrcToTargetDesc, updateGlobalDescBinding } from './define'; import { RenderReflectionProbeQueue } from '../render-reflection-probe-queue'; import { ReflectionProbeManager } from '../reflection-probe-manager'; +import { builtinResMgr } from '../../asset/asset-manager/builtin-res-mgr'; +import { Texture2D } from '../../asset/assets/texture-2d'; class DeviceResource { protected _context: ExecutorContext; @@ -233,7 +234,7 @@ class BlitDesc { inputAssemblerData.quadIA = quadIA; return inputAssemblerData; } - createSreenQuad () { + createScreenQuad () { if (!this._screenQuad) { this._screenQuad = this._createQuadInputAssembler(); } @@ -409,7 +410,7 @@ class DeviceRenderQueue { return; } this._blitDesc = new BlitDesc(blit, this); - this._blitDesc.createSreenQuad(); + this._blitDesc.createScreenQuad(); this._blitDesc.createStageDescriptor(); } addSceneTask (scene: GraphScene): void { @@ -497,19 +498,19 @@ class RenderPassLayoutInfo { // find descriptor binding for (const block of layoutData.descriptorSetLayoutData.descriptorBlocks) { for (let i = 0; i !== block.descriptors.length; ++i) { - const buffer = layoutDesc.getBuffer(block.offset + i); - const texture = layoutDesc.getTexture(block.offset + i); + // const buffer = layoutDesc.getBuffer(block.offset + i); + // const texture = layoutDesc.getTexture(block.offset + i); if (descriptorID === block.descriptors[i].descriptorID) { layoutDesc.bindTexture(block.offset + i, gfxTex); layoutDesc.bindSampler(block.offset + i, context.device.getSampler(samplerInfo)); if (!this._descriptorSet) this._descriptorSet = layoutDesc; continue; } - if (!buffer && !texture) { - layoutDesc.bindBuffer(block.offset + i, globalDesc.getBuffer(block.offset + i)); - layoutDesc.bindTexture(block.offset + i, globalDesc.getTexture(block.offset + i)); - layoutDesc.bindSampler(block.offset + i, globalDesc.getSampler(block.offset + i)); - } + // if (!buffer && !texture) { + // layoutDesc.bindBuffer(block.offset + i, globalDesc.getBuffer(block.offset + i)); + // layoutDesc.bindTexture(block.offset + i, globalDesc.getTexture(block.offset + i)); + // layoutDesc.bindSampler(block.offset + i, globalDesc.getSampler(block.offset + i)); + // } } } } @@ -739,6 +740,36 @@ class DeviceRenderPass { this._viewport = viewport; } } + + protected _showProfiler (rect: Rect) { + const profiler = this.context.pipeline.profiler!; + if (!profiler || !profiler.enabled) { + return; + } + const context = this.context; + const renderPass = this._renderPass; + const cmdBuff = this.context.commandBuffer; + const submodel = profiler.subModels[0]; + const pass = submodel.passes[0]; + const ia = submodel.inputAssembler; + const device = this.context.device; + const pso = PipelineStateManager.getOrCreatePipelineState(device, pass, + submodel.shaders[0], renderPass, ia); + const descData = getDescriptorSetDataFromLayoutId(pass.passID)!; + mergeSrcToTargetDesc(descData.descriptorSet, context.pipeline.descriptorSet, true); + const profilerViewport = new Viewport(); + profilerViewport.width = rect.width; + profilerViewport.height = rect.height; + + cmdBuff.setViewport(profilerViewport); + cmdBuff.setScissor(rect); + cmdBuff.bindPipelineState(pso); + cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); + cmdBuff.bindDescriptorSet(SetIndex.LOCAL, submodel.descriptorSet); + cmdBuff.bindInputAssembler(ia); + cmdBuff.draw(ia); + } + // record common buffer record () { const tex = this.framebuffer.colorTextures[0]!; @@ -754,6 +785,9 @@ class DeviceRenderPass { for (const queue of this._deviceQueues) { queue.record(); } + if (this._rasterInfo.pass.showStatistics) { + this._showProfiler(renderArea); + } cmdBuff.endRenderPass(); } @@ -885,11 +919,13 @@ class DevicePreSceneTask extends WebSceneTask { submitMap.set(this.camera, this._submitInfo); } // shadowmap - if (this._isShadowMap() && !this._submitInfo.shadowMap) { + if (this._isShadowMap()) { assert(this.graphScene.scene!.light.light); - this._submitInfo.shadowMap = context.shadowMapBatched; - this._submitInfo.shadowMap.gatherLightPasses(this.camera, this.graphScene.scene!.light.light, this._cmdBuff, this.graphScene.scene!.light.level); + if (!this._submitInfo.shadowMap) { + this._submitInfo.shadowMap = context.shadowMapBatched; + } this.sceneData.shadowFrameBufferMap.set(this.graphScene.scene!.light.light, devicePass.framebuffer); + this._submitInfo.shadowMap.gatherLightPasses(this.camera, this.graphScene.scene!.light.light, this._cmdBuff, this.graphScene.scene!.light.level); return; } // reflection probe @@ -1036,8 +1072,9 @@ class DevicePreSceneTask extends WebSceneTask { } protected _updateGlobal (context: ExecutorContext, data: RenderData) { - updateGlobalDescBinding(context.pipeline, data); - context.pipeline.descriptorSet.update(); + const devicePass = this._currentQueue.devicePass; + updateGlobalDescBinding(data, isEnableEffect() ? context.renderGraph.getLayout(devicePass.rasterPassInfo.id) : 'default'); + if (!isEnableEffect()) context.pipeline.descriptorSet.update(); } protected _setMainLightShadowTex (context: ExecutorContext, data: RenderData) { @@ -1046,9 +1083,14 @@ class DevicePreSceneTask extends WebSceneTask { const mainLight = graphScene.scene.camera.scene!.mainLight; const shadowFrameBufferMap = this.sceneData.shadowFrameBufferMap; if (mainLight && shadowFrameBufferMap.has(mainLight)) { + const shadowAttrID = context.layoutGraph.attributeIndex.get('cc_shadowMap'); + const defaultTex = builtinResMgr.get('default-texture').getGFXTexture()!; for (const [key, value] of data.textures) { - if (key === context.layoutGraph.attributeIndex.get('cc_shadowMap')) { - data.textures.set(key, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!); + if (key === shadowAttrID) { + const tex = data.textures.get(shadowAttrID); + if (tex === defaultTex) { + data.textures.set(key, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!); + } return; } } @@ -1068,6 +1110,11 @@ class DevicePreSceneTask extends WebSceneTask { const queueRenderData = context.renderGraph.getData(queueId)!; this._setMainLightShadowTex(context, queueRenderData); this._updateGlobal(context, queueRenderData); + if (isEnableEffect()) { + const layoutName = context.renderGraph.getLayout(rasterId); + const descSetData = getDescriptorSetDataFromLayout(layoutName); + mergeSrcToTargetDesc(descSetData!.descriptorSet, context.pipeline.descriptorSet, true); + } } public submit () { @@ -1220,30 +1267,6 @@ class DeviceSceneTask extends WebSceneTask { && this.graphScene.scene && this.graphScene.scene.flags & SceneFlags.SHADOW_CASTER; } - private _mergeSrcToTarDesc (fromDesc, toDesc) { - fromDesc.update(); - const fromGpuDesc = fromDesc.gpuDescriptorSet; - const toGpuDesc = toDesc.gpuDescriptorSet; - const extResId: number[] = []; - for (let i = 0; i < toGpuDesc.gpuDescriptors.length; i++) { - const fromRes = fromGpuDesc.gpuDescriptors[i]; - if (!fromRes) continue; - const currRes = toGpuDesc.gpuDescriptors[i]; - if (!currRes.gpuBuffer && fromRes.gpuBuffer) { - currRes.gpuBuffer = fromRes.gpuBuffer; - extResId.push(i); - } else if ('gpuTextureView' in currRes && !currRes.gpuTextureView) { - currRes.gpuTextureView = fromRes.gpuTextureView; - currRes.gpuSampler = fromRes.gpuSampler; - extResId.push(i); - } else if ('gpuTexture' in currRes && !currRes.gpuTexture) { - currRes.gpuTexture = fromRes.gpuTexture; - currRes.gpuSampler = fromRes.gpuSampler; - extResId.push(i); - } - } - return extResId; - } private _clearExtBlitDesc (desc, extResId: number[]) { const toGpuDesc = desc.gpuDescriptorSet; @@ -1280,15 +1303,15 @@ class DeviceSceneTask extends WebSceneTask { this.visitor.bindPipelineState(pso); const layoutStage = devicePass.renderLayout; const layoutDesc = layoutStage!.descriptorSet!; - const extResId: number[] = isEnableEffect() ? [] : this._mergeSrcToTarDesc(pass.descriptorSet, layoutDesc); - if (isEnableEffect()) this.visitor.bindDescriptorSet(SetIndex.GLOBAL, layoutDesc); + const extResId: number[] = isEnableEffect() ? [] : mergeSrcToTargetDesc(pass.descriptorSet, layoutDesc); + // if (isEnableEffect()) this.visitor.bindDescriptorSet(SetIndex.GLOBAL, layoutDesc); this.visitor.bindDescriptorSet(SetIndex.MATERIAL, isEnableEffect() ? pass.descriptorSet : layoutDesc); this.visitor.bindDescriptorSet(SetIndex.LOCAL, this._currentQueue.blitDesc!.stageDesc!); this.visitor.bindInputAssembler(screenIa); this.visitor.draw(screenIa); // The desc data obtained from the outside should be cleaned up so that the data can be modified this._clearExtBlitDesc(layoutDesc, extResId); - if (isEnableEffect()) this.visitor.bindDescriptorSet(SetIndex.GLOBAL, globalDesc); + // if (isEnableEffect()) this.visitor.bindDescriptorSet(SetIndex.GLOBAL, globalDesc); } } private _recordAdditiveLights () { @@ -1358,10 +1381,6 @@ class DeviceSceneTask extends WebSceneTask { if (graphSceneData.flags & SceneFlags.UI) { this._recordUI(); } - if (graphSceneData.flags & SceneFlags.PROFILER) { - renderProfiler(context.device, devicePass.renderPass, - context.commandBuffer, context.pipeline.profiler, this.camera!); - } if (graphSceneData.flags & SceneFlags.REFLECTION_PROBE) { this._recordReflectionProbe(); } @@ -1539,7 +1558,8 @@ class PreRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor { } else { const passHash = pass.versionName; this.currPass = devicePasses.get(passHash); - if (!this.currPass || this.currPass.version !== pass.version) { + const currRasterPass = this.currPass ? this.currPass.rasterPassInfo.pass : null; + if (!this.currPass || currRasterPass.version !== pass.version) { this.currPass = new DeviceRenderPass(this.context, new RasterPassInfo(this.passID, pass)); devicePasses.set(passHash, this.currPass); } else { diff --git a/cocos/rendering/custom/index.jsb.ts b/cocos/rendering/custom/index.jsb.ts index 9599859065..34364d0547 100644 --- a/cocos/rendering/custom/index.jsb.ts +++ b/cocos/rendering/custom/index.jsb.ts @@ -25,8 +25,6 @@ declare const render: any; import { Pipeline, PipelineBuilder, RenderingModule } from './pipeline'; -import { buildDeferredLayout, buildForwardLayout } from './effect'; -import { macro } from '../../core/platform/macro'; import { DeferredPipelineBuilder, ForwardPipelineBuilder } from './builtin-pipelines'; import { CustomPipelineBuilder, NativePipelineBuilder } from './custom-pipeline'; import { Device } from '../../gfx'; @@ -36,21 +34,12 @@ export * from './pipeline'; export * from './archive'; export const INVALID_ID = 0xFFFFFFFF; -export const enableEffectImport = false; +export const enableEffectImport = true; let _renderModule: RenderingModule; export function createCustomPipeline (): Pipeline { - const ppl = render.Factory.createPipeline(); - const pplName = macro.CUSTOM_PIPELINE_NAME; - if (!enableEffectImport) { - if (pplName === 'Deferred') { - buildDeferredLayout(ppl); - } else { - buildForwardLayout(ppl); - } - } - return ppl; + return render.Factory.createPipeline(); } export const customPipelineBuilderMap = new Map(); @@ -76,8 +65,12 @@ function addCustomBuiltinPipelines (map: Map) { addCustomBuiltinPipelines(customPipelineBuilderMap); -export function init (device: Device, arrayBuffer: ArrayBuffer) { - _renderModule = render.Factory.init(device, arrayBuffer); +export function init (device: Device, arrayBuffer: ArrayBuffer | null) { + if (arrayBuffer) { + _renderModule = render.Factory.init(device, arrayBuffer); + } else { + _renderModule = render.Factory.init(device, new ArrayBuffer(0)); + } } export function destroy () { diff --git a/cocos/rendering/custom/index.ts b/cocos/rendering/custom/index.ts index 4fc03095dd..ffea894498 100644 --- a/cocos/rendering/custom/index.ts +++ b/cocos/rendering/custom/index.ts @@ -25,7 +25,6 @@ import { EDITOR } from 'internal:constants'; import { Pipeline, PipelineBuilder } from './pipeline'; import { WebPipeline } from './web-pipeline'; -import { buildDeferredLayout, buildForwardLayout } from './effect'; import { macro } from '../../core/platform/macro'; import { DeferredPipelineBuilder, ForwardPipelineBuilder } from './builtin-pipelines'; import { CustomPipelineBuilder, NativePipelineBuilder } from './custom-pipeline'; @@ -45,24 +44,16 @@ export * from './types'; export * from './pipeline'; export * from './archive'; -export const enableEffectImport = !EDITOR; +export const enableEffectImport = true; export const programLib: ProgramLibrary = new WebProgramLibrary(defaultLayoutGraph); export function createCustomPipeline (): Pipeline { - const layoutGraph = enableEffectImport ? defaultLayoutGraph : new LayoutGraphData(); + const layoutGraph = defaultLayoutGraph; const ppl = new WebPipeline(layoutGraph); const pplName = macro.CUSTOM_PIPELINE_NAME; ppl.setCustomPipelineName(pplName); - - if (!enableEffectImport) { - if (pplName === 'Deferred') { - buildDeferredLayout(ppl); - } else { - buildForwardLayout(ppl); - } - } - + (programLib as WebProgramLibrary).pipeline = ppl; _pipeline = ppl; return ppl; } @@ -90,9 +81,11 @@ function addCustomBuiltinPipelines (map: Map) { addCustomBuiltinPipelines(customPipelineBuilderMap); -export function init (device: Device, arrayBuffer: ArrayBuffer) { - const readBinaryData = new BinaryInputArchive(arrayBuffer); - loadLayoutGraphData(readBinaryData, defaultLayoutGraph); +export function init (device: Device, arrayBuffer: ArrayBuffer | null) { + if (arrayBuffer) { + const readBinaryData = new BinaryInputArchive(arrayBuffer); + loadLayoutGraphData(readBinaryData, defaultLayoutGraph); + } initializeLayoutGraphData(device, defaultLayoutGraph); } diff --git a/cocos/rendering/custom/layout-graph-utils.ts b/cocos/rendering/custom/layout-graph-utils.ts index 06c8626977..6da6ca94b4 100644 --- a/cocos/rendering/custom/layout-graph-utils.ts +++ b/cocos/rendering/custom/layout-graph-utils.ts @@ -25,10 +25,9 @@ /* eslint-disable max-len */ import { EffectAsset } from '../../asset/assets'; import { assert } from '../../core'; -import { DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorSetLayoutInfo, DescriptorType, Device, PipelineLayout, PipelineLayoutInfo, ShaderStageFlagBit, Type, Uniform, UniformBlock } from '../../gfx'; +import { DescriptorSetInfo, DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorSetLayoutInfo, DescriptorType, Device, PipelineLayout, PipelineLayoutInfo, ShaderStageFlagBit, Type, Uniform, UniformBlock } from '../../gfx'; import { DefaultVisitor, depthFirstSearch, GraphColor, MutableVertexPropertyMap } from './graph'; import { DescriptorBlockData, DescriptorData, DescriptorDB, DescriptorSetData, DescriptorSetLayoutData, LayoutGraph, LayoutGraphData, LayoutGraphDataValue, LayoutGraphValue, PipelineLayoutData, RenderPhase, RenderPhaseData, RenderStageData, ShaderProgramData } from './layout-graph'; -import { LayoutGraphBuilder } from './pipeline'; import { UpdateFrequency, getUpdateFrequencyName, getDescriptorTypeOrderName, Descriptor, DescriptorBlock, DescriptorBlockFlattened, DescriptorBlockIndex, DescriptorTypeOrder, ParameterType } from './types'; export const INVALID_ID = 0xFFFFFFFF; @@ -990,7 +989,7 @@ function sortDescriptorBlocks (lhs: [string, T], rhs: [string, T]): number { } // build LayoutGraphData -function buildLayoutGraphDataImpl (graph: LayoutGraph, builder: LayoutGraphBuilder) { +function buildLayoutGraphDataImpl (graph: LayoutGraph, builder: LayoutGraphBuilder2) { for (const v of graph.vertices()) { const db = graph.getDescriptors(v); let minLevel = UpdateFrequency.PER_INSTANCE; @@ -1064,8 +1063,19 @@ export function getOrCreateDescriptorID (lg: LayoutGraphData, name: string): num return nameID; } +export function getOrCreateConstantID (lg: LayoutGraphData, name: string): number { + const nameID = lg.constantIndex.get(name); + if (nameID === undefined) { + const newID = lg.valueNames.length; + lg.constantIndex.set(name, newID); + lg.valueNames.push(name); + return newID; + } + return nameID; +} + // LayoutGraphData builder -class LayoutGraphBuilder2 implements LayoutGraphBuilder { +class LayoutGraphBuilder2 { public constructor (lg: LayoutGraphData) { this.lg = lg; } @@ -1142,6 +1152,12 @@ class LayoutGraphBuilder2 implements LayoutGraphBuilder { dstBlock.descriptors.push(data); } layout.capacity += block.capacity; + if (index.descriptorType === DescriptorTypeOrder.UNIFORM_BUFFER + || index.descriptorType === DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER) { + layout.uniformBlockCapacity += block.capacity; + } else if (index.descriptorType === DescriptorTypeOrder.SAMPLER_TEXTURE) { + layout.samplerTextureCapacity += block.capacity; + } } addUniformBlock (nodeID: number, index: DescriptorBlockIndex, name: string, uniformBlock: UniformBlock): void { const g: LayoutGraphData = this.lg; @@ -1150,6 +1166,10 @@ class LayoutGraphBuilder2 implements LayoutGraphBuilder { const layout = setData.descriptorSetLayoutData; const nameID = getOrCreateDescriptorID(g, name); layout.uniformBlocks.set(nameID, uniformBlock); + // register constant names + for (const member of uniformBlock.members) { + getOrCreateConstantID(g, member.name); + } } reserveDescriptorBlock (nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void { if (block.capacity <= 0) { @@ -1165,6 +1185,12 @@ class LayoutGraphBuilder2 implements LayoutGraphBuilder { dstBlock.offset = layout.capacity; layout.descriptorBlocks.push(dstBlock); layout.capacity += block.capacity; + if (index.descriptorType === DescriptorTypeOrder.UNIFORM_BUFFER + || index.descriptorType === DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER) { + layout.uniformBlockCapacity += block.capacity; + } else if (index.descriptorType === DescriptorTypeOrder.SAMPLER_TEXTURE) { + layout.samplerTextureCapacity += block.capacity; + } } compile (): number { // console.debug(this.print()); @@ -1186,6 +1212,54 @@ export function buildLayoutGraphData (lg: LayoutGraph, lgData: LayoutGraphData) builder.compile(); } +function createDescriptorInfo (layoutData: DescriptorSetLayoutData, info: DescriptorSetLayoutInfo) { + for (let i = 0; i < layoutData.descriptorBlocks.length; ++i) { + const block = layoutData.descriptorBlocks[i]; + let slot = block.offset; + for (let j = 0; j < block.descriptors.length; ++j) { + const d = block.descriptors[j]; + const binding: DescriptorSetLayoutBinding = new DescriptorSetLayoutBinding(); + binding.binding = slot; + binding.descriptorType = getGfxDescriptorType(block.type); + binding.count = d.count; + binding.stageFlags = block.visibility; + binding.immutableSamplers = []; + info.bindings.push(binding); + slot += d.count; + } + } +} + +function createDescriptorSetLayout (device: Device | null, layoutData: DescriptorSetLayoutData) { + const info: DescriptorSetLayoutInfo = new DescriptorSetLayoutInfo(); + createDescriptorInfo(layoutData, info); + + if (device) { + return device.createDescriptorSetLayout(info); + } else { + return null; + } +} + +export function createGfxDescriptorSetsAndPipelines (device: Device | null, g: LayoutGraphData) { + for (let i = 0; i < g._layouts.length; ++i) { + const ppl: PipelineLayoutData = g.getLayout(i); + ppl.descriptorSets.forEach((value, key) => { + const level = value; + const layoutData = level.descriptorSetLayoutData; + if (device) { + const layout: DescriptorSetLayout | null = createDescriptorSetLayout(device, layoutData); + if (layout) { + level.descriptorSetLayout = (layout); + level.descriptorSet = (device.createDescriptorSet(new DescriptorSetInfo(layout))); + } + } else { + createDescriptorInfo(layoutData, level.descriptorSetLayoutInfo); + } + }); + } +} + export function printLayoutGraphData (g: LayoutGraphData): string { const visitor = new PrintVisitor(); const colorMap = new VectorGraphColorMap(g.numVertices()); @@ -1322,6 +1396,13 @@ export function makeDescriptorSetLayoutData (lg: LayoutGraphData, } // increate total capacity capacity += block.capacity; + data.capacity += block.capacity; + if (index.descriptorType === DescriptorTypeOrder.UNIFORM_BUFFER + || index.descriptorType === DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER) { + data.uniformBlockCapacity += block.capacity; + } else if (index.descriptorType === DescriptorTypeOrder.SAMPLER_TEXTURE) { + data.samplerTextureCapacity += block.capacity; + } data.descriptorBlocks.push(block); } return data; diff --git a/cocos/rendering/custom/layout-graph.ts b/cocos/rendering/custom/layout-graph.ts index 600746bb9b..e7f2edd26f 100644 --- a/cocos/rendering/custom/layout-graph.ts +++ b/cocos/rendering/custom/layout-graph.ts @@ -619,6 +619,8 @@ export class DescriptorSetLayoutData { } slot: number; capacity: number; + uniformBlockCapacity = 0; + samplerTextureCapacity = 0; readonly descriptorBlocks: DescriptorBlockData[]; readonly uniformBlocks: Map; readonly bindingMap: Map; @@ -1418,6 +1420,8 @@ export function loadDescriptorBlockData (ar: InputArchive, v: DescriptorBlockDat export function saveDescriptorSetLayoutData (ar: OutputArchive, v: DescriptorSetLayoutData) { ar.writeNumber(v.slot); ar.writeNumber(v.capacity); + ar.writeNumber(v.uniformBlockCapacity); + ar.writeNumber(v.samplerTextureCapacity); ar.writeNumber(v.descriptorBlocks.length); // DescriptorBlockData[] for (const v1 of v.descriptorBlocks) { saveDescriptorBlockData(ar, v1); @@ -1437,6 +1441,8 @@ export function saveDescriptorSetLayoutData (ar: OutputArchive, v: DescriptorSet export function loadDescriptorSetLayoutData (ar: InputArchive, v: DescriptorSetLayoutData) { v.slot = ar.readNumber(); v.capacity = ar.readNumber(); + v.uniformBlockCapacity = ar.readNumber(); + v.samplerTextureCapacity = ar.readNumber(); let sz = 0; sz = ar.readNumber(); // DescriptorBlockData[] v.descriptorBlocks.length = sz; diff --git a/cocos/rendering/custom/pipeline.ts b/cocos/rendering/custom/pipeline.ts index a526cae49f..f41b06377d 100644 --- a/cocos/rendering/custom/pipeline.ts +++ b/cocos/rendering/custom/pipeline.ts @@ -31,12 +31,12 @@ import { Material } from '../../asset/assets'; import { Camera } from '../../render-scene/scene/camera'; import { GeometryRenderer } from '../geometry-renderer'; -import { Buffer, Color, CommandBuffer, DescriptorSet, DescriptorSetLayout, Device, DrawInfo, Format, InputAssembler, PipelineState, Rect, Sampler, Swapchain, Texture, UniformBlock, Viewport } from '../../gfx'; +import { Buffer, Color, CommandBuffer, DescriptorSet, DescriptorSetLayout, Device, DrawInfo, Format, InputAssembler, PipelineState, Rect, Sampler, Swapchain, Texture, Viewport } from '../../gfx'; import { GlobalDSManager } from '../global-descriptor-set-manager'; import { Mat4, Quat, Vec2, Vec4 } from '../../core/math'; import { MacroRecord } from '../../render-scene/core/pass-utils'; import { PipelineSceneData } from '../pipeline-scene-data'; -import { ComputeView, CopyPair, DescriptorBlockFlattened, DescriptorBlockIndex, LightInfo, MovePair, QueueHint, RasterView, ResourceResidency, SceneFlags, TaskType, UpdateFrequency } from './types'; +import { ComputeView, CopyPair, LightInfo, MovePair, QueueHint, RasterView, ResourceResidency, SceneFlags, TaskType, UpdateFrequency } from './types'; import { RenderScene } from '../../render-scene/core/render-scene'; import { RenderWindow } from '../../render-scene/core/render-window'; import { Model } from '../../render-scene/scene'; @@ -104,6 +104,7 @@ export interface RasterPassBuilder extends Setter { addQueue (/*QueueHint.NONE*/): RasterQueueBuilder; setViewport (viewport: Viewport): void; setVersion (name: string, version: number): void; + showStatistics: boolean; } export interface ComputeQueueBuilder extends Setter { @@ -146,18 +147,6 @@ export interface SceneTransversal { transverse (visitor: SceneVisitor): SceneTask; } -export interface LayoutGraphBuilder { - clear (): void; - addRenderStage (name: string): number; - addRenderPhase (name: string, parentID: number): number; - addShader (name: string, parentPhaseID: number): void; - addDescriptorBlock (nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void; - addUniformBlock (nodeID: number, index: DescriptorBlockIndex, name: string, uniformBlock: UniformBlock): void; - reserveDescriptorBlock (nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void; - compile (): number; - print (): string; -} - export interface Pipeline extends PipelineRuntime { beginSetup (): void; endSetup (): void; @@ -181,7 +170,6 @@ export interface Pipeline extends PipelineRuntime { addCopyPass (): CopyPassBuilder; presentAll (): void; createSceneTransversal (camera: Camera, scene: RenderScene): SceneTransversal; - readonly layoutGraphBuilder: LayoutGraphBuilder; getDescriptorSetLayout (shaderName: string, freq: UpdateFrequency): DescriptorSetLayout | null; } diff --git a/cocos/rendering/custom/render-graph.ts b/cocos/rendering/custom/render-graph.ts index 1ea87b4be8..8def7abf44 100644 --- a/cocos/rendering/custom/render-graph.ts +++ b/cocos/rendering/custom/render-graph.ts @@ -31,7 +31,7 @@ import { AdjI, AdjacencyGraph, BidirectionalGraph, ComponentGraph, ED, InEI, MutableGraph, MutableReferenceGraph, NamedGraph, OutE, OutEI, PolymorphicGraph, PropertyGraph, PropertyMap, ReferenceGraph, UuidGraph, VertexListGraph, directional, parallel, reindexEdgeList, traversal } from './graph'; import { Material } from '../../asset/assets'; import { Camera } from '../../render-scene/scene/camera'; -import { AccessFlagBit, Buffer, ClearFlagBit, Color, Format, Framebuffer, SampleCount, Sampler, SamplerInfo, Swapchain, Texture, TextureFlagBit, Viewport } from '../../gfx'; +import { AccessFlagBit, Buffer, ClearFlagBit, Color, Format, Framebuffer, RenderPass, SampleCount, Sampler, SamplerInfo, Swapchain, Texture, TextureFlagBit, Viewport } from '../../gfx'; import { ComputeView, CopyPair, LightInfo, MovePair, QueueHint, RasterView, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags } from './types'; export class ResourceDesc { @@ -61,6 +61,7 @@ export class RenderSwapchain { /*pointer*/ swapchain: Swapchain | null; currentID = 0; numBackBuffers = 0; + generation = 0xFFFFFFFF; } export class ResourceStates { @@ -87,6 +88,338 @@ export class ManagedResource { unused = 0; } +export class RasterSubpass { + readonly rasterViews: Map = new Map(); + readonly computeViews: Map = new Map(); +} + +//================================================================= +// SubpassGraph +//================================================================= +// Graph Concept +export class SubpassGraphVertex { + constructor () { + } + readonly _outEdges: OutE[] = []; + readonly _inEdges: OutE[] = []; +} + +//----------------------------------------------------------------- +// PropertyGraph Concept +export class SubpassGraphNameMap implements PropertyMap { + constructor (readonly names: string[]) { + this._names = names; + } + get (v: number): string { + return this._names[v]; + } + set (v: number, names: string): void { + this._names[v] = names; + } + readonly _names: string[]; +} + +export class SubpassGraphSubpassMap implements PropertyMap { + constructor (readonly subpasses: RasterSubpass[]) { + this._subpasses = subpasses; + } + get (v: number): RasterSubpass { + return this._subpasses[v]; + } + readonly _subpasses: RasterSubpass[]; +} + +//----------------------------------------------------------------- +// ComponentGraph Concept +export const enum SubpassGraphComponent { + Name, + Subpass, +} + +export interface SubpassGraphComponentType { + [SubpassGraphComponent.Name]: string; + [SubpassGraphComponent.Subpass]: RasterSubpass; +} + +export interface SubpassGraphComponentPropertyMap { + [SubpassGraphComponent.Name]: SubpassGraphNameMap; + [SubpassGraphComponent.Subpass]: SubpassGraphSubpassMap; +} + +//----------------------------------------------------------------- +// SubpassGraph Implementation +export class SubpassGraph implements BidirectionalGraph +, AdjacencyGraph +, VertexListGraph +, MutableGraph +, PropertyGraph +, NamedGraph +, ComponentGraph { + //----------------------------------------------------------------- + // Graph + // type vertex_descriptor = number; + nullVertex (): number { return 0xFFFFFFFF; } + // type edge_descriptor = ED; + readonly directed_category: directional = directional.bidirectional; + readonly edge_parallel_category: parallel = parallel.allow; + readonly traversal_category: traversal = traversal.incidence + | traversal.bidirectional + | traversal.adjacency + | traversal.vertex_list; + //----------------------------------------------------------------- + // IncidenceGraph + // type out_edge_iterator = OutEI; + // type degree_size_type = number; + edge (u: number, v: number): boolean { + for (const oe of this._vertices[u]._outEdges) { + if (v === oe.target as number) { + return true; + } + } + return false; + } + source (e: ED): number { + return e.source as number; + } + target (e: ED): number { + return e.target as number; + } + outEdges (v: number): OutEI { + return new OutEI(this._vertices[v]._outEdges.values(), v); + } + outDegree (v: number): number { + return this._vertices[v]._outEdges.length; + } + //----------------------------------------------------------------- + // BidirectionalGraph + // type in_edge_iterator = InEI; + inEdges (v: number): InEI { + return new InEI(this._vertices[v]._inEdges.values(), v); + } + inDegree (v: number): number { + return this._vertices[v]._inEdges.length; + } + degree (v: number): number { + return this.outDegree(v) + this.inDegree(v); + } + //----------------------------------------------------------------- + // AdjacencyGraph + // type adjacency_iterator = AdjI; + adjacentVertices (v: number): AdjI { + return new AdjI(this, this.outEdges(v)); + } + //----------------------------------------------------------------- + // VertexListGraph + vertices (): IterableIterator { + return this._vertices.keys(); + } + numVertices (): number { + return this._vertices.length; + } + //----------------------------------------------------------------- + // EdgeListGraph + numEdges (): number { + let numEdges = 0; + for (const v of this.vertices()) { + numEdges += this.outDegree(v); + } + return numEdges; + } + //----------------------------------------------------------------- + // MutableGraph + clear (): void { + // ComponentGraph + this._names.length = 0; + this._subpasses.length = 0; + // Graph Vertices + this._vertices.length = 0; + } + addVertex ( + name: string, + subpass: RasterSubpass, + ): number { + const vert = new SubpassGraphVertex(); + const v = this._vertices.length; + this._vertices.push(vert); + this._names.push(name); + this._subpasses.push(subpass); + return v; + } + clearVertex (v: number): void { + const vert = this._vertices[v]; + // clear out edges + for (const oe of vert._outEdges) { + const target = this._vertices[oe.target as number]; + for (let i = 0; i !== target._inEdges.length;) { // remove all edges + if (target._inEdges[i].target === v) { + target._inEdges.splice(i, 1); + } else { + ++i; + } + } + } + vert._outEdges.length = 0; + + // clear in edges + for (const ie of vert._inEdges) { + const source = this._vertices[ie.target as number]; + for (let i = 0; i !== source._outEdges.length;) { // remove all edges + if (source._outEdges[i].target === v) { + source._outEdges.splice(i, 1); + } else { + ++i; + } + } + } + vert._inEdges.length = 0; + } + removeVertex (u: number): void { + this._vertices.splice(u, 1); + this._names.splice(u, 1); + this._subpasses.splice(u, 1); + + const sz = this._vertices.length; + if (u === sz) { + return; + } + + for (let v = 0; v !== sz; ++v) { + const vert = this._vertices[v]; + reindexEdgeList(vert._outEdges, u); + reindexEdgeList(vert._inEdges, u); + } + } + addEdge (u: number, v: number): ED | null { + // update in/out edge list + this._vertices[u]._outEdges.push(new OutE(v)); + this._vertices[v]._inEdges.push(new OutE(u)); + return new ED(u, v); + } + removeEdges (u: number, v: number): void { + const source = this._vertices[u]; + // remove out edges of u + for (let i = 0; i !== source._outEdges.length;) { // remove all edges + if (source._outEdges[i].target === v) { + source._outEdges.splice(i, 1); + } else { + ++i; + } + } + // remove in edges of v + const target = this._vertices[v]; + for (let i = 0; i !== target._inEdges.length;) { // remove all edges + if (target._inEdges[i].target === u) { + target._inEdges.splice(i, 1); + } else { + ++i; + } + } + } + removeEdge (e: ED): void { + const u = e.source as number; + const v = e.target as number; + const source = this._vertices[u]; + for (let i = 0; i !== source._outEdges.length;) { + if (source._outEdges[i].target === v) { + source._outEdges.splice(i, 1); + break; // remove one edge + } else { + ++i; + } + } + const target = this._vertices[v]; + for (let i = 0; i !== target._inEdges.length;) { + if (target._inEdges[i].target === u) { + target._inEdges.splice(i, 1); + break; // remove one edge + } else { + ++i; + } + } + } + //----------------------------------------------------------------- + // NamedGraph + vertexName (v: number): string { + return this._names[v]; + } + vertexNameMap (): SubpassGraphNameMap { + return new SubpassGraphNameMap(this._names); + } + //----------------------------------------------------------------- + // PropertyGraph + get (tag: string): SubpassGraphNameMap | SubpassGraphSubpassMap { + switch (tag) { + // Components + case 'Name': + return new SubpassGraphNameMap(this._names); + case 'Subpass': + return new SubpassGraphSubpassMap(this._subpasses); + default: + throw Error('property map not found'); + } + } + //----------------------------------------------------------------- + // ComponentGraph + component (id: T, v: number): SubpassGraphComponentType[T] { + switch (id) { + case SubpassGraphComponent.Name: + return this._names[v] as SubpassGraphComponentType[T]; + case SubpassGraphComponent.Subpass: + return this._subpasses[v] as SubpassGraphComponentType[T]; + default: + throw Error('component not found'); + } + } + componentMap (id: T): SubpassGraphComponentPropertyMap[T] { + switch (id) { + case SubpassGraphComponent.Name: + return new SubpassGraphNameMap(this._names) as SubpassGraphComponentPropertyMap[T]; + case SubpassGraphComponent.Subpass: + return new SubpassGraphSubpassMap(this._subpasses) as SubpassGraphComponentPropertyMap[T]; + default: + throw Error('component map not found'); + } + } + getName (v: number): string { + return this._names[v]; + } + setName (v: number, value: string) { + this._names[v] = value; + } + getSubpass (v: number): RasterSubpass { + return this._subpasses[v]; + } + + readonly components: string[] = ['Name', 'Subpass']; + readonly _vertices: SubpassGraphVertex[] = []; + readonly _names: string[] = []; + readonly _subpasses: RasterSubpass[] = []; +} + +export class RasterPass { + readonly rasterViews: Map = new Map(); + readonly computeViews: Map = new Map(); + readonly subpassGraph: SubpassGraph = new SubpassGraph(); + width = 0; + height = 0; + readonly viewport: Viewport = new Viewport(); + versionName = ''; + version = 0; + showStatistics = false; +} + +export class PersistentRenderPassAndFramebuffer { + constructor (renderPass: RenderPass, framebuffer: Framebuffer) { + this.renderPass = renderPass; + this.framebuffer = framebuffer; + } + /*refcount*/ renderPass: RenderPass; + /*refcount*/ framebuffer: Framebuffer; + readonly clearColors: Color[] = []; + clearDepth = 0; + clearStencil = 0; +} + //================================================================= // ResourceGraph //================================================================= @@ -324,6 +657,7 @@ export class ResourceGraph implements BidirectionalGraph // MutableGraph clear (): void { // Members + this.renderPasses.clear(); this.nextFenceValue = 0; this.version = 0; // UuidGraph @@ -705,329 +1039,11 @@ export class ResourceGraph implements BidirectionalGraph readonly _states: ResourceStates[] = []; readonly _samplerInfo: SamplerInfo[] = []; readonly _valueIndex: Map = new Map(); + readonly renderPasses: Map = new Map(); nextFenceValue = 0; version = 0; } -export class RasterSubpass { - readonly rasterViews: Map = new Map(); - readonly computeViews: Map = new Map(); -} - -//================================================================= -// SubpassGraph -//================================================================= -// Graph Concept -export class SubpassGraphVertex { - constructor () { - } - readonly _outEdges: OutE[] = []; - readonly _inEdges: OutE[] = []; -} - -//----------------------------------------------------------------- -// PropertyGraph Concept -export class SubpassGraphNameMap implements PropertyMap { - constructor (readonly names: string[]) { - this._names = names; - } - get (v: number): string { - return this._names[v]; - } - set (v: number, names: string): void { - this._names[v] = names; - } - readonly _names: string[]; -} - -export class SubpassGraphSubpassMap implements PropertyMap { - constructor (readonly subpasses: RasterSubpass[]) { - this._subpasses = subpasses; - } - get (v: number): RasterSubpass { - return this._subpasses[v]; - } - readonly _subpasses: RasterSubpass[]; -} - -//----------------------------------------------------------------- -// ComponentGraph Concept -export const enum SubpassGraphComponent { - Name, - Subpass, -} - -export interface SubpassGraphComponentType { - [SubpassGraphComponent.Name]: string; - [SubpassGraphComponent.Subpass]: RasterSubpass; -} - -export interface SubpassGraphComponentPropertyMap { - [SubpassGraphComponent.Name]: SubpassGraphNameMap; - [SubpassGraphComponent.Subpass]: SubpassGraphSubpassMap; -} - -//----------------------------------------------------------------- -// SubpassGraph Implementation -export class SubpassGraph implements BidirectionalGraph -, AdjacencyGraph -, VertexListGraph -, MutableGraph -, PropertyGraph -, NamedGraph -, ComponentGraph { - //----------------------------------------------------------------- - // Graph - // type vertex_descriptor = number; - nullVertex (): number { return 0xFFFFFFFF; } - // type edge_descriptor = ED; - readonly directed_category: directional = directional.bidirectional; - readonly edge_parallel_category: parallel = parallel.allow; - readonly traversal_category: traversal = traversal.incidence - | traversal.bidirectional - | traversal.adjacency - | traversal.vertex_list; - //----------------------------------------------------------------- - // IncidenceGraph - // type out_edge_iterator = OutEI; - // type degree_size_type = number; - edge (u: number, v: number): boolean { - for (const oe of this._vertices[u]._outEdges) { - if (v === oe.target as number) { - return true; - } - } - return false; - } - source (e: ED): number { - return e.source as number; - } - target (e: ED): number { - return e.target as number; - } - outEdges (v: number): OutEI { - return new OutEI(this._vertices[v]._outEdges.values(), v); - } - outDegree (v: number): number { - return this._vertices[v]._outEdges.length; - } - //----------------------------------------------------------------- - // BidirectionalGraph - // type in_edge_iterator = InEI; - inEdges (v: number): InEI { - return new InEI(this._vertices[v]._inEdges.values(), v); - } - inDegree (v: number): number { - return this._vertices[v]._inEdges.length; - } - degree (v: number): number { - return this.outDegree(v) + this.inDegree(v); - } - //----------------------------------------------------------------- - // AdjacencyGraph - // type adjacency_iterator = AdjI; - adjacentVertices (v: number): AdjI { - return new AdjI(this, this.outEdges(v)); - } - //----------------------------------------------------------------- - // VertexListGraph - vertices (): IterableIterator { - return this._vertices.keys(); - } - numVertices (): number { - return this._vertices.length; - } - //----------------------------------------------------------------- - // EdgeListGraph - numEdges (): number { - let numEdges = 0; - for (const v of this.vertices()) { - numEdges += this.outDegree(v); - } - return numEdges; - } - //----------------------------------------------------------------- - // MutableGraph - clear (): void { - // ComponentGraph - this._names.length = 0; - this._subpasses.length = 0; - // Graph Vertices - this._vertices.length = 0; - } - addVertex ( - name: string, - subpass: RasterSubpass, - ): number { - const vert = new SubpassGraphVertex(); - const v = this._vertices.length; - this._vertices.push(vert); - this._names.push(name); - this._subpasses.push(subpass); - return v; - } - clearVertex (v: number): void { - const vert = this._vertices[v]; - // clear out edges - for (const oe of vert._outEdges) { - const target = this._vertices[oe.target as number]; - for (let i = 0; i !== target._inEdges.length;) { // remove all edges - if (target._inEdges[i].target === v) { - target._inEdges.splice(i, 1); - } else { - ++i; - } - } - } - vert._outEdges.length = 0; - - // clear in edges - for (const ie of vert._inEdges) { - const source = this._vertices[ie.target as number]; - for (let i = 0; i !== source._outEdges.length;) { // remove all edges - if (source._outEdges[i].target === v) { - source._outEdges.splice(i, 1); - } else { - ++i; - } - } - } - vert._inEdges.length = 0; - } - removeVertex (u: number): void { - this._vertices.splice(u, 1); - this._names.splice(u, 1); - this._subpasses.splice(u, 1); - - const sz = this._vertices.length; - if (u === sz) { - return; - } - - for (let v = 0; v !== sz; ++v) { - const vert = this._vertices[v]; - reindexEdgeList(vert._outEdges, u); - reindexEdgeList(vert._inEdges, u); - } - } - addEdge (u: number, v: number): ED | null { - // update in/out edge list - this._vertices[u]._outEdges.push(new OutE(v)); - this._vertices[v]._inEdges.push(new OutE(u)); - return new ED(u, v); - } - removeEdges (u: number, v: number): void { - const source = this._vertices[u]; - // remove out edges of u - for (let i = 0; i !== source._outEdges.length;) { // remove all edges - if (source._outEdges[i].target === v) { - source._outEdges.splice(i, 1); - } else { - ++i; - } - } - // remove in edges of v - const target = this._vertices[v]; - for (let i = 0; i !== target._inEdges.length;) { // remove all edges - if (target._inEdges[i].target === u) { - target._inEdges.splice(i, 1); - } else { - ++i; - } - } - } - removeEdge (e: ED): void { - const u = e.source as number; - const v = e.target as number; - const source = this._vertices[u]; - for (let i = 0; i !== source._outEdges.length;) { - if (source._outEdges[i].target === v) { - source._outEdges.splice(i, 1); - break; // remove one edge - } else { - ++i; - } - } - const target = this._vertices[v]; - for (let i = 0; i !== target._inEdges.length;) { - if (target._inEdges[i].target === u) { - target._inEdges.splice(i, 1); - break; // remove one edge - } else { - ++i; - } - } - } - //----------------------------------------------------------------- - // NamedGraph - vertexName (v: number): string { - return this._names[v]; - } - vertexNameMap (): SubpassGraphNameMap { - return new SubpassGraphNameMap(this._names); - } - //----------------------------------------------------------------- - // PropertyGraph - get (tag: string): SubpassGraphNameMap | SubpassGraphSubpassMap { - switch (tag) { - // Components - case 'Name': - return new SubpassGraphNameMap(this._names); - case 'Subpass': - return new SubpassGraphSubpassMap(this._subpasses); - default: - throw Error('property map not found'); - } - } - //----------------------------------------------------------------- - // ComponentGraph - component (id: T, v: number): SubpassGraphComponentType[T] { - switch (id) { - case SubpassGraphComponent.Name: - return this._names[v] as SubpassGraphComponentType[T]; - case SubpassGraphComponent.Subpass: - return this._subpasses[v] as SubpassGraphComponentType[T]; - default: - throw Error('component not found'); - } - } - componentMap (id: T): SubpassGraphComponentPropertyMap[T] { - switch (id) { - case SubpassGraphComponent.Name: - return new SubpassGraphNameMap(this._names) as SubpassGraphComponentPropertyMap[T]; - case SubpassGraphComponent.Subpass: - return new SubpassGraphSubpassMap(this._subpasses) as SubpassGraphComponentPropertyMap[T]; - default: - throw Error('component map not found'); - } - } - getName (v: number): string { - return this._names[v]; - } - setName (v: number, value: string) { - this._names[v] = value; - } - getSubpass (v: number): RasterSubpass { - return this._subpasses[v]; - } - - readonly components: string[] = ['Name', 'Subpass']; - readonly _vertices: SubpassGraphVertex[] = []; - readonly _names: string[] = []; - readonly _subpasses: RasterSubpass[] = []; -} - -export class RasterPass { - readonly rasterViews: Map = new Map(); - readonly computeViews: Map = new Map(); - readonly subpassGraph: SubpassGraph = new SubpassGraph(); - width = 0; - height = 0; - readonly viewport: Viewport = new Viewport(); - versionName = ''; - version = 0; -} - export class ComputePass { readonly computeViews: Map = new Map(); } diff --git a/cocos/rendering/custom/types.ts b/cocos/rendering/custom/types.ts index 6e02f1b51c..7b61c4995e 100644 --- a/cocos/rendering/custom/types.ts +++ b/cocos/rendering/custom/types.ts @@ -280,6 +280,7 @@ export class RasterView { storeOp: StoreOp; clearFlags: ClearFlagBit; readonly clearColor: Color; + slotID = 0; } export enum ClearValueType { @@ -473,6 +474,7 @@ export function saveRasterView (ar: OutputArchive, v: RasterView) { ar.writeNumber(v.storeOp); ar.writeNumber(v.clearFlags); saveColor(ar, v.clearColor); + ar.writeNumber(v.slotID); } export function loadRasterView (ar: InputArchive, v: RasterView) { @@ -483,6 +485,7 @@ export function loadRasterView (ar: InputArchive, v: RasterView) { v.storeOp = ar.readNumber(); v.clearFlags = ar.readNumber(); loadColor(ar, v.clearColor); + v.slotID = ar.readNumber(); } export function saveComputeView (ar: OutputArchive, v: ComputeView) { diff --git a/cocos/rendering/custom/utils.ts b/cocos/rendering/custom/utils.ts index b69a79be4c..5489f4a602 100644 --- a/cocos/rendering/custom/utils.ts +++ b/cocos/rendering/custom/utils.ts @@ -25,6 +25,19 @@ // https://stackoverflow.com/questions/56714318/how-to-disable-multiple-rules-for-eslint-nextline?msclkid=5d4c2298ba7911eca34d0ab30591752e import { Type } from '../../gfx'; +import { Camera } from '../../render-scene/scene/camera'; + +export function isUICamera (camera: Camera): boolean { + const scene = camera.scene!; + const batches = scene.batches; + for (let i = 0; i < batches.length; i++) { + const batch = batches[i]; + if (camera.visibility & batch.visFlags) { + return true; + } + } + return false; +} // eslint-disable-next-line @typescript-eslint/no-unused-vars export function replacer (key: unknown, value: unknown) { diff --git a/cocos/rendering/custom/web-descriptor-hierarchy.ts b/cocos/rendering/custom/web-descriptor-hierarchy.ts deleted file mode 100644 index 29ca4316de..0000000000 --- a/cocos/rendering/custom/web-descriptor-hierarchy.ts +++ /dev/null @@ -1,694 +0,0 @@ -/* eslint-disable max-len */ -/**************************************************************************** - Copyright (c) 2021-2023 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 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 { EffectAsset } from '../../asset/assets'; -import { DescriptorDB, LayoutGraph, LayoutGraphValue, RenderPhase } from './layout-graph'; -import { ShaderStageFlagBit, Type, Uniform, UniformBlock } from '../../gfx'; -import { Descriptor, DescriptorBlock, DescriptorBlockIndex, DescriptorTypeOrder, ParameterType, UpdateFrequency } from './types'; -import { JOINT_UNIFORM_CAPACITY, RenderPassStage, SetIndex, UBOCamera, UBOCSM, UBOForwardLight, UBOGlobal, UBOLocal, UBOLocalBatched, UBOMorph, UBOShadow, UBOSkinning, UBOSkinningAnimation, UBOSkinningTexture, UBOUILocal, UBOWorldBound } from '../define'; -import { DefaultVisitor, edge_descriptor } from './graph'; - -export class WebDescriptorHierarchy { - public uniformBlockIndex: Map; - public blockMerged: Map>; - public dbsToMerge: Map; - - constructor () { - this._layoutGraph = new LayoutGraph(); - this.uniformBlockIndex = new Map(); - this.blockMerged = new Map>(); - this.dbsToMerge = new Map(); - } - - public getLayoutBlock (freq: UpdateFrequency, paraType: ParameterType, descType: DescriptorTypeOrder, vis: ShaderStageFlagBit, descriptorDB: DescriptorDB): DescriptorBlock { - const blockIndex: DescriptorBlockIndex = new DescriptorBlockIndex(freq, paraType, descType, vis); - const key = JSON.stringify(blockIndex); - if (descriptorDB.blocks.get(key) === undefined) { - const uniformBlock: DescriptorBlock = new DescriptorBlock(); - descriptorDB.blocks.set(key, uniformBlock); - - this.uniformBlockIndex.set(uniformBlock, blockIndex); - } - return descriptorDB.blocks.get(key) as DescriptorBlock; - } - - public getLayoutBlockByKey (key: string, descriptorDB: DescriptorDB): DescriptorBlock { - if (descriptorDB.blocks.get(key) === undefined) { - const uniformBlock: DescriptorBlock = new DescriptorBlock(); - descriptorDB.blocks.set(key, uniformBlock); - - const blockIndedx: DescriptorBlockIndex = JSON.parse(key) as DescriptorBlockIndex; - this.uniformBlockIndex.set(uniformBlock, blockIndedx); - } - return descriptorDB.blocks.get(key) as DescriptorBlock; - } - - public getUniformBlock (set: number, binding: number, blockName: string, targetBlock: DescriptorBlock): UniformBlock { - if (targetBlock.uniformBlocks.get(blockName) === undefined) { - const uniformDB: UniformBlock = new UniformBlock(set, binding, blockName, [], 1); - targetBlock.uniformBlocks.set(blockName, uniformDB); - } - return targetBlock.uniformBlocks.get(blockName) as UniformBlock; - } - - public setUniform (uniformDB: UniformBlock, name: string, type: Type, count: number) { - const uniform: Uniform = new Uniform(name, type, count); - uniformDB.members.push(uniform); - } - - public setDescriptor (targetBlock: DescriptorBlock, name: string, type: Type) { - const descriptor: Descriptor = new Descriptor(type); - targetBlock.descriptors.set(name, descriptor); - } - - public merge (descriptorDB: DescriptorDB) { - for (const entry of descriptorDB.blocks) { - const block: DescriptorBlock = entry[1]; - const typeMap: Map = new Map(); - for (const ee of block.descriptors) { - const descriptor: Descriptor = ee[1]; - const type: Type = descriptor.type; - if (typeMap.get(type) === undefined) { - typeMap.set(type, 1); - } else { - const before: number = typeMap.get(type) as number; - typeMap.set(type, before + 1); - } - block.capacity++; - } - for (const ii of typeMap) { - const type: Type = ii[0]; - const count: number = ii[1]; - if (count > 0) { - const mergedDescriptor: Descriptor = new Descriptor(type); - mergedDescriptor.count = count; - let merged: Map; - if (this.blockMerged.get(block) === undefined) { - merged = new Map(); - this.blockMerged.set(block, merged); - } - this.blockMerged.get(block)?.set(type, mergedDescriptor); - } - } - } - } - - public mergeDBs (descriptorDBs: DescriptorDB[], target: DescriptorDB) { - for (let i = 0; i < descriptorDBs.length; ++i) { - const db: DescriptorDB = descriptorDBs[i]; - for (const e of db.blocks) { - const key: string = e[0]; - const block: DescriptorBlock = e[1]; - - let merged: Map; - if (this.blockMerged.get(block) === undefined) { - merged = new Map(); - this.blockMerged.set(block, merged); - } else { - merged = this.blockMerged.get(block) as Map; - } - if (merged.size > 0) { - const targetBlock: DescriptorBlock = this.getLayoutBlockByKey(key, target); - let targetMerged: Map; - if (this.blockMerged.get(targetBlock) === undefined) { - targetMerged = new Map(); - this.blockMerged.set(targetBlock, targetMerged); - } else { - targetMerged = this.blockMerged.get(targetBlock) as Map; - } - for (const ee of merged) { - const type: Type = ee[0]; - const descriptor: Descriptor = ee[1]; - if (!targetMerged.has(type)) { - const ds: Descriptor = new Descriptor(descriptor.type); - ds.count = descriptor.count; - targetMerged.set(type, ds); - } else { - const ds: Descriptor | undefined = targetMerged.get(type); - if (ds !== undefined) { - ds.count = ds.count > descriptor.count ? ds.count : descriptor.count; - } - } - } - targetBlock.capacity = block.capacity > targetBlock.capacity ? block.capacity : targetBlock.capacity; - } - } - } - } - - public sort (descriptorDB: DescriptorDB) { - const sortedMap: Map = new Map(Array.from(descriptorDB.blocks).sort((a, b) => String(a[0]).localeCompare(b[0]))); - descriptorDB.blocks.clear(); - for (const e of sortedMap) { - descriptorDB.blocks.set(e[0], e[1]); - } - } - - public addEffect (asset: EffectAsset, parent: number): void { - const sz = asset.shaders.length; - - const dbsMap: Map = new Map(); - - for (let i = 0; i !== sz; ++i) { - const shader: EffectAsset.IShaderInfo = asset.shaders[i]; - - const queueDB: DescriptorDB = new DescriptorDB(); - - for (let k = 0; k < shader.blocks.length; ++k) { - const blockInfo: EffectAsset.IBlockInfo = shader.blocks[k]; - const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_INSTANCE, - ParameterType.TABLE, DescriptorTypeOrder.UNIFORM_BUFFER, blockInfo.stageFlags, queueDB); - const uniformDB: UniformBlock = this.getUniformBlock(SetIndex.MATERIAL, blockInfo.binding, blockInfo.name, targetBlock); - for (let kk = 0; kk < blockInfo.members.length; ++kk) { - const uniform: Uniform = blockInfo.members[kk]; - uniformDB.members.push(uniform); - } - } - - for (let k = 0; k < shader.buffers.length; ++k) { - const bufferInfo: EffectAsset.IBufferInfo = shader.buffers[k]; - const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, - ParameterType.TABLE, DescriptorTypeOrder.STORAGE_BUFFER, bufferInfo.stageFlags, queueDB); - this.setDescriptor(targetBlock, bufferInfo.name, Type.UNKNOWN); - } - - for (let k = 0; k < shader.images.length; ++k) { - const imageInfo: EffectAsset.IImageInfo = shader.images[k]; - const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, - ParameterType.TABLE, DescriptorTypeOrder.STORAGE_IMAGE, imageInfo.stageFlags, queueDB); - this.setDescriptor(targetBlock, imageInfo.name, imageInfo.type); - } - - for (let k = 0; k < shader.samplerTextures.length; ++k) { - const samplerTexInfo: EffectAsset.ISamplerTextureInfo = shader.samplerTextures[k]; - const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, - ParameterType.TABLE, DescriptorTypeOrder.SAMPLER_TEXTURE, samplerTexInfo.stageFlags, queueDB); - this.setDescriptor(targetBlock, samplerTexInfo.name, samplerTexInfo.type); - } - - for (let k = 0; k < shader.samplers.length; ++k) { - const samplerInfo: EffectAsset.ISamplerInfo = shader.samplers[k]; - const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, - ParameterType.TABLE, DescriptorTypeOrder.SAMPLER, samplerInfo.stageFlags, queueDB); - this.setDescriptor(targetBlock, samplerInfo.name, Type.SAMPLER); - } - - for (let k = 0; k < shader.textures.length; ++k) { - const texInfo: EffectAsset.ITextureInfo = shader.textures[k]; - const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, - ParameterType.TABLE, DescriptorTypeOrder.TEXTURE, texInfo.stageFlags, queueDB); - this.setDescriptor(targetBlock, texInfo.name, texInfo.type); - } - - for (let k = 0; k < shader.subpassInputs.length; ++k) { - const subpassInfo: EffectAsset.IInputAttachmentInfo = shader.subpassInputs[k]; - const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, - ParameterType.TABLE, DescriptorTypeOrder.INPUT_ATTACHMENT, subpassInfo.stageFlags, queueDB); - this.setDescriptor(targetBlock, subpassInfo.name, Type.SUBPASS_INPUT); - } - - // Add queue layout from define.ts - const localUniformTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_INSTANCE, - ParameterType.TABLE, DescriptorTypeOrder.UNIFORM_BUFFER, ShaderStageFlagBit.VERTEX, queueDB); - const localLightTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, - ParameterType.TABLE, DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER, ShaderStageFlagBit.FRAGMENT, queueDB); - const localUITarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_INSTANCE, - ParameterType.TABLE, DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER, ShaderStageFlagBit.VERTEX, queueDB); - const localModelTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_INSTANCE, - ParameterType.TABLE, DescriptorTypeOrder.UNIFORM_BUFFER, ShaderStageFlagBit.VERTEX | ShaderStageFlagBit.COMPUTE, queueDB); - const localSamplerVertTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, - ParameterType.TABLE, DescriptorTypeOrder.SAMPLER_TEXTURE, ShaderStageFlagBit.VERTEX, queueDB); - const localSamplerFragTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, - ParameterType.TABLE, DescriptorTypeOrder.SAMPLER_TEXTURE, ShaderStageFlagBit.FRAGMENT, queueDB); - const localSamplerCompTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, - ParameterType.TABLE, DescriptorTypeOrder.SAMPLER_TEXTURE, ShaderStageFlagBit.COMPUTE, queueDB); - - for (let k = 0; k < shader.builtins.locals.blocks.length; ++k) { - const blockName: string = shader.builtins.locals.blocks[k].name; - if (blockName === 'CCMorph') { - const morphDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOMorph.BINDING, 'CCMorph', localUniformTarget); - this.setUniform(morphDB, 'cc_displacementWeights', Type.FLOAT4, UBOMorph.MAX_MORPH_TARGET_COUNT / 4); - this.setUniform(morphDB, 'cc_displacementTextureInfo', Type.FLOAT4, 1); - } else if (blockName === 'CCSkinningTexture') { - const skinningTexDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOSkinningTexture.BINDING, 'CCSkinningTexture', localUniformTarget); - this.setUniform(skinningTexDB, 'cc_jointTextureInfo', Type.FLOAT4, 1); - } else if (blockName === 'CCSkinningAnimation') { - const skinningAnimDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOSkinningAnimation.BINDING, 'CCSkinningAnimation', localUniformTarget); - this.setUniform(skinningAnimDB, 'cc_jointAnimInfo', Type.FLOAT4, 1); - } else if (blockName === 'CCSkinning') { - const skinningDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOSkinning.BINDING, 'CCSkinning', localUniformTarget); - this.setUniform(skinningDB, 'cc_joints', Type.FLOAT4, JOINT_UNIFORM_CAPACITY * 3); - } else if (blockName === 'CCUILocal') { - const uiDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOUILocal.BINDING, 'CCUILocal', localUITarget); - this.setUniform(uiDB, 'cc_local_data', Type.FLOAT4, 1); - } else if (blockName === 'CCForwardLight') { - const lightDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOForwardLight.BINDING, 'CCForwardLight', localLightTarget); - this.setUniform(lightDB, 'cc_lightPos', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS); - this.setUniform(lightDB, 'cc_lightColor', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS); - this.setUniform(lightDB, 'cc_lightSizeRangeAngle', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS); - this.setUniform(lightDB, 'cc_lightDir', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS); - } else if (blockName === 'CCLocal') { - const localDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOLocal.BINDING, 'CCLocal', localModelTarget); - this.setUniform(localDB, 'cc_matWorld', Type.MAT4, 1); - this.setUniform(localDB, 'cc_matWorldIT', Type.MAT4, 1); - this.setUniform(localDB, 'cc_lightingMapUVParam', Type.FLOAT4, 1); - } else if (blockName === 'CCLocalBatched') { - const batchDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOLocalBatched.BINDING, 'CCLocalBatched', localModelTarget); - this.setUniform(batchDB, 'cc_matWorlds', Type.MAT4, UBOLocalBatched.BATCHING_COUNT); - } else if (blockName === 'CCWorldBound') { - const boundDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOWorldBound.BINDING, 'CCWorldBound', localModelTarget); - this.setUniform(boundDB, 'cc_worldBoundCenter', Type.FLOAT4, 1); - this.setUniform(boundDB, 'cc_worldBoundHalfExtents', Type.FLOAT4, 1); - } - } - - for (let k = 0; k < shader.builtins.locals.samplerTextures.length; ++k) { - const samplerName: string = shader.builtins.locals.samplerTextures[k].name; - if (samplerName === 'cc_jointTexture') { - this.setDescriptor(localSamplerVertTarget, 'cc_jointTexture', Type.SAMPLER2D); - } else if (samplerName === 'cc_PositionDisplacements') { - this.setDescriptor(localSamplerVertTarget, 'cc_PositionDisplacements', Type.SAMPLER2D); - } else if (samplerName === 'cc_realtimeJoint') { - this.setDescriptor(localSamplerVertTarget, 'cc_realtimeJoint', Type.SAMPLER2D); - } else if (samplerName === 'cc_NormalDisplacements') { - this.setDescriptor(localSamplerVertTarget, 'cc_NormalDisplacements', Type.SAMPLER2D); - } else if (samplerName === 'cc_TangentDisplacements') { - this.setDescriptor(localSamplerVertTarget, 'cc_TangentDisplacements', Type.SAMPLER2D); - } else if (samplerName === 'cc_lightingMap') { - this.setDescriptor(localSamplerFragTarget, 'cc_lightingMap', Type.SAMPLER2D); - } else if (samplerName === 'cc_spriteTexture') { - this.setDescriptor(localSamplerFragTarget, 'cc_spriteTexture', Type.SAMPLER2D); - } else if (samplerName === 'cc_reflectionTexture') { - this.setDescriptor(localSamplerFragTarget, 'cc_reflectionTexture', Type.SAMPLER2D); - } else if (samplerName === 'cc_reflectionProbeCubemap') { - this.setDescriptor(localSamplerFragTarget, 'cc_reflectionProbeCubemap', Type.SAMPLER_CUBE); - } else if (samplerName === 'cc_reflectionProbePlanarMap') { - this.setDescriptor(localSamplerFragTarget, 'cc_reflectionProbePlanarMap', Type.SAMPLER2D); - } - } - - for (let k = 0; k < shader.builtins.locals.images.length; ++k) { - const imgName: string = shader.builtins.locals.images[k].name; - if (imgName === 'cc_reflectionStorage') { - this.setDescriptor(localSamplerCompTarget, 'cc_reflectionStorage', Type.IMAGE2D); - } - } - - dbsMap.set(shader.name, queueDB); - - this.merge(queueDB); - this.sort(queueDB); - - const parentDB: DescriptorDB = this._layoutGraph.getDescriptors(parent); - if (this.dbsToMerge.get(parentDB) === undefined) { - this.dbsToMerge.set(parentDB, []); - } - this.dbsToMerge.get(parentDB)?.push(queueDB); - } - - const pName = this._layoutGraph.getName(parent); - - for (let i = 0; i < asset.techniques.length; ++i) { - const tech = asset.techniques[i]; - for (let j = 0; j < tech.passes.length; ++j) { - const pass = tech.passes[j]; - const passPhase = pass.phase; - let phase = ''; - if (passPhase === undefined) { - phase = `${pName}_`; - } else if (typeof passPhase === 'number') { - phase = passPhase.toString(); - } else { - phase = passPhase; - } - const db2add = dbsMap.get(pass.program); - if (db2add) { - const v2add = this._layoutGraph.locate(`/${pName}/${phase}`); - if (v2add === 0xFFFFFFFF) { - const v = this.addRenderPhase(phase, parent); - const renderPhase = this._layoutGraph.getRenderPhase(v); - renderPhase.shaders.add(pass.program); - const dbStored = this._layoutGraph.getDescriptors(v); - for (const ee of db2add.blocks) { - const blockIndex = ee[0]; - const block = ee[1]; - const b2add = new DescriptorBlock(); - for (const dd of block.descriptors) { - b2add.descriptors.set(dd[0], dd[1]); - b2add.count++; - b2add.capacity++; - } - for (const uu of block.uniformBlocks) { - b2add.uniformBlocks.set(uu[0], uu[1]); - b2add.count++; - b2add.capacity++; - } - if (b2add.capacity > 0 || b2add.count > 0) { - dbStored.blocks.set(blockIndex, b2add); - } - } - } else { - const dbStored = this._layoutGraph.getDescriptors(v2add); - for (const ee of db2add.blocks) { - const blockIndex = ee[0]; - const block = ee[1]; - const blockStored = dbStored.blocks.get(blockIndex); - if (blockStored === undefined) { - const b2add = new DescriptorBlock(); - for (const dd of block.descriptors) { - b2add.descriptors.set(dd[0], dd[1]); - b2add.count++; - b2add.capacity++; - } - for (const uu of block.uniformBlocks) { - b2add.uniformBlocks.set(uu[0], uu[1]); - b2add.count++; - b2add.capacity++; - } - if (b2add.capacity > 0 || b2add.count > 0) { - dbStored.blocks.set(blockIndex, b2add); - } - } else { - const index = JSON.parse(blockIndex) as DescriptorBlockIndex; - if (index.descriptorType !== DescriptorTypeOrder.UNIFORM_BUFFER && index.descriptorType !== DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER) { - if (index.updateFrequency <= UpdateFrequency.PER_BATCH) { - let capacityToAdd = 0; - for (const dd of block.descriptors) { - capacityToAdd++; - } - if (capacityToAdd > blockStored.capacity) { - blockStored.capacity = capacityToAdd; - blockStored.count = capacityToAdd; - } - - let capacityStored = 0; - for (const dd of blockStored.descriptors) { - capacityStored++; - } - for (const dd of block.descriptors) { - if (blockStored.descriptors.get(dd[0]) === undefined /*&& capacityStored < capacityToAdd*/) { - blockStored.descriptors.set(dd[0], dd[1]); - capacityStored++; - } - } - } else { - for (const dd of block.descriptors) { - if (blockStored.descriptors.get(dd[0]) === undefined) { - blockStored.descriptors.set(dd[0], dd[1]); - blockStored.count++; - blockStored.capacity++; - } - } - } - } else if (index.descriptorType === DescriptorTypeOrder.UNIFORM_BUFFER || index.descriptorType === DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER) { - if (index.updateFrequency <= UpdateFrequency.PER_BATCH) { - let capacityToAdd = 0; - for (const uu of block.uniformBlocks) { - capacityToAdd++; - } - if (capacityToAdd > blockStored.capacity) { - blockStored.capacity = capacityToAdd; - blockStored.count = capacityToAdd; - } - - let capacityStored = 0; - for (const dd of blockStored.uniformBlocks) { - capacityStored++; - } - for (const uu of block.uniformBlocks) { - if (blockStored.uniformBlocks.get(uu[0]) === undefined /*&& capacityStored < capacityToAdd*/) { - blockStored.uniformBlocks.set(uu[0], uu[1]); - capacityStored++; - } - } - } else { - for (const uu of block.uniformBlocks) { - if (blockStored.uniformBlocks.get(uu[0]) === undefined) { - blockStored.uniformBlocks.set(uu[0], uu[1]); - blockStored.count++; - blockStored.capacity++; - } - } - } - } - } - } - } - } - } - } - } - - public addGlobal (vName: string, hasCCGlobal, hasCCCamera, hasCCShadow, hasCCCSM, hasShadowmap, hasEnv, hasDiffuse, hasSpot): number { - const passDB: DescriptorDB = new DescriptorDB(); - // Add pass layout from define.ts - const globalUniformTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, DescriptorTypeOrder.UNIFORM_BUFFER, ShaderStageFlagBit.ALL, passDB); - const globalSamplerTexTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, DescriptorTypeOrder.SAMPLER_TEXTURE, ShaderStageFlagBit.FRAGMENT, passDB); - - if (hasCCGlobal) { - const globalDB: UniformBlock = this.getUniformBlock(SetIndex.GLOBAL, - UBOGlobal.BINDING, 'CCGlobal', globalUniformTarget); - this.setUniform(globalDB, 'cc_time', Type.FLOAT4, 1); - this.setUniform(globalDB, 'cc_screenSize', Type.FLOAT4, 1); - this.setUniform(globalDB, 'cc_nativeSize', Type.FLOAT4, 1); - this.setUniform(globalDB, 'cc_debug_view_mode', Type.FLOAT, 4); - this.setUniform(globalDB, 'cc_debug_view_composite_pack_1', Type.FLOAT, 4); - this.setUniform(globalDB, 'cc_debug_view_composite_pack_2', Type.FLOAT, 4); - this.setUniform(globalDB, 'cc_debug_view_composite_pack_3', Type.FLOAT, 4); - this.setDescriptor(globalUniformTarget, 'CCGlobal', Type.UNKNOWN); - } - - if (hasCCCamera) { - const cameraDB: UniformBlock = this.getUniformBlock(SetIndex.GLOBAL, - UBOCamera.BINDING, 'CCCamera', globalUniformTarget); - this.setUniform(cameraDB, 'cc_matView', Type.MAT4, 1); - this.setUniform(cameraDB, 'cc_matViewInv', Type.MAT4, 1); - this.setUniform(cameraDB, 'cc_matProj', Type.MAT4, 1); - this.setUniform(cameraDB, 'cc_matProjInv', Type.MAT4, 1); - this.setUniform(cameraDB, 'cc_matViewProj', Type.MAT4, 1); - this.setUniform(cameraDB, 'cc_matViewProjInv', Type.MAT4, 1); - this.setUniform(cameraDB, 'cc_cameraPos', Type.FLOAT4, 1); - this.setUniform(cameraDB, 'cc_surfaceTransform', Type.FLOAT4, 1); - this.setUniform(cameraDB, 'cc_screenScale', Type.FLOAT4, 1); - this.setUniform(cameraDB, 'cc_exposure', Type.FLOAT4, 1); - this.setUniform(cameraDB, 'cc_mainLitDir', Type.FLOAT4, 1); - this.setUniform(cameraDB, 'cc_mainLitColor', Type.FLOAT4, 1); - this.setUniform(cameraDB, 'cc_ambientSky', Type.FLOAT4, 1); - this.setUniform(cameraDB, 'cc_ambientGround', Type.FLOAT4, 1); - this.setUniform(cameraDB, 'cc_fogColor', Type.FLOAT4, 1); - this.setUniform(cameraDB, 'cc_fogBase', Type.FLOAT4, 1); - this.setUniform(cameraDB, 'cc_fogAdd', Type.FLOAT4, 1); - this.setUniform(cameraDB, 'cc_nearFar', Type.FLOAT4, 1); - this.setUniform(cameraDB, 'cc_viewPort', Type.FLOAT4, 1); - - this.setDescriptor(globalUniformTarget, 'CCCamera', Type.UNKNOWN); - } - - if (hasCCShadow) { - const shadowDB: UniformBlock = this.getUniformBlock(SetIndex.GLOBAL, - UBOShadow.BINDING, 'CCShadow', globalUniformTarget); - this.setUniform(shadowDB, 'cc_matLightView', Type.MAT4, 1); - this.setUniform(shadowDB, 'cc_matLightViewProj', Type.MAT4, 1); - this.setUniform(shadowDB, 'cc_shadowInvProjDepthInfo', Type.FLOAT4, 1); - this.setUniform(shadowDB, 'cc_shadowProjDepthInfo', Type.FLOAT4, 1); - this.setUniform(shadowDB, 'cc_shadowProjInfo', Type.FLOAT4, 1); - this.setUniform(shadowDB, 'cc_shadowNFLSInfo', Type.FLOAT4, 1); - this.setUniform(shadowDB, 'cc_shadowWHPBInfo', Type.FLOAT4, 1); - this.setUniform(shadowDB, 'cc_shadowLPNNInfo', Type.FLOAT4, 1); - this.setUniform(shadowDB, 'cc_shadowColor', Type.FLOAT4, 1); - this.setUniform(shadowDB, 'cc_planarNDInfo', Type.FLOAT4, 1); - - this.setDescriptor(globalUniformTarget, 'CCShadow', Type.UNKNOWN); - } - - if (hasCCCSM) { - const csmDB: UniformBlock = this.getUniformBlock(SetIndex.GLOBAL, - UBOCSM.BINDING, 'CCCSM', globalUniformTarget); - this.setUniform(csmDB, 'cc_csmViewDir0', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT); - this.setUniform(csmDB, 'cc_csmViewDir1', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT); - this.setUniform(csmDB, 'cc_csmViewDir2', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT); - this.setUniform(csmDB, 'cc_csmAtlas', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT); - this.setUniform(csmDB, 'cc_matCSMViewProj', Type.MAT4, UBOCSM.CSM_LEVEL_COUNT); - this.setUniform(csmDB, 'cc_csmProjDepthInfo', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT); - this.setUniform(csmDB, 'cc_csmProjInfo', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT); - this.setUniform(csmDB, 'cc_csmSplitsInfo', Type.FLOAT4, 1); - - this.setDescriptor(globalUniformTarget, 'CCCSM', Type.UNKNOWN); - } - - if (hasShadowmap) { - this.setDescriptor(globalSamplerTexTarget, 'cc_shadowMap', Type.SAMPLER2D); - } - if (hasEnv) { - this.setDescriptor(globalSamplerTexTarget, 'cc_environment', Type.SAMPLER_CUBE); - } - if (hasSpot) { - this.setDescriptor(globalSamplerTexTarget, 'cc_spotShadowMap', Type.SAMPLER2D); - } - if (hasDiffuse) { - this.setDescriptor(globalSamplerTexTarget, 'cc_diffuseMap', Type.SAMPLER_CUBE); - } - - this.merge(passDB); - this.sort(passDB); - - const vid = this._layoutGraph.addVertex( - LayoutGraphValue.RenderStage, RenderPassStage.DEFAULT, vName, passDB, - ); - - return vid; - } - - public mergeDescriptors (vid: number) { - const target: DescriptorDB = this._layoutGraph.getDescriptors(vid); - const toMerge = this.dbsToMerge.get(target); - if (toMerge !== undefined) { - this.mergeDBs(toMerge, target); - this.sort(target); - } - } - - public addRenderStage (name: string, stageID: number): number { - const passDB: DescriptorDB = new DescriptorDB(); - return this._layoutGraph.addVertex(LayoutGraphValue.RenderStage, - stageID, name, passDB); - } - - public addRenderPhase (name: string, parentStageID: number): number { - const passDB: DescriptorDB = new DescriptorDB(); - return this._layoutGraph.addVertex(LayoutGraphValue.RenderPhase, - new RenderPhase(), name, passDB, parentStageID); - } - - public _layoutGraph: LayoutGraph; - - public get layoutGraph () { - return this._layoutGraph; - } -} - -function getNumDescriptors (block: DescriptorBlock): number { - let count = 0; - for (const [, d] of block.descriptors) { - count += d.count; - } - return count; -} - -function checkDescriptorConsistency (lhs: Descriptor, rhs: Descriptor): boolean { - if (lhs.type !== rhs.type) { - return false; - } - if (lhs.count !== rhs.count) { - return false; - } - return true; -} - -export class CollectVisitor extends DefaultVisitor { - getFrequency (g: LayoutGraph, v: number): UpdateFrequency { - let freq: UpdateFrequency; - if (g.holds(LayoutGraphValue.RenderStage, v)) { - freq = UpdateFrequency.PER_PASS; - } else { - freq = UpdateFrequency.PER_PHASE; - } - return freq; - } - - mergeDescriptors (srcBlock: DescriptorBlock, dstBlock: DescriptorBlock): string { - for (const [name, src] of srcBlock.descriptors) { - const dst = dstBlock.descriptors.get(name); - if (dst !== undefined) { - if (!checkDescriptorConsistency(src, dst)) { - return `Descriptor ${name} is inconsistent`; - } - } else { - dstBlock.descriptors.set(name, src); - } - } - return ''; - } - - mergeParent (freq: UpdateFrequency, src: DescriptorDB, dst: DescriptorDB): string { - for (const [key, srcBlock] of src.blocks) { - let dstBlock = dst.blocks.get(key); - if (dstBlock === undefined) { - dstBlock = new DescriptorBlock(); - dst.blocks.set(key, dstBlock); - } - const index = JSON.parse(key) as DescriptorBlockIndex; - if (index.updateFrequency > freq) { - const error = this.mergeDescriptors(srcBlock, dstBlock); - if (error) { - return error; - } - } - } - return ''; - } - - updateInfo (freq: UpdateFrequency, db: DescriptorDB) { - db.blocks.forEach((block: DescriptorBlock, key: string) => { - const index = JSON.parse(key) as DescriptorBlockIndex; - if (index.updateFrequency >= freq) { - block.count = getNumDescriptors(block); - block.capacity = block.count; - } - }); - } - - backEdge (e: edge_descriptor, g: LayoutGraph): void { - this._error = 'Cycle detected in graph'; - } - - finishEdge (e: edge_descriptor, g: LayoutGraph): void { - if (this._error !== '') { - return; - } - const parentID = g.source(e); - const v = g.target(e); - const dst = g.getDescriptors(parentID); - const src = g.getDescriptors(v); - const freq = this.getFrequency(g, v); - this.mergeParent(freq, src, dst); - } - - finishVertex (v: number, g: LayoutGraph): void { - if (this._error !== '') { - return; - } - const freq = this.getFrequency(g, v); - const db = g.getDescriptors(v); - this.updateInfo(freq, db); - } - - get error (): string { - return this._error; - } - private _error = ''; -} diff --git a/cocos/rendering/custom/web-layout-graph.ts b/cocos/rendering/custom/web-layout-graph.ts deleted file mode 100644 index fdc01fa864..0000000000 --- a/cocos/rendering/custom/web-layout-graph.ts +++ /dev/null @@ -1,257 +0,0 @@ -/* - Copyright (c) 2022-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 { DEBUG } from 'internal:constants'; -import { EffectAsset } from '../../asset/assets'; -// eslint-disable-next-line max-len -import { DescriptorSetInfo, DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorSetLayoutInfo, DescriptorType, Device, ShaderStageFlagBit, Type, UniformBlock } from '../../gfx'; -import { VectorGraphColorMap } from './effect'; -import { depthFirstSearch } from './graph'; -// eslint-disable-next-line max-len -import { LayoutGraphData, PipelineLayoutData, LayoutGraphDataValue, RenderStageData, RenderPhaseData, DescriptorSetLayoutData, DescriptorSetData, DescriptorBlockData, DescriptorData, ShaderProgramData } from './layout-graph'; -import { LayoutGraphBuilder } from './pipeline'; -import { WebLayoutExporter } from './web-layout-exporter'; -import { DescriptorBlockIndex, DescriptorTypeOrder, - Descriptor, DescriptorBlockFlattened, UpdateFrequency } from './types'; -import { getGfxDescriptorType, PrintVisitor } from './layout-graph-utils'; - -export class WebLayoutGraphBuilder implements LayoutGraphBuilder { - private _data: LayoutGraphData; - private _device: Device | null; - private _exporter: WebLayoutExporter; - - constructor (deviceIn: Device | null, dataIn: LayoutGraphData) { - this._device = deviceIn; - this._data = dataIn; - this._exporter = new WebLayoutExporter(this); - } - - private createDescriptorInfo (layoutData: DescriptorSetLayoutData, info: DescriptorSetLayoutInfo) { - for (let i = 0; i < layoutData.descriptorBlocks.length; ++i) { - const block = layoutData.descriptorBlocks[i]; - let slot = block.offset; - for (let j = 0; j < block.descriptors.length; ++j) { - const d = block.descriptors[j]; - const binding: DescriptorSetLayoutBinding = new DescriptorSetLayoutBinding(); - binding.binding = slot; - binding.descriptorType = getGfxDescriptorType(block.type); - binding.count = d.count; - binding.stageFlags = block.visibility; - binding.immutableSamplers = []; - info.bindings.push(binding); - slot += d.count; - } - } - } - - private createDescriptorSetLayout (layoutData: DescriptorSetLayoutData) { - const info: DescriptorSetLayoutInfo = new DescriptorSetLayoutInfo(); - this.createDescriptorInfo(layoutData, info); - - if (this._device) { - return this._device.createDescriptorSetLayout(info); - } else { - return null; - } - } - - public clear (): void { - this._data.clear(); - } - - public addRenderStage (name: string): number { - return this._data.addVertex(LayoutGraphDataValue.RenderStage, - new RenderStageData(), name, - UpdateFrequency.PER_PASS, new PipelineLayoutData()); - } - - public addRenderPhase (name: string, parentID: number): number { - return this._data.addVertex(LayoutGraphDataValue.RenderPhase, - new RenderPhaseData(), name, - UpdateFrequency.PER_PHASE, new PipelineLayoutData(), - parentID); - } - - public addShader (name: string, parentPhaseID: number): void { - const phaseData = this._data.getRenderPhase(parentPhaseID); - const id = phaseData.shaderPrograms.length; - const shaderData = new ShaderProgramData(); - // 填充shaderData数据 - phaseData.shaderPrograms.push(shaderData); - phaseData.shaderIndex.set(name, id); - - // 注册shader所在的phase的ID - this._data.shaderLayoutIndex.set(name, parentPhaseID); - } - - public addDescriptorBlock (nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void { - const g: LayoutGraphData = this._data; - const ppl: PipelineLayoutData = g.getLayout(nodeID); - if (block.capacity <= 0) { - console.error('empty block'); - return; - } - if (block.descriptorNames.length !== block.descriptors.length) { - console.error('error descriptor'); - return; - } - if (block.uniformBlockNames.length !== block.uniformBlocks.length) { - console.error('error uniform'); - return; - } - let data: DescriptorSetData | undefined = ppl.descriptorSets.get(index.updateFrequency); - if (!data) { - data = new DescriptorSetData(new DescriptorSetLayoutData(), null, null); - ppl.descriptorSets.set(index.updateFrequency, data); - } - const layout = data.descriptorSetLayoutData; - - const dstBlock = new DescriptorBlockData(index.descriptorType, index.visibility, block.capacity); - layout.descriptorBlocks.push(dstBlock); - dstBlock.offset = layout.capacity; - dstBlock.capacity = block.capacity; - for (let j = 0; j < block.descriptors.length; ++j) { - const name: string = block.descriptorNames[j]; - const d: Descriptor = block.descriptors[j]; - let nameID: number | undefined = g.attributeIndex.get(name); - if (nameID === undefined) { - const id = g.valueNames.length; - g.attributeIndex.set(name, id); - g.valueNames.push(name); - } - - nameID = g.attributeIndex.get(name); - const data: DescriptorData = new DescriptorData(nameID); - data.count = d.count; - dstBlock.descriptors.push(data); - } - layout.capacity += block.capacity; - } - - public reorderDescriptorBlock (nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void { - const g: LayoutGraphData = this._data; - const ppl: PipelineLayoutData = g.getLayout(nodeID); - if (block.capacity <= 0) { - console.error('empty block'); - return; - } - if (block.descriptorNames.length !== block.descriptors.length) { - console.error('error descriptor'); - return; - } - if (block.uniformBlockNames.length !== block.uniformBlocks.length) { - console.error('error uniform'); - return; - } - let data: DescriptorSetData | undefined = ppl.descriptorSets.get(index.updateFrequency); - if (!data) { - data = new DescriptorSetData(new DescriptorSetLayoutData(), null, null); - ppl.descriptorSets.set(index.updateFrequency, data); - } - const layout = data.descriptorSetLayoutData; - - layout.descriptorBlocks.sort((a, b) => a.type - b.type); - - let cap = 0; - for (let i = 0; i < layout.descriptorBlocks.length; ++i) { - const block = layout.descriptorBlocks[i]; - block.offset = cap; - cap += block.capacity; - } - } - - public addUniformBlock (nodeID: number, index: DescriptorBlockIndex, name: string, uniformBlock: UniformBlock): void { - const g: LayoutGraphData = this._data; - const ppl: PipelineLayoutData = g.getLayout(nodeID); - const layout: DescriptorSetLayoutData | undefined = ppl.descriptorSets.get(index.updateFrequency)?.descriptorSetLayoutData; - if (layout !== undefined) { - let nameID: number | undefined = g.attributeIndex.get(name); - if (nameID === undefined) { - const id = g.valueNames.length; - g.attributeIndex.set(name, id); - g.valueNames.push(name); - } - - nameID = g.attributeIndex.get(name); - layout.uniformBlocks.set(nameID as number, uniformBlock); - } - } - - public reserveDescriptorBlock (nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void { - const g: LayoutGraphData = this._data; - const ppl: PipelineLayoutData = g.getLayout(nodeID); - if (block.capacity <= 0) { - console.error('empty block'); - return; - } - - const layout: DescriptorSetLayoutData | undefined = ppl.descriptorSets.get(index.updateFrequency)?.descriptorSetLayoutData; - if (layout !== undefined) { - layout.descriptorBlocks.push(new DescriptorBlockData(index.descriptorType, index.visibility, block.capacity)); - const dstBlock = layout.descriptorBlocks[layout.descriptorBlocks.length - 1]; - dstBlock.offset = layout.capacity; - dstBlock.capacity = block.capacity; - layout.capacity += block.capacity; - } else { - console.error('no layout'); - } - } - - public compile (): number { - const g: LayoutGraphData = this._data; - for (let i = 0; i < g._layouts.length; ++i) { - const ppl: PipelineLayoutData = g.getLayout(i); - ppl.descriptorSets.forEach((value, key) => { - const level = value; - const layoutData = level.descriptorSetLayoutData; - if (this._device) { - const layout: DescriptorSetLayout | null = this.createDescriptorSetLayout(layoutData); - if (layout) { - level.descriptorSetLayout = (layout); - level.descriptorSet = (this._device.createDescriptorSet(new DescriptorSetInfo(layout))); - } - } else { - this.createDescriptorInfo(layoutData, level.descriptorSetLayoutInfo); - } - }); - } - return 0; - } - - public print (): string { - const g: LayoutGraphData = this._data; - const visitor = new PrintVisitor(); - const colorMap = new VectorGraphColorMap(g.numVertices()); - depthFirstSearch(g, visitor, colorMap); - return visitor.oss; - } - - public get data () { - return this._data; - } - - public exportEffect (effect: EffectAsset) { - this._exporter.exportEffect(effect); - } -} diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index 2d013dda8a..897eec3586 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -24,26 +24,25 @@ /* eslint-disable max-len */ import { systemInfo } from 'pal/system-info'; -import { Color, Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, ClearFlagBit, DescriptorSet, deviceManager, Viewport, API, CommandBuffer, Type, SamplerInfo, Filter, Address } from '../../gfx'; +import { Color, Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, ClearFlagBit, DescriptorSet, deviceManager, Viewport, API, CommandBuffer, Type, SamplerInfo, Filter, Address, DescriptorSetInfo } from '../../gfx'; import { Mat4, Quat, toRadian, Vec2, Vec3, Vec4, assert, macro, cclegacy } from '../../core'; import { ComputeView, CopyPair, LightInfo, LightingMode, MovePair, QueueHint, RasterView, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; import { Blit, ClearView, ComputePass, CopyPass, Dispatch, ManagedResource, MovePass, RasterPass, RenderData, RenderGraph, RenderGraphComponent, RenderGraphValue, RenderQueue, RenderSwapchain, ResourceDesc, ResourceGraph, ResourceGraphValue, ResourceStates, ResourceTraits, SceneData } from './render-graph'; -import { ComputePassBuilder, ComputeQueueBuilder, CopyPassBuilder, LayoutGraphBuilder, MovePassBuilder, Pipeline, PipelineBuilder, RasterPassBuilder, RasterQueueBuilder, SceneTransversal } from './pipeline'; +import { ComputePassBuilder, ComputeQueueBuilder, CopyPassBuilder, MovePassBuilder, Pipeline, PipelineBuilder, RasterPassBuilder, RasterQueueBuilder, SceneTransversal } from './pipeline'; import { PipelineSceneData } from '../pipeline-scene-data'; import { Model, Camera, ShadowType, CSMLevel, DirectionalLight, SpotLight, PCFType, Shadows } from '../../render-scene/scene'; import { Light, LightType } from '../../render-scene/scene/light'; -import { DescriptorSetData, DescriptorSetLayoutData, LayoutGraphData } from './layout-graph'; +import { DescriptorSetData, LayoutGraphData } from './layout-graph'; import { Executor } from './executor'; import { RenderWindow } from '../../render-scene/core/render-window'; import { MacroRecord, RenderScene } from '../../render-scene'; import { GlobalDSManager } from '../global-descriptor-set-manager'; -import { supportsR32FloatTexture, UBOSkinning } from '../define'; +import { isEnableEffect, supportsR32FloatTexture, UBOSkinning } from '../define'; import { OS } from '../../../pal/system-info/enum-type'; import { Compiler } from './compiler'; import { PipelineUBO } from '../pipeline-ubo'; import { builtinResMgr } from '../../asset/asset-manager'; import { Texture2D } from '../../asset/assets/texture-2d'; -import { WebLayoutGraphBuilder } from './web-layout-graph'; import { GeometryRenderer } from '../geometry-renderer'; import { Material, TextureCube } from '../../asset/assets'; import { DeferredPipelineBuilder, ForwardPipelineBuilder } from './builtin-pipelines'; @@ -52,6 +51,7 @@ import { decideProfilerCamera } from '../pipeline-funcs'; import { DebugViewCompositeType } from '../debug-view'; import { getUBOTypeCount } from './utils'; import { initGlobalDescBinding } from './define'; +import { createGfxDescriptorSetsAndPipelines } from './layout-graph-utils'; export class WebSetter { constructor (data: RenderData, lg: LayoutGraphData) { @@ -85,6 +85,7 @@ export class WebSetter { protected _getUniformOffset (name: string, type: Type, idx = 0) { const currBlock = this._getCurrUniformBlock(); + if (!currBlock) return -1; let offset = 0; const typeCount = getUBOTypeCount(type); for (const uniform of currBlock.members) { @@ -110,7 +111,22 @@ export class WebSetter { const ppl = this._lg.getLayout(nodeId); const layout = ppl.descriptorSets.get(UpdateFrequency.PER_PASS)!.descriptorSetLayoutData; const nameID: number = this._lg.attributeIndex.get(block)!; - return layout.uniformBlocks.get(nameID)!; + return layout.uniformBlocks.get(nameID); + } + + protected _getCurrDescriptorBlock (block: string) { + const nodeId = this._lg.locateChild(0xFFFFFFFF, this._currStage); + const ppl = this._lg.getLayout(nodeId); + const layout = ppl.descriptorSets.get(UpdateFrequency.PER_PASS)!.descriptorSetLayoutData; + const nameID: number = this._lg.attributeIndex.get(block)!; + for (const block of layout.descriptorBlocks) { + for (let i = 0; i !== block.descriptors.length; ++i) { + if (nameID === block.descriptors[i].descriptorID) { + return block.offset + i; + } + } + } + return -1; } setCurrConstant (block: string, stage = 'default') { @@ -119,10 +135,12 @@ export class WebSetter { const nameID: number = this._lg.attributeIndex.get(block)!; this._currCount = 0; const currBlock = this._getCurrUniformBlock(); + if (!currBlock) return false; for (const uniform of currBlock.members) { this._currCount += getUBOTypeCount(uniform.type) * uniform.count; } this._currConstant = this._data.constants.get(nameID)!; + return true; } getCurrConstant () { @@ -135,6 +153,7 @@ export class WebSetter { const num = this._lg.attributeIndex.get(block)!; this._currCount = 0; const currBlock = this._getCurrUniformBlock(); + if (!currBlock) return false; for (const uniform of currBlock.members) { this._currCount += getUBOTypeCount(uniform.type) * uniform.count; } @@ -144,6 +163,7 @@ export class WebSetter { this._data.constants.set(num, value); } this.setCurrConstant(block); + return true; } public setMat4 (name: string, mat: Mat4, idx = 0): void { this._applyCurrConstantBuffer(name, mat, Type.MAT4, idx); @@ -165,15 +185,35 @@ export class WebSetter { } public setBuffer (name: string, buffer: Buffer): void {} public setTexture (name: string, texture: Texture): void { + if (this._getCurrDescriptorBlock(name) === -1) { + return; + } const num = this._lg.attributeIndex.get(name)!; this._data.textures.set(num, texture); } public setReadWriteBuffer (name: string, buffer: Buffer): void {} public setReadWriteTexture (name: string, texture: Texture): void {} public setSampler (name: string, sampler: Sampler): void { + if (this._getCurrDescriptorBlock(name) === -1) { + return; + } const num = this._lg.attributeIndex.get(name)!; this._data.samplers.set(num, sampler); } + public hasSampler (name: string): boolean { + const id = this._lg.attributeIndex.get(name); + if (id === undefined) { + return false; + } + return this._data.samplers.has(id); + } + public hasTexture (name: string): boolean { + const id = this._lg.attributeIndex.get(name); + if (id === undefined) { + return false; + } + return this._data.textures.has(id); + } // protected protected readonly _data: RenderData; @@ -185,8 +225,10 @@ export class WebSetter { } function setShadowUBOLightView (setter: WebSetter, + camera: Camera, light: Light, - level: number) { + level: number, + layout = 'default') { const director = cclegacy.director; const pipeline = director.root.pipeline; const device = pipeline.device; @@ -196,9 +238,17 @@ function setShadowUBOLightView (setter: WebSetter, const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; const cap = pipeline.device.capabilities; const _vec4ShadowInfo = new Vec4(); - setter.addConstant('CCCSM'); + setter.addConstant('CCCSM', layout); // ShadowMap - setter.addConstant('CCShadow'); + if (!setter.addConstant('CCShadow', layout)) return; + if (shadowInfo.enabled) { + if (shadowInfo.type === ShadowType.ShadowMap) { + // update CSM layers + if (light && light.node) { + csmLayers.update(sceneData, camera); + } + } + } switch (light.type) { case LightType.DIRECTIONAL: { const mainLight = light as DirectionalLight; @@ -279,8 +329,8 @@ function setShadowUBOLightView (setter: WebSetter, } default: } - setter.setColor('cc_shadowColor', new Color(shadowInfo.shadowColor.r, shadowInfo.shadowColor.g, - shadowInfo.shadowColor.b, shadowInfo.shadowColor.a)); + setter.setColor('cc_shadowColor', new Color(shadowInfo.shadowColor.x, shadowInfo.shadowColor.y, + shadowInfo.shadowColor.z, shadowInfo.shadowColor.w)); } function getPCFRadius (shadowInfo: Shadows, mainLight: DirectionalLight): number { @@ -299,7 +349,7 @@ function getPCFRadius (shadowInfo: Shadows, mainLight: DirectionalLight): number return 0.0; } -function setShadowUBOView (setter: WebSetter, camera: Camera) { +function setShadowUBOView (setter: WebSetter, camera: Camera, layout = 'default') { const director = cclegacy.director; const pipeline = director.root.pipeline; const device = pipeline.device; @@ -310,89 +360,99 @@ function setShadowUBOView (setter: WebSetter, camera: Camera) { const csmSupported = sceneData.csmSupported; const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; const _vec4ShadowInfo = new Vec4(); - setter.addConstant('CCShadow'); - setter.addConstant('CCCSM'); + const hasCCShadow = setter.addConstant('CCShadow', layout); + const hasCCCSM = setter.addConstant('CCCSM', layout); if (mainLight && shadowInfo.enabled) { if (shadowInfo.type === ShadowType.ShadowMap) { if (mainLight.shadowEnabled) { if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !csmSupported) { - setter.setCurrConstant('CCShadow'); - const matShadowView = csmLayers.specialLayer.matShadowView; - const matShadowProj = csmLayers.specialLayer.matShadowProj; - const matShadowViewProj = csmLayers.specialLayer.matShadowViewProj; - const near = mainLight.shadowNear; - const far = mainLight.shadowFar; + if (hasCCShadow) { + setter.setCurrConstant('CCShadow', layout); + const matShadowView = csmLayers.specialLayer.matShadowView; + const matShadowProj = csmLayers.specialLayer.matShadowProj; + const matShadowViewProj = csmLayers.specialLayer.matShadowViewProj; + const near = mainLight.shadowNear; + const far = mainLight.shadowFar; - setter.setMat4('cc_matLightView', matShadowView); - setter.setVec4('cc_shadowProjDepthInfo', new Vec4(matShadowProj.m10, matShadowProj.m14, - matShadowProj.m11, matShadowProj.m15)); + setter.setMat4('cc_matLightView', matShadowView); + setter.setVec4('cc_shadowProjDepthInfo', new Vec4(matShadowProj.m10, matShadowProj.m14, + matShadowProj.m11, matShadowProj.m15)); - setter.setVec4('cc_shadowProjInfo', new Vec4(matShadowProj.m00, matShadowProj.m05, - 1.0 / matShadowProj.m00, 1.0 / matShadowProj.m05)); - setter.setMat4('cc_matLightViewProj', matShadowViewProj); - _vec4ShadowInfo.set(near, far, 0, 1.0 - mainLight.shadowSaturation); - setter.setVec4('cc_shadowNFLSInfo', _vec4ShadowInfo); - _vec4ShadowInfo.set(0.0, packing, mainLight.shadowNormalBias, 0); - setter.setVec4('cc_shadowLPNNInfo', _vec4ShadowInfo); - } else { - const layerThreshold = getPCFRadius(shadowInfo, mainLight); - setter.setCurrConstant('CCCSM'); - for (let i = 0; i < mainLight.csmLevel; i++) { - const matShadowView = csmLayers.layers[i].matShadowView; - _vec4ShadowInfo.set(matShadowView.m00, matShadowView.m04, matShadowView.m08, layerThreshold); - setter.setVec4('cc_csmViewDir0', _vec4ShadowInfo, i); - _vec4ShadowInfo.set(matShadowView.m01, matShadowView.m05, matShadowView.m09, 0.0); - setter.setVec4('cc_csmViewDir1', _vec4ShadowInfo, i); - _vec4ShadowInfo.set(matShadowView.m02, matShadowView.m06, matShadowView.m10, 0.0); - setter.setVec4('cc_csmViewDir2', _vec4ShadowInfo, i); - - const csmAtlas = csmLayers.layers[i].csmAtlas; - setter.setVec4('cc_csmAtlas', csmAtlas, i); - - setter.setFloat('cc_csmSplitsInfo', csmLayers.layers[i].splitCameraFar / mainLight.shadowDistance, i); - const matShadowViewProj = csmLayers.layers[i].matShadowViewProj; - setter.setMat4('cc_matCSMViewProj', matShadowViewProj, i); - - const matShadowProj = csmLayers.layers[i].matShadowProj; - setter.setVec4('cc_csmProjDepthInfo', new Vec4(matShadowProj.m10, - matShadowProj.m14, matShadowProj.m11, matShadowProj.m15), i); - - setter.setVec4('cc_csmProjInfo', new Vec4(matShadowProj.m00, - matShadowProj.m05, 1.0 / matShadowProj.m00, 1.0 / matShadowProj.m05), i); + setter.setVec4('cc_shadowProjInfo', new Vec4(matShadowProj.m00, matShadowProj.m05, + 1.0 / matShadowProj.m00, 1.0 / matShadowProj.m05)); + setter.setMat4('cc_matLightViewProj', matShadowViewProj); + _vec4ShadowInfo.set(near, far, 0, 1.0 - mainLight.shadowSaturation); + setter.setVec4('cc_shadowNFLSInfo', _vec4ShadowInfo); + _vec4ShadowInfo.set(0.0, packing, mainLight.shadowNormalBias, 0); + setter.setVec4('cc_shadowLPNNInfo', _vec4ShadowInfo); + } + } else { + if (hasCCCSM) { + const layerThreshold = getPCFRadius(shadowInfo, mainLight); + setter.setCurrConstant('CCCSM', layout); + for (let i = 0; i < mainLight.csmLevel; i++) { + const matShadowView = csmLayers.layers[i].matShadowView; + _vec4ShadowInfo.set(matShadowView.m00, matShadowView.m04, matShadowView.m08, layerThreshold); + setter.setVec4('cc_csmViewDir0', _vec4ShadowInfo, i); + _vec4ShadowInfo.set(matShadowView.m01, matShadowView.m05, matShadowView.m09, 0.0); + setter.setVec4('cc_csmViewDir1', _vec4ShadowInfo, i); + _vec4ShadowInfo.set(matShadowView.m02, matShadowView.m06, matShadowView.m10, 0.0); + setter.setVec4('cc_csmViewDir2', _vec4ShadowInfo, i); + + const csmAtlas = csmLayers.layers[i].csmAtlas; + setter.setVec4('cc_csmAtlas', csmAtlas, i); + + setter.setFloat('cc_csmSplitsInfo', csmLayers.layers[i].splitCameraFar / mainLight.shadowDistance, i); + const matShadowViewProj = csmLayers.layers[i].matShadowViewProj; + setter.setMat4('cc_matCSMViewProj', matShadowViewProj, i); + + const matShadowProj = csmLayers.layers[i].matShadowProj; + setter.setVec4('cc_csmProjDepthInfo', new Vec4(matShadowProj.m10, + matShadowProj.m14, matShadowProj.m11, matShadowProj.m15), i); + + setter.setVec4('cc_csmProjInfo', new Vec4(matShadowProj.m00, + matShadowProj.m05, 1.0 / matShadowProj.m00, 1.0 / matShadowProj.m05), i); + } + } + if (hasCCShadow) { + setter.setCurrConstant('CCShadow', layout); + _vec4ShadowInfo.set(0, 0, 0, 1.0 - mainLight.shadowSaturation); + setter.setVec4('cc_shadowNFLSInfo', _vec4ShadowInfo); + _vec4ShadowInfo.set(0.0, packing, mainLight.shadowNormalBias, mainLight.csmLevel); + setter.setVec4('cc_shadowLPNNInfo', _vec4ShadowInfo); } - setter.setCurrConstant('CCShadow'); - _vec4ShadowInfo.set(0, 0, 0, 1.0 - mainLight.shadowSaturation); - setter.setVec4('cc_shadowNFLSInfo', _vec4ShadowInfo); - _vec4ShadowInfo.set(0.0, packing, mainLight.shadowNormalBias, mainLight.csmLevel); - setter.setVec4('cc_shadowLPNNInfo', _vec4ShadowInfo); } - setter.setCurrConstant('CCShadow'); - _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, mainLight.shadowPcf, mainLight.shadowBias); - setter.setVec4('cc_shadowWHPBInfo', _vec4ShadowInfo); + if (hasCCShadow) { + setter.setCurrConstant('CCShadow', layout); + _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, mainLight.shadowPcf, mainLight.shadowBias); + setter.setVec4('cc_shadowWHPBInfo', _vec4ShadowInfo); + } } - } else { - setter.setCurrConstant('CCShadow'); + } else if (hasCCShadow) { + setter.setCurrConstant('CCShadow', layout); const _tempVec3 = new Vec3(); Vec3.normalize(_tempVec3, shadowInfo.normal); setter.setVec4('cc_planarNDInfo', new Vec4(_tempVec3.x, _tempVec3.y, _tempVec3.z, -shadowInfo.distance)); } - setter.setCurrConstant('CCShadow'); - setter.setColor('cc_shadowColor', shadowInfo.shadowColor); + if (hasCCShadow) { + setter.setCurrConstant('CCShadow', layout); + setter.setColor('cc_shadowColor', shadowInfo.shadowColor); + } } } function setCameraUBOValues (setter: WebSetter, camera: Readonly, cfg: Readonly, - scene: Readonly) { + scene: Readonly, + layoutName = 'default') { const director = cclegacy.director; const root = director.root; const pipeline = root.pipeline as WebPipeline; - const layoutGraph = pipeline.layoutGraph; const shadowInfo = cfg.shadows; const skybox = cfg.skybox; const shadingScale = cfg.shadingScale; // Camera - setter.addConstant('CCCamera'); + if (!setter.addConstant('CCCamera', layoutName)) return; setter.setMat4('cc_matView', camera.matView); setter.setMat4('cc_matViewInv', camera.node.worldMatrix); setter.setMat4('cc_matProj', camera.matProj); @@ -445,7 +505,7 @@ function setCameraUBOValues (setter: WebSetter, setter.setVec4('cc_viewPort', new Vec4(camera.viewport.x, camera.viewport.y, shadingScale * camera.window.width * camera.viewport.z, shadingScale * camera.window.height * camera.viewport.w)); } -function setTextureUBOView (setter: WebSetter, camera: Camera, cfg: Readonly) { +function setTextureUBOView (setter: WebSetter, camera: Camera, cfg: Readonly, layout = 'default') { const skybox = cfg.skybox; const director = cclegacy.director; const root = director.root; @@ -478,11 +538,20 @@ function setTextureUBOView (setter: WebSetter, camera: Camera, cfg: Readonly('default-texture').getGFXTexture()!); - setter.setSampler('cc_spotShadowMap', pointSampler); - setter.setTexture('cc_spotShadowMap', builtinResMgr.get('default-texture').getGFXTexture()!); + if (!setter.hasSampler('cc_shadowMap')) { + setter.setSampler('cc_shadowMap', pointSampler); + } + if (!setter.hasTexture('cc_shadowMap')) { + setter.setTexture('cc_shadowMap', builtinResMgr.get('default-texture').getGFXTexture()!); + } + if (!setter.hasSampler('cc_spotShadowMap')) { + setter.setSampler('cc_spotShadowMap', pointSampler); + } + if (!setter.hasTexture('cc_spotShadowMap')) { + setter.setTexture('cc_spotShadowMap', builtinResMgr.get('default-texture').getGFXTexture()!); + } } function getFirstChildLayoutName (lg: LayoutGraphData, parentID: number): string { @@ -510,21 +579,30 @@ export class WebRasterQueueBuilder extends WebSetter implements RasterQueueBuild set name (name: string) { this._renderGraph.setName(this._vertID, name); } + + getLayoutName () { + const parId = this._renderGraph.getParent(this._vertID); + const layoutName = isEnableEffect() ? this._renderGraph.getLayout(parId) : 'default'; + return layoutName; + } + addSceneOfCamera (camera: Camera, light: LightInfo, sceneFlags = SceneFlags.NONE, name = 'Camera'): void { const sceneData = new SceneData(name, sceneFlags, light); sceneData.camera = camera; this._renderGraph.addVertex( RenderGraphValue.Scene, sceneData, name, '', new RenderData(), false, this._vertID, ); + const layoutName = this.getLayoutName(); setCameraUBOValues(this, camera, this._pipeline, - camera.scene ? camera.scene : cclegacy.director.getScene().renderScene); + camera.scene ? camera.scene : cclegacy.director.getScene().renderScene, + layoutName); if (sceneFlags & SceneFlags.SHADOW_CASTER) { - setShadowUBOLightView(this, light.light!, light.level); + setShadowUBOLightView(this, camera, light.light!, light.level, layoutName); } else { - setShadowUBOView(this, camera); + setShadowUBOView(this, camera, layoutName); } setTextureUBOView(this, camera, this._pipeline); - initGlobalDescBinding(cclegacy.director.root.pipeline, this._data); + initGlobalDescBinding(this._data, layoutName); } addScene (sceneName: string, sceneFlags = SceneFlags.NONE): void { const sceneData = new SceneData(sceneName, sceneFlags); @@ -543,15 +621,16 @@ export class WebRasterQueueBuilder extends WebSetter implements RasterQueueBuild RenderGraphValue.Blit, new Blit(material, passID, sceneFlags, camera), 'CameraQuad', '', new RenderData(), false, this._vertID, ); + const layoutName = this.getLayoutName(); setCameraUBOValues(this, camera, this._pipeline, - camera.scene ? camera.scene : cclegacy.director.getScene().renderScene); + camera.scene ? camera.scene : cclegacy.director.getScene().renderScene, layoutName); if (sceneFlags & SceneFlags.SHADOW_CASTER) { // setShadowUBOLightView(this, light.light!, light.level); } else { - setShadowUBOView(this, camera); + setShadowUBOView(this, camera, layoutName); } setTextureUBOView(this, camera, this._pipeline); - initGlobalDescBinding(cclegacy.director.root.pipeline, this._data); + initGlobalDescBinding(this._data, layoutName); } clearRenderTarget (name: string, color: Color = new Color()) { this._renderGraph.addVertex( @@ -642,6 +721,12 @@ export class WebRasterPassBuilder extends WebSetter implements RasterPassBuilder setViewport (viewport: Viewport): void { this._pass.viewport.copy(viewport); } + get showStatistics (): boolean { + return this._pass.showStatistics; + } + set showStatistics (enable: boolean) { + this._pass.showStatistics = enable; + } private readonly _renderGraph: RenderGraph; private readonly _vertID: number; private readonly _layoutID: number; @@ -868,11 +953,12 @@ export class WebPipeline implements Pipeline { public activate (swapchain: Swapchain): boolean { this._device = deviceManager.gfxDevice; - this.layoutGraphBuilder.compile(); + createGfxDescriptorSetsAndPipelines(this._device, this._layoutGraph); this._globalDSManager = new GlobalDSManager(this._device); this._globalDescSetData = this.getGlobalDescriptorSetData()!; this._globalDescriptorSetLayout = this._globalDescSetData.descriptorSetLayout; - this._globalDescriptorSet = this._globalDescSetData.descriptorSet!; + this._globalDescriptorSet = isEnableEffect() ? this._device.createDescriptorSet(new DescriptorSetInfo(this._globalDescriptorSetLayout!)) + : this._globalDescSetData.descriptorSet; this._globalDSManager.globalDescriptorSet = this.globalDescriptorSet; this.setMacroBool('CC_USE_HDR', this._pipelineSceneData.isHDR); this._generateConstantMacros(false); @@ -928,9 +1014,6 @@ export class WebPipeline implements Pipeline { public set lightingMode (mode: LightingMode) { this._lightingMode = mode; } - public get layoutGraphBuilder (): LayoutGraphBuilder { - return new WebLayoutGraphBuilder(this._device, this._layoutGraph); - } public get usesDeferredPipeline (): boolean { return this._usesDeferredPipeline; } @@ -1152,8 +1235,8 @@ export class WebPipeline implements Pipeline { RenderGraphValue.Raster, pass, name, layoutName, data, false, ); const result = new WebRasterPassBuilder(data, this._renderGraph!, this._layoutGraph, vertID, pass, this._pipelineSceneData); - this._updateRasterPassConstants(result, width, height); - initGlobalDescBinding(cclegacy.director.root.pipeline, data); + this._updateRasterPassConstants(result, width, height, isEnableEffect() ? layoutName : 'default'); + initGlobalDescBinding(data, layoutName); return result; } public getDescriptorSetLayout (shaderName: string, freq: UpdateFrequency): DescriptorSetLayout { @@ -1173,7 +1256,7 @@ export class WebPipeline implements Pipeline { return this._layoutGraph; } - protected _updateRasterPassConstants (setter: WebSetter, width: number, height: number) { + protected _updateRasterPassConstants (setter: WebSetter, width: number, height: number, layoutName = 'default') { const director = cclegacy.director; const root = director.root; const shadingWidth = width; @@ -1181,7 +1264,7 @@ export class WebPipeline implements Pipeline { const pipeline = root.pipeline as WebPipeline; const layoutGraph = pipeline.layoutGraph; // Global - setter.addConstant('CCGlobal'); + if (!setter.addConstant('CCGlobal', layoutName)) return; setter.setVec4('cc_time', new Vec4(root.cumulativeTime, root.frameTime, director.getTotalFrames())); setter.setVec4('cc_screenSize', new Vec4(shadingWidth, shadingHeight, 1.0 / shadingWidth, 1.0 / shadingHeight)); setter.setVec4('cc_nativeSize', new Vec4(shadingWidth, shadingHeight, 1.0 / shadingWidth, 1.0 / shadingHeight)); diff --git a/cocos/rendering/custom/web-program-library.ts b/cocos/rendering/custom/web-program-library.ts index 4f7873baab..51e720e141 100644 --- a/cocos/rendering/custom/web-program-library.ts +++ b/cocos/rendering/custom/web-program-library.ts @@ -24,17 +24,18 @@ /* eslint-disable max-len */ import { EffectAsset } from '../../asset/assets'; -import { Attribute, DescriptorSetLayout, DESCRIPTOR_BUFFER_TYPE, DESCRIPTOR_SAMPLER_TYPE, Device, MemoryAccessBit, PipelineLayout, PipelineLayoutInfo, Shader, ShaderInfo, ShaderStage, ShaderStageFlagBit, Type, Uniform, UniformBlock, UniformInputAttachment, UniformSampler, UniformSamplerTexture, UniformStorageBuffer, UniformStorageImage, UniformTexture } from '../../gfx'; +import { Attribute, DescriptorSetLayout, DescriptorType, DESCRIPTOR_BUFFER_TYPE, DESCRIPTOR_SAMPLER_TYPE, Device, MemoryAccessBit, PipelineLayout, PipelineLayoutInfo, Shader, ShaderInfo, ShaderStage, ShaderStageFlagBit, Type, Uniform, UniformBlock, UniformInputAttachment, UniformSampler, UniformSamplerTexture, UniformStorageBuffer, UniformStorageImage, UniformTexture } from '../../gfx'; import { genHandles, getActiveAttributes, getCombinationDefines, getShaderInstanceName, getSize, getVariantKey, populateMacros, prepareDefines } from '../../render-scene/core/program-utils'; import { getDeviceShaderVersion, MacroRecord } from '../../render-scene'; import { IProgramInfo } from '../../render-scene/core/program-lib'; import { DescriptorBlockData, DescriptorData, DescriptorSetData, DescriptorSetLayoutData, LayoutGraphData, LayoutGraphDataValue, PipelineLayoutData, RenderPhaseData, ShaderProgramData } from './layout-graph'; import { ProgramLibrary, ProgramProxy } from './private'; import { DescriptorTypeOrder, UpdateFrequency } from './types'; -import { ProgramGroup, ProgramHost, ProgramInfo } from './web-types'; +import { ProgramGroup, ProgramInfo } from './web-types'; import { getCustomPassID, getCustomPhaseID, getOrCreateDescriptorSetLayout, getEmptyDescriptorSetLayout, getEmptyPipelineLayout, initializeDescriptorSetLayoutInfo, makeDescriptorSetLayoutData, getDescriptorSetLayout, getOrCreateDescriptorID, getDescriptorTypeOrder, getProgramID, getDescriptorNameID, getDescriptorName, INVALID_ID } from './layout-graph-utils'; import { assert } from '../../core/platform/debug'; import { IDescriptorSetLayoutInfo, localDescriptorSetLayout } from '../define'; +import { PipelineRuntime } from './pipeline'; const _setIndex = [2, 1, 3, 0]; @@ -339,56 +340,110 @@ function populateLocalShaderInfo ( } } -function setFlattenedBinding (setOffsets: number[], - descriptors: UniformBlock[] - | UniformSamplerTexture[] +function getIDescriptorSetLayoutInfoUniformBlockCapacity (info: IDescriptorSetLayoutInfo): number { + let capacity = 0; + for (const binding of info.bindings) { + if (binding.descriptorType === DescriptorType.UNIFORM_BUFFER + || binding.descriptorType === DescriptorType.DYNAMIC_UNIFORM_BUFFER) { + capacity += binding.count; + } + } + return capacity; +} + +function getIDescriptorSetLayoutInfoSamplerTextureCapacity (info: IDescriptorSetLayoutInfo): number { + let capacity = 0; + for (const binding of info.bindings) { + if (binding.descriptorType !== DescriptorType.UNIFORM_BUFFER + && binding.descriptorType !== DescriptorType.DYNAMIC_UNIFORM_BUFFER) { + capacity += binding.count; + } + } + return capacity; +} + +function setFlattenedUniformBlockBinding (setOffsets: number[], + descriptors: UniformBlock[]) { + for (const d of descriptors) { + d.flattened = setOffsets[d.set] + d.binding; + } +} + +function setFlattenedSamplerTextureBinding (setOffsets: number[], + uniformBlockCapacities: number[], + descriptors: UniformSamplerTexture[] | UniformSampler[] | UniformTexture[] | UniformStorageBuffer[] | UniformStorageImage[] | UniformInputAttachment[]) { for (const d of descriptors) { - d.flattened = setOffsets[d.set] + d.binding; + d.flattened = setOffsets[d.set] + d.binding - uniformBlockCapacities[d.set]; } } -function getIDescriptorSetLayoutInfoCapacity (info: IDescriptorSetLayoutInfo): number { - let capacity = 0; - for (const binding of info.bindings) { - capacity += binding.count; - } - return capacity; -} - function calculateFlattenedBinding ( descriptorSets: (DescriptorSetLayoutData | null)[], fixedInstanceDescriptorSetLayout: IDescriptorSetLayoutInfo | null, shaderInfo: ShaderInfo, ) { - const passCapacity = descriptorSets[UpdateFrequency.PER_PASS]?.capacity || 0; - const phaseCapacity = descriptorSets[UpdateFrequency.PER_PHASE]?.capacity || 0; - // const batchCapacity = descriptorSets[UpdateFrequency.PER_BATCH]?.capacity || 0; // dynamic size - const instanceCapacity = fixedInstanceDescriptorSetLayout - ? getIDescriptorSetLayoutInfoCapacity(fixedInstanceDescriptorSetLayout) - : (descriptorSets[UpdateFrequency.PER_INSTANCE]?.capacity || 0); + // Descriptors of UniformBlock starts from 0, and Descriptors of SamplerTexture starts from the end of UniformBlock. + const uniformBlockCapacities = new Array(4); + { + const passCapacity = descriptorSets[UpdateFrequency.PER_PASS]?.uniformBlockCapacity || 0; + const phaseCapacity = descriptorSets[UpdateFrequency.PER_PHASE]?.uniformBlockCapacity || 0; + const batchCapacity = descriptorSets[UpdateFrequency.PER_BATCH]?.uniformBlockCapacity || 0; // dynamic size + const instanceCapacity = fixedInstanceDescriptorSetLayout + ? getIDescriptorSetLayoutInfoUniformBlockCapacity(fixedInstanceDescriptorSetLayout) + : (descriptorSets[UpdateFrequency.PER_INSTANCE]?.uniformBlockCapacity || 0); - const passOffset = 0; - const phaseOffset = passOffset + passCapacity; - const instanceOffset = phaseOffset + phaseCapacity; - const batchOffset = instanceOffset + instanceCapacity; + // update uniform block capacities + uniformBlockCapacities[_setIndex[UpdateFrequency.PER_PASS]] = passCapacity; + uniformBlockCapacities[_setIndex[UpdateFrequency.PER_PHASE]] = phaseCapacity; + uniformBlockCapacities[_setIndex[UpdateFrequency.PER_BATCH]] = batchCapacity; + uniformBlockCapacities[_setIndex[UpdateFrequency.PER_INSTANCE]] = instanceCapacity; - const offsets = new Array(4); - offsets[_setIndex[UpdateFrequency.PER_PASS]] = passOffset; - offsets[_setIndex[UpdateFrequency.PER_PHASE]] = phaseOffset; - offsets[_setIndex[UpdateFrequency.PER_BATCH]] = batchOffset; - offsets[_setIndex[UpdateFrequency.PER_INSTANCE]] = instanceOffset; + // calculate uniform block offsets + const passOffset = 0; + const phaseOffset = passOffset + passCapacity; + const instanceOffset = phaseOffset + phaseCapacity; + const batchOffset = instanceOffset + instanceCapacity; - setFlattenedBinding(offsets, shaderInfo.blocks); - setFlattenedBinding(offsets, shaderInfo.samplerTextures); - setFlattenedBinding(offsets, shaderInfo.samplers); - setFlattenedBinding(offsets, shaderInfo.textures); - setFlattenedBinding(offsets, shaderInfo.buffers); - setFlattenedBinding(offsets, shaderInfo.images); + // save uniform block offsets by set index + const uniformBlockOffsets = new Array(4); + uniformBlockOffsets[_setIndex[UpdateFrequency.PER_PASS]] = passOffset; + uniformBlockOffsets[_setIndex[UpdateFrequency.PER_PHASE]] = phaseOffset; + uniformBlockOffsets[_setIndex[UpdateFrequency.PER_BATCH]] = batchOffset; + uniformBlockOffsets[_setIndex[UpdateFrequency.PER_INSTANCE]] = instanceOffset; + + // update flattened uniform block binding + setFlattenedUniformBlockBinding(uniformBlockOffsets, shaderInfo.blocks); + } + { + // calculate sampler texture capacities + const passCapacity = descriptorSets[UpdateFrequency.PER_PASS]?.samplerTextureCapacity || 0; + const phaseCapacity = descriptorSets[UpdateFrequency.PER_PHASE]?.samplerTextureCapacity || 0; + // const batchCapacity = descriptorSets[UpdateFrequency.PER_BATCH]?.capacity || 0; // dynamic size + const instanceCapacity = fixedInstanceDescriptorSetLayout + ? getIDescriptorSetLayoutInfoSamplerTextureCapacity(fixedInstanceDescriptorSetLayout) + : (descriptorSets[UpdateFrequency.PER_INSTANCE]?.samplerTextureCapacity || 0); + + // calculate sampler texture offsets + const passOffset = 0; + const phaseOffset = passOffset + passCapacity; + const instanceOffset = phaseOffset + phaseCapacity; + const batchOffset = instanceOffset + instanceCapacity; + + // save sampler texture offsets by set index + const samplerTextureOffsets = new Array(4); + samplerTextureOffsets[_setIndex[UpdateFrequency.PER_PASS]] = passOffset; + samplerTextureOffsets[_setIndex[UpdateFrequency.PER_PHASE]] = phaseOffset; + samplerTextureOffsets[_setIndex[UpdateFrequency.PER_BATCH]] = batchOffset; + samplerTextureOffsets[_setIndex[UpdateFrequency.PER_INSTANCE]] = instanceOffset; + + // update flattened sampler texture binding + setFlattenedSamplerTextureBinding(samplerTextureOffsets, uniformBlockCapacities, shaderInfo.samplerTextures); + } } // make gfx.ShaderInfo @@ -470,16 +525,13 @@ function makeShaderInfo ( } class WebProgramProxy implements ProgramProxy { - constructor (host: ProgramHost) { - this.host = host; + constructor (shader: Shader) { + this.shader = shader; } get name (): string { - return this.host.program.name; + return this.shader.name; } - get shader (): Shader { - return this.host.program; - } - host: ProgramHost; + readonly shader: Shader; } // find name and type from local descriptor set info @@ -785,6 +837,7 @@ export class WebProgramLibrary implements ProgramLibrary { } // get program variant getProgramVariant (device: Device, phaseID: number, name: string, defines: MacroRecord, key: string | null = null): ProgramProxy | null { + Object.assign(defines, this.pipeline?.macros); assert(phaseID !== INVALID_ID); // get phase const group = this.phases.get(phaseID); @@ -804,10 +857,10 @@ export class WebProgramLibrary implements ProgramLibrary { } // try get program - const programHosts = group.programHosts; + const programHosts = group.programProxies; const programHost = programHosts.get(key); if (programHost !== undefined) { - return new WebProgramProxy(programHost); + return programHost; } // prepare variant @@ -834,11 +887,11 @@ export class WebProgramLibrary implements ProgramLibrary { const shader = device.createShader(shaderInfo); // create program host and register - const host = new ProgramHost(shader); + const host = new WebProgramProxy(shader); programHosts.set(key, host); // create - return new WebProgramProxy(host); + return host; } // get material descriptor set layout getMaterialDescriptorSetLayout (device: Device, phaseID: number, programName: string): DescriptorSetLayout { @@ -944,8 +997,9 @@ export class WebProgramLibrary implements ProgramLibrary { getDescriptorName (nameID: number): string { return getDescriptorName(this.layoutGraph, nameID); } - layoutGraph: LayoutGraphData; + readonly layoutGraph: LayoutGraphData; readonly phases: Map = new Map(); mergeHighFrequency = false; fixedLocal = true; + pipeline: PipelineRuntime | null = null; } diff --git a/cocos/rendering/custom/web-types.ts b/cocos/rendering/custom/web-types.ts index 8b2add1e25..b275b9abde 100644 --- a/cocos/rendering/custom/web-types.ts +++ b/cocos/rendering/custom/web-types.ts @@ -28,7 +28,8 @@ * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= */ /* eslint-disable max-len */ -import { Attribute, Shader, ShaderInfo } from '../../gfx'; +import { Attribute, ShaderInfo } from '../../gfx'; +import { ProgramProxy } from './private'; import { IProgramInfo } from '../../render-scene/core/program-lib'; export class ProgramInfo { @@ -52,14 +53,7 @@ export class ProgramInfo { readonly handleMap: Record; } -export class ProgramHost { - constructor (program: Shader) { - this.program = program; - } - /*refcount*/ program: Shader; -} - export class ProgramGroup { readonly programInfos: Map = new Map(); - readonly programHosts: Map = new Map(); + readonly programProxies: Map = new Map(); } diff --git a/cocos/rendering/debug-view.ts b/cocos/rendering/debug-view.ts index 508f0a12f3..e2e5fe19c1 100644 --- a/cocos/rendering/debug-view.ts +++ b/cocos/rendering/debug-view.ts @@ -63,6 +63,7 @@ export const enum DebugViewSingleType { METALLIC, ROUGHNESS, SPECULAR_INTENSITY, + IOR, DIRECT_DIFFUSE, DIRECT_SPECULAR, @@ -75,6 +76,16 @@ export const enum DebugViewSingleType { SHADOW, AO, + FRESNEL, + DIRECT_TRANSMIT_DIFFUSE, + DIRECT_TRANSMIT_SPECULAR, + ENV_TRANSMIT_DIFFUSE, + ENV_TRANSMIT_SPECULAR, + TRANSMIT_ALL, + DIRECT_TRT, + ENV_TRT, + TRT_ALL, + FOG, } @@ -100,6 +111,12 @@ export const enum DebugViewCompositeType { TONE_MAPPING, GAMMA_CORRECTION, + + FRESNEL, + TRANSMIT_DIFFUSE, + TRANSMIT_SPECULAR, + TRT, + MAX_BIT_COUNT } @@ -112,63 +129,45 @@ export class DebugView { * @en Toggle rendering single debug mode. * @zh 设置渲染单项调试模式。 */ - public get singleMode () : DebugViewSingleType { + public get singleMode (): DebugViewSingleType { return this._singleMode; } - public set singleMode (val : DebugViewSingleType) { + public set singleMode (val: DebugViewSingleType) { this._singleMode = val; this._updatePipeline(); - - if (JSB && this._nativeConfig) { - this._nativeConfig.singleMode = this._singleMode; - } } /** * @en Toggle normal / pure lighting mode. * @zh 切换正常光照和仅光照模式。 */ - public get lightingWithAlbedo () : boolean { + public get lightingWithAlbedo (): boolean { return this._lightingWithAlbedo; } - public set lightingWithAlbedo (val : boolean) { + public set lightingWithAlbedo (val: boolean) { this._lightingWithAlbedo = val; this._updatePipeline(); - - if (JSB && this._nativeConfig) { - this._nativeConfig.lightingWithAlbedo = this._lightingWithAlbedo; - } } /** * @en Toggle CSM layer coloration mode. * @zh 切换级联阴影染色调试模式。 */ - public get csmLayerColoration () : boolean { + public get csmLayerColoration (): boolean { return this._csmLayerColoration; } - public set csmLayerColoration (val : boolean) { + public set csmLayerColoration (val: boolean) { this._csmLayerColoration = val; this._updatePipeline(); - - if (JSB && this._nativeConfig) { - this._nativeConfig.csmLayerColoration = this._csmLayerColoration; - } } protected _singleMode = DebugViewSingleType.NONE; protected _compositeModeValue = 0; protected _lightingWithAlbedo = true; protected _csmLayerColoration = false; - protected _nativeConfig: any = null; constructor () { this._activate(); - if (JSB && this._nativeConfig === null) { - // @ts-expect-error jsb object access - this._nativeConfig = new jsb.DebugViewConfig(); - this._nativeConfig.compositeModeBitCount = DebugViewCompositeType.MAX_BIT_COUNT; - } } /** @@ -176,7 +175,7 @@ export class DebugView { * @zh 获取指定的渲染组合调试模式是否开启。 * @param Specified composite type. */ - public isCompositeModeEnabled (val : number) : boolean { + public isCompositeModeEnabled (val: number): boolean { const mode = this._compositeModeValue & (1 << val); return mode !== 0; } @@ -224,13 +223,6 @@ export class DebugView { this._enableAllCompositeMode(true); this._lightingWithAlbedo = true; this._csmLayerColoration = false; - - if (JSB && this._nativeConfig) { - this._nativeConfig.singleMode = this._singleMode; - this._nativeConfig.compositeModeValue = this._compositeModeValue; - this._nativeConfig.lightingWithAlbedo = this._lightingWithAlbedo; - this._nativeConfig.csmLayerColoration = this._csmLayerColoration; - } } protected _updatePipeline () { @@ -251,10 +243,6 @@ export class DebugView { } else { this._compositeModeValue &= (~(1 << val)); } - - if (JSB && this._nativeConfig) { - this._nativeConfig.compositeModeValue = this._compositeModeValue; - } } private _enableAllCompositeMode (enable: boolean) { @@ -264,14 +252,10 @@ export class DebugView { } else { this._compositeModeValue &= (~(1 << i)); } - - if (JSB && this._nativeConfig) { - this._nativeConfig.compositeModeValue = this._compositeModeValue; - } } } - private _getType () : RenderingDebugViewType { + private _getType (): RenderingDebugViewType { if (this._singleMode !== DebugViewSingleType.NONE) { return RenderingDebugViewType.SINGLE; } else if (this._lightingWithAlbedo !== true || this._csmLayerColoration !== false) { diff --git a/cocos/rendering/define.ts b/cocos/rendering/define.ts index da085fad1a..2b426dbe3b 100644 --- a/cocos/rendering/define.ts +++ b/cocos/rendering/define.ts @@ -183,8 +183,9 @@ export class UBOGlobal { public static readonly DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET = UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 4; public static readonly DEBUG_VIEW_COMPOSITE_PACK_2_OFFSET = UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET + 4; public static readonly DEBUG_VIEW_COMPOSITE_PACK_3_OFFSET = UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_2_OFFSET + 4; + public static readonly DEBUG_VIEW_COMPOSITE_PACK_4_OFFSET = UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_3_OFFSET + 4; - public static readonly COUNT = UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_3_OFFSET + 4; + public static readonly COUNT = UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_4_OFFSET + 4; public static readonly SIZE = UBOGlobal.COUNT * 4; public static readonly NAME = 'CCGlobal'; @@ -195,10 +196,11 @@ export class UBOGlobal { new Uniform('cc_screenSize', Type.FLOAT4, 1), new Uniform('cc_nativeSize', Type.FLOAT4, 1), - new Uniform('cc_debug_view_mode', Type.FLOAT, 4), - new Uniform('cc_debug_view_composite_pack_1', Type.FLOAT, 4), - new Uniform('cc_debug_view_composite_pack_2', Type.FLOAT, 4), - new Uniform('cc_debug_view_composite_pack_3', Type.FLOAT, 4), + new Uniform('cc_debug_view_mode', Type.FLOAT4, 1), + new Uniform('cc_debug_view_composite_pack_1', Type.FLOAT4, 1), + new Uniform('cc_debug_view_composite_pack_2', Type.FLOAT4, 1), + new Uniform('cc_debug_view_composite_pack_3', Type.FLOAT4, 1), + new Uniform('cc_debug_view_composite_pack_4', Type.FLOAT4, 1), ], 1); } globalDescriptorSetLayout.layouts[UBOGlobal.NAME] = UBOGlobal.LAYOUT; diff --git a/cocos/rendering/global-descriptor-set-manager.ts b/cocos/rendering/global-descriptor-set-manager.ts index 61e2dc7b95..810f4fe2b6 100644 --- a/cocos/rendering/global-descriptor-set-manager.ts +++ b/cocos/rendering/global-descriptor-set-manager.ts @@ -26,7 +26,7 @@ import { cclegacy } from '../core'; import { Device, BufferUsageBit, MemoryUsageBit, BufferInfo, Filter, Address, Sampler, DescriptorSet, DescriptorSetInfo, Buffer, Texture, DescriptorSetLayoutInfo, DescriptorSetLayout, SamplerInfo } from '../gfx'; import { Light } from '../render-scene/scene'; -import { getDescBindingFromName } from './custom/define'; +import { getDescBindingFromName, getDescriptorSetDataFromLayout } from './custom/define'; import { UBOShadow, globalDescriptorSetLayout, PipelineGlobalBindings, isEnableEffect } from './define'; const _samplerLinearInfo = new SamplerInfo( @@ -178,8 +178,9 @@ export class GlobalDSManager { // The global descriptorSet is managed by the pipeline and binds the buffer if (!this._descriptorSetMap.has(light)) { - const globalDescriptorSet = this._globalDescriptorSet; - const descriptorSet = device.createDescriptorSet(new DescriptorSetInfo(this._descriptorSetLayout)); + const globalDescriptorSet = isEnableEffect() ? getDescriptorSetDataFromLayout('default')!.descriptorSet! : this._globalDescriptorSet; + const descriptorSet = device.createDescriptorSet(new DescriptorSetInfo(isEnableEffect() + ? getDescriptorSetDataFromLayout('default')!.descriptorSetLayout! : this._descriptorSetLayout)); this._descriptorSetMap.set(light, descriptorSet); // Create & Sync ALL UBO Buffer, Texture, Sampler diff --git a/cocos/rendering/index.jsb.ts b/cocos/rendering/index.jsb.ts index be1f12e5fe..05f774f2bb 100644 --- a/cocos/rendering/index.jsb.ts +++ b/cocos/rendering/index.jsb.ts @@ -54,6 +54,24 @@ export const ReflectionProbeFlow = nr.ReflectionProbeFlow; export const ReflectionProbeStage = nr.ReflectionProbeStage; export { PipelineEventType } from './pipeline-event'; +interface IRenderFlowInfo { + name: string; + priority: number; + stages: any[]; + tag: number; +} + +interface IRenderPipelineInfo { + flows: any[]; + tag: number; +} +interface IRenderStageInfo { + name: string; + priority: number; + tag: number; + renderQueues: RenderQueueDesc[]; +} + let getOrCreatePipelineState = nr.PipelineStateManager.getOrCreatePipelineState; nr.PipelineStateManager.getOrCreatePipelineState = function (device, pass, shader, renderPass, ia) { return getOrCreatePipelineState(pass, shader, renderPass, ia); //cjh TODO: remove hacking. c++ API doesn't access device argument. @@ -70,7 +88,7 @@ forwardPipelineProto.init = function () { for (let i = 0; i < this._flows.length; i++) { this._flows[i].init(this); } - const info = new nr.RenderPipelineInfo(this._tag, this._flows); + const info: IRenderPipelineInfo = { tag: this._tag, flows: this._flows }; this.initialize(info); }; @@ -81,7 +99,7 @@ forwardPipelineProto.onLoaded = function () { for (let i = 0; i < this._flows.length; i++) { this._flows[i].init(this); } - const info = new nr.RenderPipelineInfo(this._tag, this._flows); + const info: IRenderPipelineInfo = { tag: this._tag, flows: this._flows }; this.initialize(info); } @@ -96,7 +114,7 @@ forwardFlowProto.init = function (pipeline) { for (let i = 0; i < this._stages.length; i++) { this._stages[i].init(pipeline); } - const info = new nr.RenderFlowInfo(this._name, this._priority, this._tag, this._stages); + const info: IRenderFlowInfo = { name: this._name, priority: this._priority, tag: this._tag, stages: this._stages }; this.initialize(info); } @@ -111,7 +129,7 @@ shadowFlowProto.init = function (pipeline) { for (let i = 0; i < this._stages.length; i++) { this._stages[i].init(pipeline); } - const info = new nr.RenderFlowInfo(this._name, this._priority, this._tag, this._stages); + const info: IRenderFlowInfo = { name: this._name, priority: this._priority, tag: this._tag, stages: this._stages }; this.initialize(info); } @@ -126,7 +144,7 @@ reflectionProbeFlowProto.init = function (pipeline) { for (let i = 0; i < this._stages.length; i++) { this._stages[i].init(pipeline); } - const info = new nr.RenderFlowInfo(this._name, this._priority, this._tag, this._stages); + const info: IRenderFlowInfo = { name: this._name, priority: this._priority, tag: this._tag, stages: this._stages }; this.initialize(info); } @@ -143,7 +161,7 @@ forwardStageProto.init = function (pipeline) { // @ts-ignore queues.push(this.renderQueues[i].init()); } - const info = new nr.RenderStageInfo(this._name, this._priority, this._tag, queues); + const info: IRenderStageInfo = { name: this._name, priority: this._priority, tag: this._tag, renderQueues: queues }; this.initialize(info); } @@ -167,7 +185,7 @@ reflectionProbeStage.init = function (pipeline) { // @ts-ignore queues.push(this.renderQueues[i].init()); } - const info = new nr.RenderStageInfo(this._name, this._priority, this._tag, queues); + const info: IRenderStageInfo = { name: this._name, priority: this._priority, tag: this._tag, renderQueues: queues }; this.initialize(info); } @@ -179,7 +197,7 @@ export enum RenderQueueSortMode { ccenum(RenderQueueSortMode); shadowStageProto.init = function (pipeline) { - const info = new nr.RenderStageInfo(this._name, this._priority, this._tag, []); + const info: IRenderStageInfo = { name: this._name, priority: this._priority, tag: this._tag, renderQueues: [] }; this.initialize(info); } @@ -232,7 +250,7 @@ deferredPipelineProto.onLoaded = function () { for (let i = 0; i < this._flows.length; i++) { this._flows[i].init(this); } - let info = new nr.RenderPipelineInfo(this._tag, this._flows); + let info = { tag: this._tag, flows: this._flows }; this.initialize(info); } @@ -247,7 +265,7 @@ mainFlowProto.init = function (pipeline) { for (let i = 0; i < this._stages.length; i++) { this._stages[i].init(pipeline); } - let info = new nr.RenderFlowInfo(this._name, this._priority, this._tag, this._stages); + const info: IRenderFlowInfo = { name: this._name, priority: this._priority, tag: this._tag, stages: this._stages }; this.initialize(info); } @@ -264,7 +282,7 @@ gbufferStageProto.init = function (pipeline) { // @ts-ignore queues.push(this.renderQueues[i].init()); } - let info = new nr.RenderStageInfo(this._name, this._priority, this._tag, queues); + const info: IRenderStageInfo = { name: this._name, priority: this._priority, tag: this._tag, renderQueues: queues }; this.initialize(info); } @@ -284,7 +302,7 @@ lightingStageProto.init = function (pipeline) { queues.push(this.renderQueues[i].init()); } pipeline.pipelineSceneData.deferredLightingMaterial = this._deferredMaterial; - let info = new nr.RenderStageInfo(this._name, this._priority, this._tag, queues); + const info: IRenderStageInfo = { name: this._name, priority: this._priority, tag: this._tag, renderQueues: queues }; this.initialize(info); } @@ -303,7 +321,7 @@ bloomStageProto.init = function (pipeline) { queues.push(this.renderQueues[i].init()); } pipeline.pipelineSceneData.bloomMaterial = this._bloomMaterial; - let info = new nr.RenderStageInfo(this._name, this._priority, this._tag, queues); + const info: IRenderStageInfo = { name: this._name, priority: this._priority, tag: this._tag, renderQueues: queues }; this.initialize(info); } @@ -322,8 +340,7 @@ postProcessStageProto.init = function (pipeline) { queues.push(this.renderQueues[i].init()); } pipeline.pipelineSceneData.postProcessMaterial = this._postProcessMaterial; - let info = - new nr.RenderStageInfo(this._name, this._priority, this._tag, queues); + const info: IRenderStageInfo = { name: this._name, priority: this._priority, tag: this._tag, renderQueues: queues }; this.initialize(info); } @@ -344,34 +361,30 @@ class RenderTextureConfig { } -function proxyArrayAttribute(proto: any, attr: string) { - const underlyingAttr = `_udl_${attr}`; - const underlyingPropt = Object.getOwnPropertyDescriptor(proto, attr); - if (!underlyingPropt) { - console.error(`Attribute ${attr} is not defined in function ${proto.constructor.name}`); - return; +function proxyArrayAttributeImpl(proto: any, attr: string) { + const proxyTarget = `_${attr}_target`; + let arrayProxy = (self, targetArrayAttr: string) => { + return new Proxy(self[targetArrayAttr], { + get(targetArray, prop, receiver) { + return Reflect.get(targetArray, prop, receiver); + }, + set(targetArray, prop, receiver) { + const ret = Reflect.set(targetArray, prop, receiver); + self[targetArrayAttr] = targetArray; + return ret; + } + }); } - Object.defineProperty(proto, underlyingAttr, underlyingPropt!); + Object.defineProperty(proto, attr, { configurable: true, enumerable: true, get: function () { - const self = this; - return new Proxy(this[underlyingAttr], { - get(target, prop, receiver) { - // console.log('GET: ' + String(prop) ); - return Reflect.get(target, prop, receiver); - }, - set(target, prop, receiver) { - // console.log('SET: ' + String(prop) ); - const ret = Reflect.set(target, prop, receiver); - self[underlyingAttr] = target; - return ret; - } - }); + this[proxyTarget] ||= []; + return arrayProxy(this, proxyTarget); }, set: function (v) { - this[underlyingAttr] = v; + this[proxyTarget] = v; } }); } @@ -381,56 +394,10 @@ function declType(proto: any, attrType: any, attr: string, dft: () => any) { } -function declArrayPropetry(proto: any, attr: string) { - const udKey = `__arr_${attr}`; - Object.defineProperty(proto, attr, { - configurable: true, - enumerable: true, - get() { - if (!this[udKey]) { - this[udKey] = []; - } - return this[udKey]; - }, - set(v: any) { - if (!this[udKey]) { - this[udKey] = []; - } - this[udKey] = v; - } - }); -} -function declObjectPropetry(proto: any, attr: string, dftValue: any) { - const udKey = `__obj_${attr}`; - Object.defineProperty(proto, attr, { - configurable: true, - enumerable: true, - get() { - if (this[udKey] === undefined) { - this[udKey] = dftValue; - } - return this[udKey]; - }, - set(v: any) { - if (this[udKey] === undefined) { - this[udKey] = dftValue; - } - this[udKey] = v; - } - }); -} -declArrayPropetry(DeferredPipeline.prototype, 'renderTextures'); -declArrayPropetry(ForwardPipeline.prototype, 'renderTextures'); -declArrayPropetry(GbufferStage.prototype, 'renderQueues'); -declArrayPropetry(LightingStage.prototype, 'renderQueues'); -declArrayPropetry(PostProcessStage.prototype, 'renderQueues'); -declArrayPropetry(ForwardStage.prototype, 'renderQueues'); -declObjectPropetry(LightingStage.prototype, '_deferredMaterial', null); -declObjectPropetry(BloomStage.prototype, '_bloomMaterial', null); -declObjectPropetry(PostProcessStage.prototype, '_postProcessMaterial', null); +let proxyArrayAttribute = proxyArrayAttributeImpl; editable(RenderStage.prototype, '_name', () => ''); editable(RenderStage.prototype, '_tag', () => 0); @@ -461,30 +428,25 @@ serializable(RenderPipeline.prototype, '_flows', () => []); editable(DeferredPipeline.prototype, 'renderTextures', () => []); declType(DeferredPipeline.prototype, [RenderTextureConfig], "renderTextures", () => []); -proxyArrayAttribute(DeferredPipeline.prototype, 'renderTextures'); serializable(DeferredPipeline.prototype, 'renderTextures', () => []); +editable(DeferredPipeline.prototype, 'renderTextures', () => []); editable(ForwardPipeline.prototype, 'renderTextures', () => []); declType(ForwardPipeline.prototype, [RenderTextureConfig], "renderTextures", () => []); -proxyArrayAttribute(ForwardPipeline.prototype, 'renderTextures'); serializable(ForwardPipeline.prototype, 'renderTextures', () => []); declType(GbufferStage.prototype, [RenderQueueDesc], 'renderQueues', () => []); -proxyArrayAttribute(GbufferStage.prototype, 'renderQueues'); serializable(GbufferStage.prototype, 'renderQueues', () => []); +editable(GbufferStage.prototype, 'renderQueues', () => []); -// serializable(RenderQueueDesc.prototype, 'isTransparent', () => false); -// editable(RenderQueueDesc.prototype, 'isTransparent', () => false); -// editable(RenderQueueDesc.prototype, 'sortMode', () => false); -// editable(RenderQueueDesc.prototype, 'stages', () => []); editable(LightingStage.prototype, '_deferredMaterial', () => null); declType(LightingStage.prototype, jsb.Material, '_deferredMaterial', () => null); declType(LightingStage.prototype, [RenderQueueDesc], 'renderQueues', () => []); -proxyArrayAttribute(LightingStage.prototype, 'renderQueues'); serializable(LightingStage.prototype, '_deferredMaterial', () => null); serializable(LightingStage.prototype, 'renderQueue', () => []); +editable(LightingStage.prototype, 'renderQueue', () => []); editable(BloomStage.prototype, '_bloomMaterial', () => null); declType(BloomStage.prototype, jsb.Material, '_bloomMaterial', () => []); @@ -492,31 +454,33 @@ serializable(BloomStage.prototype, '_bloomMaterial', () => null); declType(PostProcessStage.prototype, [RenderQueueDesc], 'renderQueues', () => []); -proxyArrayAttribute(PostProcessStage.prototype, 'renderQueues'); editable(PostProcessStage.prototype, '_postProcessMaterial', () => null); declType(PostProcessStage.prototype, jsb.Material, '_postProcessMaterial', () => null); serializable(PostProcessStage.prototype, 'renderQueues', () => []); +editable(PostProcessStage.prototype, 'renderQueues', () => []); serializable(PostProcessStage.prototype, '_postProcessMaterial', () => null); declType(ForwardStage.prototype, [RenderQueueDesc], 'renderQueues', () => []); -proxyArrayAttribute(ForwardStage.prototype, 'renderQueues'); serializable(ForwardStage.prototype, 'renderQueues', () => []); +editable(ForwardStage.prototype, 'renderQueues', () => []); //-------------------- register types -------------------- -ccclass('cc.RenderPipeline')(RenderPipeline); +ccclass('RenderQueueDesc')(RenderQueueDesc); ccclass('RenderStage')(RenderStage) -ccclass('RenderFlow')(RenderFlow) -ccclass('ForwardPipeline')(ForwardPipeline); -ccclass('DeferredPipeline')(DeferredPipeline); -ccclass('MainFlow')(MainFlow); -ccclass('ForwardFlow')(ForwardFlow); -ccclass('ShadowFlow')(ShadowFlow); +ccclass('ReflectionProbeStage')(ReflectionProbeStage); ccclass('GbufferStage')(GbufferStage); ccclass('LightingStage')(LightingStage); ccclass('BloomStage')(BloomStage); ccclass('PostProcessStage')(PostProcessStage); ccclass('ForwardStage')(ForwardStage); ccclass('ShadowStage')(ShadowStage); -ccclass('RenderQueueDesc')(RenderQueueDesc); + +ccclass('RenderFlow')(RenderFlow) +ccclass('MainFlow')(MainFlow); +ccclass('ForwardFlow')(ForwardFlow); +ccclass('ShadowFlow')(ShadowFlow); ccclass('ReflectionProbeFlow')(ReflectionProbeFlow); -ccclass('ReflectionProbeStage')(ReflectionProbeStage); \ No newline at end of file + +ccclass('cc.RenderPipeline')(RenderPipeline); +ccclass('ForwardPipeline')(ForwardPipeline); +ccclass('DeferredPipeline')(DeferredPipeline); \ No newline at end of file diff --git a/cocos/rendering/pipeline-funcs.ts b/cocos/rendering/pipeline-funcs.ts index b212288ded..b8792cbceb 100644 --- a/cocos/rendering/pipeline-funcs.ts +++ b/cocos/rendering/pipeline-funcs.ts @@ -26,7 +26,7 @@ import { EDITOR } from 'internal:constants'; import { CommandBuffer, Device, Rect, RenderPass, Viewport } from '../gfx'; import { IVec4Like } from '../core'; import { PipelineStateManager } from './pipeline-state-manager'; -import { SetIndex } from './define'; +import { isEnableEffect, SetIndex } from './define'; import { Camera, Model } from '../render-scene/scene'; import { Layers } from '../scene-graph/layers'; @@ -65,6 +65,10 @@ export function LinearToSRGB (out: IVec4Like, linear: IVec4Like) { let profilerCamera: Camera | null = null; +export function getProfilerCamera (): Camera | null { + return profilerCamera; +} + export function decideProfilerCamera (cameras: Camera[]) { for (let i = cameras.length - 1; i >= 0; --i) { const camera = cameras[i]; @@ -77,6 +81,9 @@ export function decideProfilerCamera (cameras: Camera[]) { } export function renderProfiler (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer, profiler: Model | null, camera: Camera) { + if (isEnableEffect()) { + return; + } if (!profiler || !profiler.enabled) { return; } diff --git a/cocos/rendering/pipeline-ubo.ts b/cocos/rendering/pipeline-ubo.ts index ad08c2c47b..e7c6f23d6b 100644 --- a/cocos/rendering/pipeline-ubo.ts +++ b/cocos/rendering/pipeline-ubo.ts @@ -71,20 +71,11 @@ export class PipelineUBO { fv[UBOGlobal.NATIVE_SIZE_OFFSET + 3] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1]; const debugView = root.debugView; - if (debugView) { - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET] = debugView.singleMode as number; - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 1] = debugView.lightingWithAlbedo ? 1.0 : 0.0; - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 2] = debugView.csmLayerColoration ? 1.0 : 0.0; - for (let i = DebugViewCompositeType.DIRECT_DIFFUSE as number; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) { - fv[UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET + i] = debugView.isCompositeModeEnabled(i) ? 1.0 : 0.0; - } - } else { - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET] = 0.0; - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 1] = 1.0; - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 2] = 0.0; - for (let i = DebugViewCompositeType.DIRECT_DIFFUSE as number; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) { - fv[UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET + i] = 1.0; - } + fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET] = debugView.singleMode as number; + fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 1] = debugView.lightingWithAlbedo ? 1.0 : 0.0; + fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 2] = debugView.csmLayerColoration ? 1.0 : 0.0; + for (let i = DebugViewCompositeType.DIRECT_DIFFUSE as number; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) { + fv[UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET + i] = debugView.isCompositeModeEnabled(i) ? 1.0 : 0.0; } } diff --git a/cocos/rendering/reflection-probe-manager.ts b/cocos/rendering/reflection-probe-manager.ts index 53ce9a1695..df69960125 100644 --- a/cocos/rendering/reflection-probe-manager.ts +++ b/cocos/rendering/reflection-probe-manager.ts @@ -53,15 +53,29 @@ export class ReflectionProbeManager { */ private _usePlanarModels = new Map(); + private _updateForRuntime = true; + constructor () { director.on(Director.EVENT_BEFORE_UPDATE, this.onUpdateProbes, this); } + /** + * @en Set and get whether to detect objects leaving or entering the reflection probe's bounding box at runtime. + * @zh 设置和获取是否在运行时检测物体离开或者进入反射探针的包围盒。 + */ + set updateForRuntime (val: boolean) { + this._updateForRuntime = val; + } + get updateForRuntime () { + return this._updateForRuntime; + } + /** * @en refresh all reflection probe * @zh 刷新所有反射探针 */ public onUpdateProbes (forceUpdate = false) { + if (!this._updateForRuntime) return; if (this._probes.length === 0) return; const scene = director.getScene(); if (!scene || !scene.renderScene) { @@ -311,6 +325,23 @@ export class ReflectionProbeManager { } } + /** + * @en Get the reflection probe used by the model. + * @zh 获取模型使用的反射探针。 + */ + public getUsedReflectionProbe (model: Model, probeType: ReflectionProbeType) { + if (probeType === ReflectionProbeType.BAKED_CUBEMAP) { + if (this._useCubeModels.has(model)) { + return this._useCubeModels.get(model); + } + } else if (probeType === ReflectionProbeType.PLANAR_REFLECTION) { + if (this._usePlanarModels.has(model)) { + return this._usePlanarModels.get(model); + } + } + return null; + } + /** * @en * select the probe with the nearest distance. @@ -360,10 +391,7 @@ export class ReflectionProbeManager { const p = this._useCubeModels.get(key); if (p !== undefined && p === probe) { this._useCubeModels.delete(key); - const meshRender = key.node.getComponent(MeshRenderer); - if (meshRender) { - meshRender.updateProbeCubemap(null); - } + this.updateUseCubeModels(key); } } for (const key of this._usePlanarModels.keys()) { diff --git a/cocos/rendering/render-additive-light-queue.ts b/cocos/rendering/render-additive-light-queue.ts index 84254af6c1..c8c4b9335a 100644 --- a/cocos/rendering/render-additive-light-queue.ts +++ b/cocos/rendering/render-additive-light-queue.ts @@ -109,15 +109,13 @@ export class RenderAdditiveLightQueue { private _lightBuffer: Buffer; private _firstLightBufferView: Buffer; private _lightBufferData: Float32Array; - private _instancedQueue: RenderInstancedQueue; - private _batchedQueue: RenderBatchedQueue; + private _instancedQueues: RenderInstancedQueue[] = []; + private _batchedQueues: RenderBatchedQueue[] = []; private _lightMeterScale = 10000.0; constructor (pipeline: PipelineRuntime) { this._pipeline = pipeline; this._device = pipeline.device; - this._instancedQueue = new RenderInstancedQueue(); - this._batchedQueue = new RenderBatchedQueue(); const alignment = this._device.capabilities.uboOffsetAlignment; this._lightBufferStride = Math.ceil(UBOForwardLight.SIZE / alignment) * alignment; @@ -136,8 +134,14 @@ export class RenderAdditiveLightQueue { } public clear () { - this._instancedQueue.clear(); - this._batchedQueue.clear(); + this._instancedQueues.forEach((instancedQueue) => { + instancedQueue.clear(); + }); + this._instancedQueues.length = 0; + this._batchedQueues.forEach((batchedQueue) => { + batchedQueue.clear(); + }); + this._batchedQueues.length = 0; for (let i = 0; i < this._lightPasses.length; i++) { const lp = this._lightPasses[i]; @@ -218,24 +222,29 @@ export class RenderAdditiveLightQueue { this._batchedLightPassPool.lights.push(light); this._batchedLightPassPool.dynamicOffsets.push(this._lightBufferStride * l); } - this._instancedQueue.uploadBuffers(cmdBuff); - this._batchedQueue.uploadBuffers(cmdBuff); + + this._instancedQueues.forEach((instancedQueue) => { + instancedQueue.uploadBuffers(cmdBuff); + }); + this._batchedQueues.forEach((batchedQueue) => { + batchedQueue.uploadBuffers(cmdBuff); + }); } public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer) { const globalDSManager: GlobalDSManager = this._pipeline.globalDSManager; - for (let j = 0; j < this._instancedLightPassPool.lights.length; ++j) { + for (let j = 0; j < this._instancedQueues.length; ++j) { const light = this._instancedLightPassPool.lights[j]; _dynamicOffsets[0] = this._instancedLightPassPool.dynamicOffsets[j]; const descriptorSet = globalDSManager.getOrCreateDescriptorSet(light); - this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff, descriptorSet, _dynamicOffsets); + this._instancedQueues[j].recordCommandBuffer(device, renderPass, cmdBuff, descriptorSet, _dynamicOffsets); } - for (let j = 0; j < this._batchedLightPassPool.lights.length; ++j) { + for (let j = 0; j < this._batchedQueues.length; ++j) { const light = this._batchedLightPassPool.lights[j]; _dynamicOffsets[0] = this._batchedLightPassPool.dynamicOffsets[j]; const descriptorSet = globalDSManager.getOrCreateDescriptorSet(light); - this._batchedQueue.recordCommandBuffer(device, renderPass, cmdBuff, descriptorSet, _dynamicOffsets); + this._batchedQueues[j].recordCommandBuffer(device, renderPass, cmdBuff, descriptorSet, _dynamicOffsets); } for (let i = 0; i < this._lightPasses.length; i++) { @@ -304,13 +313,15 @@ export class RenderAdditiveLightQueue { const buffer = pass.getInstancedBuffer(l); buffer.merge(subModel, lightPassIdx); buffer.dynamicOffsets[0] = this._lightBufferStride; - this._instancedQueue.queue.add(buffer); + if (!this._instancedQueues[l]) { this._instancedQueues[l] = new RenderInstancedQueue(); } + this._instancedQueues[l].queue.add(buffer); } break; case BatchingSchemes.VB_MERGING: { const buffer = pass.getBatchedBuffer(l); buffer.merge(subModel, lightPassIdx, model); buffer.dynamicOffsets[0] = this._lightBufferStride; - this._batchedQueue.queue.add(buffer); + if (!this._batchedQueues[l]) { this._batchedQueues[l] = new RenderBatchedQueue(); } + this._batchedQueues[l].queue.add(buffer); } break; default: lp!.lights.push(light); diff --git a/cocos/rendering/render-pipeline.ts b/cocos/rendering/render-pipeline.ts index 8cef2c0c9f..76e721d174 100644 --- a/cocos/rendering/render-pipeline.ts +++ b/cocos/rendering/render-pipeline.ts @@ -563,7 +563,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi this._pipelineRenderData!.bloom = null; } - private _genQuadVertexData (surfaceTransform: SurfaceTransform, renderArea: Rect) : Float32Array { + private _genQuadVertexData (surfaceTransform: SurfaceTransform, renderArea: Rect): Float32Array { const vbData = new Float32Array(4 * 4); const minX = renderArea.x / this._width; diff --git a/cocos/rendering/scene-culling.ts b/cocos/rendering/scene-culling.ts index 31eeaf9792..84ee578b08 100644 --- a/cocos/rendering/scene-culling.ts +++ b/cocos/rendering/scene-culling.ts @@ -77,6 +77,8 @@ export function validPunctualLightsCulling (pipeline: RenderPipeline, camera: Ca validPunctualLights.push(light); } } + // in jsb, std::vector is not synchronized, so we need to assign it manually + sceneData.validPunctualLights = validPunctualLights; } export function shadowCulling (camera: Camera, sceneData: PipelineSceneData, layer: ShadowLayerVolume) { const scene = camera.scene!; @@ -88,34 +90,37 @@ export function shadowCulling (camera: Camera, sceneData: PipelineSceneData, lay dirShadowObjects.length = 0; const visibility = camera.visibility; - csmLayerObjects.array.forEach((obj, index) => { + for (let i = csmLayerObjects.length - 1; i >= 0; i--) { + const obj = csmLayerObjects.array[i]; if (!obj) { - return; + csmLayerObjects.fastRemove(i); + continue; } const model = obj.model; if (!model || !model.enabled || !model.node) { - return; + csmLayerObjects.fastRemove(i); + continue; } - if (((visibility & model.node.layer) !== model.node.layer) && !(visibility & model.visFlags)) { - return; + if (((visibility & model.node.layer) !== model.node.layer) && (!(visibility & model.visFlags))) { + csmLayerObjects.fastRemove(i); + continue; } if (!model.worldBounds || !model.castShadow) { - return; + csmLayerObjects.fastRemove(i); + continue; } - - // frustum culling const accurate = geometry.intersect.aabbFrustum(model.worldBounds, dirLightFrustum); if (!accurate) { - return; + continue; } dirShadowObjects.push(obj); if (layer.level < mainLight.csmLevel) { if (mainLight.csmOptimizationMode === CSMOptimizationMode.RemoveDuplicates && geometry.intersect.aabbFrustumCompletelyInside(model.worldBounds, dirLightFrustum)) { - csmLayerObjects.fastRemove(index); + csmLayerObjects.fastRemove(i); } } - }); + } } export function sceneCulling (pipeline: RenderPipeline, camera: Camera) { diff --git a/cocos/root.jsb.ts b/cocos/root.jsb.ts index 956ff61c14..69754e3127 100644 --- a/cocos/root.jsb.ts +++ b/cocos/root.jsb.ts @@ -25,9 +25,6 @@ import { legacyCC } from './core/global-exports'; import { DataPoolManager } from './3d/skeletal-animation/data-pool-manager'; import { Device, deviceManager } from './gfx'; -import { EDITOR } from "internal:constants"; -import { DebugView } from './rendering/debug-view'; -import { buildDeferredLayout, buildForwardLayout } from './rendering/custom/effect'; import { settings, Settings, warnID, Pool, macro } from './core'; import { ForwardPipeline } from './rendering'; @@ -89,14 +86,6 @@ Object.defineProperty(rootProto, 'pipelineEvent', { } }); -Object.defineProperty(rootProto, 'debugView', { - configurable: true, - enumerable: true, - get() { - return this._debugView; - } -}); - class DummyPipelineEvent { on(type: any, callback: any, target?: any, once?: boolean) { } once(type: any, callback: any, target?: any) { } @@ -114,8 +103,6 @@ rootProto._ctor = function (device: Device) { this._lightPools = new Map(); this._batcher = null; this._pipelineEvent = new DummyPipelineEvent(); - this._debugView = new DebugView(); - this.setDebugViewConfig(this._debugView._nativeConfig); this._registerListeners(); }; @@ -230,15 +217,8 @@ const oldSetPipeline = rootProto.setRenderPipeline; rootProto.setRenderPipeline = function (pipeline) { let ppl; if (macro.CUSTOM_PIPELINE_NAME !== '' && legacyCC.rendering && this.usesCustomPipeline) { - const result = oldSetPipeline.call(this, null); - const ppl = this.customPipeline; - if (this.useDeferredPipeline) { - buildDeferredLayout(ppl); - } else { - buildForwardLayout(ppl); - } - ppl.layoutGraphBuilder.compile(); - return result; + legacyCC.rendering.createCustomPipeline(); + ppl = oldSetPipeline.call(this, null); } else { if (!pipeline) { // pipeline should not be created in C++, ._ctor need to be triggered diff --git a/cocos/root.ts b/cocos/root.ts index 4dac0346b1..eb000bbff6 100644 --- a/cocos/root.ts +++ b/cocos/root.ts @@ -33,7 +33,7 @@ import { DirectionalLight } from './render-scene/scene/directional-light'; import { SphereLight } from './render-scene/scene/sphere-light'; import { SpotLight } from './render-scene/scene/spot-light'; import { RenderWindow, IRenderWindowInfo } from './render-scene/core/render-window'; -import { ColorAttachment, DepthStencilAttachment, RenderPassInfo, StoreOp, Device, Swapchain, Feature, deviceManager } from './gfx'; +import { ColorAttachment, DepthStencilAttachment, RenderPassInfo, StoreOp, Device, Swapchain, Feature, deviceManager, LegacyRenderMode } from './gfx'; import { Pipeline, PipelineRuntime } from './rendering/custom/pipeline'; import { Batcher2D } from './2d/renderer/batcher-2d'; import { IPipelineEvent } from './rendering/pipeline-event'; @@ -397,16 +397,19 @@ export class Root { this._usesCustomPipeline = false; } - if (!this._pipeline.activate(this._mainWindow!.swapchain)) { - if (isCreateDefaultPipeline) { - this._pipeline.destroy(); - } - this._classicPipeline = null; - this._customPipeline = null; - this._pipeline = null; - this._pipelineEvent = null; + const renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode'); + if (renderMode !== LegacyRenderMode.HEADLESS || this._classicPipeline) { + if (!this._pipeline.activate(this._mainWindow!.swapchain)) { + if (isCreateDefaultPipeline) { + this._pipeline.destroy(); + } + this._classicPipeline = null; + this._customPipeline = null; + this._pipeline = null; + this._pipelineEvent = null; - return false; + return false; + } } //----------------------------------------------- diff --git a/cocos/scene-graph/node-dev.ts b/cocos/scene-graph/node-dev.ts index 11818e4ed7..3dde917d87 100644 --- a/cocos/scene-graph/node-dev.ts +++ b/cocos/scene-graph/node-dev.ts @@ -33,6 +33,18 @@ const Destroying = CCObject.Flags.Destroying; const IS_PREVIEW = !!legacyCC.GAME_VIEW; export function nodePolyfill (Node) { + if ((EDITOR && !IS_PREVIEW) || TEST) { + Node.prototype._onPreDestroy = function () { + const destroyByParent: boolean = this._onPreDestroyBase(); + if (!destroyByParent) { + // ensure this node can reattach to scene by undo system + // (simulate some destruct logic to make undo system work correctly) + this._parent = null; + } + return destroyByParent; + }; + } + if (EDITOR || TEST) { Node.prototype._checkMultipleComp = function (ctor) { const existing = this.getComponent(ctor._disallowMultiple); @@ -71,8 +83,6 @@ export function nodePolyfill (Node) { } return dependant; }; - } - if ((EDITOR && !IS_PREVIEW) || TEST) { /** * This api should only used by undo system * @method _addComponentAt @@ -133,21 +143,8 @@ export function nodePolyfill (Node) { legacyCC.director._nodeActivator.activateNode(this, shouldActiveNow); } }; - - Node.prototype._onPreDestroy = function () { - const destroyByParent: boolean = this._onPreDestroyBase(); - if (!destroyByParent) { - // ensure this node can reattach to scene by undo system - // (simulate some destruct logic to make undo system work correctly) - this._parent = null; - } - return destroyByParent; - }; - Node.prototype._onRestoreBase = Node.prototype.onRestore; - } - if ((EDITOR && !IS_PREVIEW) || TEST) { Node.prototype._registerIfAttached = function (register) { if (!this._id) { console.warn(`Node(${this && this.name}}) is invalid or its data is corrupted.`); diff --git a/cocos/scene-graph/node-event.ts b/cocos/scene-graph/node-event.ts index 8db3316d83..9d18185c68 100644 --- a/cocos/scene-graph/node-event.ts +++ b/cocos/scene-graph/node-event.ts @@ -282,4 +282,12 @@ export enum NodeEventType { * 当光照探针组组件的探针改变时触发的事件 */ LIGHT_PROBE_CHANGED = 'light-probe-changed', + + /** + * @en + * The event occur after light probe's baking data is changed + * @zh + * 当光照探针烘焙数据修改后触发的事件 + */ + LIGHT_PROBE_BAKING_CHANGED = 'light-probe-baking-changed', } diff --git a/cocos/scene-graph/node.jsb.ts b/cocos/scene-graph/node.jsb.ts index 2e7b532e8e..7edbc71670 100644 --- a/cocos/scene-graph/node.jsb.ts +++ b/cocos/scene-graph/node.jsb.ts @@ -241,6 +241,7 @@ const REGISTERED_EVENT_MASK_LAYER_CHANGED = (1 << 3); const REGISTERED_EVENT_MASK_CHILD_REMOVED_CHANGED = (1 << 4); const REGISTERED_EVENT_MASK_CHILD_ADDED_CHANGED = (1 << 5); const REGISTERED_EVENT_MASK_SIBLING_ORDER_CHANGED_CHANGED = (1 << 6); +const REGISTERED_EVENT_MASK_LIGHT_PROBE_BAKING_CHANGED = (1 << 7); nodeProto.on = function (type, callback, target, useCapture: any = false) { switch (type) { @@ -287,6 +288,12 @@ nodeProto.on = function (type, callback, target, useCapture: any = false) { this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_SIBLING_ORDER_CHANGED_CHANGED; } break; + case NodeEventType.LIGHT_PROBE_BAKING_CHANGED: + if (!(this._registeredNodeEventTypeMask & REGISTERED_EVENT_MASK_LIGHT_PROBE_BAKING_CHANGED)) { + this._registerOnLightProbeBakingChanged(); + this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_LIGHT_PROBE_BAKING_CHANGED; + } + break; default: break; } @@ -507,6 +514,10 @@ nodeProto._onPostActivated = function (active: boolean) { } }; +nodeProto._onLightProbeBakingChanged = function () { + this.emit(NodeEventType.LIGHT_PROBE_BAKING_CHANGED); +}; + // Static functions. NodeCls._findComponent = function (node, constructor) { diff --git a/cocos/scene-graph/prefab/utils.ts b/cocos/scene-graph/prefab/utils.ts index a35f84f9bb..8b46e08592 100644 --- a/cocos/scene-graph/prefab/utils.ts +++ b/cocos/scene-graph/prefab/utils.ts @@ -432,8 +432,10 @@ export function expandNestedPrefabInstanceNode (node: Node) { prefabInfo.nestedPrefabInstanceRoots.forEach((instanceNode: Node) => { expandPrefabInstanceNode(instanceNode); // when expanding the prefab,it's children will be change,so need to apply after expanded - // @ts-expect-error private member access - applyNodeAndComponentId(instanceNode, instanceNode._prefab?.instance?.fileId); + if (!EDITOR) { + // @ts-expect-error private member access + applyNodeAndComponentId(instanceNode, instanceNode._prefab?.instance?.fileId); + } }); } } diff --git a/cocos/scene-graph/scene-globals.ts b/cocos/scene-graph/scene-globals.ts index 3aea69c424..fa120c4186 100644 --- a/cocos/scene-graph/scene-globals.ts +++ b/cocos/scene-graph/scene-globals.ts @@ -40,6 +40,7 @@ import { warnID } from '../core/platform/debug'; import { Material } from '../asset/assets/material'; import { cclegacy } from '../core'; import { Scene } from './scene'; +import { NodeEventType } from './node-event'; const _up = new Vec3(0, 1, 0); const _v3 = new Vec3(); @@ -48,7 +49,7 @@ const _col = new Color(); const _qt = new Quat(); // Normalize HDR color -const normalizeHDRColor = (color : Vec4) => { +const normalizeHDRColor = (color: Vec4) => { const intensity = 1.0 / Math.max(Math.max(Math.max(color.x, color.y), color.z), 0.0001); if (intensity < 1.0) { color.x *= intensity; @@ -66,7 +67,7 @@ export class AmbientInfo { * @en The sky color in HDR mode * @zh HDR 模式下的天空光照色 */ - get skyColorHDR () : Readonly { + get skyColorHDR (): Readonly { return this._skyColorHDR; } @@ -74,7 +75,7 @@ export class AmbientInfo { * @en The ground color in HDR mode * @zh HDR 模式下的地面光照色 */ - get groundAlbedoHDR () : Readonly { + get groundAlbedoHDR (): Readonly { return this._groundAlbedoHDR; } @@ -90,7 +91,7 @@ export class AmbientInfo { * @en The sky color in LDR mode * @zh LDR 模式下的天空光照色 */ - get skyColorLDR () : Readonly { + get skyColorLDR (): Readonly { return this._skyColorLDR; } @@ -98,7 +99,7 @@ export class AmbientInfo { * @en The ground color in LDR mode * @zh LDR 模式下的地面光照色 */ - get groundAlbedoLDR () : Readonly { + get groundAlbedoLDR (): Readonly { return this._groundAlbedoLDR; } @@ -418,8 +419,7 @@ export class SkyboxInfo { * @zh 旋转天空盒 */ @type(CCFloat) - @range([0, 360]) - @rangeStep(1) + @range([0, 360, 1]) @slide @tooltip('i18n:skybox.rotationAngle') set rotationAngle (val: number) { @@ -434,7 +434,7 @@ export class SkyboxInfo { * @en The optional diffusion convolution map used in tandem with IBL * @zh 使用的漫反射卷积图 */ - @visible(function (this : SkyboxInfo) { + @visible(function (this: SkyboxInfo) { if (this.useIBL && this.applyDiffuseMap) { return true; } @@ -444,7 +444,7 @@ export class SkyboxInfo { @readOnly @type(TextureCube) @displayOrder(100) - set diffuseMap (val : TextureCube | null) { + set diffuseMap (val: TextureCube | null) { const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { this._diffuseMapHDR = val; @@ -469,7 +469,7 @@ export class SkyboxInfo { * @en Convolutional map using environmental reflections * @zh 使用环境反射卷积图 */ - @visible(function (this : SkyboxInfo) { + @visible(function (this: SkyboxInfo) { if (this._resource?.reflectionMap) { return true; } @@ -631,7 +631,7 @@ export class FogInfo { if (this._resource) { this._resource.fogColor = this._fogColor; } } - get fogColor () : Readonly { + get fogColor (): Readonly { return this._fogColor; } @@ -660,8 +660,7 @@ export class FogInfo { return this._type !== FogType.LAYERED && this._type !== FogType.LINEAR; }) @type(CCFloat) - @range([0, 1]) - @rangeStep(0.01) + @range([0, 1, 0.01]) @slide @tooltip('i18n:fog.fogDensity') get fogDensity () { @@ -849,7 +848,7 @@ export class ShadowsInfo { this._shadowColor.set(val); if (this._resource) { this._resource.shadowColor = val; } } - get shadowColor () : Readonly { + get shadowColor (): Readonly { return this._shadowColor; } @@ -863,7 +862,7 @@ export class ShadowsInfo { Vec3.copy(this._normal, val); if (this._resource) { this._resource.normal = val; } } - get planeDirection () : Readonly { + get planeDirection (): Readonly { return this._normal; } @@ -1093,7 +1092,7 @@ export class LightProbeInfo { * @zh GI 采样数量 */ @editable - @range([64, 65536, 1]) + @range([64, 65535, 1]) @type(CCInteger) @tooltip('i18n:light_probe.giSamples') @displayName('GISamples') @@ -1240,6 +1239,28 @@ export class LightProbeInfo { this._resource.initialize(this); } + public onProbeBakeFinished () { + this.onProbeBakingChanged(this._scene); + } + + public onProbeBakeCleared () { + this.clearSHCoefficients(); + this.onProbeBakingChanged(this._scene); + } + + private onProbeBakingChanged (node: Node | null) { + if (!node) { + return; + } + + node.emit(NodeEventType.LIGHT_PROBE_BAKING_CHANGED); + + for (let i = 0; i < node.children.length; i++) { + const child = node.children[i]; + this.onProbeBakingChanged(child); + } + } + public clearSHCoefficients () { if (!this._data) { return; @@ -1444,6 +1465,14 @@ export class SceneGlobals { @serializable public bakedWithStationaryMainLight = false; + /** + * @en bake lightmap with highp mode + * @zh 是否使用高精度模式烘培光照图 + */ + @editable + @serializable + public bakedWithHighpLightmap = false; + /** * @en Activate and initialize the global configurations of the scene, no need to invoke manually. * @zh 启用和初始化场景全局配置,不需要手动调用 diff --git a/cocos/spine/lib/LICENSE b/cocos/spine/lib/LICENSE index b5136f1d38..4501a611fd 100644 --- a/cocos/spine/lib/LICENSE +++ b/cocos/spine/lib/LICENSE @@ -1,27 +1,3 @@ -/**************************************************************************** - Copyright (c) 2022-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. -****************************************************************************/ - Spine Runtimes License Agreement Last updated May 1, 2019. Replaces all prior versions. diff --git a/cocos/tween/tween.ts b/cocos/tween/tween.ts index fdf7ce4ecf..4b808601d8 100644 --- a/cocos/tween/tween.ts +++ b/cocos/tween/tween.ts @@ -166,7 +166,7 @@ export class Tween { /** * @en - * Add an action which calculate with absolute value. + * Add an action which calculates with absolute value. * @zh * 添加一个对属性进行绝对值计算的 action。 * @method to @@ -186,7 +186,7 @@ export class Tween { /** * @en - * Add an action which calculate with relative value. + * Add an action which calculates with relative value. * @zh * 添加一个对属性进行相对值计算的 action。 * @method by @@ -222,7 +222,7 @@ export class Tween { /** * @en - * Add an delay action. + * Add a delay action. * @zh * 添加一个延时 action。 * @method delay @@ -237,7 +237,7 @@ export class Tween { /** * @en - * Add an callback action. + * Add a callback action. * @zh * 添加一个回调 action。 * @method call @@ -253,7 +253,7 @@ export class Tween { /** * @en - * Add an sequence action. + * Add a sequence action. * @zh * 添加一个队列 action。 * @method sequence @@ -267,7 +267,7 @@ export class Tween { /** * @en - * Add an parallel action. + * Add a parallel action. * @zh * 添加一个并行 action。 * @method parallel @@ -281,7 +281,7 @@ export class Tween { /** * @en - * Add an repeat action. + * Add a repeat action. * This action will integrate before actions to a sequence action as their parameters. * @zh * 添加一个重复 action,这个 action 会将前一个动作作为他的参数。 @@ -309,7 +309,7 @@ export class Tween { /** * @en - * Add an repeat forever action. + * Add a repeat forever action. * This action will integrate before actions to a sequence action as their parameters. * @zh * 添加一个永久重复 action,这个 action 会将前一个动作作为他的参数。 @@ -332,7 +332,7 @@ export class Tween { /** * @en - * Add an reverse time action. + * Add a reverse time action. * This action will integrate before actions to a sequence action as their parameters. * @zh * 添加一个倒置时间 action,这个 action 会将前一个动作作为他的参数。 @@ -355,7 +355,7 @@ export class Tween { /** * @en - * Add an hide action, only for node target. + * Add a hide action, only for node target. * @zh * 添加一个隐藏 action,只适用于 target 是节点类型的。 */ @@ -367,7 +367,7 @@ export class Tween { /** * @en - * Add an show action, only for node target. + * Add a show action, only for node target. * @zh * 添加一个显示 action,只适用于 target 是节点类型的。 */ @@ -379,7 +379,7 @@ export class Tween { /** * @en - * Add an removeSelf action, only for node target. + * Add a removeSelf action, only for node target. * @zh * 添加一个移除自己 action,只适用于 target 是节点类型的。 */ diff --git a/cocos/ui/button.ts b/cocos/ui/button.ts index fbf8f0c615..b7f9fadf57 100644 --- a/cocos/ui/button.ts +++ b/cocos/ui/button.ts @@ -242,6 +242,9 @@ export class Button extends Component { } } + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ set _resizeToTarget (value: boolean) { if (value) { this._resizeNodeToTargetNode(); @@ -515,7 +518,15 @@ export class Button extends Component { this._updateState(); } + /** + * @en Enum for transition type. + * @zh 过渡类型。 + */ public static Transition = Transition; + /** + * @en The event types of [[Button]]. All button events are distributed by the owner Node, not the component + * @zh [[Button]] 的事件类型,注意:事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 + */ public static EventType = EventType; /** * @en diff --git a/cocos/ui/editbox/edit-box.ts b/cocos/ui/editbox/edit-box.ts index c3ee9e4e67..6ac0ee6fb4 100644 --- a/cocos/ui/editbox/edit-box.ts +++ b/cocos/ui/editbox/edit-box.ts @@ -124,10 +124,10 @@ export class EditBox extends Component { /** * @en - * The Label component attached to the node for EditBox's input text label + * The Label component attached to the node for EditBox's input text label. * * @zh - * 输入框输入文本节点上挂载的 Label 组件对象 + * 输入框输入文本节点上挂载的 Label 组件对象。 */ @type(Label) @displayOrder(3) @@ -302,10 +302,29 @@ export class EditBox extends Component { } } + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public static _EditBoxImpl = EditBoxImplBase; + /** + * @en Keyboard Return Type. + * @zh 键盘的返回键类型。 + */ public static KeyboardReturnType = KeyboardReturnType; + /** + * @en Defines some flag bits for setting text display and text formatting. + * @zh 定义了一些用于设置文本显示和文本格式化的标志位。 + */ public static InputFlag = InputFlag; + /** + * @en Input Mode. + * @zh 输入模式。 + */ public static InputMode = InputMode; + /** + * @en Keyboard event enumeration. + * @zh 键盘的事件枚举。 + */ public static EventType = EventType; /** * @en @@ -351,7 +370,7 @@ export class EditBox extends Component { * The event handler to be called when return key is pressed. Windows is not supported. * * @zh - * 当用户按下回车按键时的事件回调,目前不支持 windows 平台 + * 当用户按下回车按键时的事件回调,目前不支持 windows 平台。 */ @type([ComponentEventHandler]) @serializable @@ -426,7 +445,7 @@ export class EditBox extends Component { } /** - * @en Let the EditBox get focus + * @en Let the EditBox get focus. * @zh 让当前 EditBox 获得焦点。 */ public setFocus () { @@ -436,8 +455,8 @@ export class EditBox extends Component { } /** - * @en Let the EditBox get focus - * @zh 让当前 EditBox 获得焦点 + * @en Let the EditBox get focus. + * @zh 让当前 EditBox 获得焦点。 */ public focus () { if (this._impl) { @@ -446,8 +465,8 @@ export class EditBox extends Component { } /** - * @en Let the EditBox lose focus - * @zh 让当前 EditBox 失去焦点 + * @en Let the EditBox lose focus. + * @zh 让当前 EditBox 失去焦点。 */ public blur () { if (this._impl) { @@ -589,10 +608,6 @@ export class EditBox extends Component { this._textLabel = textLabel; } - // update - const transformComp = this._textLabel!.node._uiProps.uiTransformComp; - transformComp!.setAnchorPoint(0, 1); - textLabel.overflow = Label.Overflow.CLAMP; if (this._inputMode === InputMode.ANY) { textLabel.verticalAlign = VerticalTextAlignment.TOP; textLabel.enableWrapText = true; @@ -620,9 +635,6 @@ export class EditBox extends Component { this._placeholderLabel = placeholderLabel; } - // update - const transform = this._placeholderLabel!.node._uiProps.uiTransformComp; - transform!.setAnchorPoint(0, 1); if (this._inputMode === InputMode.ANY) { placeholderLabel.enableWrapText = true; } else { @@ -788,46 +800,6 @@ if (typeof window === 'object' && typeof document === 'object' && !MINIGAME && ! EditBox._EditBoxImpl = EditBoxImpl; } -/** - * @en - * Note: This event is emitted from the node to which the component belongs. - * @zh - * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 - * @event editing-did-began - * @param {Event.EventCustom} event - * @param {EditBox} editbox - The EditBox component. - */ - -/** - * @en - * Note: This event is emitted from the node to which the component belongs. - * @zh - * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 - * @event editing-did-ended - * @param {Event.EventCustom} event - * @param {EditBox} editbox - The EditBox component. - */ - -/** - * @en - * Note: This event is emitted from the node to which the component belongs. - * @zh - * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 - * @event text-changed - * @param {Event.EventCustom} event - * @param {EditBox} editbox - The EditBox component. - */ - -/** - * @en - * Note: This event is emitted from the node to which the component belongs. - * @zh - * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 - * @event editing-return - * @param {Event.EventCustom} event - * @param {EditBox} editbox - The EditBox component. - */ - /** * @en if you don't need the EditBox and it isn't in any running Scene, you should * call the destroy method on this component or the associated node explicitly. diff --git a/cocos/ui/layout.ts b/cocos/ui/layout.ts index 77251cdb26..b1f0d7978d 100644 --- a/cocos/ui/layout.ts +++ b/cocos/ui/layout.ts @@ -333,7 +333,7 @@ export class Layout extends Component { /** * @en * The start axis for grid layout. If you choose horizontal, then children will layout horizontally at first, - * and then break line on demand. Choose vertical if you want to layout vertically at first . + * and then break line on demand. Choose vertical if you want to layout vertically at first. * * @zh * 起始轴方向类型,可进行水平和垂直布局排列,只有布局类型为 GRID 的时候才有效。 @@ -608,11 +608,35 @@ export class Layout extends Component { this._doLayoutDirty(); } + /** + * @en Layout type. + * @zh 布局类型。 + */ public static Type = Type; + /** + * @en Vertical layout direction. + * @zh 垂直方向布局方式。 + */ public static VerticalDirection = VerticalDirection; + /** + * @en Horizontal layout direction. + * @zh 水平方向布局方式。 + */ public static HorizontalDirection = HorizontalDirection; + /** + * @en Layout Resize Mode. + * @zh 缩放模式。 + */ public static ResizeMode = ResizeMode; + /** + * @en Grid Layout start axis direction. + * @zh 布局轴向,只用于 GRID 布局。 + */ public static AxisDirection = AxisDirection; + /** + * @en Layout constraint. + * @zh 布局约束。 + */ public static Constraint = Constraint; @serializable @@ -660,7 +684,7 @@ export class Layout extends Component { * * @zh * 立即执行更新布局。 - * + * @param force @en force update or not. @zh 是否强制更新。 * @example * ```ts * import { Layout, log } from 'cc'; diff --git a/cocos/ui/page-view-indicator.ts b/cocos/ui/page-view-indicator.ts index 23ec00c695..6ba3fd1f74 100644 --- a/cocos/ui/page-view-indicator.ts +++ b/cocos/ui/page-view-indicator.ts @@ -40,7 +40,7 @@ const _color = new Color(); /** * @en Enum for PageView Indicator direction. * - * @zh 页面视图指示器的摆放方向 + * @zh 页面视图指示器的摆放方向。 * * @enum PageViewIndicator.Direction */ @@ -48,14 +48,14 @@ enum Direction { /** * @en The horizontal direction. * - * @zh 水平方向 + * @zh 水平方向。 */ HORIZONTAL = 0, /** * @en The vertical direction. * - * @zh 垂直方向 + * @zh 垂直方向。 */ VERTICAL = 1, } @@ -66,7 +66,7 @@ ccenum(Direction); * The Page View Indicator Component. * * @zh - * 页面视图每页标记组件 + * 页面视图每页标记组件。 */ @ccclass('cc.PageViewIndicator') @help('i18n:cc.PageViewIndicator') @@ -78,7 +78,7 @@ export class PageViewIndicator extends Component { * The spriteFrame for each element. * * @zh - * 每个页面标记显示的图片 + * 每个页面标记显示的图片。 */ @type(SpriteFrame) @tooltip('i18n:pageview_indicator.spriteFrame') @@ -98,9 +98,9 @@ export class PageViewIndicator extends Component { * The location direction of PageViewIndicator. * * @zh - * 页面标记摆放方向 + * 页面标记摆放方向。 * - * @param direction @en The direction of the PageViewIndicator @zh 页面标记的摆放方向 + * @param direction @en The direction of the PageViewIndicator. @zh 页面标记的摆放方向。 */ @type(Direction) @tooltip('i18n:pageview_indicator.direction') @@ -120,7 +120,7 @@ export class PageViewIndicator extends Component { * The cellSize for each element. * * @zh - * 每个页面标记的大小 + * 每个页面标记的大小。 */ @type(Size) @tooltip('i18n:pageview_indicator.cell_size') @@ -135,6 +135,11 @@ export class PageViewIndicator extends Component { this._cellSize = value; } + /** + * @en Enum for PageView Indicator direction. + * @zh 页面视图指示器的摆放方向。 + * @enum PageViewIndicator.Direction + */ public static Direction = Direction; /** @@ -142,7 +147,7 @@ export class PageViewIndicator extends Component { * The distance between each element. * * @zh - * 每个页面标记之间的边距 + * 每个页面标记之间的边距。 */ @serializable @tooltip('i18n:pageview_indicator.spacing') @@ -166,9 +171,9 @@ export class PageViewIndicator extends Component { * Set Page View. * * @zh - * 设置页面视图 + * 设置页面视图。 * - * @param target @en The page view which is attached with this indicator @zh 当前标记对象附着到的页面视图对象 + * @param target @en The page view which is attached with this indicator. @zh 当前标记对象附着到的页面视图对象。 */ public setPageView (target: PageView) { this._pageView = target; diff --git a/cocos/ui/page-view.ts b/cocos/ui/page-view.ts index aa625b8c0a..71a281cb4b 100644 --- a/cocos/ui/page-view.ts +++ b/cocos/ui/page-view.ts @@ -43,17 +43,17 @@ const _tempVec2 = new Vec2(); /** * @en Enum for Page View Size Mode. * - * @zh 页面视图每个页面统一的大小类型 + * @zh 页面视图每个页面统一的大小类型。 */ enum SizeMode { /** - * @en Each page is unified in size - * @zh 每个页面统一大小 + * @en Each page is unified in size. + * @zh 每个页面统一大小。 */ Unified = 0, /** - * @en Each page is in free size - * @zh 每个页面大小随意 + * @en Each page is in free size. + * @zh 每个页面大小随意。 */ Free = 1, } @@ -63,17 +63,17 @@ ccenum(SizeMode); /** * @en Enum for Page View Direction. * - * @zh 页面视图滚动类型 + * @zh 页面视图滚动类型。 */ enum Direction { /** * @en Horizontal scroll. - * @zh 水平滚动 + * @zh 水平滚动。 */ Horizontal = 0, /** * @en Vertical scroll. - * @zh 垂直滚动 + * @zh 垂直滚动。 */ Vertical = 1, } @@ -83,7 +83,7 @@ ccenum(Direction); /** * @en Enum for ScrollView event type. * - * @zh 滚动视图事件类型 + * @zh 滚动视图事件类型。 */ enum EventType { PAGE_TURNING = 'page-turning', @@ -94,7 +94,7 @@ enum EventType { * The PageView control. * * @zh - * 页面视图组件 + * 页面视图组件。 */ @ccclass('cc.PageView') @help('i18n:cc.PageView') @@ -106,7 +106,7 @@ export class PageView extends ScrollView { * Specify the size type of each page in PageView. * * @zh - * 页面视图中每个页面大小类型 + * 页面视图中每个页面大小类型。 */ @type(SizeMode) @tooltip('i18n:pageview.sizeMode') @@ -128,7 +128,7 @@ export class PageView extends ScrollView { * The page view direction. * * @zh - * 页面视图滚动类型 + * 页面视图滚动类型。 */ @type(Direction) @tooltip('i18n:pageview.direction') @@ -195,7 +195,7 @@ export class PageView extends ScrollView { * The Page View Indicator. * * @zh - * 页面视图指示器组件 + * 页面视图指示器组件。 */ @type(PageViewIndicator) @tooltip('i18n:pageview.indicator') @@ -218,8 +218,20 @@ export class PageView extends ScrollView { return this._curPageIdx; } + /** + * @en Enum for Page View Size Mode. + * @zh 页面视图每个页面统一的大小类型。 + */ public static SizeMode = SizeMode; + /** + * @en Enum for Page View Direction. + * @zh 页面视图滚动类型。 + */ public static Direction = Direction; + /** + * @en Enum for Page View event. + * @zh 页面视图事件枚举 + */ public static EventType = extendsEnum(EventType, ScrollEventType); /** @@ -237,6 +249,12 @@ export class PageView extends ScrollView { @tooltip('i18n:pageview.autoPageTurningThreshold') public autoPageTurningThreshold = 100; + /** + * @en + * The vertical scrollbar reference. + * @zh + * 垂直滚动的 ScrollBar。 + */ @type(ScrollBar) @override @visible(false) @@ -248,6 +266,12 @@ export class PageView extends ScrollView { super.verticalScrollBar = value; } + /** + * @en + * The horizontal scrollbar reference. + * @zh + * 水平滚动的 ScrollBar。 + */ @type(ScrollBar) @override @visible(false) @@ -259,21 +283,47 @@ export class PageView extends ScrollView { super.horizontalScrollBar = value; } + /** + * @en + * Enable horizontal scroll. + * @zh + * 是否开启水平滚动。 + */ @override @serializable @visible(false) public horizontal = true; + /** + * @en + * Enable vertical scroll. + * @zh + * 是否开启垂直滚动。 + */ @override @serializable @visible(false) public vertical = true; + /** + * @en + * If cancelInnerEvents is set to true, the scroll behavior will cancel touch events on inner content nodes + * It's set to true by default. + * @zh + * 如果这个属性被设置为 true,那么滚动行为会取消子节点上注册的触摸事件,默认被设置为 true。
+ * 注意,子节点上的 touchstart 事件仍然会触发,触点移动距离非常短的情况下 touchmove 和 touchend 也不会受影响。 + */ @override @serializable @visible(false) public cancelInnerEvents = true; + /** + * @en + * ScrollView events callback. + * @zh + * 滚动视图的事件回调函数。 + */ @type([ComponentEventHandler]) @serializable @override @@ -281,8 +331,8 @@ export class PageView extends ScrollView { public scrollEvents: ComponentEventHandler[] = []; /** - * @en The time required to turn over a page. unit: second - * @zh 每个页面翻页时所需时间。单位:秒 + * @en The time required to turn over a page, unit: second. + * @zh 每个页面翻页时所需时间,单位:秒。 */ @serializable @editable @@ -290,8 +340,8 @@ export class PageView extends ScrollView { public pageTurningSpeed = 0.3; /** - * @en PageView events callback - * @zh 滚动视图的事件回调函数 + * @en PageView events callback. + * @zh 滚动视图的事件回调函数。 */ @type([ComponentEventHandler]) @serializable @@ -348,7 +398,7 @@ export class PageView extends ScrollView { * @zh * 返回当前页面索引。 * - * @returns @en Current page index of this page view @zh 当前页面索引。 + * @returns @en Current page index of this page view. @zh 当前页面索引。 */ public getCurrentPageIndex () { return this._curPageIdx; @@ -360,7 +410,7 @@ export class PageView extends ScrollView { * * @zh * 设置当前页面索引。 - * @param index @en The page index to scroll to @zh 需要滚动到的页面索引 + * @param index @en The page index to scroll to. @zh 需要滚动到的页面索引。 */ public setCurrentPageIndex (index: number) { this.scrollToPage(index, 1); @@ -373,7 +423,7 @@ export class PageView extends ScrollView { * @zh * 返回视图中的所有页面。 * - * @returns @en return all pages of this page view @zh 返回当前视图所有页面 + * @returns @en return all pages of this page view. @zh 返回当前视图所有页面。 */ public getPages () { return this._pages; @@ -386,7 +436,7 @@ export class PageView extends ScrollView { * @zh * 在当前页面视图的尾部插入一个新视图。 * - * @param page @en New page to add to this page view @zh 新加入的视图 + * @param page @en New page to add to this page view. @zh 新加入的视图。 */ public addPage (page: Node) { if (!page || this._pages.indexOf(page) !== -1 || !this.content) { @@ -408,8 +458,8 @@ export class PageView extends ScrollView { * @zh * 将页面插入指定位置中。 * - * @param page @en New page to insert to this page view @zh 新插入的视图 - * @param index @en The index of new page to be inserted @zh 新插入视图的索引 + * @param page @en New page to insert to this page view. @zh 新插入的视图。 + * @param index @en The index of new page to be inserted. @zh 新插入视图的索引。 */ public insertPage (page: Node, index: number) { if (index < 0 || !page || this._pages.indexOf(page) !== -1 || !this.content) { @@ -436,7 +486,7 @@ export class PageView extends ScrollView { * @zh * 移除指定页面。 * - * @param page @en The page to be removed @zh 将被移除的页面 + * @param page @en The page to be removed. @zh 将被移除的页面。 */ public removePage (page: Node) { if (!page || !this.content) { return; } @@ -455,7 +505,7 @@ export class PageView extends ScrollView { * @zh * 移除指定下标的页面。 * - * @param index @en The index of the page to be removed @zh 将被移除界面的页面下标 + * @param index @en The index of the page to be removed. @zh 将被移除界面的页面下标。 */ public removePageAtIndex (index: number) { const pageList = this._pages; @@ -491,8 +541,8 @@ export class PageView extends ScrollView { * @zh * 滚动到指定页面 * - * @param idx @en The index of page to be scroll to @zh 希望滚动到的页面下标 - * @param timeInSecond @en How long time to scroll to the page, in seconds @zh 滚动到指定页面所需时间,单位:秒 + * @param idx @en The index of page to be scroll to. @zh 希望滚动到的页面下标。 + * @param timeInSecond @en How long time to scroll to the page, in seconds. @zh 滚动到指定页面所需时间,单位:秒。 */ public scrollToPage (idx: number, timeInSecond = 0.3) { if (idx < 0 || idx >= this._pages.length) { diff --git a/cocos/ui/safe-area.ts b/cocos/ui/safe-area.ts index 91c62d8a7f..a2f1f61c8d 100644 --- a/cocos/ui/safe-area.ts +++ b/cocos/ui/safe-area.ts @@ -71,8 +71,8 @@ export class SafeArea extends Component { } /** - * @en Adapt to safe area - * @zh 立即适配安全区域 + * @en Adapt to safe area. + * @zh 立即适配安全区域。 * @method updateArea * @example * let safeArea = this.node.addComponent(cc.SafeArea); diff --git a/cocos/ui/scroll-bar.ts b/cocos/ui/scroll-bar.ts index 163d2a34ec..d4a4f29aaa 100644 --- a/cocos/ui/scroll-bar.ts +++ b/cocos/ui/scroll-bar.ts @@ -225,7 +225,7 @@ export class ScrollBar extends Component { * @zh * 重置滚动条位置。 * - * @param outOfBoundary @en Rolling displacement @zh 滚动位移。 + * @param outOfBoundary @en Rolling displacement. @zh 滚动位移。 */ public onScroll (outOfBoundary: Vec2 | Readonly) { if (!this._scrollView) { @@ -291,7 +291,7 @@ export class ScrollBar extends Component { * @zh * 滚动视窗设置。 * - * @param scrollView @en The scroll view which is attached with this scroll bar @zh 当前滚动条附着的滚动视窗 + * @param scrollView @en The scroll view which is attached with this scroll bar. @zh 当前滚动条附着的滚动视窗。 */ public setScrollView (scrollView: ScrollView) { this._scrollView = scrollView; diff --git a/cocos/ui/scroll-view.ts b/cocos/ui/scroll-view.ts index 5243a210f7..0468a27420 100644 --- a/cocos/ui/scroll-view.ts +++ b/cocos/ui/scroll-view.ts @@ -28,7 +28,7 @@ import { EDITOR } from 'internal:constants'; import { EventHandler as ComponentEventHandler } from '../scene-graph/component-event-handler'; import { UITransform } from '../2d/framework'; import { Event, EventMouse, EventTouch, Touch, SystemEventType, EventHandle, EventGamepad } from '../input/types'; -import { logID } from '../core/platform/debug'; +import { errorID, logID } from '../core/platform/debug'; import { Size, Vec2, Vec3 } from '../core/math'; import { Layout } from './layout'; import { ScrollBar } from './scroll-bar'; @@ -82,7 +82,7 @@ const eventMap = { * Enum for ScrollView event type. * * @zh - * 滚动视图事件类型 + * 滚动视图事件类型。 */ export enum EventType { /** @@ -314,6 +314,9 @@ export class ScrollView extends ViewGroup { @displayOrder(0) @tooltip('i18n:scrollview.horizontal_bar') get horizontalScrollBar () { + if (this._horizontalScrollBar && !this._horizontalScrollBar.isValid) { + errorID(4303, 'horizontal', this.node.name); + } return this._horizontalScrollBar; } @@ -353,6 +356,9 @@ export class ScrollView extends ViewGroup { @displayOrder(1) @tooltip('i18n:scrollview.vertical_bar') get verticalScrollBar () { + if (this._verticalScrollBar && !this._verticalScrollBar.isValid) { + errorID(4303, 'vertical', this.node.name); + } return this._verticalScrollBar; } @@ -396,6 +402,10 @@ export class ScrollView extends ViewGroup { @tooltip('i18n:scrollview.scrollEvents') public scrollEvents: ComponentEventHandler[] = []; + /** + * @en The display view in the scroll view component. + * @zh scroll view 组件中的显示区域。 + */ get view () { const parent = this._content && this._content.parent; if (!parent) { @@ -483,7 +493,7 @@ export class ScrollView extends ViewGroup { * * @param timeInSecond * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 - * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true). @zh 滚动加速是否衰减,默认为 true * @example * ```ts * // Scroll to the top of the view. @@ -513,7 +523,7 @@ export class ScrollView extends ViewGroup { * * @param timeInSecond * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 - * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true). @zh 滚动加速是否衰减,默认为 true。 * @example * ```ts * // Scroll to the left of the view. @@ -543,7 +553,7 @@ export class ScrollView extends ViewGroup { * * @param timeInSecond * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 - * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true). @zh 滚动加速是否衰减,默认为 true。 * @example * ```ts * // Scroll to the right of the view. @@ -573,7 +583,7 @@ export class ScrollView extends ViewGroup { * * @param timeInSecond * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 - * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true). @zh 滚动加速是否衰减,默认为 true。 * @example * ```ts * // Scroll to the upper left corner of the view. @@ -603,7 +613,7 @@ export class ScrollView extends ViewGroup { * * @param timeInSecond * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 - * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true). @zh 滚动加速是否衰减,默认为 true。 * @example * ```ts * // Scroll to the top right corner of the view. @@ -633,7 +643,7 @@ export class ScrollView extends ViewGroup { * * @param timeInSecond * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 - * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true). @zh 滚动加速是否衰减,默认为 true。 * @example * ```ts * // Scroll to the lower left corner of the view. @@ -663,7 +673,7 @@ export class ScrollView extends ViewGroup { * * @param timeInSecond * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 - * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true). @zh 滚动加速是否衰减,默认为 true。 * @example * ```ts * // Scroll to the lower right corner of the view. @@ -696,7 +706,7 @@ export class ScrollView extends ViewGroup { * @en After scrolling the view, the position of the view content relative to the view window. @zh 滚动视图后,视图内容(content)相对于视图窗口(viewport)的位置。 * @param timeInSecond * @en Scroll time (s). If it times out, the content immediately jumps to the specified offset. @zh 滚动时间(s)。 如果超时,内容将立即跳到指定偏移量处。 - * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true). @zh 滚动加速是否衰减,默认为 true。 * @example * ```ts * // Scroll to middle position in 0.1 second in x-axis @@ -731,7 +741,7 @@ export class ScrollView extends ViewGroup { * @zh * 获取滚动视图相对于视图窗口左上角原点的位置。 * - * @return @en Current rolling offset @zh 当前滚动偏移量 + * @return @en Current rolling offset. @zh 当前滚动偏移量。 */ public getScrollOffset () { const topDelta = this._getContentTopBoundary() - this._topBoundary; @@ -747,7 +757,7 @@ export class ScrollView extends ViewGroup { * @zh * 获取滚动视图最大可以滚动的偏移量。 * - * @return @en Maximum scrollable offset @zh 最大可滚动偏移量 + * @return @en Maximum scrollable offset. @zh 最大可滚动偏移量。 */ public getMaxScrollOffset () { if (!this._content || !this.view) { @@ -773,7 +783,7 @@ export class ScrollView extends ViewGroup { * @en Scroll to the destination which is located at the percent interpolation from left border to the right border @zh 滚动到从左到右指定百分比插值的位置 * @param timeInSecond * @en Scroll time (s). If it times out, the content immediately jumps to the specified offset. @zh 滚动时间(s)。 如果超时,内容将立即跳到指定偏移量处。 - * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true). @zh 滚动加速是否衰减,默认为 true。 * @example * ```ts * // Scroll to middle position. @@ -802,11 +812,11 @@ export class ScrollView extends ViewGroup { * 视图内容在规定时间内进行垂直方向和水平方向的滚动,并且滚动到指定百分比位置上。 * * @param anchor - * @en Scroll to the destination which is located at the anchor interpolation from left/top border to the right/bottom border - * @zh 滚动到从左/上到右/下指定锚点对应分量插值的位置 + * @en Scroll to the destination which is located at the anchor interpolation from left/top border to the right/bottom border. + * @zh 滚动到从左/上到右/下指定锚点对应分量插值的位置。 * @param timeInSecond * @en Scroll time (s). If it times out, the content immediately jumps to the specified offset. @zh 滚动时间(s)。 如果超时,内容将立即跳到指定偏移量处。 - * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true). @zh 滚动加速是否衰减,默认为 true。 * @example * ```ts * // Vertical scroll to the bottom of the view. @@ -838,10 +848,10 @@ export class ScrollView extends ViewGroup { * 视图内容在规定时间内滚动到 ScrollView 垂直方向的百分比位置上。 * * @param percent - * @en Scroll to the destination which is located at the percent interpolation from top border to the bottom border @zh 滚动到从上到下指定百分比插值的位置 + * @en Scroll to the destination which is located at the percent interpolation from top border to the bottom border. @zh 滚动到从上到下指定百分比插值的位置。 * @param timeInSecond * @en Scroll time (s). If it times out, the content immediately jumps to the specified offset. @zh 滚动时间(s)。 如果超时,内容将立即跳到指定偏移量处。 - * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true). @zh 滚动加速是否衰减,默认为 true。 * @example * ```ts * scrollView.scrollToPercentVertical(0.5, 0.1); @@ -880,7 +890,7 @@ export class ScrollView extends ViewGroup { * @zh * 设置当前视图内容的坐标点。 * - * @param position @en Current content position @zh 希望设置内容框体的位置 + * @param position @en Current content position. @zh 希望设置内容框体的位置。 * @deprecated Since 3.1.0, setContentPosition is deprecated, please use scrollToOffset instead. */ public setContentPosition (position: Vec3) { @@ -907,7 +917,7 @@ export class ScrollView extends ViewGroup { * @zh * 获取当前视图内容的坐标点。 * - * @returns - current content position. + * @returns @en current content position. @zh 当前视图内容的坐标点。 * @deprecated Since 3.1.0, getContentPosition is deprecated. */ public getContentPosition () { @@ -930,7 +940,7 @@ export class ScrollView extends ViewGroup { * @zh * 用户是否在拖拽当前滚动视图。 * - * @returns - 是否在拖拽当前滚动视图。 + * @returns @en If or not the current scrolling view is being dragged. @zh 是否在拖拽当前滚动视图。 */ public isScrolling () { return this._scrolling; @@ -943,12 +953,17 @@ export class ScrollView extends ViewGroup { * @zh * 当前滚动视图是否在惯性滚动。 * - * @returns - 滚动视图是否在惯性滚动。 + * @returns @en Whether the scrolling view is scrolling inertially. @zh 滚动视图是否在惯性滚动。 */ public isAutoScrolling () { return this._autoScrolling; } + /** + * @en Get the minimum precision time of the end-of-scroll event. + * @zh 获得滚动结束的事件的最小精度时间。 + * @returns @en Minimum time. @zh 最小时间。 + */ public getScrollEndedEventTiming () { return EPSILON; } @@ -1362,32 +1377,32 @@ export class ScrollView extends ViewGroup { } protected _updateScrollBar (outOfBoundary: Vec2 | Readonly) { - if (this._horizontalScrollBar) { + if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) { this._horizontalScrollBar.onScroll(outOfBoundary); } - if (this.verticalScrollBar) { - this.verticalScrollBar.onScroll(outOfBoundary); + if (this._verticalScrollBar && this._verticalScrollBar.isValid) { + this._verticalScrollBar.onScroll(outOfBoundary); } } protected _onScrollBarTouchBegan () { - if (this._horizontalScrollBar) { + if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) { this._horizontalScrollBar.onTouchBegan(); } - if (this.verticalScrollBar) { - this.verticalScrollBar.onTouchBegan(); + if (this._verticalScrollBar && this._verticalScrollBar.isValid) { + this._verticalScrollBar.onTouchBegan(); } } protected _onScrollBarTouchEnded () { - if (this._horizontalScrollBar) { + if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) { this._horizontalScrollBar.onTouchEnded(); } - if (this.verticalScrollBar) { - this.verticalScrollBar.onTouchEnded(); + if (this._verticalScrollBar && this._verticalScrollBar.isValid) { + this._verticalScrollBar.onTouchEnded(); } } @@ -1426,11 +1441,11 @@ export class ScrollView extends ViewGroup { } protected _hideScrollBar () { - if (this._horizontalScrollBar) { + if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) { this._horizontalScrollBar.hide(); } - if (this._verticalScrollBar) { + if (this._verticalScrollBar && this._verticalScrollBar.isValid) { this._verticalScrollBar.hide(); } } @@ -1441,19 +1456,19 @@ export class ScrollView extends ViewGroup { } const viewTrans = this.view; const uiTrans = this._content._uiProps.uiTransformComp!; - if (this.verticalScrollBar) { + if (this._verticalScrollBar && this._verticalScrollBar.isValid) { if (uiTrans.height < viewTrans.height) { - this.verticalScrollBar.hide(); + this._verticalScrollBar.hide(); } else { - this.verticalScrollBar.show(); + this._verticalScrollBar.show(); } } - if (this.horizontalScrollBar) { + if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) { if (uiTrans.width < viewTrans.width) { - this.horizontalScrollBar.hide(); + this._horizontalScrollBar.hide(); } else { - this.horizontalScrollBar.show(); + this._horizontalScrollBar.show(); } } } diff --git a/cocos/ui/toggle-container.ts b/cocos/ui/toggle-container.ts index 7f537efc75..eed1e4eafe 100644 --- a/cocos/ui/toggle-container.ts +++ b/cocos/ui/toggle-container.ts @@ -121,8 +121,8 @@ export class ToggleContainer extends Component { * @zh * 刷新管理的 toggle 状态。 * - * @param toggle @en The toggle to be updated @zh 需要被更新的切换键 - * @param emitEvent @en Whether events are needed to be emitted @zh 是否需要触发事件 + * @param toggle @en The toggle to be updated. @zh 需要被更新的切换键。 + * @param emitEvent @en Whether events are needed to be emitted. @zh 是否需要触发事件。 */ public notifyToggleCheck (toggle: Toggle, emitEvent = true) { if (!this.enabledInHierarchy) { return; } @@ -144,6 +144,10 @@ export class ToggleContainer extends Component { } } + /** + * @en Ensure toggles state valid. + * @zh 确保 toggles 状态有效。 + */ public ensureValidState () { const toggles = this.toggleItems; if (!this._allowSwitchOff && !this.anyTogglesChecked() && toggles.length !== 0) { diff --git a/cocos/ui/toggle.ts b/cocos/ui/toggle.ts index 6a1724c9aa..6a0855fce4 100644 --- a/cocos/ui/toggle.ts +++ b/cocos/ui/toggle.ts @@ -91,6 +91,9 @@ export class Toggle extends Button { this._checkMark = value; } + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ set _resizeToTarget (value: boolean) { if (value) { this._resizeNodeToTargetNode(); @@ -108,6 +111,10 @@ export class Toggle extends Button { return null; } + /** + * @en Enum for toggle event. + * @zh toggle 事件枚举。 + */ public static EventType = extendsEnum(EventType, ButtonEventType); /** @@ -149,7 +156,9 @@ export class Toggle extends Button { } } - // + /** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ public playEffect () { if (this._checkMark) { this._checkMark.node.active = this._isChecked; @@ -163,7 +172,7 @@ export class Toggle extends Button { * @zh * 设置 isChecked 而不调用 checkEvents 回调。 * - * @param value @en Whether this toggle is pressed @zh 是否被按下 + * @param value @en Whether this toggle is pressed. @zh 是否被按下。 */ public setIsCheckedWithoutNotify (value: boolean) { this._set(value, false); @@ -199,8 +208,8 @@ export class Toggle extends Button { * @zh * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 * @event toggle - * @param event @en The event when toggle is pressed up or down @zh 切换键被按下或抬起时发送的事件 - * @param toggle @en The Toggle component @zh 切换键组件 + * @param event @en The event when toggle is pressed up or down. @zh 切换键被按下或抬起时发送的事件。 + * @param toggle @en The Toggle component. @zh 切换键组件。 */ legacyCC.Toggle = Toggle; diff --git a/cocos/ui/widget-manager.ts b/cocos/ui/widget-manager.ts index fc17e2f2fc..ddd6b8aaa1 100644 --- a/cocos/ui/widget-manager.ts +++ b/cocos/ui/widget-manager.ts @@ -261,6 +261,11 @@ function updateAlignment (node: Node) { } } +/** + * @en widget Manager, use to align widget + * @zh widget 管理器,用于对齐操作 + * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. + */ export const widgetManager = cclegacy._widgetManager = { isAligning: false, _nodesOrderDirty: false, diff --git a/cocos/ui/widget.ts b/cocos/ui/widget.ts index e2cc51995c..e101f31a6a 100644 --- a/cocos/ui/widget.ts +++ b/cocos/ui/widget.ts @@ -699,7 +699,9 @@ export class Widget extends Component { /** * @zh - * 对齐开关,由 AlignFlags 组成 + * 对齐标志位。 + * @en + * Align flags. */ @editable get alignFlags () { @@ -1013,6 +1015,9 @@ export class Widget extends Component { } } +/** + * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. + */ export declare namespace Widget { export type AlignMode = EnumAlias; } diff --git a/cocos/video/video-downloader.ts b/cocos/video/video-downloader.ts index 25168bfab8..06c5b43e5e 100644 --- a/cocos/video/video-downloader.ts +++ b/cocos/video/video-downloader.ts @@ -25,7 +25,6 @@ import downloader from '../asset/asset-manager/downloader'; import factory from '../asset/asset-manager/factory'; -import { CompleteCallback, IDownloadParseOptions } from '../asset/asset-manager/shared'; import { log } from '../core/platform/debug'; import { VideoClip } from './assets/video-clip'; import { ccwindow } from '../core/global-exports'; @@ -33,7 +32,7 @@ import { ccwindow } from '../core/global-exports'; const ccdocument = ccwindow.document; // eslint-disable-next-line consistent-return -export function downloadVideo (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) { +export function downloadVideo (url: string, options: Record, onComplete: (err: Error | null, data?: any | null) => void) { const video = ccdocument.createElement('video'); const source = ccdocument.createElement('source'); video.appendChild(source); @@ -57,7 +56,7 @@ export function downloadVideo (url: string, options: IDownloadParseOptions, onCo req.send(); } -function createVideoClip (id: string, data: HTMLVideoElement, options: IDownloadParseOptions, onComplete: CompleteCallback) { +function createVideoClip (id: string, data: HTMLVideoElement, options: Record, onComplete: (err: Error | null, data?: VideoClip | null) => void) { const out = new VideoClip(); out._nativeUrl = id; out._nativeAsset = data; diff --git a/editor/assets/chunks/builtin/functionalities/sh.chunk b/editor/assets/chunks/builtin/functionalities/sh.chunk index 952763b3fe..7430c4939f 100644 --- a/editor/assets/chunks/builtin/functionalities/sh.chunk +++ b/editor/assets/chunks/builtin/functionalities/sh.chunk @@ -3,17 +3,16 @@ #if CC_USE_LIGHT_PROBE vec3 SHEvaluate(vec3 normal) { -#if USE_INSTANCING vec3 result; + +#if USE_INSTANCING // calculate linear and const terms vec4 normal4 = vec4(normal, 1.0); result.r = dot(v_sh_linear_const_r, normal4); result.g = dot(v_sh_linear_const_g, normal4); result.b = dot(v_sh_linear_const_b, normal4); - return result; #else - vec3 result; // calculate linear and const terms vec4 normal4 = vec4(normal, 1.0); result.r = dot(cc_sh_linear_const_r, normal4); @@ -28,8 +27,14 @@ vec3 SHEvaluate(vec3 normal) result.g += dot(cc_sh_quadratic_g, n14); result.b += dot(cc_sh_quadratic_b, n14); result += (cc_sh_quadratic_a.rgb * n5); - - return result; #endif + + #if CC_USE_HDR + // convert from standard camera exposure parameters to current exposure value + // baked in LDR scene still regarded as exposured with standard camera parameters + result *= cc_exposure.w * cc_exposure.x; + #endif + + return result; } #endif diff --git a/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk b/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk index bc22e41c47..40654b6fa0 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk @@ -9,7 +9,7 @@ #if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0 #pragma builtin(local) layout(set = 2, binding = 1) uniform CCForwardLight { - highp vec4 cc_lightPos[LIGHTS_PER_PASS]; // xyz: pos, w: isSpotLight + highp vec4 cc_lightPos[LIGHTS_PER_PASS]; // xyz: pos, w: light type vec4 cc_lightColor[LIGHTS_PER_PASS]; // xyz: color, w: intensity vec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS]; // x: size, y: range, z: cos(half outterAngle), w: enable shadow vec4 cc_lightDir[LIGHTS_PER_PASS]; // xyz: dir, w: valid light count diff --git a/editor/assets/chunks/builtin/uniforms/cc-global.chunk b/editor/assets/chunks/builtin/uniforms/cc-global.chunk index 8b75cbe57a..8e815860f1 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-global.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-global.chunk @@ -12,6 +12,7 @@ layout(set = 0, binding = 0) uniform CCGlobal { mediump vec4 cc_debug_view_composite_pack_1; // x: dir diffuse, y: dir specular, z: env diffuse, w: env specular mediump vec4 cc_debug_view_composite_pack_2; // x: emissive, y: lightmap, z: shadow, w: ao mediump vec4 cc_debug_view_composite_pack_3; // x: normalmap, y: fog, z: tonemapping, w: gamma correction + mediump vec4 cc_debug_view_composite_pack_4; // x: fresnel, y: transmit diffuse, z: transmit specular, w: trt }; #pragma builtin(global) diff --git a/editor/assets/chunks/common/common-define.chunk b/editor/assets/chunks/common/common-define.chunk index bb0ae7b590..8d434609de 100644 --- a/editor/assets/chunks/common/common-define.chunk +++ b/editor/assets/chunks/common/common-define.chunk @@ -26,6 +26,8 @@ // common function #pragma define equalf(data1, data2) (abs(float(data1) - float(data2)) < EPSILON) +#pragma define equalf_lowp(data1, data2) (abs(float(data1) - float(data2)) < EPSILON_LOWP) +#pragma define equalf_epsilon(data1, data2, epsilonValue) (abs(float(data1) - float(data2)) < epsilonValue) // runtime constants #pragma define-meta CC_DEVICE_SUPPORT_FLOAT_TEXTURE default(1) @@ -54,8 +56,12 @@ // Light Type #define LIGHT_TYPE_DIRECTIONAL 0.0 -#define LIGHT_TYPE_SPHERE 1.0 +#define LIGHT_TYPE_POINT 1.0 #define LIGHT_TYPE_SPOT 2.0 -#define IS_DIRECTIONAL_LIGHT(light_type) equalf(light_type, LIGHT_TYPE_DIRECTIONAL) -#define IS_SPHERE_LIGHT(light_type) equalf(light_type, LIGHT_TYPE_SPHERE) -#define IS_SPOT_LIGHT(light_type) equalf(light_type, LIGHT_TYPE_SPOT) +#define LIGHT_TYPE_SPHERE 3.0 +#define LIGHT_TYPE_RANGED_DIRECTIONAL 4.0 +#define IS_DIRECTIONAL_LIGHT(light_type) equalf_lowp(light_type, LIGHT_TYPE_DIRECTIONAL) +#define IS_SPHERE_LIGHT(light_type) equalf_lowp(light_type, LIGHT_TYPE_SPHERE) +#define IS_SPOT_LIGHT(light_type) equalf_lowp(light_type, LIGHT_TYPE_SPOT) +#define IS_POINT_LIGHT(light_type) equalf_lowp(light_type, LIGHT_TYPE_POINT) +#define IS_RANGED_DIRECTIONAL_LIGHT(light_type) equalf_lowp(light_type, LIGHT_TYPE_RANGED_DIRECTIONAL) diff --git a/editor/assets/chunks/common/debug/debug-view-define.chunk b/editor/assets/chunks/common/debug/debug-view-define.chunk index 5af05c548e..ae653b7c3c 100644 --- a/editor/assets/chunks/common/debug/debug-view-define.chunk +++ b/editor/assets/chunks/common/debug/debug-view-define.chunk @@ -22,9 +22,10 @@ #define CC_SURFACES_DEBUG_VIEW_METALLIC CC_SURFACES_DEBUG_VIEW_TRANSPARENCY + 1 #define CC_SURFACES_DEBUG_VIEW_ROUGHNESS CC_SURFACES_DEBUG_VIEW_METALLIC + 1 #define CC_SURFACES_DEBUG_VIEW_SPECULAR_INTENSITY CC_SURFACES_DEBUG_VIEW_ROUGHNESS + 1 +#define CC_SURFACES_DEBUG_VIEW_IOR CC_SURFACES_DEBUG_VIEW_SPECULAR_INTENSITY + 1 // lighting data -#define CC_SURFACES_DEBUG_VIEW_DIRECT_DIFFUSE CC_SURFACES_DEBUG_VIEW_SPECULAR_INTENSITY + 1 +#define CC_SURFACES_DEBUG_VIEW_DIRECT_DIFFUSE CC_SURFACES_DEBUG_VIEW_IOR + 1 #define CC_SURFACES_DEBUG_VIEW_DIRECT_SPECULAR CC_SURFACES_DEBUG_VIEW_DIRECT_DIFFUSE + 1 #define CC_SURFACES_DEBUG_VIEW_DIRECT_ALL CC_SURFACES_DEBUG_VIEW_DIRECT_SPECULAR + 1 #define CC_SURFACES_DEBUG_VIEW_ENV_DIFFUSE CC_SURFACES_DEBUG_VIEW_DIRECT_ALL + 1 @@ -35,7 +36,19 @@ #define CC_SURFACES_DEBUG_VIEW_SHADOW CC_SURFACES_DEBUG_VIEW_LIGHT_MAP + 1 #define CC_SURFACES_DEBUG_VIEW_AO CC_SURFACES_DEBUG_VIEW_SHADOW + 1 -#define CC_SURFACES_DEBUG_VIEW_FOG CC_SURFACES_DEBUG_VIEW_AO + 1 +// advanced lighting data +#define CC_SURFACES_DEBUG_VIEW_FRESNEL CC_SURFACES_DEBUG_VIEW_AO + 1 +#define CC_SURFACES_DEBUG_VIEW_TRANSMIT_DIRECT_DIFFUSE CC_SURFACES_DEBUG_VIEW_FRESNEL + 1 +#define CC_SURFACES_DEBUG_VIEW_TRANSMIT_DIRECT_SPECULAR CC_SURFACES_DEBUG_VIEW_TRANSMIT_DIRECT_DIFFUSE + 1 +#define CC_SURFACES_DEBUG_VIEW_TRANSMIT_ENV_DIFFUSE CC_SURFACES_DEBUG_VIEW_TRANSMIT_DIRECT_SPECULAR + 1 +#define CC_SURFACES_DEBUG_VIEW_TRANSMIT_ENV_SPECULAR CC_SURFACES_DEBUG_VIEW_TRANSMIT_ENV_DIFFUSE + 1 +#define CC_SURFACES_DEBUG_VIEW_TRANSMIT_ALL CC_SURFACES_DEBUG_VIEW_TRANSMIT_ENV_SPECULAR + 1 +#define CC_SURFACES_DEBUG_VIEW_TRT_DIRECT CC_SURFACES_DEBUG_VIEW_TRANSMIT_ALL + 1 +#define CC_SURFACES_DEBUG_VIEW_TRT_ENVIRONMENT CC_SURFACES_DEBUG_VIEW_TRT_DIRECT + 1 +#define CC_SURFACES_DEBUG_VIEW_TRT_ALL CC_SURFACES_DEBUG_VIEW_TRT_ENVIRONMENT + 1 + +// misc data +#define CC_SURFACES_DEBUG_VIEW_FOG CC_SURFACES_DEBUG_VIEW_TRT_ALL + 1 // Debug view UI and macros // #pragma define-meta CC_USE_DEBUG_VIEW range([0, 2]) @@ -45,7 +58,7 @@ #define CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC 2 #define IS_DEBUG_VIEW_ENABLE_WITH_CAMERA (cc_surfaceTransform.y != 3.0) -#pragma define IS_DEBUG_VIEW_SINGLE_MODE(mode) (equalf(cc_debug_view_mode.x, mode) && (cc_surfaceTransform.y != 3.0)) +#pragma define IS_DEBUG_VIEW_SINGLE_MODE(mode) (equalf_lowp(cc_debug_view_mode.x, mode) && (cc_surfaceTransform.y != 3.0)) #define IS_DEBUG_VIEW_LIGHTING_ENABLE_WITH_ALBEDO ((cc_debug_view_mode.y > 0.0) || !IS_DEBUG_VIEW_ENABLE_WITH_CAMERA) #define IS_DEBUG_VIEW_MISC_ENABLE_CSM_LAYER_COLORATION ((cc_debug_view_mode.z > 0.0) && IS_DEBUG_VIEW_ENABLE_WITH_CAMERA) #define IS_DEBUG_VIEW_COMPOSITE_ENABLE_DIRECT_DIFFUSE ((cc_debug_view_composite_pack_1.x > 0.0) || !IS_DEBUG_VIEW_ENABLE_WITH_CAMERA) @@ -60,3 +73,7 @@ #define IS_DEBUG_VIEW_COMPOSITE_ENABLE_FOG ((cc_debug_view_composite_pack_3.y > 0.0) || !IS_DEBUG_VIEW_ENABLE_WITH_CAMERA) #define IS_DEBUG_VIEW_COMPOSITE_ENABLE_TONE_MAPPING ((cc_debug_view_composite_pack_3.z > 0.0) || !IS_DEBUG_VIEW_ENABLE_WITH_CAMERA) #define IS_DEBUG_VIEW_COMPOSITE_ENABLE_GAMMA_CORRECTION ((cc_debug_view_composite_pack_3.w > 0.0) || !IS_DEBUG_VIEW_ENABLE_WITH_CAMERA) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_FRESNEL ((cc_debug_view_composite_pack_4.x > 0.0) || !IS_DEBUG_VIEW_ENABLE_WITH_CAMERA) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_TRANSMIT_DIFFUSE ((cc_debug_view_composite_pack_4.y > 0.0) || !IS_DEBUG_VIEW_ENABLE_WITH_CAMERA) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_TRANSMIT_SPECULAR ((cc_debug_view_composite_pack_4.z > 0.0) || !IS_DEBUG_VIEW_ENABLE_WITH_CAMERA) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_TRT ((cc_debug_view_composite_pack_4.w > 0.0) || !IS_DEBUG_VIEW_ENABLE_WITH_CAMERA) diff --git a/editor/assets/chunks/common/lighting/attenuation.chunk b/editor/assets/chunks/common/lighting/attenuation.chunk index f6ef44e5cd..15bf16c2f6 100644 --- a/editor/assets/chunks/common/lighting/attenuation.chunk +++ b/editor/assets/chunks/common/lighting/attenuation.chunk @@ -1,4 +1,4 @@ - +// base float SmoothDistAtt2 (float distSqr, float invSqrAttRadius) { float factor = distSqr * invSqrAttRadius; // ^2 float factor2 = factor * factor; // ^4 @@ -24,3 +24,25 @@ float GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffse float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0); return (attenuation * attenuation); } + + + +// advanced +float CalculateDistanceAttenuation(float distToLightSqr, float lightRadius, float lightRange) +{ + float litRadiusSqr = lightRadius * lightRadius; + float attRadiusSqrInv = 1.0 / max(lightRange, 0.01); + attRadiusSqrInv *= attRadiusSqrInv; + + // soft edge fading + float edgeAttenuation = litRadiusSqr / max(litRadiusSqr, distToLightSqr); + return GetDistAtt(distToLightSqr, attRadiusSqrInv) * edgeAttenuation; +} + +float CalculateAngleAttenuation(vec3 spotLightDir, vec3 L, float cosAngleOuter) +{ + float cosInner = max(dot(spotLightDir, L), 0.01); + float litAngleScale = 1.0 / max(0.001, cosInner - cosAngleOuter); + float litAngleOffset = -cosAngleOuter * litAngleScale; + return GetAngleAtt(L, spotLightDir, litAngleScale, litAngleOffset); +} diff --git a/editor/assets/chunks/common/lighting/brdf.chunk b/editor/assets/chunks/common/lighting/brdf.chunk index 93043acbaf..abd2d1a24c 100644 --- a/editor/assets/chunks/common/lighting/brdf.chunk +++ b/editor/assets/chunks/common/lighting/brdf.chunk @@ -12,7 +12,7 @@ float D_GGXMobile(float roughness, float NoH) { float OneMinusNoHSqr = 1.0 - NoH * NoH; float a = roughness * roughness; float n = NoH * a; - float p = a / (OneMinusNoHSqr + n * n); + float p = a / max(EPSILON, OneMinusNoHSqr + n * n); return p * p; } diff --git a/editor/assets/chunks/common/lighting/functions.chunk b/editor/assets/chunks/common/lighting/functions.chunk index 9b98ea2707..025ab31d3b 100644 --- a/editor/assets/chunks/common/lighting/functions.chunk +++ b/editor/assets/chunks/common/lighting/functions.chunk @@ -1,26 +1,5 @@ -#include - // helper functions for lighting model-functions -float CalculateDistanceAttenuation(float distToLightSqr, float lightRadius, float lightRange) -{ - float litRadiusSqr = lightRadius * lightRadius; - float attRadiusSqrInv = 1.0 / max(lightRange, 0.01); - attRadiusSqrInv *= attRadiusSqrInv; - - // soft edge fading - float edgeAttenuation = litRadiusSqr / max(litRadiusSqr, distToLightSqr); - return GetDistAtt(distToLightSqr, attRadiusSqrInv) * edgeAttenuation; -} - -float CalculateAngleAttenuation(vec3 spotLightDir, vec3 L, float cosAngleOuter) -{ - float cosInner = max(dot(spotLightDir, L), 0.01); - float litAngleScale = 1.0 / max(0.001, cosInner - cosAngleOuter); - float litAngleOffset = -cosAngleOuter * litAngleScale; - return GetAngleAtt(L, spotLightDir, litAngleScale, litAngleOffset); -} - // return unnormalized vector, support oppo-side // V from pixel to camera vec3 CalculateRefractDirection(vec3 N, vec3 V, float NoV, float ior) @@ -43,3 +22,28 @@ vec3 CalculateReflectDirection(vec3 N, vec3 V, float NoV) N *= sideSign; return reflect(-V, N); } + +// for bumped planar reflection +vec3 CalculatePlanarReflectPositionOnPlane(vec3 N, vec3 V, vec3 worldPos, vec4 plane, vec3 cameraPos, float probeReflectedDepth) +{ + float distPixelToPlane = -dot(plane, vec4(worldPos, 1.0)); + // bring plane to worldPos, avoid artifacts when reflected point away from plane (do not bring worldPos to plane) + plane.w += distPixelToPlane; + float distCameraToPlane = abs(-dot(plane, vec4(cameraPos, 1.0))); + vec3 planeN = plane.xyz; + vec3 virtualCameraPos = cameraPos - 2.0 * distCameraToPlane * planeN; + /*support for two-sided reflections + float sideSignPlaneN = dot(planeN, V) < 0.0 ? -1.0 : 1.0; + float sideSignN = dot(N, V) < 0.0 ? -1.0 : 1.0; + planeN *= sideSignPlaneN; + N *= sideSignN;*/ + vec3 bumpedR = normalize(reflect(-V, N)); //R' + + // actually reflected pos alone bumpedR direction, avoid tracing by specified a fake depth + vec3 reflectedPointPos = worldPos + probeReflectedDepth * bumpedR; + vec3 virtualCameraToReflectedPoint = normalize(reflectedPointPos - virtualCameraPos); + + // the ray from virtual camera to reflected point, will intersect with plane on P' + float y = distCameraToPlane / max(EPSILON_LOWP, dot(planeN, virtualCameraToReflectedPoint)); + return virtualCameraPos + y * virtualCameraToReflectedPoint; +} diff --git a/editor/assets/chunks/common/lighting/light-map.chunk b/editor/assets/chunks/common/lighting/light-map.chunk index 3fec7c38af..1e31b5db4b 100644 --- a/editor/assets/chunks/common/lighting/light-map.chunk +++ b/editor/assets/chunks/common/lighting/light-map.chunk @@ -5,10 +5,9 @@ void SampleAndDecodeLightMapColor(out vec3 lightmapColor, out float dirShadow, o #if CC_LIGHT_MAP_VERSION > 2 // has high precision data #elif CC_LIGHT_MAP_VERSION > 1 - luv.x *= 0.5; vec4 dataLow = texture(lightingMap, luv); vec4 dataHigh = texture(lightingMap, luv + vec2(0.5, 0.0)); - lightmapColor.xyz = dataLow + dataHigh * 0.00392156862745098; + lightmapColor.xyz = dataLow.xyz + dataHigh.xyz * 0.00392156862745098; lightmapColor.rgb *= lum; dirShadow = dataLow.a; ao = dataHigh.a; diff --git a/editor/assets/chunks/common/mesh/vat-animation.chunk b/editor/assets/chunks/common/mesh/vat-animation.chunk index 040f86d5e3..1d2a20c7a0 100644 --- a/editor/assets/chunks/common/mesh/vat-animation.chunk +++ b/editor/assets/chunks/common/mesh/vat-animation.chunk @@ -3,16 +3,26 @@ // Vertex Animation Texture (VAT), baked physically simulation result for rigid-body, soft-body and fluid -// Houdini export settings: - // 1. Select Unity mode (Y-axis is up and position scale is 0.01), otherwise animation will become crack - // 2. Select LDR - // 3. Do not check paddle, two-position textures and pack normals - // 4. Export json for numOfFrames(frameCount) +// Houdini VAT Plugin Version: + // 1. Soft-body and fluids use 3.0, Select Unity mode, otherwise animation will become crack + // 2. Rigid-body use 2.0, Select UE mode with initialize settings, needs export json for numOfFrames(frameCount) and max/min values + +// Houdini misc export settings: + // 1. Select LDR + // 2. Do not check paddle, two-position textures and pack normals // Cocos import settings: // 1. LUT texture should set filter to "nearest" and uncheck "fix alpha transparency" + // 2. Rigid-body select import normal and tangent + // 3. Rigid-body and soft-body need check HAS_SECOND_UV + // 4. If no sign texture with exr image, use white texture instead -#define VAT_UNITY_TO_COCOS_COORDINATE_SCALE 0.01 +// For resources exported by UE mode, invoke functions like: + // 1. VATFunction(inout_pos.xzy / VAT_FBX_TO_COCOS_COORDINATE_SCALE, inout_vector.xzy); + // 2. out_pos.xyz = inout_pos.xzy * VAT_FBX_TO_COCOS_COORDINATE_SCALE; + // 2. out_vector.xyz = inout_vector.xzy; + +#define VAT_FBX_TO_COCOS_COORDINATE_SCALE 0.01 #define VAT_LUT_PRECISION_VALUE_LDR 255.0 #define VAT_LUT_PRECISION_VALUE_HDR 2048.0 @@ -60,11 +70,11 @@ float VATGetAnimUV(out vec2 thisFrameUV, out vec2 nextFrameUV, vec2 meshUV, floa } // return absolute position for fluid -// return position offset for rigid-body and soft-body +// return position offset for soft-body vec3 VATGetLocalPosition(vec2 thisFrameUV, sampler2D vatPositionTexture, sampler2D vatPositionSignTexture) { vec3 thisFramePos = SampleTextureExr(vatPositionTexture, vatPositionSignTexture, thisFrameUV); - return thisFramePos * VAT_UNITY_TO_COCOS_COORDINATE_SCALE; + return thisFramePos * VAT_FBX_TO_COCOS_COORDINATE_SCALE; } // meshNormal is up-axis for fluid vec3 VATGetLocalNormal(vec3 meshNormal, vec2 thisFrameUV, sampler2D vatRotationTexture, sampler2D vatRotationSignTexture, sampler2D vatRotationAlphaTexture) @@ -79,7 +89,7 @@ vec3 VATGetLocalPosition(vec2 thisFrameUV, vec2 nextFrameUV, float frameLerp, sa { vec3 thisFramePos = SampleTextureExr(vatPositionTexture, vatPositionSignTexture, thisFrameUV); vec3 nextFramePos = SampleTextureExr(vatPositionTexture, vatPositionSignTexture, nextFrameUV); - return mix(thisFramePos, nextFramePos, frameLerp) * VAT_UNITY_TO_COCOS_COORDINATE_SCALE; + return mix(thisFramePos, nextFramePos, frameLerp) * VAT_FBX_TO_COCOS_COORDINATE_SCALE; } vec3 VATGetLocalNormal(vec3 meshNormal, vec2 thisFrameUV, vec2 nextFrameUV, float frameLerp, sampler2D vatRotationTexture, sampler2D vatRotationSignTexture, sampler2D vatRotationAlphaTexture) { @@ -95,10 +105,168 @@ vec3 VATGetLocalNormal(vec3 meshNormal, vec2 thisFrameUV, vec2 nextFrameUV, floa vec3 VATCalculateFluidVoxelUV(vec3 vatBoundingBoxMin, vec3 vatBoundingBoxMax, vec3 localPos) { // bounding box in exported json is unscaled - vatBoundingBoxMin *= VAT_UNITY_TO_COCOS_COORDINATE_SCALE; - vatBoundingBoxMax *= VAT_UNITY_TO_COCOS_COORDINATE_SCALE; + vatBoundingBoxMin *= VAT_FBX_TO_COCOS_COORDINATE_SCALE; + vatBoundingBoxMax *= VAT_FBX_TO_COCOS_COORDINATE_SCALE; vec3 size = vatBoundingBoxMax - vatBoundingBoxMin; vec3 coef = (localPos - vatBoundingBoxMin) / size; return coef; -} \ No newline at end of file +} + + + + + +////////////////////////////////////////////////////////////////Rigid-body +void VATGetLocalPositionRigidBody20(inout vec3 meshLocalPos, inout vec3 meshLocalNormal, inout vec3 meshLocalTangent, in vec4 meshVertexColor, vec2 thisFrameUV, float pivMax, float pivMin, float posMax, float posMin, sampler2D vatPositionTexture, sampler2D vatPositionSignTexture, sampler2D vatPositionAlphaTexture, sampler2D vatRotationTexture, sampler2D vatRotationSignTexture, sampler2D vatRotationAlphaTexture) +{ + // pivot + float pivExpand = pivMax - pivMin; + float posExpand = posMax - posMin; + + vec3 pivot = meshVertexColor.xyz; + pivot.xyz *= pivExpand; + pivot.xyz += vec3(pivMin); + + // anim pos + vec3 posData = SampleTextureExr(vatPositionTexture, vatPositionSignTexture, thisFrameUV); + vec3 texturePos = posData; + texturePos.xyz *= posExpand; + texturePos.xyz += posMin; + + // rotate pos + vec4 quat = SampleTextureExrWithAlpha(vatRotationTexture, vatRotationSignTexture, vatRotationAlphaTexture, thisFrameUV); + quat = quat * 2.0 - vec4(1.0); + + vec3 originPos = meshLocalPos - pivot; + vec3 rotatedPos; + rotatedPos = 2.0 * cross(quat.xyz, cross(quat.xyz, originPos.xyz) + quat.w * originPos.xyz); + + // result + meshLocalPos = meshLocalPos + rotatedPos + texturePos; + rotateVecFromQuat(meshLocalNormal, quat); + rotateVecFromQuat(meshLocalTangent, quat); +} + +void VATGetLocalPositionRigidBody20_UE(inout vec3 meshLocalPos, inout vec3 meshLocalNormal, inout vec3 meshLocalTangent, in vec4 meshVertexColor, vec2 thisFrameUV, float pivMax, float pivMin, float posMax, float posMin, sampler2D vatPositionTexture, sampler2D vatPositionSignTexture, sampler2D vatPositionAlphaTexture, sampler2D vatRotationTexture, sampler2D vatRotationSignTexture, sampler2D vatRotationAlphaTexture) +{ + // input + vec3 preSkinnedPos = meshLocalPos.xzy / VAT_FBX_TO_COCOS_COORDINATE_SCALE; + vec3 preSkinnedNorm = meshLocalNormal.xzy; + vec3 preSkinnedTangent = meshLocalTangent.xzy; + + VATGetLocalPositionRigidBody20(preSkinnedPos, preSkinnedNorm, preSkinnedTangent, meshVertexColor, thisFrameUV, pivMax, pivMin, posMax, posMin, vatPositionTexture, vatPositionSignTexture, vatPositionAlphaTexture, vatRotationTexture, vatRotationSignTexture, vatRotationAlphaTexture); + + // output + meshLocalPos.xyz = preSkinnedPos.xzy * VAT_FBX_TO_COCOS_COORDINATE_SCALE; + meshLocalNormal.xyz = preSkinnedNorm.xzy; + meshLocalTangent.xyz = preSkinnedTangent.xzy; +} + + +// Experimental +float CalculateVATDecodeUV(float A, float B) +{ +#if __VERSION__ >= 110 + uint a = floatBitsToUint(A); //asuint(A) + uint b = floatBitsToUint(B); + a = ((a >> 16u) & 0x8000u) | + ((((a >> 23u) & 0xFFu) - 112u) << 10u) | + ((a >> 13u) & 0x3FFu); + b = ((b >> 16u) & 0x8000u) | + ((((b >> 23u) & 0xFFu) - 112u) << 10u) | + ((b >> 13u) & 0x3FFu); + a = (a & 0x8000u) | ((a << 2u) & 0x7FF8u); + b = (b & 0x8000u) | ((b << 2u) & 0x7FF8u); + a = (a << 16u) | (b << 3u); + return uintBitsToFloat(a); //asfloat(a); +#endif + return 0.0; +} +void VATGetLocalPositionRigidBody30(inout vec3 meshLocalPos, inout vec3 meshLocalNormal, inout vec3 meshLocalTangent, in vec2 meshUV2, in vec2 meshUV3, vec2 thisFrameUV, sampler2D vatPositionTexture, sampler2D vatPositionSignTexture, sampler2D vatPositionAlphaTexture, sampler2D vatRotationTexture, sampler2D vatRotationSignTexture, sampler2D vatRotationAlphaTexture, bool isZUp) +{ + // pivot offset + vec3 direction; + direction.x = meshUV2.x; + direction.y = sqrt(1.0 - (meshUV2.x*meshUV2.x + meshUV3.x*meshUV3.x)); + direction.z = meshUV3.x; + float Magnitude = CalculateVATDecodeUV(meshUV2.y, meshUV3.y); + float Up = Magnitude; + + vec3 org, pivot; + org = vec3(meshUV2.x, Up, meshUV3.x); + if(abs(meshUV3.y) > 2.0) + pivot = direction.xyz * Magnitude; + else + pivot = org.xyz; + + if(isZUp) + pivot.xyz = pivot.xzy / VAT_FBX_TO_COCOS_COORDINATE_SCALE; + vec3 originPos = meshLocalPos - pivot; + + // rotation offset + vec4 posData = SampleTextureExrWithAlpha(vatPositionTexture, vatPositionSignTexture, vatPositionAlphaTexture, thisFrameUV); + vec4 XYZW = SampleTextureExrWithAlpha(vatRotationTexture, vatRotationSignTexture, vatRotationAlphaTexture, thisFrameUV); + float w = sqrt(1.0 - dot(XYZW.xyz, XYZW.xyz)); //sqrt(1.0 - quat.x*quat.x - quat.y*quat.y - quat.z*quat.z); //r + // restore origin quaternion for slerp between frames + // float cycle_count = XYZW.w; // rotation cycle count for slerp between frames + // float rot_angle = cycle_count * PI2 + acos(w); + // w = cos(rot_angle); + vec4 quat = vec4(0.0, 0.0, 0.0, 1.0); + + // upper is UE, lower is Houdini + float maxComponent = floor(posData.a * 4.0); + if(equalf_epsilon(maxComponent, 1.0, 0.01)) { + quat = vec4(-w, XYZW.yzx); + quat = vec4(w, XYZW.yzx); + } + else if(equalf_epsilon(maxComponent, 2.0, 0.01)) { + quat = vec4(XYZW.xy, -w, -XYZW.z); + quat = vec4(XYZW.x, w, XYZW.zy); + } + else if(equalf_epsilon(maxComponent, 3.0, 0.01)) { + quat = vec4(XYZW.x, -w, -XYZW.zy); + quat = vec4(XYZW.xy, w, XYZW.z); + } + else + quat = vec4(XYZW.xyz, w); + + // quat = quat.xzyw; + + vec3 rotatedPos; + rotatedPos = 2.0 * cross(quat.xyz, cross(quat.xyz, originPos.xyz) + quat.w * originPos.xyz); + + // result + meshLocalPos = originPos + rotatedPos + posData.xyz; + meshLocalNormal = 2.0 * cross(quat.xyz, cross(quat.xyz, meshLocalNormal.xyz)+ quat.w * meshLocalNormal.xyz); + meshLocalTangent = 2.0 * cross(quat.xyz, cross(quat.xyz, meshLocalTangent.xyz)+ quat.w * meshLocalTangent.xyz); +} + +void VATGetLocalPositionRigidBody30_UE(inout vec3 meshLocalPos, inout vec3 meshLocalNormal, inout vec3 meshLocalTangent, in vec2 meshUV2, in vec2 meshUV3, vec2 thisFrameUV, sampler2D vatPositionTexture, sampler2D vatPositionSignTexture, sampler2D vatPositionAlphaTexture, sampler2D vatRotationTexture, sampler2D vatRotationSignTexture, sampler2D vatRotationAlphaTexture) +{ + // input + vec3 preSkinnedPos = meshLocalPos.xzy / VAT_FBX_TO_COCOS_COORDINATE_SCALE; + vec3 preSkinnedNorm = meshLocalNormal.xzy; + vec3 preSkinnedTangent = meshLocalTangent.xzy; + + VATGetLocalPositionRigidBody30(preSkinnedPos, preSkinnedNorm, preSkinnedTangent, meshUV2, meshUV3, thisFrameUV, vatPositionTexture, vatPositionSignTexture, vatPositionAlphaTexture, vatRotationTexture, vatRotationSignTexture, vatRotationAlphaTexture, true); + + // output + meshLocalPos = preSkinnedPos.xzy * VAT_FBX_TO_COCOS_COORDINATE_SCALE; + meshLocalNormal = preSkinnedNorm.xzy; + meshLocalTangent = preSkinnedTangent.xzy; +} +void VATGetLocalPositionRigidBody30_Cocos(inout vec3 meshLocalPos, inout vec3 meshLocalNormal, inout vec3 meshLocalTangent, in vec2 meshUV2, in vec2 meshUV3, vec2 thisFrameUV, sampler2D vatPositionTexture, sampler2D vatPositionSignTexture, sampler2D vatPositionAlphaTexture, sampler2D vatRotationTexture, sampler2D vatRotationSignTexture, sampler2D vatRotationAlphaTexture) +{ + // input + vec3 preSkinnedPos = meshLocalPos.xyz / VAT_FBX_TO_COCOS_COORDINATE_SCALE; + vec3 preSkinnedNorm = meshLocalNormal.xyz; + vec3 preSkinnedTangent = meshLocalTangent.xyz; + + VATGetLocalPositionRigidBody30(preSkinnedPos, preSkinnedNorm, preSkinnedTangent, meshUV2, meshUV3, thisFrameUV, vatPositionTexture, vatPositionSignTexture, vatPositionAlphaTexture, vatRotationTexture, vatRotationSignTexture, vatRotationAlphaTexture, false); + + // output + meshLocalPos = preSkinnedPos.xyz * VAT_FBX_TO_COCOS_COORDINATE_SCALE; + meshLocalNormal = preSkinnedNorm.xyz; + meshLocalTangent = preSkinnedTangent.xyz; +} diff --git a/editor/assets/chunks/common/shadow/native-pcf.chunk b/editor/assets/chunks/common/shadow/native-pcf.chunk index 3b5ecd413a..5b5167e89c 100644 --- a/editor/assets/chunks/common/shadow/native-pcf.chunk +++ b/editor/assets/chunks/common/shadow/native-pcf.chunk @@ -5,7 +5,7 @@ #pragma define CC_SHADOW_PCF_SOFT_3X 2 #pragma define CC_SHADOW_PCF_SOFT_5X 3 -float SampleShadowMap (vec3 shadowNDCPos, sampler2D shadowMap) +float SampleShadowMap (vec3 shadowNDCPos, highp sampler2D shadowMap) { #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 return unpackRGBAToDepth(texture(shadowMap, shadowNDCPos.xy)); @@ -14,7 +14,7 @@ float SampleShadowMap (vec3 shadowNDCPos, sampler2D shadowMap) #endif } -float NativePCFShadowFactorHard (vec3 shadowNDCPos, sampler2D shadowMap, vec2 shadowMapResolution) +float NativePCFShadowFactorHard (vec3 shadowNDCPos, highp sampler2D shadowMap, vec2 shadowMapResolution) { #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 return step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, shadowNDCPos.xy))); @@ -23,7 +23,7 @@ float NativePCFShadowFactorHard (vec3 shadowNDCPos, sampler2D shadowMap, vec2 sh #endif } -float NativePCFShadowFactorSoft (vec3 shadowNDCPos, sampler2D shadowMap, vec2 shadowMapResolution) +float NativePCFShadowFactorSoft (vec3 shadowNDCPos, highp sampler2D shadowMap, vec2 shadowMapResolution) { vec2 oneTap = 1.0 / shadowMapResolution; vec2 shadowNDCPos_offset = shadowNDCPos.xy + oneTap; @@ -49,7 +49,7 @@ float NativePCFShadowFactorSoft (vec3 shadowNDCPos, sampler2D shadowMap, vec2 sh return mix(resultX, resultY, coefY); } -float NativePCFShadowFactorSoft3X (vec3 shadowNDCPos, sampler2D shadowMap, vec2 shadowMapResolution) +float NativePCFShadowFactorSoft3X (vec3 shadowNDCPos, highp sampler2D shadowMap, vec2 shadowMapResolution) { vec2 oneTap = 1.0 / shadowMapResolution; float shadowNDCPos_offset_L = shadowNDCPos.x - oneTap.x; @@ -103,7 +103,7 @@ float NativePCFShadowFactorSoft3X (vec3 shadowNDCPos, sampler2D shadowMap, vec2 return shadow * 0.25; } -float NativePCFShadowFactorSoft5X (vec3 shadowNDCPos, sampler2D shadowMap, vec2 shadowMapResolution) +float NativePCFShadowFactorSoft5X (vec3 shadowNDCPos, highp sampler2D shadowMap, vec2 shadowMapResolution) { vec2 oneTap = 1.0 / shadowMapResolution; vec2 twoTap = oneTap * 2.0; diff --git a/editor/assets/chunks/common/texture/texture-misc.chunk b/editor/assets/chunks/common/texture/texture-misc.chunk index 8c401792ec..acf1bb6ed8 100644 --- a/editor/assets/chunks/common/texture/texture-misc.chunk +++ b/editor/assets/chunks/common/texture/texture-misc.chunk @@ -1,5 +1,11 @@ // for exr data texture and sub resources +vec3 SampleTextureExr(sampler2D exrRGBE, vec2 uv) +{ + vec3 data = unpackRGBE(texture(exrRGBE, uv)); + return data; +} + vec3 SampleTextureExr(sampler2D exrRGBE, sampler2D exrSign, vec2 uv) { vec3 data = unpackRGBE(texture(exrRGBE, uv)); diff --git a/editor/assets/chunks/legacy/output-standard.chunk b/editor/assets/chunks/legacy/output-standard.chunk index 7e15576c57..f8472da6c6 100644 --- a/editor/assets/chunks/legacy/output-standard.chunk +++ b/editor/assets/chunks/legacy/output-standard.chunk @@ -3,9 +3,11 @@ #include vec4 CCFragOutput (vec4 color) { - #if CC_USE_HDR - color.rgb = ACESToneMap(color.rgb); + #if !CC_USE_RGBE_OUTPUT + #if CC_USE_HDR + color.rgb = ACESToneMap(color.rgb); + #endif + color.rgb = LinearToSRGB(color.rgb); #endif - color.rgb = LinearToSRGB(color.rgb); return color; } diff --git a/editor/assets/chunks/legacy/shading-standard-base.chunk b/editor/assets/chunks/legacy/shading-standard-base.chunk index 09848b152d..e2130729c1 100644 --- a/editor/assets/chunks/legacy/shading-standard-base.chunk +++ b/editor/assets/chunks/legacy/shading-standard-base.chunk @@ -27,7 +27,7 @@ float GGXMobile (float roughness, float NoH, vec3 H, vec3 N) { float OneMinusNoHSqr = dot(NxH, NxH); float a = roughness * roughness; float n = NoH * a; - float p = a / (OneMinusNoHSqr + n * n); + float p = a / max(EPSILON, OneMinusNoHSqr + n * n); return p * p; } @@ -149,7 +149,7 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { #endif #endif - #if CC_USE_LIGHTMAP != LIGHT_MAP_TYPE_ALL_IN_ONE + #if CC_RECEIVE_DIRECTIONAL_LIGHT float NV = max(abs(dot(N, V)), 0.0); specular = BRDFApprox(specular, s.roughness, NV); @@ -166,7 +166,7 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { finalColor += lightingColor * dirlightContrib; #endif - float fAmb = 0.5 - N.y * 0.5; + float fAmb = max(EPSILON, 0.5 - N.y * 0.5); vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb); vec3 env = vec3(0.0); diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk index de2424b16d..33f4e81de2 100644 --- a/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk @@ -21,16 +21,15 @@ struct LightingIntermediateData float anisotropyShape; #endif -#if CC_SURFACES_LIGHTING_TRANSMITTENCE +#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE vec4 shadowPosAndDepth; //xy: shadowmap uv, z: camera depth from pixel LVP, w: camera depth from shadowmap - vec4 transmittenceParams; //zw: min/max DepthWS for shadowmap and 0 means disable shadow transmit, x: transmit coef, y: additional transmit depth mask, 可补充shadowmap cover不到的地方,也可以在minmax屏蔽掉shadowmap之后给专门的薄片穿透 + vec4 transmitDiffuseParams; //zw: min/max DepthWS for shadowmap and 0 means disable shadow transmit, x: transmit irradiance apply shadow, y: additional transmit depth mask, 可补充shadowmap cover不到的地方,也可以在minmax屏蔽掉shadowmap之后给专门的薄片穿透 +#endif +#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR || CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + vec4 transmitParams; // xy: extinction coef for out/in-scattering, z: in-scattering coef, w: transmit distance(water depth, leaf thickness) + vec3 inScatteringLightColor; #endif - // #if CC_SURFACES_LIGHTING_SPECULAR_2ND - // float specularParam2nd, specularIntensity2nd, specularRotation2nd; // for hair - // vec3 specularColor2nd; - // #endif // #if CC_SURFACES_LIGHTING_CLEAR_COAT - // float ior; // float roughnessClearCoat; // for clear coat or multi-layer pbr // #endif }; @@ -61,7 +60,11 @@ void CCSurfacesLightingGetIntermediateData_PerPixel(inout LightingIntermediateDa #if CC_SURFACES_LIGHTING_ANISOTROPIC data.anisotropyShape = anisotropyShape; #endif -#if CC_SURFACES_LIGHTING_TRANSMITTENCE +#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR || CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + data.inScatteringLightColor = vec3(0.0); + data.transmitParams = vec4(0.0); +#endif +#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE data.shadowPosAndDepth = vec4(0.0, 0.0, 999999.0, 999999.0); #endif } diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-misc-data.chunk b/editor/assets/chunks/lighting-models/data-structures/lighting-misc-data.chunk new file mode 100644 index 0000000000..93b6a9e507 --- /dev/null +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-misc-data.chunk @@ -0,0 +1,9 @@ +// for user modified lighting result +struct LightingMiscData +{ + // local light source attributes, like CCForwardLight + float lightType; + vec3 lightPos, lightDir; + vec4 lightColorAndIntensity; + vec4 lightSizeRangeAngle; +}; diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-misc-data.chunk.meta b/editor/assets/chunks/lighting-models/data-structures/lighting-misc-data.chunk.meta new file mode 100644 index 0000000000..f0d6c190d3 --- /dev/null +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-misc-data.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.7", + "importer": "effect-header", + "imported": true, + "uuid": "f5326068-1588-43b4-9f15-c190688fc7c0", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk index 34b9ca0726..b87dedc244 100644 --- a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk @@ -9,15 +9,17 @@ struct LightingResult float shadow, ao; vec3 lightmapColor; vec3 emissive; + + // advanced #if CC_SURFACES_LIGHTING_USE_FRESNEL float fresnel; #endif + #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR - vec3 directTransmitSpecular; - vec3 environmentTransmitSpecular; + vec3 directTransmitSpecular, environmentTransmitSpecular; #endif -#if CC_SURFACES_LIGHTING_TRANSMITTENCE - vec3 transmittence; +#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + vec3 directTransmitDiffuse, environmentTransmitDiffuse; #endif #if CC_SURFACES_LIGHTING_TRT vec3 directTRT, environmentTRT; diff --git a/editor/assets/chunks/lighting-models/default-functions/standard.chunk b/editor/assets/chunks/lighting-models/default-functions/standard.chunk index dcd24eddb6..0dbbc3ffb3 100644 --- a/editor/assets/chunks/lighting-models/default-functions/standard.chunk +++ b/editor/assets/chunks/lighting-models/default-functions/standard.chunk @@ -5,7 +5,7 @@ //#include // #define CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT -// void SurfacesLightingModifyFinalResult(inout LightingResult result, in LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData) +// void SurfacesLightingModifyFinalResult(inout LightingResult result, in LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData, in LightingMiscData miscData) // { // } diff --git a/editor/assets/chunks/lighting-models/includes/common.chunk b/editor/assets/chunks/lighting-models/includes/common.chunk index 0e82d152b2..fa0b70b11a 100644 --- a/editor/assets/chunks/lighting-models/includes/common.chunk +++ b/editor/assets/chunks/lighting-models/includes/common.chunk @@ -1,4 +1,5 @@ // Lighting-model common includes #include #include +#include diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk index d20d88e9a4..b230a78e34 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk @@ -1,16 +1,19 @@ #if (CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_FORWARD || CC_FORCE_FORWARD_SHADING) #if CC_FORWARD_ADD && !CC_ENABLE_CLUSTERED_LIGHT_CULLING - void CCSurfacesLighting(inout LightingResult lightingResult, in SurfacesMaterialData surfaceData, in vec2 shadowBias) + void CCSurfacesLighting(inout LightingResult lightingResultAccumulated, in SurfacesMaterialData surfaceData, in vec2 shadowBias) { vec3 worldPos; HIGHP_VALUE_FROM_STRUCT_DEFINED(worldPos, surfaceData.worldPos); + CCSurfacesInitializeLightingResult(lightingResultAccumulated); + LightingIntermediateData lightingData; CCSurfacesInitializeLightingIntermediateData(lightingData, surfaceData); + LightingResult lightingResult; CCSurfacesLightingInitializeColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); - - lightingResult.directDiffuse = lightingResult.directSpecular = vec3(0.0); + lightingResultAccumulated.diffuseColorWithLighting = lightingResult.diffuseColorWithLighting; + lightingResultAccumulated.specularColorWithLighting = lightingResult.specularColorWithLighting; int numLights = CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_FORWARD ? LIGHTS_PER_PASS : int(cc_lightDir[0].w); for (int i = 0; i < LIGHTS_PER_PASS; i++) { @@ -27,11 +30,6 @@ fresnel = lightingResult.fresnel = CCSurfaceLightingCalculateFresnel(lightingData); #endif - #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR - vec3 transmitSpecularLighting; - CCSurfacesLightingCalculateDirectTransmitSpecular(transmitSpecularLighting, lightingData, cc_lightColor[i]); - #endif - float shadow = 1.0; #if CC_RECEIVE_SHADOW && CC_SHADOW_TYPE == CC_SHADOW_MAP if (cc_lightPos[i].w > 0.0 && cc_lightSizeRangeAngle[i].w > 0.0) { @@ -40,10 +38,14 @@ shadowPos = cc_matLightViewProj * vec4(surfaceData.worldPos, 1.0); shadow = CCSpotShadowFactorBase(shadowNDCPosWithBias, shadowPos, worldPos, shadowBias); } - #if CC_SURFACES_LIGHTING_TRANSMITTENCE - lightingData.shadowPosAndDepth.xy = shadowNDCPosWithBias.xy; - lightingData.shadowPosAndDepth.z = shadowPos.z; - lightingData.shadowPosAndDepth.w = GetViewSpaceDepthFromNDCDepth_Perspective(SampleShadowMap(shadowNDCPosWithBias.xyz, cc_spotShadowMap), shadowNDCPosWithBias.w, cc_shadowInvProjDepthInfo.x, cc_shadowInvProjDepthInfo.y); + #if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + #if CC_SURFACES_LIGHTING_USE_SHADOWMAP_TRANSMIT + lightingData.shadowPosAndDepth.xy = shadowNDCPosWithBias.xy; + lightingData.shadowPosAndDepth.z = shadowPos.z; + lightingData.shadowPosAndDepth.w = GetViewSpaceDepthFromNDCDepth_Perspective(SampleShadowMap(shadowNDCPosWithBias.xyz, cc_spotShadowMap), shadowNDCPosWithBias.w, cc_shadowInvProjDepthInfo.x, cc_shadowInvProjDepthInfo.y); + #else + lightingData.transmitDiffuseParams.zw = vec2(0.0); + #endif #endif } #endif @@ -54,6 +56,8 @@ } #endif + lightingResult.shadow = shadow; + float distAtt = CCSurfacesLightingCalculateDistanceAttenuation(lightingData, cc_lightSizeRangeAngle[i]); float angleAtt = 1.0; @@ -61,20 +65,43 @@ angleAtt = CCSurfacesLightingCalculateAngleAttenuation(lightingData, cc_lightSizeRangeAngle[i], -cc_lightDir[i].xyz); } - float multiplier = distAtt * angleAtt * shadow; + float multiplier = distAtt * angleAtt; - lightingResult.directDiffuse += diffuseLighting * multiplier; - lightingResult.directSpecular += specularLighting * multiplier * fresnel; + lightingResult.directDiffuse = diffuseLighting * multiplier; + lightingResult.directSpecular = specularLighting * multiplier * fresnel; #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR - lightingResult.directTransmitSpecular += transmitSpecularLighting * multiplier * (1.0 - fresnel); + vec3 transmitSpecularLighting; + CCSurfacesLightingCalculateDirectTransmitSpecular(transmitSpecularLighting, lightingData, cc_lightColor[i]); + lightingResult.directTransmitSpecular = transmitSpecularLighting * multiplier * (1.0 - fresnel); #endif - #if CC_SURFACES_LIGHTING_TRANSMITTENCE - lightingResult.transmittence = CCSurfacesLightingCalculateDirectTransmittence(lightingResult, lightingData, cc_lightColor[i]); + + #if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + lightingResult.directTransmitDiffuse = CCSurfacesLightingCalculateDirectTransmitDiffuse(lightingResult, lightingData, cc_lightColor[i]); #endif + #if CC_SURFACES_LIGHTING_TRT - CCSurfacesLightingCalculateDirectTRT(lightingResult.directTRT, lightingData, cc_lightColor[i]); + vec3 TRTLighting; + LightingIntermediateData lightingDataTRT; + CCSurfacesGetLightingIntermediateDataTRT(lightingDataTRT, lightingData, surfaceData); + CCSurfacesLightingCalculateDirectTRT(TRTLighting, lightingDataTRT, cc_lightColor[i]); + lightingResult.directTRT = TRTLighting; #endif + + + // user-defined lighting model + #ifdef CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT + LightingMiscData miscData; + miscData.lightType = cc_lightPos[i].w; + miscData.lightPos = cc_lightPos[i].xyz; + miscData.lightDir = cc_lightDir[i].xyz; + miscData.lightColorAndIntensity = cc_lightColor[i]; + miscData.lightSizeRangeAngle = cc_lightSizeRangeAngle[i]; + SurfacesLightingModifyFinalResult(lightingResult, lightingData, surfaceData, miscData); + #endif + + // accumulate per-light results + CCSurfacesAccumulateLightingResult(lightingResultAccumulated, lightingResult); } } #else @@ -105,10 +132,14 @@ #endif } } - #if CC_SURFACES_LIGHTING_TRANSMITTENCE - lightingData.shadowPosAndDepth.xy = shadowNDCPosWithBias.xy; - lightingData.shadowPosAndDepth.z = shadowPos.z; - lightingData.shadowPosAndDepth.w = GetViewSpaceDepthFromNDCDepth_Orthgraphic(SampleShadowMap(shadowNDCPosWithBias.xyz, cc_shadowMap), cc_shadowProjDepthInfo.x, cc_shadowProjDepthInfo.y); + #if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + #if CC_SURFACES_LIGHTING_USE_SHADOWMAP_TRANSMIT + lightingData.shadowPosAndDepth.xy = shadowNDCPosWithBias.xy; + lightingData.shadowPosAndDepth.z = shadowPos.z; + lightingData.shadowPosAndDepth.w = GetViewSpaceDepthFromNDCDepth_Orthgraphic(SampleShadowMap(shadowNDCPosWithBias.xyz, cc_shadowMap), cc_shadowProjDepthInfo.x, cc_shadowProjDepthInfo.y); + #else + lightingData.transmitDiffuseParams.zw = vec2(0.0); + #endif #endif } #endif @@ -127,7 +158,7 @@ // dynamic & stationary dir light lightingResult.directDiffuse = lightingResult.directSpecular = vec3(0.0); - #if CC_SURFACES_USE_LIGHT_MAP != LIGHT_MAP_TYPE_ALL_IN_ONE && !CC_FORWARD_ADD + #if CC_RECEIVE_DIRECTIONAL_LIGHT && !CC_FORWARD_ADD CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); CCSurfacesLightingCalculateDirect(lightingResult.directDiffuse, lightingResult.directSpecular, lightingData, cc_mainLitColor); @@ -145,9 +176,9 @@ CCSurfacesLightingCalculateEnvironmentTransmitSpecular(lightingResult.environmentTransmitSpecular, lightingData, cc_ambientSky.w); #endif - #if CC_SURFACES_LIGHTING_TRANSMITTENCE - lightingResult.transmittence = CCSurfacesLightingCalculateDirectTransmittence(lightingResult, lightingData, cc_mainLitColor); - lightingResult.transmittence += CCSurfacesLightingCalculateEnvironmentTransmittence(lightingResult, lightingData, cc_ambientSky.w); + #if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + CCSurfacesLightingCalculateDirectTransmitDiffuse(lightingResult.directTransmitDiffuse, lightingResult, lightingData, cc_mainLitColor); + CCSurfacesLightingCalculateEnvironmentTransmitDiffuse(lightingResult.environmentTransmitDiffuse, lightingResult, lightingData, cc_ambientSky.w); #endif #if CC_SURFACES_LIGHTING_TRT LightingIntermediateData lightingDataTRT; @@ -159,17 +190,23 @@ // apply screen-space shadow and ao // lightingResult.shadow/ao *= XXX; - - - //#todo: cluster related lighting flow - #if CC_ENABLE_CLUSTERED_LIGHT_CULLING - //#include - #endif - // user-defined lighting model #ifdef CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT - SurfacesLightingModifyFinalResult(lightingResult, lightingData, surfaceData); + LightingMiscData miscData; + miscData.lightType = LIGHT_TYPE_DIRECTIONAL; + miscData.lightPos = vec3(0.0); + miscData.lightDir = cc_mainLitDir.xyz; + miscData.lightColorAndIntensity = cc_mainLitColor; + miscData.lightSizeRangeAngle = vec4(0.0, 0.0, 0.0, 0.0); + SurfacesLightingModifyFinalResult(lightingResult, lightingData, surfaceData, miscData); #endif } - #endif -#endif + #if CC_ENABLE_CLUSTERED_LIGHT_CULLING + // #todo: cluster related lighting flow, invoke after CCSurfacesLighting + // use same code as additive-pass + // void CCSurfacesLighting_Cluster(inout LightingResult lightingResult, in SurfacesMaterialData surfaceData, in vec2 shadowBias) + // { + // } + #endif // cluster lighting + #endif // base pass +#endif // forward shading diff --git a/editor/assets/chunks/lighting-models/model-functions/standard-common.chunk b/editor/assets/chunks/lighting-models/model-functions/standard-common.chunk index 515ff46b65..75007da34e 100644 --- a/editor/assets/chunks/lighting-models/model-functions/standard-common.chunk +++ b/editor/assets/chunks/lighting-models/model-functions/standard-common.chunk @@ -4,22 +4,30 @@ void LightingCalculateDirect(out vec3 lightingDiffuse, out vec3 lightingSpecular, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity) { vec3 irradiance = vec3(lightingData.NoLSat) * lightSourceColorAndIntensity.rgb * lightSourceColorAndIntensity.w; - - lightingDiffuse = irradiance * DiffuseCoefficient_EnergyConservation; - float roughness = lightingData.specularParam; -#if CC_SURFACES_LIGHTING_ANISOTROPIC - float rT, rB; - GetAnisotropicRoughness(roughness, lightingData.anisotropyShape, rT, rB); - float calcSpec = D_GGXAniso(rT, rB, lightingData.NoHSat, lightingData.H, lightingData.T, lightingData.B); +#if CC_SURFACES_LIGHTING_CALCULATE_DIFFUSE + lightingDiffuse = irradiance * DiffuseCoefficient_EnergyConservation; #else - #if CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING - float calcSpec = (roughness * 0.25 + 0.25) * D_GGXMobile(roughness, lightingData.NoHSat); - #else - float calcSpec = D_GGX(roughness, lightingData.NoHSat); - #endif + lightingDiffuse = vec3(0.0); #endif + +#if CC_SURFACES_LIGHTING_CALCULATE_SPECULAR + float roughness = lightingData.specularParam; + #if CC_SURFACES_LIGHTING_ANISOTROPIC + float rT, rB; + GetAnisotropicRoughness(roughness, lightingData.anisotropyShape, rT, rB); + float calcSpec = D_GGXAniso(rT, rB, lightingData.NoHSat, lightingData.H, lightingData.T, lightingData.B); + #else + #if CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING + float calcSpec = (roughness * 0.25 + 0.25) * D_GGXMobile(roughness, lightingData.NoHSat); + #else + float calcSpec = D_GGX(roughness, lightingData.NoHSat); + #endif + #endif lightingSpecular = irradiance * calcSpec; +#else + lightingSpecular = vec3(0.0); +#endif } @@ -84,7 +92,7 @@ vec3 SampleEnvironmentSpecular(samplerCube tex, in LightingIntermediateData ligh vec3 CalculateEnvironmentDiffuse(in LightingIntermediateData lightingData, float lightIntensity) { // Hemisphere Lighting - float fAmb = 0.5 - lightingData.N.y * 0.5; + float fAmb = max(EPSILON, 0.5 - lightingData.N.y * 0.5); vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb); // Diffuse Map diff --git a/editor/assets/chunks/lighting-models/model-functions/standard.chunk b/editor/assets/chunks/lighting-models/model-functions/standard.chunk index a1bfba152f..55013bed63 100644 --- a/editor/assets/chunks/lighting-models/model-functions/standard.chunk +++ b/editor/assets/chunks/lighting-models/model-functions/standard.chunk @@ -1,5 +1,6 @@ #include #include +#include #include #include @@ -26,8 +27,17 @@ void CCSurfacesLightingCalculateDirect(out vec3 lightingDiffuse, out vec3 lighti void CCSurfacesLightingCalculateEnvironment(out vec3 lightingDiffuse, out vec3 lightingSpecular, in LightingIntermediateData lightingData, float lightIntensity) { +#if CC_SURFACES_LIGHTING_CALCULATE_DIFFUSE lightingDiffuse = CalculateEnvironmentDiffuse(lightingData, lightIntensity); +#else + lightingDiffuse = vec3(0.0); +#endif + +#if CC_SURFACES_LIGHTING_CALCULATE_SPECULAR lightingSpecular = CalculateEnvironmentSpecular(lightingData, lightIntensity); +#else + lightingSpecular = vec3(0.0); +#endif } #if CC_SURFACES_LIGHTING_USE_FRESNEL @@ -38,14 +48,15 @@ void CCSurfacesLightingCalculateEnvironment(out vec3 lightingDiffuse, out vec3 l #endif #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR - // do not support planar reflection and anisotropy + // do not support anisotropy void CCSurfacesLightingCalculateDirectTransmitSpecular(out vec3 lightingSpecular, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity) { float roughness = lightingData.specularParam; - vec3 irradiance = vec3(lightingData.NoLSat) * lightSourceColorAndIntensity.rgb * lightSourceColorAndIntensity.w; + float NoLSat = saturate(dot(lightingData.N, -lightingData.L)); + vec3 irradiance = NoLSat * lightSourceColorAndIntensity.rgb * lightSourceColorAndIntensity.w; vec3 R = CalculateRefractDirection(lightingData.N, lightingData.V, lightingData.NoV, lightingData.ior); - float RoL = dot(lightingData.L, R); + float RoL = dot(lightingData.L, normalize(R)); float calcSpec = D_GGX(roughness, saturate(RoL)); lightingSpecular = irradiance * calcSpec; @@ -56,37 +67,46 @@ void CCSurfacesLightingCalculateEnvironment(out vec3 lightingDiffuse, out vec3 l vec3 R = CalculateRefractDirection(lightingData.N, lightingData.V, lightingData.NoV, lightingData.ior); float roughness = lightingData.specularParam; - #if USE_REFLECTION_PROBE - #if USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_CUBE + #if CC_USE_REFLECTION_PROBE + #if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_CUBE envSpec = EnvReflection(cc_reflectionProbeCubemap, R, roughness, cc_ambientGround.w); #endif //todo: planar refraction from scene color #endif - #if CC_USE_IBL && USE_REFLECTION_PROBE != REFLECTION_PROBE_TYPE_CUBE + #if CC_USE_IBL && CC_USE_REFLECTION_PROBE != REFLECTION_PROBE_TYPE_CUBE envSpec = EnvReflection(cc_environment, R, roughness, cc_ambientGround.w); #endif lightingSpecular = envSpec * lightIntensity; + + // scattering + float distance = lightingData.transmitParams.w, inScatterCoef = lightingData.transmitParams.z; + vec2 e = lightingData.transmitParams.xy; + vec2 extinction = exp(-e * distance * vec2(1.0, inScatterCoef)); + vec3 inScattered = (1.0 - extinction.y) * lightingData.inScatteringLightColor.rgb; + lightingSpecular = lightingSpecular * extinction.x + inScattered; } #endif -#if CC_SURFACES_LIGHTING_TRANSMITTENCE - vec3 CCSurfacesLightingCalculateDirectTransmittence(in LightingResult lightingResult, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity) +#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + void CCSurfacesLightingCalculateDirectTransmitDiffuse(out vec3 transmitDiffuse, in LightingResult lightingResult, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity) { vec3 backIrradiance = vec3(saturate(-lightingData.NoL)) * lightSourceColorAndIntensity.rgb * lightSourceColorAndIntensity.w; vec3 transmitDiffuse = backIrradiance * DiffuseCoefficient_EnergyConservation; //todo: add some - lightingData.transmittenceParams; - return vec3(0.0); + lightingData.transmitParams; + lightingData.transmitDiffuseParams; + transmitDiffuse = vec3(0.0); } - vec3 CCSurfacesLightingCalculateEnvironmentTransmittence(in LightingResult lightingResult, in LightingIntermediateData lightingData, float lightIntensity) + void CCSurfacesLightingCalculateEnvironmentTransmitDiffuse(out vec3 transmitDiffuse, in LightingResult lightingResult, in LightingIntermediateData lightingData, float lightIntensity) { // negativate lightingData.N before invoking CalculateEnvironmentDiffuse lightingData.N *= -1.0; vec3 backIrradiance = CalculateEnvironmentDiffuse(lightingData, lightIntensity); - lightingData.transmittenceParams; - return vec3(0.0); + lightingData.transmitParams; + lightingData.transmitDiffuseParams; + transmitDiffuse = vec3(0.0); //backIrradiance * lightingResult.ao; } #endif @@ -100,25 +120,26 @@ void CCSurfacesLightingCalculateEnvironment(out vec3 lightingDiffuse, out vec3 l } #endif - void CCSurfacesLightingCalculateDirectTRT(out vec3 TRTColor, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity) + void CCSurfacesLightingCalculateDirectTRT(out vec3 TRTLighting, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity) { vec3 unused; // light color has less influence - CCSurfacesLightingCalculateDirect(unused, TRTColor, lightingData, vec4(1.0)); - vec3 Color = SurfacesLightingGetTRTSpecularColor(TRTColor.x, true); + CCSurfacesLightingCalculateDirect(unused, TRTLighting, lightingData, vec4(1.0)); + float brdf = TRTLighting.x; + vec3 Color = SurfacesLightingGetTRTSpecularColor(brdf, true); // todo: modify Color to add some light color influence - TRTColor *= Color * lightSourceColorAndIntensity.w; + TRTLighting *= Color * lightSourceColorAndIntensity.w; } - void CCSurfacesLightingCalculateEnvironmentTRT(out vec3 TRTColor, in LightingIntermediateData lightingData, float lightIntensity) + void CCSurfacesLightingCalculateEnvironmentTRT(out vec3 TRTLighting, in LightingIntermediateData lightingData, float lightIntensity) { vec3 unused; // light color has less influence - TRTColor = CalculateEnvironmentSpecular(lightingData, 1.0); - float brdf = length(TRTColor); + TRTLighting = CalculateEnvironmentSpecular(lightingData, 1.0); + float brdf = length(TRTLighting); vec3 Color = SurfacesLightingGetTRTSpecularColor(brdf, false); // todo: modify Color to add some light color influence - TRTColor *= Color * lightIntensity; + TRTLighting *= Color * lightIntensity; } #endif diff --git a/editor/assets/chunks/lighting-models/model-functions/toon.chunk b/editor/assets/chunks/lighting-models/model-functions/toon.chunk index 8017b9a575..d6f8540dc8 100644 --- a/editor/assets/chunks/lighting-models/model-functions/toon.chunk +++ b/editor/assets/chunks/lighting-models/model-functions/toon.chunk @@ -1,4 +1,5 @@ #include +#include #include bool CCSurfacesLightingEnableShadow(in float NoL) diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk index b8fa5af41a..239974e685 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk @@ -119,6 +119,11 @@ void main() { #endif // Color output + #if CC_USE_RGBE_OUTPUT + fragColorX = packRGBE(color.rgb); // for reflection-map + return; + #endif + #if CC_USE_HDR #if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC && CC_SURFACES_ENABLE_DEBUG_VIEW if (IS_DEBUG_VIEW_COMPOSITE_ENABLE_TONE_MAPPING) diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk index eefaaaf9a6..392f91b91a 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk @@ -9,7 +9,8 @@ void main() In.normal.xyz = SurfacesVertexModifyLocalNormal(In); #if CC_SURFACES_USE_TANGENT_SPACE In.tangent = SurfacesVertexModifyLocalTangent(In); - #endif + #endif + SurfacesVertexModifyLocalSharedData(In); // World Space CCSurfacesVertexWorldTransform(In); @@ -20,13 +21,13 @@ void main() In.clipPos = SurfacesVertexModifyClipPos(In); // Other Surfaces Function - SurfacesVertexModifyUV(In); - SurfacesVertexModifySharedData(In); - vec3 viewDirect = normalize(cc_cameraPos.xyz - In.worldPos); In.worldNormal.w = dot(In.worldNormal.xyz, viewDirect) < 0.0 ? -1.0 : 1.0; In.worldNormal.xyz = SurfacesVertexModifyWorldNormal(In); + SurfacesVertexModifyUV(In); + SurfacesVertexModifySharedData(In); + // Other Data CCSurfacesVertexTransformUV(In); CCSurfacesVertexTransferFog(In); diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk index 9b17e812bd..cecd57a617 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk @@ -11,6 +11,7 @@ void main() CCSurfacesVertexInput(In); CCSurfacesVertexAnimation(In); In.position.xyz = SurfacesVertexModifyLocalPos(In); + SurfacesVertexModifyLocalSharedData(In); // World Space CCSurfacesVertexWorldTransform(In); diff --git a/editor/assets/chunks/surfaces/data-structures/standard.chunk b/editor/assets/chunks/surfaces/data-structures/standard.chunk index 0584bf453f..40d83496a7 100644 --- a/editor/assets/chunks/surfaces/data-structures/standard.chunk +++ b/editor/assets/chunks/surfaces/data-structures/standard.chunk @@ -18,9 +18,13 @@ struct SurfacesMaterialData #if CC_SURFACES_LIGHTING_ANISOTROPIC float anisotropyShape; #endif - -#if CC_SURFACES_LIGHTING_TRANSMITTENCE - vec4 transmittenceParams; + +#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR || CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + vec3 inScatteringLightColor; + vec4 transmitParams; +#endif +#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + vec4 transmitDiffuseParams; #endif #if CC_SURFACES_LIGHTING_TRT float roughnessTRT; diff --git a/editor/assets/chunks/surfaces/default-functions/common-vs.chunk b/editor/assets/chunks/surfaces/default-functions/common-vs.chunk index 5f1118a99e..794b3dfeac 100644 --- a/editor/assets/chunks/surfaces/default-functions/common-vs.chunk +++ b/editor/assets/chunks/surfaces/default-functions/common-vs.chunk @@ -21,6 +21,15 @@ vec3 SurfacesVertexModifyLocalNormal(in SurfacesStandardVertexIntermediate In) #endif #endif +// some vertex datas use shared raw data, avoid sample / calculate same raw data multiply times, use this function for better performance +// this function invokes before world transform +#ifndef CC_SURFACES_VERTEX_MODIFY_LOCAL_SHARED_DATA +void SurfacesVertexModifyLocalSharedData(inout SurfacesStandardVertexIntermediate In) +{ +} +#endif + + #ifndef CC_SURFACES_VERTEX_MODIFY_WORLD_POS vec3 SurfacesVertexModifyWorldPos(in SurfacesStandardVertexIntermediate In) { diff --git a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk index 70fe9b108b..e4e6961a98 100644 --- a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk @@ -70,11 +70,22 @@ vec4 SurfacesFragmentModifyPBRParams() } #endif -#ifndef CC_SURFACES_FRAGMENT_MODIFY_TRANSMITTENCE_PARAMS -vec4 SurfacesFragmentModifytransmittenceParamss() +#ifndef CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_PARAMS +void SurfacesFragmentModifyTransmitParams(out vec4 transmitParams, out vec3 inScatteringLightColor) { - // x: exponential transmit coef - // y: additional transmit depth mask, add light transport for area which cannot be covered by shadowmap transmittence, or stand for thin transmittence + // xy: extinction coef for out/in-scattering (should be same) + // z: in-scattering coef (constant phase function) + // w: transmit distance(water depth, leaf thickness) + transmitParams = vec4(0.0, 0.0, 0.0, 0.0); + inScatteringLightColor = vec3(0.0); +} +#endif + +#ifndef CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_DIFFUSE_PARAMS +vec4 SurfacesFragmentModifyTransmitDiffuseParams() +{ + // x: transmit irradiance apply shadow + // y: additional transmit depth mask, add light transport for area which cannot be covered by shadowmap transmittance, or stand for thin transmittance // zw: min/max DepthWS for shadowmap, 0 means disable shadow transmit return vec4(1.0, 0.0, 0.0, 0.0); } diff --git a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk index 217fc24906..e0b2c4f7b6 100644 --- a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk +++ b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk @@ -56,8 +56,11 @@ #ifndef CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR #define CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR 0 #endif -#ifndef CC_SURFACES_LIGHTING_TRANSMITTENCE - #define CC_SURFACES_LIGHTING_TRANSMITTENCE 0 +#ifndef CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + #define CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE 0 +#endif +#ifndef CC_SURFACES_LIGHTING_USE_SHADOWMAP_TRANSMIT + #define CC_SURFACES_LIGHTING_USE_SHADOWMAP_TRANSMIT 0 #endif #ifndef CC_SURFACES_LIGHTING_TRT #define CC_SURFACES_LIGHTING_TRT 0 @@ -67,3 +70,11 @@ #ifndef CC_SURFACES_ENABLE_DEBUG_VIEW #define CC_SURFACES_ENABLE_DEBUG_VIEW 1 #endif + +// for skin +#ifndef CC_SURFACES_LIGHTING_CALCULATE_DIFFUSE + #define CC_SURFACES_LIGHTING_CALCULATE_DIFFUSE 1 +#endif +#ifndef CC_SURFACES_LIGHTING_CALCULATE_SPECULAR + #define CC_SURFACES_LIGHTING_CALCULATE_SPECULAR 1 +#endif diff --git a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk index 1aff7c1717..e25d8c9ce2 100644 --- a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk +++ b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk @@ -100,68 +100,139 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) #if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_SINGLE bool CCSurfacesDebugViewLightingResult(inout vec4 color, in LightingResult lightingResult) { - bool isDebugMatched = false; + // whether need tone mapping & LinearToSRGB + bool isSRGBColor = false; if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_DIFFUSE)) { color.rgb = lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting; - isDebugMatched = true; + isSRGBColor = true; } if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_SPECULAR)) { color.rgb = lightingResult.directSpecular * lightingResult.specularColorWithLighting; - isDebugMatched = true; + isSRGBColor = true; } if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_ALL)) { color.rgb = lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.directSpecular * lightingResult.specularColorWithLighting; - isDebugMatched = true; + isSRGBColor = true; } if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_ENV_DIFFUSE)) { color.rgb = lightingResult.environmentDiffuse * lightingResult.diffuseColorWithLighting; - isDebugMatched = true; + isSRGBColor = true; } if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_ENV_SPECULAR)) { color.rgb = lightingResult.environmentSpecular * lightingResult.specularColorWithLighting; - isDebugMatched = true; + isSRGBColor = true; } if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_ENV_ALL)) { color.rgb = lightingResult.environmentDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.environmentSpecular * lightingResult.specularColorWithLighting; - isDebugMatched = true; + isSRGBColor = true; } if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_LIGHT_MAP)) { color.rgb = lightingResult.lightmapColor; - isDebugMatched = true; + isSRGBColor = true; } if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_EMISSIVE)) { color.rgb = lightingResult.emissive; - isDebugMatched = true; + isSRGBColor = true; } if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_AO)) { color.rgb = vec3(lightingResult.ao); - isDebugMatched = true; + isSRGBColor = false; } if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_SHADOW)) { color.rgb = vec3(lightingResult.shadow); - isDebugMatched = true; + isSRGBColor = false; } - return isDebugMatched; + float fresnel = 0.0; + vec3 directTransmitSpecular = vec3(0.0), environmentTransmitSpecular = vec3(0.0); + vec3 directTransmitDiffuse = vec3(0.0), environmentTransmitDiffuse = vec3(0.0); + vec3 directTRT = vec3(0.0), environmentTRT = vec3(0.0); + #if CC_SURFACES_LIGHTING_USE_FRESNEL + fresnel = lightingResult.fresnel; + #endif + #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR + directTransmitSpecular = lightingResult.directTransmitSpecular; + environmentTransmitSpecular = lightingResult.environmentTransmitSpecular; + #endif + #if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + directTransmitDiffuse = lightingResult.directTransmitDiffuse; + environmentTransmitDiffuse = lightingResult.environmentTransmitDiffuse; + #endif + #if CC_SURFACES_LIGHTING_TRT + directTRT = lightingResult.directTRT; + environmentTRT = lightingResult.environmentTRT; + #endif + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_FRESNEL)) + { + color.rgb = vec3(fresnel); + isSRGBColor = false; + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_TRANSMIT_DIRECT_SPECULAR)) + { + color.rgb = directTransmitSpecular; + isSRGBColor = true; + } + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_TRANSMIT_ENV_SPECULAR)) + { + color.rgb = environmentTransmitSpecular; + isSRGBColor = true; + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_TRANSMIT_DIRECT_DIFFUSE)) + { + color.rgb = directTransmitDiffuse; + isSRGBColor = true; + } + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_TRANSMIT_ENV_DIFFUSE)) + { + color.rgb = environmentTransmitDiffuse; + isSRGBColor = true; + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_TRANSMIT_ALL)) + { + color.rgb = directTransmitSpecular + environmentTransmitSpecular + directTransmitDiffuse + environmentTransmitDiffuse; + isSRGBColor = true; + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_TRT_DIRECT)) + { + color.rgb = directTRT; + isSRGBColor = true; + } + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_TRT_ENVIRONMENT)) + { + color.rgb = environmentTRT; + isSRGBColor = true; + } + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_TRT_ALL)) + { + color.rgb = directTRT + environmentTRT; + isSRGBColor = true; + } + + return isSRGBColor; } #endif @@ -182,6 +253,21 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_ENV_SPECULAR) lightingResult.environmentSpecular = vec3(0.0); + #if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_TRANSMIT_DIFFUSE) + lightingResult.directTransmitDiffuse = lightingResult.environmentTransmitDiffuse = vec3(0.0); + #endif + + #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_TRANSMIT_SPECULAR) + lightingResult.directTransmitSpecular = lightingResult.environmentTransmitSpecular = vec3(0.0); + #endif + + #if CC_SURFACES_LIGHTING_TRT + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_TRT) + lightingResult.directTRT = lightingResult.environmentTRT = vec3(0.0); + #endif + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_EMISSIVE) lightingResult.emissive = vec3(0.0); @@ -193,5 +279,10 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_AO) lightingResult.ao = 1.0; + + #if CC_SURFACES_LIGHTING_USE_FRESNEL + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_FRESNEL) + lightingResult.fresnel = 1.0; + #endif } #endif diff --git a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk index 950d2fdba5..e65c9035b2 100644 --- a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk @@ -34,8 +34,11 @@ void CCSurfacesFragmentGetMaterialData(inout SurfacesMaterialData surfaceData) surfaceData.metallic = pbr.z; surfaceData.specularIntensity = pbr.w; -#if CC_SURFACES_LIGHTING_TRANSMITTENCE - surfaceData.transmittenceParams =SurfacesFragmentModifytransmittenceParamss(); +#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR || CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + SurfacesFragmentModifyTransmitParams(surfaceData.transmitParams, surfaceData.inScatteringLightColor); +#endif +#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + surfaceData.transmitDiffuseParams = SurfacesFragmentModifyTransmitDiffuseParams(); #endif #if CC_SURFACES_LIGHTING_TRT vec4 trt = SurfacesFragmentModifyTRTParams(); @@ -94,13 +97,18 @@ void CCSurfacesInitializeLightingIntermediateData(inout LightingIntermediateData ); lightingData.specularParam = surfaceData.roughness; lightingData.ior = surfaceData.ior; +#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR || CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + lightingData.transmitParams = surfaceData.transmitParams; + lightingData.inScatteringLightColor = surfaceData.inScatteringLightColor; +#endif +#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + lightingData.transmitDiffuseParams = surfaceData.transmitDiffuseParams; +#endif } + void CCSurfacesLightingCalculateIntermediateData_PerLight(inout LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData, vec3 lightDirWithDist) { CCSurfacesLightingGetIntermediateData_PerLight(lightingData, lightDirWithDist); -#if CC_SURFACES_LIGHTING_TRANSMITTENCE - lightingData.transmittenceParams = surfaceData.transmittenceParams; -#endif } // pass original lightingData, get TRT lightingData @@ -113,13 +121,46 @@ void CCSurfacesGetLightingIntermediateDataTRT(out LightingIntermediateData light #endif -// Copy material data to lighting results +// Copy material data to lighting results for base pass void CCSurfacesInitializeLightingResult(inout LightingResult lightingResult, in SurfacesMaterialData surfaceData) { lightingResult.ao = surfaceData.ao; lightingResult.emissive = surfaceData.emissive; } +// Init accumulated lighting results for additive pass +void CCSurfacesInitializeLightingResult(inout LightingResult lightingResult) +{ + lightingResult.directDiffuse = lightingResult.directSpecular = vec3(0.0); + +#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR + lightingResult.directTransmitSpecular = vec3(0.0); +#endif +#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + lightingResult.directTransmitDiffuse = vec3(0.0); +#endif +#if CC_SURFACES_LIGHTING_TRT + lightingResult.directTRT = vec3(0.0); +#endif +} + +// Accumulated lighting results for additive pass +void CCSurfacesAccumulateLightingResult(inout LightingResult lightingResultAccumulated, in LightingResult lightingResult) +{ + lightingResultAccumulated.directDiffuse += lightingResult.directDiffuse * lightingResult.shadow; + lightingResultAccumulated.directSpecular += lightingResult.directSpecular * lightingResult.shadow; + + #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR + lightingResultAccumulated.directTransmitSpecular += lightingResult.directTransmitSpecular; + #endif + #if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + lightingResultAccumulated.directTransmitDiffuse += lightingResult.directTransmitDiffuse; + #endif + #if CC_SURFACES_LIGHTING_TRT + lightingResultAccumulated.directTRT += lightingResult.directTRT; + #endif +} + #if CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_DEFERRED @@ -157,12 +198,16 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li #if CC_SURFACES_LIGHTING_USE_FRESNEL fresnel = lightingResult.fresnel; #endif + float invFresnel = 1.0 - fresnel; color.xyz += ( lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.directSpecular * lightingResult.specularColorWithLighting * fresnel #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR - + lightingResult.directTransmitSpecular * lightingResult.specularColorWithLighting * (1.0 - fresnel) + + lightingResult.directTransmitSpecular * lightingResult.specularColorWithLighting * invFresnel + #endif + #if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + + lightingResult.directTransmitDiffuse #endif #if CC_SURFACES_LIGHTING_TRT + lightingResult.directTRT * lightingResult.specularColorWithLighting @@ -180,7 +225,10 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li ( lightingResult.environmentDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.environmentSpecular * lightingResult.specularColorWithLighting * fresnel #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR - + lightingResult.environmentTransmitSpecular * lightingResult.specularColorWithLighting * (1.0 - fresnel) + + lightingResult.environmentTransmitSpecular * lightingResult.specularColorWithLighting * invFresnel + #endif + #if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE + + lightingResult.environmentTransmitDiffuse #endif #if CC_SURFACES_LIGHTING_TRT + lightingResult.environmentTRT * lightingResult.specularColorWithLighting @@ -247,6 +295,10 @@ void CCSurfacesDebugViewSurfaceData(inout vec4 color, in SurfacesMaterialData su scalar = surfaceData.specularIntensity; color = vec4(scalar, scalar, scalar, 1.0); } + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_IOR)) { + scalar = surfaceData.ior - 1.0; + color = vec4(scalar, scalar, scalar, 1.0); + } } #endif diff --git a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk index d2ebbfa913..43becca4b6 100644 --- a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk @@ -83,12 +83,25 @@ void CCSurfacesLightingCalculateIntermediateData_PerLight(inout LightingIntermed CCSurfacesLightingGetIntermediateData_PerLight(lightingData, lightDirWithDist); } -// Copy material data to lighting results +// Copy material data to lighting results for base pass void CCSurfacesInitializeLightingResult(inout LightingResult lightingResult, in SurfacesMaterialData surfaceData) { lightingResult.emissive = surfaceData.emissive; } +// Init accumulated lighting results for additive pass +void CCSurfacesInitializeLightingResult(inout LightingResult lightingResult) +{ + lightingResult.directDiffuse = lightingResult.directSpecular = vec3(0.0); +} + +// Accumulated lighting results for additive pass +void CCSurfacesAccumulateLightingResult(inout LightingResult lightingResultAccumulated, in LightingResult lightingResult) +{ + lightingResultAccumulated.directDiffuse += lightingResult.directDiffuse * lightingResult.shadow; + lightingResultAccumulated.directSpecular += lightingResult.directSpecular * lightingResult.shadow; +} + // Lighting #if CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_DEFERRED vec4 CCSurfacesDeferredOutput0(in SurfacesMaterialData surfaceData) diff --git a/editor/assets/default_materials/default-billboard-material.mtl.meta b/editor/assets/default_materials/default-billboard-material.mtl.meta index cb1d5c83ef..97c632b971 100644 --- a/editor/assets/default_materials/default-billboard-material.mtl.meta +++ b/editor/assets/default_materials/default-billboard-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "78e0584a-4343-4727-8f37-e14e65c2a2db", diff --git a/editor/assets/default_materials/default-clear-stencil.mtl.meta b/editor/assets/default_materials/default-clear-stencil.mtl.meta index 698e68a3d2..59957ce2d9 100644 --- a/editor/assets/default_materials/default-clear-stencil.mtl.meta +++ b/editor/assets/default_materials/default-clear-stencil.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "8bbdbcdd-5cd4-4100-b6d5-b7c9625b6107", diff --git a/editor/assets/default_materials/default-material-transparent.mtl.meta b/editor/assets/default_materials/default-material-transparent.mtl.meta index 81f73e7a5e..3004bebb7e 100644 --- a/editor/assets/default_materials/default-material-transparent.mtl.meta +++ b/editor/assets/default_materials/default-material-transparent.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "c31a901b-671b-4c3d-9246-f9a6e5f14b90", diff --git a/editor/assets/default_materials/default-material.mtl.meta b/editor/assets/default_materials/default-material.mtl.meta index d7779aece3..83e5e18ca3 100644 --- a/editor/assets/default_materials/default-material.mtl.meta +++ b/editor/assets/default_materials/default-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "d3c7820c-2a98-4429-8bc7-b8453bc9ac41", diff --git a/editor/assets/default_materials/default-particle-gpu-material.mtl.meta b/editor/assets/default_materials/default-particle-gpu-material.mtl.meta index 8a1fad6be5..3101eed10c 100644 --- a/editor/assets/default_materials/default-particle-gpu-material.mtl.meta +++ b/editor/assets/default_materials/default-particle-gpu-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "14da1725-c4c2-42b4-ab08-ee0aeb6898b3", diff --git a/editor/assets/default_materials/default-particle-material.mtl.meta b/editor/assets/default_materials/default-particle-material.mtl.meta index 3deafde7c0..27adeff5d1 100644 --- a/editor/assets/default_materials/default-particle-material.mtl.meta +++ b/editor/assets/default_materials/default-particle-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "c0143906-9aed-447e-9436-2ae8512d1b6e", diff --git a/editor/assets/default_materials/default-spine-material.mtl.meta b/editor/assets/default_materials/default-spine-material.mtl.meta index b7633f9960..239ea62237 100644 --- a/editor/assets/default_materials/default-spine-material.mtl.meta +++ b/editor/assets/default_materials/default-spine-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "b5d6115f-0370-4d7c-aad3-c194cc71cf98", diff --git a/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta b/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta index 358bd8c07e..36d4b1b9d7 100644 --- a/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta +++ b/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "ade8a15a-dcca-4b3c-84c6-f6476ac875bb", diff --git a/editor/assets/default_materials/default-trail-material.mtl.meta b/editor/assets/default_materials/default-trail-material.mtl.meta index ed0b65f9da..ca98959efa 100644 --- a/editor/assets/default_materials/default-trail-material.mtl.meta +++ b/editor/assets/default_materials/default-trail-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "081cab31-dccd-428e-8652-f2404cc81c47", diff --git a/editor/assets/default_materials/missing-effect-material.mtl.meta b/editor/assets/default_materials/missing-effect-material.mtl.meta index f7b476df18..0d6c0175c7 100644 --- a/editor/assets/default_materials/missing-effect-material.mtl.meta +++ b/editor/assets/default_materials/missing-effect-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "bcd64cc6-2dd9-43f6-abbe-66318d332032", diff --git a/editor/assets/default_materials/missing-material.mtl.meta b/editor/assets/default_materials/missing-material.mtl.meta index 39c73f1dd0..c0eca933e1 100644 --- a/editor/assets/default_materials/missing-material.mtl.meta +++ b/editor/assets/default_materials/missing-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "d930590d-bb92-4cc8-8bd1-23cd027f9edf", diff --git a/editor/assets/default_materials/particle-add.mtl.meta b/editor/assets/default_materials/particle-add.mtl.meta index 7da3fbfde2..f39079d594 100644 --- a/editor/assets/default_materials/particle-add.mtl.meta +++ b/editor/assets/default_materials/particle-add.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "ea7478b0-408d-4052-b703-f0d2355e095f", diff --git a/editor/assets/default_materials/standard-material.mtl.meta b/editor/assets/default_materials/standard-material.mtl.meta index bd16ce2d14..efa764a77f 100644 --- a/editor/assets/default_materials/standard-material.mtl.meta +++ b/editor/assets/default_materials/standard-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "620b6bf3-0369-4560-837f-2a2c00b73c26", diff --git a/editor/assets/default_materials/ui-alpha-test-material.mtl.meta b/editor/assets/default_materials/ui-alpha-test-material.mtl.meta index 660fd4c4f0..9668081cb8 100644 --- a/editor/assets/default_materials/ui-alpha-test-material.mtl.meta +++ b/editor/assets/default_materials/ui-alpha-test-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "50f4348b-c883-4e2f-8f11-ce233b859fa1", diff --git a/editor/assets/default_materials/ui-base-material.mtl.meta b/editor/assets/default_materials/ui-base-material.mtl.meta index c201a713ea..3868077a16 100644 --- a/editor/assets/default_materials/ui-base-material.mtl.meta +++ b/editor/assets/default_materials/ui-base-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "e9aa9a3e-5b2b-4ac7-a2c7-073de2b2b24f", diff --git a/editor/assets/default_materials/ui-graphics-material.mtl.meta b/editor/assets/default_materials/ui-graphics-material.mtl.meta index aaeef22aef..e675d6d428 100644 --- a/editor/assets/default_materials/ui-graphics-material.mtl.meta +++ b/editor/assets/default_materials/ui-graphics-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "f0416e68-0200-4b77-a926-4f9d16e494da", diff --git a/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta b/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta index c69c2433d1..3daa36ec41 100644 --- a/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta +++ b/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "f92806d7-1768-443f-afe8-12bcde84d0f0", diff --git a/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta b/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta index 88249fa911..bd23e80516 100644 --- a/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta +++ b/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "dd3a144d-ab7f-41f0-82b8-2e43a090d496", diff --git a/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta b/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta index 5c509368a3..27b4f4eaf2 100644 --- a/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta +++ b/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "efe8e2a3-eace-427b-b4f1-cb8a937ec77d", diff --git a/editor/assets/default_materials/ui-sprite-material.mtl.meta b/editor/assets/default_materials/ui-sprite-material.mtl.meta index 70f563df02..bbcc1cf185 100644 --- a/editor/assets/default_materials/ui-sprite-material.mtl.meta +++ b/editor/assets/default_materials/ui-sprite-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "fda095cb-831d-4601-ad94-846013963de8", diff --git a/editor/assets/default_renderpipeline/deferred-lighting.mtl.meta b/editor/assets/default_renderpipeline/deferred-lighting.mtl.meta index a3c9540bb5..c696d8160c 100644 --- a/editor/assets/default_renderpipeline/deferred-lighting.mtl.meta +++ b/editor/assets/default_renderpipeline/deferred-lighting.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "016951c5-5a09-4dd0-9bb7-f4958a82d690", diff --git a/editor/assets/default_renderpipeline/post-process.mtl.meta b/editor/assets/default_renderpipeline/post-process.mtl.meta index 5ff01451c5..9fc995df58 100644 --- a/editor/assets/default_renderpipeline/post-process.mtl.meta +++ b/editor/assets/default_renderpipeline/post-process.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "85c4d630-c264-4b18-90a4-c52d594e6099", diff --git a/editor/assets/default_renderpipeline/tonemap.mtl.meta b/editor/assets/default_renderpipeline/tonemap.mtl.meta index 036df00abd..544c5e1308 100644 --- a/editor/assets/default_renderpipeline/tonemap.mtl.meta +++ b/editor/assets/default_renderpipeline/tonemap.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "9d9704d8-08b4-4917-ba47-9d778bc77ac6", diff --git a/editor/assets/default_ui/atom.plist b/editor/assets/default_ui/atom.plist index 117d7a7365..9392b28eee 100644 --- a/editor/assets/default_ui/atom.plist +++ b/editor/assets/default_ui/atom.plist @@ -23,13 +23,13 @@ finishColorRed 0.68082684278488159 finishColorVarianceAlpha - 0.74000000953674316 + 0.0 finishColorVarianceBlue - 0.98000001907348633 + 0.0 finishColorVarianceGreen - 0.98000001907348633 + 0.0 finishColorVarianceRed - 0.41999998688697815 + 0.0 finishParticleSize 30.319999694824219 finishParticleSizeVariance @@ -87,13 +87,13 @@ startColorRed 0.794921875 startColorVarianceAlpha - 0.77999997138977051 + 0.0 startColorVarianceBlue - 0.68000000715255737 + 0.0 startColorVarianceGreen - 1 + 0.0 startColorVarianceRed - 0.89999997615814209 + 0.0 startParticleSize 3.369999885559082 startParticleSizeVariance diff --git a/editor/assets/effects/builtin-toon.effect b/editor/assets/effects/builtin-toon.effect index 431d5e4f4d..e4b025068a 100644 --- a/editor/assets/effects/builtin-toon.effect +++ b/editor/assets/effects/builtin-toon.effect @@ -200,11 +200,11 @@ CCProgram toon-fs %{ #endif #endif - vec4 baseColor = baseColor; + vec4 localBaseColor = baseColor; #if USE_BASE_COLOR_MAP vec4 baseColorMap = texture(baseColorMap, v_uv); baseColorMap.rgb = SRGBToLinear(baseColorMap.rgb); - baseColor *= baseColorMap; + localBaseColor *= baseColorMap; #if BASE_COLOR_MAP_AS_SHADE_MAP_1 s.shade1 *= baseColorMap.rgb; #endif @@ -212,7 +212,7 @@ CCProgram toon-fs %{ s.shade2 *= baseColorMap.rgb; #endif #endif - s.baseColor = baseColor; + s.baseColor = localBaseColor; s.baseColor.rgb *= colorScaleAndCutoff.xyz; #if USE_ALPHA_TEST diff --git a/editor/assets/effects/editor/gizmo.effect b/editor/assets/effects/editor/gizmo.effect index d086428fc7..f43d1f25f3 100644 --- a/editor/assets/effects/editor/gizmo.effect +++ b/editor/assets/effects/editor/gizmo.effect @@ -109,7 +109,11 @@ CCProgram gizmo-fs %{ #include #include #include - #include + #if CC_USE_LIGHT_PROBE + #include + #else + #include + #endif in vec3 normal_w; in vec3 pos_w; @@ -120,48 +124,59 @@ CCProgram gizmo-fs %{ uniform Constant { vec4 mainColor; + + // SH coefficents used for light probe visualization + vec4 cc_sh_linear_const_r; + vec4 cc_sh_linear_const_g; + vec4 cc_sh_linear_const_b; + vec4 cc_sh_quadratic_r; + vec4 cc_sh_quadratic_g; + vec4 cc_sh_quadratic_b; + vec4 cc_sh_quadratic_a; }; - vec4 front () { - vec3 N = normalize(normal_w) * (float(gl_FrontFacing) * 2.0 - 1.0); - vec3 V = normalize(cc_cameraPos.xyz - pos_w); + #if CC_USE_LIGHT_PROBE + #include + #endif + + vec4 gizmo_fs (float alpha) { + #if CC_USE_LIGHT_PROBE + vec3 N = normalize(normal_w) * (float(gl_FrontFacing) * 2.0 - 1.0); + vec3 diffuse = SHEvaluate(N); - // vec3 L = normalize(cross(forward, vec3(0, 1, 0))); - // vec3 diffuse = color.rgb * (0.2 + max(0.0, dot(N, L)) * 0.8); - - vec3 points [4]; - //vec3 up = vec3(0, 1, 0); - points[0] = (forward * 3.0 + right + up) * 40.0; - points[1] = (forward * 3.0 - right + up) * 40.0; - points[2] = (forward * 3.0 - right - up) * 40.0; - points[3] = (forward * 3.0 + right - up) * 40.0; - vec3 diffuse = LinearToSRGB(mainColor.rgb * LTC_Evaluate(N, V, pos_l, mat3(1), points)); - #if USE_FORWARD_PIPELINE - return CCFragOutput(vec4(diffuse, mainColor.a)); + #if USE_FORWARD_PIPELINE + return CCFragOutput(vec4(diffuse, mainColor.a * alpha)); + #else + return vec4(diffuse, mainColor.a * alpha); + #endif #else - return vec4(diffuse, mainColor.a); + vec3 N = normalize(normal_w) * (float(gl_FrontFacing) * 2.0 - 1.0); + vec3 V = normalize(cc_cameraPos.xyz - pos_w); + + // vec3 L = normalize(cross(forward, vec3(0, 1, 0))); + // vec3 diffuse = color.rgb * (0.2 + max(0.0, dot(N, L)) * 0.8); + + vec3 points [4]; + //vec3 up = vec3(0, 1, 0); + points[0] = (forward * 3.0 + right + up) * 40.0; + points[1] = (forward * 3.0 - right + up) * 40.0; + points[2] = (forward * 3.0 - right - up) * 40.0; + points[3] = (forward * 3.0 + right - up) * 40.0; + vec3 diffuse = LinearToSRGB(mainColor.rgb * LTC_Evaluate(N, V, pos_l, mat3(1), points)); + #if USE_FORWARD_PIPELINE + return CCFragOutput(vec4(diffuse, mainColor.a * alpha)); + #else + return vec4(diffuse, mainColor.a * alpha); + #endif #endif } + vec4 front () { + return gizmo_fs(1.0); + } + vec4 back () { - vec3 N = normalize(normal_w) * (float(gl_FrontFacing) * 2.0 - 1.0); - vec3 V = normalize(cc_cameraPos.xyz - pos_w); - - // vec3 L = normalize(cross(forward, vec3(0, 1, 0))); - // vec3 diffuse = color.rgb * (0.2 + max(0.0, dot(N, L)) * 0.8); - - vec3 points [4]; - //vec3 up = vec3(0, 1, 0); - points[0] = (forward * 3.0 + right + up) * 40.0; - points[1] = (forward * 3.0 - right + up) * 40.0; - points[2] = (forward * 3.0 - right - up) * 40.0; - points[3] = (forward * 3.0 + right - up) * 40.0; - vec3 diffuse = LinearToSRGB(mainColor.rgb * LTC_Evaluate(N, V, pos_l, mat3(1), points)); - #if USE_FORWARD_PIPELINE - return CCFragOutput(vec4(diffuse, mainColor.a * 0.2)); - #else - return vec4(diffuse, mainColor.a * 0.2); - #endif + return gizmo_fs(0.2); } }% diff --git a/editor/assets/effects/pipeline/deferred-lighting.effect b/editor/assets/effects/pipeline/deferred-lighting.effect index e6287ad97c..809a967af6 100644 --- a/editor/assets/effects/pipeline/deferred-lighting.effect +++ b/editor/assets/effects/pipeline/deferred-lighting.effect @@ -44,36 +44,16 @@ CCProgram lighting-fs %{ in vec2 v_uv; - #if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT - #pragma extension([GL_EXT_shader_framebuffer_fetch, __VERSION__ < 450, enable]) - #if __VERSION__ >= 450 - layout(binding = 0, input_attachment_index = 0) uniform subpassInput gbuffer_albedoMap; - layout(binding = 1, input_attachment_index = 1) uniform subpassInput gbuffer_normalMap; - layout(binding = 2, input_attachment_index = 2) uniform subpassInput gbuffer_emissiveMap; - layout(binding = 3, input_attachment_index = 3) uniform subpassInput depth_stencil; - #elif __VERSION__ >= 300 - layout(location = 0) inout vec4 gbuffer_albedoMap; - layout(location = 1) inout vec4 gbuffer_normalMap; - layout(location = 2) inout vec4 gbuffer_emissiveMap; - layout(binding = 3) uniform sampler2D depth_stencil; - #else - layout(binding = 3) uniform sampler2D depth_stencil; - #endif - #else - #pragma rate gbuffer_albedoMap pass - layout(binding = 0) uniform sampler2D gbuffer_albedoMap; - #pragma rate gbuffer_normalMap pass - layout(binding = 1) uniform sampler2D gbuffer_normalMap; - #pragma rate gbuffer_emissiveMap pass - layout(binding = 2) uniform sampler2D gbuffer_emissiveMap; - #pragma rate depth_stencil pass - layout(binding = 3) uniform sampler2D depth_stencil; - #endif - - #if !CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT || __VERSION__ >= 450 - layout(location = 0) out vec4 fragColor; - #endif + #pragma rate gbuffer_albedoMap pass + layout(binding = 0) uniform sampler2D gbuffer_albedoMap; + #pragma rate gbuffer_normalMap pass + layout(binding = 1) uniform sampler2D gbuffer_normalMap; + #pragma rate gbuffer_emissiveMap pass + layout(binding = 2) uniform sampler2D gbuffer_emissiveMap; + #pragma rate depth_stencil pass + layout(binding = 3) uniform sampler2D depth_stencil; + layout(location = 0) out vec4 fragColor; vec4 screen2WS(vec3 coord) { vec3 ndc = vec3( @@ -91,29 +71,10 @@ CCProgram lighting-fs %{ void main () { StandardSurface s; - #if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT - #if __VERSION__ >= 450 - vec4 albedoMap = subpassLoad(gbuffer_albedoMap); - vec4 normalMap = subpassLoad(gbuffer_normalMap); - vec4 emissiveMap = subpassLoad(gbuffer_emissiveMap); - float depth = subpassLoad(depth_stencil).x; - #elif __VERSION__ >= 300 - vec4 albedoMap = gbuffer_albedoMap; - vec4 normalMap = gbuffer_normalMap; - vec4 emissiveMap = gbuffer_emissiveMap; - float depth = texture(depth_stencil, v_uv).x; - #else - vec4 albedoMap = gl_LastFragData[0]; - vec4 normalMap = gl_LastFragData[1]; - vec4 emissiveMap = gl_LastFragData[2]; - float depth = texture(depth_stencil, v_uv).x; - #endif - #else - vec4 albedoMap = texture(gbuffer_albedoMap,v_uv); - vec4 normalMap = texture(gbuffer_normalMap,v_uv); - vec4 emissiveMap = texture(gbuffer_emissiveMap,v_uv); - float depth = texture(depth_stencil, v_uv).x; - #endif + vec4 albedoMap = texture(gbuffer_albedoMap,v_uv); + vec4 normalMap = texture(gbuffer_normalMap,v_uv); + vec4 emissiveMap = texture(gbuffer_emissiveMap,v_uv); + float depth = texture(depth_stencil, v_uv).x; s.albedo = albedoMap; vec3 position = screen2WS(vec3(gl_FragCoord.xy, depth)).xyz; @@ -140,16 +101,6 @@ CCProgram lighting-fs %{ CC_APPLY_FOG_BASE(color, fogFactor); color = CCFragOutput(color); - #if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT - #if __VERSION__ >= 450 - fragColor = color; - #elif __VERSION__ >= 300 - gbuffer_emissiveMap = color; - #else - gl_FragData[2] = color; - #endif - #else - fragColor = color; - #endif + fragColor = color; } }% diff --git a/editor/assets/effects/pipeline/fxaa-hq.effect b/editor/assets/effects/pipeline/fxaa-hq.effect index ecf5960716..e31c1b752d 100644 --- a/editor/assets/effects/pipeline/fxaa-hq.effect +++ b/editor/assets/effects/pipeline/fxaa-hq.effect @@ -5,6 +5,7 @@ CCEffect %{ passes: - vert: fxaa-vs:vert frag: fxaa-edge-fs:frag + pass: fxaa depthStencilState: depthTest: false depthWrite: false @@ -40,6 +41,7 @@ CCProgram fxaa-edge-fs %{ }; in vec2 v_uv; + #pragma rate sceneColorMap pass uniform sampler2D sceneColorMap; vec4 frag () { @@ -56,6 +58,7 @@ CCProgram copy-fs %{ }; in vec2 v_uv; + #pragma rate sceneColorMap pass uniform sampler2D sceneColorMap; vec4 frag () { diff --git a/editor/assets/effects/pipeline/post-process.effect b/editor/assets/effects/pipeline/post-process.effect index 5e99e8ee7a..302899d1f1 100644 --- a/editor/assets/effects/pipeline/post-process.effect +++ b/editor/assets/effects/pipeline/post-process.effect @@ -22,7 +22,7 @@ CCEffect %{ CCProgram post-process-vs %{ precision highp float; - #include + #include #include #include @@ -30,7 +30,7 @@ CCProgram post-process-vs %{ void main () { StandardVertInput In; - CCVertInput(In); + CCDecode(In); CC_HANDLE_GET_CLIP_FLIP(In.position.xy); gl_Position = In.position; gl_Position.y = gl_Position.y; diff --git a/editor/assets/effects/surfaces/standard.effect b/editor/assets/effects/surfaces/standard.effect index 70f9dd7a96..241f792395 100644 --- a/editor/assets/effects/surfaces/standard.effect +++ b/editor/assets/effects/surfaces/standard.effect @@ -316,7 +316,7 @@ CCProgram surface-fragment %{ // see for more overrided functions, XXXX is lighting-model name #include #define CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT - void SurfacesLightingModifyFinalResult(inout LightingResult result, in LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData) + void SurfacesLightingModifyFinalResult(inout LightingResult result, in LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData, in LightingMiscData miscData) { }*/ }% diff --git a/editor/assets/effects/surfaces/terrain.effect b/editor/assets/effects/surfaces/terrain.effect index 35cc74a2ab..7536128420 100644 --- a/editor/assets/effects/surfaces/terrain.effect +++ b/editor/assets/effects/surfaces/terrain.effect @@ -42,6 +42,11 @@ CCEffect %{ propertyIndex: 0 rasterizerState: cullMode: back + - &reflect-map + vert: terrain-vs + frag: reflect-map-fs + phase: reflect-map + propertyIndex: 0 }% CCProgram shared-ubos %{ @@ -56,6 +61,7 @@ CCProgram macro-remapping %{ #pragma define-meta USE_NORMALMAP #define CC_SURFACES_USE_TANGENT_SPACE USE_NORMALMAP }% + CCProgram surface-vertex %{ #define CC_SURFACES_VERTEX_MODIFY_WORLD_POS vec3 SurfacesVertexModifyWorldPos(in SurfacesStandardVertexIntermediate In) @@ -96,10 +102,13 @@ CCProgram surface-fragment %{ void SurfacesFragmentModifySharedData(inout SurfacesMaterialData surfaceData) { vec2 uvw = FSInput_texcoord; - vec2 uv0 = FSInput_localPos.xz * UVScale.x; - vec2 uv1 = FSInput_localPos.xz * UVScale.y; - vec2 uv2 = FSInput_localPos.xz * UVScale.z; - vec2 uv3 = FSInput_localPos.xz * UVScale.w; + vec2 uv0, uv1, uv2, uv3; + #if CC_SURFACES_TRANSFER_LOCAL_POS + uv0 = FSInput_localPos.xz * UVScale.x; + uv1 = FSInput_localPos.xz * UVScale.y; + uv2 = FSInput_localPos.xz * UVScale.z; + uv3 = FSInput_localPos.xz * UVScale.w; + #endif vec4 w = vec4(0.0); #if LAYERS > 1 w = texture(weightMap, uvw); @@ -204,10 +213,10 @@ CCProgram surface-fragment %{ CCProgram terrain-vs %{ precision highp float; - #include #include // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros - #include + #include + #include // 2. common include with corresponding shader stage, include before surface functions #include @@ -238,9 +247,9 @@ CCProgram shadow-caster-vs %{ CCProgram terrain-fs %{ precision highp float; - #include // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros - #include + #include + #include // 2. common include with corresponding shader stage, include before surface functions #include @@ -268,3 +277,15 @@ CCProgram shadow-caster-fs %{ #include #include }% + +CCProgram reflect-map-fs %{ + precision highp float; + #include + #include + #include + #include + #include + #include + #include + #include +}% diff --git a/editor/assets/effects/surfaces/water.effect b/editor/assets/effects/surfaces/water.effect new file mode 100644 index 0000000000..0f75f926c6 --- /dev/null +++ b/editor/assets/effects/surfaces/water.effect @@ -0,0 +1,293 @@ +// Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +CCEffect %{ + techniques: + - name: opaque + passes: + - vert: standard-vs + frag: standard-fs + properties: &props + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, linear: true, editor: { displayName: Albedo, type: color } } + normalStrength: { value: 1.0, target: pbrParams.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + roughness: { value: 0.5, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + fresnelIntensity: { value: 1.5, target: pbrParams.z, editor: { slide: true, range: [0, 3.0], step: 0.001 } } + normalMap: { value: normal } + normalMapDetailed: { value: normal } + baseTiling: { value: 100.0, target: pbrParams.x, editor: { parent: USE_NORMAL_MAP, range: [1.0, 10000.0] } } + waterSpeed: { value: 0.2, target: waterParam.x, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 1.0], step: 0.001 } } + detailedSpeed: { value: 0.2, target: waterParam.y, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 1.0], step: 0.001 } } + detailedTiling: { value: 0.2, target: waterParam.z, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 1.0], step: 0.001 } } + detailedIntensity: { value: 0.5, target: waterParam.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 1.0], step: 0.001 } } + waterInScatterColor: { value: [0.07, 0.13, 0.087, 1.0], target: waterColor, linear: true, editor: { parent: USE_WATER_SCATTERING, type: color } } + waterScatterCoef: { value: 3.0, target: waterColor.w, editor: { parent: USE_WATER_SCATTERING, range: [0, 10.0] } } + rasterizerState: + cullMode: none + - &forward-add + vert: standard-vs + frag: standard-fs + phase: forward-add + propertyIndex: 0 + embeddedMacros: { CC_FORWARD_ADD: true } + rasterizerState: + cullMode: none + depthStencilState: + depthFunc: equal + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: one + blendDst: one + blendSrcAlpha: zero + blendDstAlpha: one + - &shadow-caster + vert: shadow-caster-vs + frag: shadow-caster-fs + phase: shadow-caster + propertyIndex: 0 + rasterizerState: + cullMode: front + properties: + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + - &reflect-map + vert: standard-vs + frag: reflect-map-fs + phase: reflect-map + propertyIndex: 0 + - name: transparent + passes: + - vert: standard-vs + frag: standard-fs + embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + depthStencilState: + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendDstAlpha: one_minus_src_alpha + properties: *props + - *forward-add + - *shadow-caster +}% + +CCProgram shared-ubos %{ + uniform Constants { + vec4 albedo; + vec4 pbrParams; + vec4 waterParam; + vec4 waterColor; + }; +}% + +CCProgram macro-remapping %{ + // ui displayed macros + #pragma define-meta HAS_SECOND_UV + #pragma define-meta USE_TWOSIDE + #define CC_SURFACES_USE_SECOND_UV HAS_SECOND_UV + #define CC_SURFACES_USE_TWO_SIDED USE_TWOSIDE + #define CC_SURFACES_LIGHTING_USE_FRESNEL 1 + #define CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR 1 + + // depend on UI macros +#if USE_NORMAL_MAP + #define CC_SURFACES_USE_TANGENT_SPACE 1 +#endif +}% + +CCProgram surface-vertex %{ +}% + +CCProgram surface-fragment %{ + #if USE_ALBEDO_MAP + uniform sampler2D albedoMap; + #pragma define-meta ALBEDO_UV options([v_uv, v_uv1]) + #endif + #if USE_NORMAL_MAP + uniform sampler2D normalMap; + uniform sampler2D normalMapDetailed; + #pragma define-meta NORMAL_UV options([v_uv, v_uv1]) + #endif + #pragma define-meta DEFAULT_UV options([v_uv, v_uv1]) + + + #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY + vec4 SurfacesFragmentModifyBaseColorAndTransparency() + { + vec4 baseColor = albedo; + + #if USE_VERTEX_COLOR + baseColor.rgb *= SRGBToLinear(FSInput_vertexColor.rgb); // use linear + baseColor.a *= FSInput_vertexColor.a; + #endif + + #if USE_ALBEDO_MAP + vec4 texColor = texture(albedoMap, ALBEDO_UV); + texColor.rgb = SRGBToLinear(texColor.rgb); + baseColor *= texColor; + #endif + + return baseColor; + } + + #define CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY + void SurfacesFragmentAlphaClipOnly() + { + } + + + vec3 GetDetailedNormal(vec2 texCoord, float tiling, sampler2D normalMap, sampler2D normalMapDetailed, vec3 N, vec3 T) + { + float waterSpeed = waterParam.x; + float detailedSpeed = waterParam.y; + float detailedTiling = waterParam.z * tiling; + float detailedIntensity = waterParam.w; + float normalIntensity = pbrParams.w; + + vec2 uv = texCoord * tiling + vec2(cc_time.w, cc_time.w) * waterSpeed; + vec3 nmmp = texture(normalMap, uv).xyz - vec3(0.5); + vec2 uvDetailed = texCoord * detailedTiling + vec2(0.0, cc_time.w) * detailedSpeed; + vec3 nmmpDetailed = texture(normalMapDetailed, uvDetailed).xyz - vec3(0.5); + // normal blending + nmmp = normalize(vec3(nmmp.xy + nmmpDetailed.xy * detailedIntensity, nmmp.z)); + return normalize(CalculateNormalFromTangentSpace(nmmp, normalIntensity, N, T, FSInput_mirrorNormal)); + } + + + #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL + vec3 SurfacesFragmentModifyWorldNormal() + { + vec3 normal = FSInput_worldNormal; + #if USE_NORMAL_MAP + normal = GetDetailedNormal(NORMAL_UV, pbrParams.x, normalMap, normalMapDetailed, normal, FSInput_worldTangent); + #endif + + return normalize(normal); + } + + #define CC_SURFACES_FRAGMENT_MODIFY_IOR + float SurfacesFragmentModifyIOR() + { + return 1.33; + } +#define CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_PARAMS +void SurfacesFragmentModifyTransmitParams(out vec4 transmitParams, out vec3 inScatteringLightColor) +{ + #if USE_WATER_SCATTERING + float depth = max(abs(FSInput_texcoord.x - 0.5), abs(FSInput_texcoord.y - 0.5)) * 2.0; + depth = saturate(1.0 - depth); + transmitParams = vec4(waterColor.ww, 1.0, depth); + #else + transmitParams = vec4(0.0, 0.0, 0.0, 0.0); + #endif + + inScatteringLightColor = waterColor.rgb; +} + + #include + #include + #define CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT + void SurfacesLightingModifyFinalResult(inout LightingResult result, in LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData, in LightingMiscData miscData) + { + #if CC_SURFACES_LIGHTING_USE_FRESNEL + result.fresnel = saturate(result.fresnel * pbrParams.z); + #endif + } + + #define CC_SURFACES_FRAGMENT_MODIFY_PBRPARAMS + vec4 SurfacesFragmentModifyPBRParams() + { + // ao, roughness, metallic, specularIntensity + return vec4(1.0, pbrParams.y, 1.0, 0.5); + } +}% + +CCProgram standard-vs %{ + precision highp float; + + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. surface include with corresponding shader stage and shading-model (optional) + #include + + // 5. shader entry with corresponding shader stage and technique usage/type + #include +}% + + +CCProgram shadow-caster-vs %{ + precision highp float; + #include + #include + #include + #include + #include +}% + + + +CCProgram standard-fs %{ + // shading-model : standard + // lighting-model : standard (isotropy / anisotropy pbr) + // shader stage : fs + // technique usage/type : render-to-scene + + precision highp float; + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. lighting-model (optional) + #include + + // 5. surface include with corresponding shader stage and shading-model (optional) + #include + + // 6. shader entry with corresponding shader stage and technique usage/type + #include +}% + +CCProgram shadow-caster-fs %{ + precision highp float; + #include + #include + #include + #include + #include +}% + + +CCProgram reflect-map-fs %{ + precision highp float; + #include + #include + #include + #include + #include + #include + #include + #include +}% diff --git a/editor/assets/effects/surfaces/water.effect.meta b/editor/assets/effects/surfaces/water.effect.meta new file mode 100644 index 0000000000..6e5efdd6a2 --- /dev/null +++ b/editor/assets/effects/surfaces/water.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.6.2", + "importer": "effect", + "imported": true, + "uuid": "113a72d8-20cd-42cd-ba96-37cc1046971a", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/gizmo/scene-gizmo.mtl.meta b/editor/assets/gizmo/scene-gizmo.mtl.meta index 87e6fdd74a..fc18a472ab 100644 --- a/editor/assets/gizmo/scene-gizmo.mtl.meta +++ b/editor/assets/gizmo/scene-gizmo.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.19", + "ver": "1.0.20", "importer": "material", "imported": true, "uuid": "6d3bfb1f-604a-4fb3-9fd8-789862cc55e7", diff --git a/editor/assets/tools.meta b/editor/assets/tools.meta new file mode 100644 index 0000000000..84a595987a --- /dev/null +++ b/editor/assets/tools.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "99317b62-549d-421a-9cd0-f575591bf3cd", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/tools/debug-view-runtime-control.prefab b/editor/assets/tools/debug-view-runtime-control.prefab new file mode 100644 index 0000000000..c5c7f1cdb9 --- /dev/null +++ b/editor/assets/tools/debug-view-runtime-control.prefab @@ -0,0 +1,1683 @@ +[ + { + "__type__": "cc.Prefab", + "_name": "debug-view-runtime-control", + "_objFlags": 0, + "_native": "", + "data": { + "__id__": 1 + }, + "optimizationPolicy": 0, + "persistent": false + }, + { + "__type__": "cc.Node", + "_name": "debug-view-runtime-control", + "_objFlags": 0, + "__editorExtras__": {}, + "_parent": null, + "_children": [ + { + "__id__": 2 + }, + { + "__id__": 26 + }, + { + "__id__": 50 + }, + { + "__id__": 54 + } + ], + "_active": true, + "_components": [ + { + "__id__": 68 + }, + { + "__id__": 70 + } + ], + "_prefab": { + "__id__": 72 + }, + "_lpos": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_mobility": 0, + "_layer": 1073741824, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "" + }, + { + "__type__": "cc.Node", + "_name": "SingleMode", + "_objFlags": 0, + "__editorExtras__": { + "editorOnly": true + }, + "_parent": { + "__id__": 1 + }, + "_children": [ + { + "__id__": 3 + } + ], + "_active": true, + "_components": [ + { + "__id__": 23 + } + ], + "_prefab": { + "__id__": 25 + }, + "_lpos": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_mobility": 0, + "_layer": 33554432, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "" + }, + { + "__type__": "cc.Node", + "_name": "Toggle1", + "_objFlags": 0, + "__editorExtras__": { + "editorOnly": true + }, + "_parent": { + "__id__": 2 + }, + "_children": [ + { + "__id__": 4 + }, + { + "__id__": 10 + } + ], + "_active": true, + "_components": [ + { + "__id__": 16 + }, + { + "__id__": 18 + }, + { + "__id__": 20 + } + ], + "_prefab": { + "__id__": 22 + }, + "_lpos": { + "__type__": "cc.Vec3", + "x": -62, + "y": 0, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_mobility": 0, + "_layer": 33554432, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "" + }, + { + "__type__": "cc.Node", + "_name": "Checkmark", + "_objFlags": 0, + "__editorExtras__": { + "editorOnly": true + }, + "_parent": { + "__id__": 3 + }, + "_children": [], + "_active": true, + "_components": [ + { + "__id__": 5 + }, + { + "__id__": 7 + } + ], + "_prefab": { + "__id__": 9 + }, + "_lpos": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_mobility": 0, + "_layer": 33554432, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "" + }, + { + "__type__": "cc.UITransform", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 4 + }, + "_enabled": true, + "__prefab": { + "__id__": 6 + }, + "_contentSize": { + "__type__": "cc.Size", + "width": 32, + "height": 32 + }, + "_anchorPoint": { + "__type__": "cc.Vec2", + "x": 0.5, + "y": 0.5 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "27HKqiuT5B4pOF1MIb61vJ" + }, + { + "__type__": "cc.Sprite", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 4 + }, + "_enabled": true, + "__prefab": { + "__id__": 8 + }, + "_customMaterial": null, + "_srcBlendFactor": 2, + "_dstBlendFactor": 4, + "_color": { + "__type__": "cc.Color", + "r": 255, + "g": 255, + "b": 255, + "a": 255 + }, + "_spriteFrame": { + "__uuid__": "45828f25-b50d-4c52-a591-e19491a62b8c@f9941", + "__expectedType__": "cc.SpriteFrame" + }, + "_type": 0, + "_fillType": 0, + "_sizeMode": 0, + "_fillCenter": { + "__type__": "cc.Vec2", + "x": 0, + "y": 0 + }, + "_fillStart": 0, + "_fillRange": 0, + "_isTrimmedMode": true, + "_useGrayscale": false, + "_atlas": null, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "23PLbx08lF64gH8Ui/ORRE" + }, + { + "__type__": "cc.PrefabInfo", + "root": { + "__id__": 1 + }, + "asset": { + "__id__": 0 + }, + "fileId": "16QjTydSxOAqvHPArla6gq", + "instance": null, + "targetOverrides": null, + "nestedPrefabInstanceRoots": null + }, + { + "__type__": "cc.Node", + "_name": "RichText", + "_objFlags": 0, + "__editorExtras__": { + "editorOnly": true + }, + "_parent": { + "__id__": 3 + }, + "_children": [], + "_active": true, + "_components": [ + { + "__id__": 11 + }, + { + "__id__": 13 + } + ], + "_prefab": { + "__id__": 15 + }, + "_lpos": { + "__type__": "cc.Vec3", + "x": 20, + "y": -40, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_mobility": 0, + "_layer": 33554432, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "" + }, + { + "__type__": "cc.UITransform", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 10 + }, + "_enabled": true, + "__prefab": { + "__id__": 12 + }, + "_contentSize": { + "__type__": "cc.Size", + "width": 97.46, + "height": 50.4 + }, + "_anchorPoint": { + "__type__": "cc.Vec2", + "x": 0, + "y": 0 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "a2m8iX/wZH17O0Jo37Lgoa" + }, + { + "__type__": "cc.RichText", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 10 + }, + "_enabled": true, + "__prefab": { + "__id__": 14 + }, + "_lineHeight": 40, + "_string": "script11111
", + "_horizontalAlign": 0, + "_verticalAlign": 0, + "_fontSize": 20, + "_maxWidth": 0, + "_fontFamily": "Arial", + "_font": null, + "_isSystemFontUsed": true, + "_userDefinedFont": null, + "_cacheMode": 0, + "_imageAtlas": null, + "_handleTouchEvent": true, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "9a0VqDYVNI8qhA+cq51+vt" + }, + { + "__type__": "cc.PrefabInfo", + "root": { + "__id__": 1 + }, + "asset": { + "__id__": 0 + }, + "fileId": "b4ZfJ/y25I+Z3/mKNHUFuF", + "instance": null, + "targetOverrides": null, + "nestedPrefabInstanceRoots": null + }, + { + "__type__": "cc.UITransform", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 3 + }, + "_enabled": true, + "__prefab": { + "__id__": 17 + }, + "_contentSize": { + "__type__": "cc.Size", + "width": 32, + "height": 32 + }, + "_anchorPoint": { + "__type__": "cc.Vec2", + "x": 0.5, + "y": 0.5 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "1f3Rr+JCxN17x4ucB/HkCS" + }, + { + "__type__": "cc.Sprite", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 3 + }, + "_enabled": true, + "__prefab": { + "__id__": 19 + }, + "_customMaterial": null, + "_srcBlendFactor": 2, + "_dstBlendFactor": 4, + "_color": { + "__type__": "cc.Color", + "r": 255, + "g": 255, + "b": 255, + "a": 255 + }, + "_spriteFrame": { + "__uuid__": "f12a23c4-b924-4322-a260-3d982428f1e8@f9941", + "__expectedType__": "cc.SpriteFrame" + }, + "_type": 0, + "_fillType": 0, + "_sizeMode": 0, + "_fillCenter": { + "__type__": "cc.Vec2", + "x": 0, + "y": 0 + }, + "_fillStart": 0, + "_fillRange": 0, + "_isTrimmedMode": true, + "_useGrayscale": false, + "_atlas": null, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "4df5t3fOxBDZD2jEh3Jh8s" + }, + { + "__type__": "cc.Toggle", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 3 + }, + "_enabled": true, + "__prefab": { + "__id__": 21 + }, + "clickEvents": [], + "_interactable": true, + "_transition": 0, + "_normalColor": { + "__type__": "cc.Color", + "r": 214, + "g": 214, + "b": 214, + "a": 255 + }, + "_hoverColor": { + "__type__": "cc.Color", + "r": 211, + "g": 211, + "b": 211, + "a": 255 + }, + "_pressedColor": { + "__type__": "cc.Color", + "r": 255, + "g": 255, + "b": 255, + "a": 255 + }, + "_disabledColor": { + "__type__": "cc.Color", + "r": 124, + "g": 124, + "b": 124, + "a": 255 + }, + "_normalSprite": { + "__uuid__": "f12a23c4-b924-4322-a260-3d982428f1e8@f9941", + "__expectedType__": "cc.SpriteFrame" + }, + "_hoverSprite": null, + "_pressedSprite": null, + "_disabledSprite": null, + "_duration": 0.1, + "_zoomScale": 1.2, + "_target": { + "__id__": 3 + }, + "checkEvents": [], + "_isChecked": true, + "_checkMark": { + "__id__": 7 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "29VhYfKnRFqp6RmJ2susGy" + }, + { + "__type__": "cc.PrefabInfo", + "root": { + "__id__": 1 + }, + "asset": { + "__id__": 0 + }, + "fileId": "d93+Cl+1xCKrE1Mg8twr87", + "instance": null, + "targetOverrides": null, + "nestedPrefabInstanceRoots": null + }, + { + "__type__": "cc.ToggleContainer", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 2 + }, + "_enabled": true, + "__prefab": { + "__id__": 24 + }, + "_allowSwitchOff": false, + "checkEvents": [], + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "40XAv0zk9BMJQg7mM85F80" + }, + { + "__type__": "cc.PrefabInfo", + "root": { + "__id__": 1 + }, + "asset": { + "__id__": 0 + }, + "fileId": "9cxP+XIN5OLIphZ7bb24Hw", + "instance": null, + "targetOverrides": null, + "nestedPrefabInstanceRoots": null + }, + { + "__type__": "cc.Node", + "_name": "CompositeMode", + "_objFlags": 0, + "__editorExtras__": { + "editorOnly": true + }, + "_parent": { + "__id__": 1 + }, + "_children": [ + { + "__id__": 27 + } + ], + "_active": true, + "_components": [ + { + "__id__": 47 + } + ], + "_prefab": { + "__id__": 49 + }, + "_lpos": { + "__type__": "cc.Vec3", + "x": 0, + "y": 78.41399999999999, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_mobility": 0, + "_layer": 33554432, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "" + }, + { + "__type__": "cc.Node", + "_name": "Toggle", + "_objFlags": 0, + "__editorExtras__": { + "editorOnly": true + }, + "_parent": { + "__id__": 26 + }, + "_children": [ + { + "__id__": 28 + }, + { + "__id__": 34 + } + ], + "_active": true, + "_components": [ + { + "__id__": 40 + }, + { + "__id__": 42 + }, + { + "__id__": 44 + } + ], + "_prefab": { + "__id__": 46 + }, + "_lpos": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_mobility": 0, + "_layer": 33554432, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "" + }, + { + "__type__": "cc.Node", + "_name": "Checkmark", + "_objFlags": 0, + "__editorExtras__": { + "editorOnly": true + }, + "_parent": { + "__id__": 27 + }, + "_children": [], + "_active": true, + "_components": [ + { + "__id__": 29 + }, + { + "__id__": 31 + } + ], + "_prefab": { + "__id__": 33 + }, + "_lpos": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_mobility": 0, + "_layer": 33554432, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "" + }, + { + "__type__": "cc.UITransform", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 28 + }, + "_enabled": true, + "__prefab": { + "__id__": 30 + }, + "_contentSize": { + "__type__": "cc.Size", + "width": 26, + "height": 26 + }, + "_anchorPoint": { + "__type__": "cc.Vec2", + "x": 0.5, + "y": 0.5 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "ba+BNK4TNH1p7Lbf5WC49b" + }, + { + "__type__": "cc.Sprite", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 28 + }, + "_enabled": true, + "__prefab": { + "__id__": 32 + }, + "_customMaterial": null, + "_srcBlendFactor": 2, + "_dstBlendFactor": 4, + "_color": { + "__type__": "cc.Color", + "r": 255, + "g": 255, + "b": 255, + "a": 255 + }, + "_spriteFrame": { + "__uuid__": "158e7e52-3220-4cd7-9694-713e0e6e8278@f9941", + "__expectedType__": "cc.SpriteFrame" + }, + "_type": 0, + "_fillType": 0, + "_sizeMode": 0, + "_fillCenter": { + "__type__": "cc.Vec2", + "x": 0, + "y": 0 + }, + "_fillStart": 0, + "_fillRange": 0, + "_isTrimmedMode": true, + "_useGrayscale": false, + "_atlas": null, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "60T5gGAZlOtL41vEBfuJpq" + }, + { + "__type__": "cc.PrefabInfo", + "root": { + "__id__": 1 + }, + "asset": { + "__id__": 0 + }, + "fileId": "15c2ZHja1Khp1VngpvBLiB", + "instance": null, + "targetOverrides": null, + "nestedPrefabInstanceRoots": null + }, + { + "__type__": "cc.Node", + "_name": "RichText", + "_objFlags": 0, + "__editorExtras__": { + "editorOnly": true + }, + "_parent": { + "__id__": 27 + }, + "_children": [], + "_active": true, + "_components": [ + { + "__id__": 35 + }, + { + "__id__": 37 + } + ], + "_prefab": { + "__id__": 39 + }, + "_lpos": { + "__type__": "cc.Vec3", + "x": 20, + "y": -40, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_mobility": 0, + "_layer": 33554432, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "" + }, + { + "__type__": "cc.UITransform", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 34 + }, + "_enabled": true, + "__prefab": { + "__id__": 36 + }, + "_contentSize": { + "__type__": "cc.Size", + "width": 36.68, + "height": 50.4 + }, + "_anchorPoint": { + "__type__": "cc.Vec2", + "x": 0, + "y": 0 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "d5mq0QO/NHjq5vlZqSf1ph" + }, + { + "__type__": "cc.RichText", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 34 + }, + "_enabled": true, + "__prefab": { + "__id__": 38 + }, + "_lineHeight": 40, + "_string": "Test", + "_horizontalAlign": 0, + "_verticalAlign": 0, + "_fontSize": 20, + "_maxWidth": 0, + "_fontFamily": "Arial", + "_font": null, + "_isSystemFontUsed": true, + "_userDefinedFont": null, + "_cacheMode": 0, + "_imageAtlas": null, + "_handleTouchEvent": true, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "54p6VvlUZNdILjEzdiRf0W" + }, + { + "__type__": "cc.PrefabInfo", + "root": { + "__id__": 1 + }, + "asset": { + "__id__": 0 + }, + "fileId": "eeAS4n/x1Bgbg3ZsIsQgRH", + "instance": null, + "targetOverrides": null, + "nestedPrefabInstanceRoots": null + }, + { + "__type__": "cc.UITransform", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 27 + }, + "_enabled": true, + "__prefab": { + "__id__": 41 + }, + "_contentSize": { + "__type__": "cc.Size", + "width": 28, + "height": 28 + }, + "_anchorPoint": { + "__type__": "cc.Vec2", + "x": 0.5, + "y": 0.5 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "d06/x9QxZA16XVJ2/YLDuI" + }, + { + "__type__": "cc.Sprite", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 27 + }, + "_enabled": true, + "__prefab": { + "__id__": 43 + }, + "_customMaterial": null, + "_srcBlendFactor": 2, + "_dstBlendFactor": 4, + "_color": { + "__type__": "cc.Color", + "r": 255, + "g": 255, + "b": 255, + "a": 255 + }, + "_spriteFrame": { + "__uuid__": "11bdc4b0-64a8-4eb7-a2a7-9fb9e233e977@f9941", + "__expectedType__": "cc.SpriteFrame" + }, + "_type": 0, + "_fillType": 0, + "_sizeMode": 1, + "_fillCenter": { + "__type__": "cc.Vec2", + "x": 0, + "y": 0 + }, + "_fillStart": 0, + "_fillRange": 0, + "_isTrimmedMode": true, + "_useGrayscale": false, + "_atlas": null, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "b469YWQjhDkq5xWkbx8Wxx" + }, + { + "__type__": "cc.Toggle", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 27 + }, + "_enabled": true, + "__prefab": { + "__id__": 45 + }, + "clickEvents": [], + "_interactable": true, + "_transition": 0, + "_normalColor": { + "__type__": "cc.Color", + "r": 214, + "g": 214, + "b": 214, + "a": 255 + }, + "_hoverColor": { + "__type__": "cc.Color", + "r": 211, + "g": 211, + "b": 211, + "a": 255 + }, + "_pressedColor": { + "__type__": "cc.Color", + "r": 255, + "g": 255, + "b": 255, + "a": 255 + }, + "_disabledColor": { + "__type__": "cc.Color", + "r": 124, + "g": 124, + "b": 124, + "a": 255 + }, + "_normalSprite": { + "__uuid__": "11bdc4b0-64a8-4eb7-a2a7-9fb9e233e977@f9941", + "__expectedType__": "cc.SpriteFrame" + }, + "_hoverSprite": null, + "_pressedSprite": null, + "_disabledSprite": null, + "_duration": 0.1, + "_zoomScale": 1.2, + "_target": { + "__id__": 27 + }, + "checkEvents": [], + "_isChecked": true, + "_checkMark": { + "__id__": 31 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "edendYRtdD4qoXC6Hzga2T" + }, + { + "__type__": "cc.PrefabInfo", + "root": { + "__id__": 1 + }, + "asset": { + "__id__": 0 + }, + "fileId": "042QZey/RH5bgDNWnI5iVJ", + "instance": null, + "targetOverrides": null, + "nestedPrefabInstanceRoots": null + }, + { + "__type__": "cc.UITransform", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 26 + }, + "_enabled": true, + "__prefab": { + "__id__": 48 + }, + "_contentSize": { + "__type__": "cc.Size", + "width": 100, + "height": 100 + }, + "_anchorPoint": { + "__type__": "cc.Vec2", + "x": 0.5, + "y": 0.5 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "24r3io5/VNHbI+rAIVw4fM" + }, + { + "__type__": "cc.PrefabInfo", + "root": { + "__id__": 1 + }, + "asset": { + "__id__": 0 + }, + "fileId": "a2wbg53b5NMJCjbD0ld4jf", + "instance": null, + "targetOverrides": null, + "nestedPrefabInstanceRoots": null + }, + { + "__type__": "cc.Node", + "_name": "MiscMode", + "_objFlags": 0, + "_parent": { + "__id__": 1 + }, + "_children": [], + "_active": true, + "_components": [ + { + "__id__": 51 + } + ], + "_prefab": { + "__id__": 53 + }, + "_lpos": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_mobility": 0, + "_layer": 33554432, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "" + }, + { + "__type__": "cc.UITransform", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 50 + }, + "_enabled": true, + "__prefab": { + "__id__": 52 + }, + "_contentSize": { + "__type__": "cc.Size", + "width": 100, + "height": 100 + }, + "_anchorPoint": { + "__type__": "cc.Vec2", + "x": 0.5, + "y": 0.5 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "25mqEEHJlAWpwqGC1LNTm/" + }, + { + "__type__": "cc.PrefabInfo", + "root": { + "__id__": 1 + }, + "asset": { + "__id__": 0 + }, + "fileId": "65gtaSQcJEXpJw6NiMvTci", + "instance": null, + "targetOverrides": null, + "nestedPrefabInstanceRoots": null + }, + { + "__type__": "cc.Node", + "_name": "EnableAllCompositeMode", + "_objFlags": 0, + "_parent": { + "__id__": 1 + }, + "_children": [ + { + "__id__": 55 + } + ], + "_active": true, + "_components": [ + { + "__id__": 61 + }, + { + "__id__": 63 + }, + { + "__id__": 65 + } + ], + "_prefab": { + "__id__": 67 + }, + "_lpos": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_mobility": 0, + "_layer": 33554432, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "" + }, + { + "__type__": "cc.Node", + "_name": "Label", + "_objFlags": 512, + "_parent": { + "__id__": 54 + }, + "_children": [], + "_active": true, + "_components": [ + { + "__id__": 56 + }, + { + "__id__": 58 + } + ], + "_prefab": { + "__id__": 60 + }, + "_lpos": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_mobility": 0, + "_layer": 33554432, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "" + }, + { + "__type__": "cc.UITransform", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 55 + }, + "_enabled": true, + "__prefab": { + "__id__": 57 + }, + "_contentSize": { + "__type__": "cc.Size", + "width": 100, + "height": 40 + }, + "_anchorPoint": { + "__type__": "cc.Vec2", + "x": 0.5, + "y": 0.5 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "dexcxB9R1L2puTvBD4ErEU" + }, + { + "__type__": "cc.Label", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 55 + }, + "_enabled": true, + "__prefab": { + "__id__": 59 + }, + "_customMaterial": null, + "_srcBlendFactor": 2, + "_dstBlendFactor": 4, + "_color": { + "__type__": "cc.Color", + "r": 0, + "g": 0, + "b": 0, + "a": 255 + }, + "_string": "RestoreAll", + "_horizontalAlign": 1, + "_verticalAlign": 1, + "_actualFontSize": 20, + "_fontSize": 20, + "_fontFamily": "Arial", + "_lineHeight": 40, + "_overflow": 1, + "_enableWrapText": false, + "_font": null, + "_isSystemFontUsed": true, + "_spacingX": 0, + "_isItalic": false, + "_isBold": false, + "_isUnderline": false, + "_underlineHeight": 2, + "_cacheMode": 0, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "20qbdUQG1E0aa9hTJNGeDI" + }, + { + "__type__": "cc.PrefabInfo", + "root": { + "__id__": 1 + }, + "asset": { + "__id__": 0 + }, + "fileId": "25uCsq3pZINZr8KXqnlXsO", + "instance": null, + "targetOverrides": null, + "nestedPrefabInstanceRoots": null + }, + { + "__type__": "cc.UITransform", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 54 + }, + "_enabled": true, + "__prefab": { + "__id__": 62 + }, + "_contentSize": { + "__type__": "cc.Size", + "width": 100, + "height": 40 + }, + "_anchorPoint": { + "__type__": "cc.Vec2", + "x": 0.5, + "y": 0.5 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "a90ruBE1hAM6DbOVsPeaOW" + }, + { + "__type__": "cc.Sprite", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 54 + }, + "_enabled": true, + "__prefab": { + "__id__": 64 + }, + "_customMaterial": null, + "_srcBlendFactor": 2, + "_dstBlendFactor": 4, + "_color": { + "__type__": "cc.Color", + "r": 255, + "g": 255, + "b": 255, + "a": 255 + }, + "_spriteFrame": { + "__uuid__": "20835ba4-6145-4fbc-a58a-051ce700aa3e@f9941", + "__expectedType__": "cc.SpriteFrame" + }, + "_type": 1, + "_fillType": 0, + "_sizeMode": 0, + "_fillCenter": { + "__type__": "cc.Vec2", + "x": 0, + "y": 0 + }, + "_fillStart": 0, + "_fillRange": 0, + "_isTrimmedMode": true, + "_useGrayscale": false, + "_atlas": null, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "3fhv3YJoJJk4ZeDM5QBces" + }, + { + "__type__": "cc.Button", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 54 + }, + "_enabled": true, + "__prefab": { + "__id__": 66 + }, + "clickEvents": [], + "_interactable": true, + "_transition": 2, + "_normalColor": { + "__type__": "cc.Color", + "r": 214, + "g": 214, + "b": 214, + "a": 255 + }, + "_hoverColor": { + "__type__": "cc.Color", + "r": 211, + "g": 211, + "b": 211, + "a": 255 + }, + "_pressedColor": { + "__type__": "cc.Color", + "r": 255, + "g": 255, + "b": 255, + "a": 255 + }, + "_disabledColor": { + "__type__": "cc.Color", + "r": 124, + "g": 124, + "b": 124, + "a": 255 + }, + "_normalSprite": { + "__uuid__": "20835ba4-6145-4fbc-a58a-051ce700aa3e@f9941", + "__expectedType__": "cc.SpriteFrame" + }, + "_hoverSprite": { + "__uuid__": "20835ba4-6145-4fbc-a58a-051ce700aa3e@f9941", + "__expectedType__": "cc.SpriteFrame" + }, + "_pressedSprite": { + "__uuid__": "544e49d6-3f05-4fa8-9a9e-091f98fc2ce8@f9941", + "__expectedType__": "cc.SpriteFrame" + }, + "_disabledSprite": { + "__uuid__": "951249e0-9f16-456d-8b85-a6ca954da16b@f9941", + "__expectedType__": "cc.SpriteFrame" + }, + "_duration": 0.1, + "_zoomScale": 1.2, + "_target": { + "__id__": 54 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "d1I6MVupxO+74XtCg4pUBY" + }, + { + "__type__": "cc.PrefabInfo", + "root": { + "__id__": 1 + }, + "asset": { + "__id__": 0 + }, + "fileId": "e520Fz5DBPxaDMxht6vCPC", + "instance": null, + "targetOverrides": null, + "nestedPrefabInstanceRoots": null + }, + { + "__type__": "cc.UITransform", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 1 + }, + "_enabled": true, + "__prefab": { + "__id__": 69 + }, + "_contentSize": { + "__type__": "cc.Size", + "width": 100, + "height": 100 + }, + "_anchorPoint": { + "__type__": "cc.Vec2", + "x": 0.5, + "y": 0.5 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "ec6RWYextBkI67Q9TwJtO6" + }, + { + "__type__": "b2bd1+njXxJxaFY3ymm06WU", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 1 + }, + "_enabled": true, + "__prefab": { + "__id__": 71 + }, + "compositeModeToggle": { + "__id__": 27 + }, + "singleModeToggle": { + "__id__": 3 + }, + "EnableAllCompositeModeButton": { + "__id__": 54 + }, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "3405wQdHBNNL8MCuRKzDov" + }, + { + "__type__": "cc.PrefabInfo", + "root": { + "__id__": 1 + }, + "asset": { + "__id__": 0 + }, + "fileId": "a0J9bM8JxF44Zr/AjHUGPT", + "instance": null, + "targetOverrides": null + } +] \ No newline at end of file diff --git a/editor/assets/tools/debug-view-runtime-control.prefab.meta b/editor/assets/tools/debug-view-runtime-control.prefab.meta new file mode 100644 index 0000000000..67fc74eb90 --- /dev/null +++ b/editor/assets/tools/debug-view-runtime-control.prefab.meta @@ -0,0 +1,13 @@ +{ + "ver": "1.1.43", + "importer": "prefab", + "imported": true, + "uuid": "7f4ddeab-efa9-4b76-bf6a-029520f68461", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": { + "syncNodeName": "debug-view-runtime-control" + } +} diff --git a/editor/assets/tools/debug-view-runtime-control.ts b/editor/assets/tools/debug-view-runtime-control.ts new file mode 100644 index 0000000000..bce983913b --- /dev/null +++ b/editor/assets/tools/debug-view-runtime-control.ts @@ -0,0 +1,317 @@ +import { Color, Canvas, UITransform, instantiate, math, Toggle, TextureCube, _decorator, Component, Button, labelAssembler, game, director, Node, Scene, renderer, CameraComponent, Label, ForwardPipeline, RichText } from 'cc'; +const { ccclass, property } = _decorator; + +@ccclass('debugViewRuntimeControl') +export class debugViewRuntimeControl extends Component { + @property(Node) + compositeModeToggle: Node | null = null; + @property(Node) + singleModeToggle: Node | null = null; + @property(Node) + EnableAllCompositeModeButton: Node | null = null; + _single: number = 0; + + private strSingle: string[] = [ + 'No Single Debug', + 'Vertex Color', + 'Vertex Normal', + 'Vertex Tangent', + 'World Position', + 'Vertex Mirror', + 'Face Side', + 'UV0', + 'UV1', + 'UV Lightmap', + 'Project Depth', + 'Linear Depth', + + 'Fragment Normal', + 'Fragment Tangent', + 'Fragment Binormal', + 'Base Color', + 'Diffuse Color', + 'Specular Color', + 'Transparency', + 'Metallic', + 'Roughness', + 'Specular Intensity', + 'IOR', + + 'Direct Diffuse', + 'Direct Specular', + 'Direct All', + 'Env Diffuse', + 'Env Specular', + 'Env All', + 'Emissive', + 'Light Map', + 'Shadow', + 'AO', + + 'Fresnel', + 'Direct Transmit Diffuse', + 'Direct Transmit Specular', + 'Env Transmit Diffuse', + 'Env Transmit Specular', + 'Transmit All', + 'Direct TRT', + 'Env TRT', + 'TRT All', + + 'Fog', + ]; + private strComposite: string[] = [ + 'Direct Diffuse', + 'Direct Specular', + 'Env Diffuse', + 'Env Specular', + 'Emissive', + 'Light Map', + 'Shadow', + 'AO', + + 'Normal Map', + 'Fog', + + 'Tone Mapping', + 'Gamma Correction', + + 'Fresnel', + 'Transmit Diffuse', + 'Transmit Specular', + 'TRT', + ]; + private strMisc: string[] = [ + 'CSM Layer Coloration', + 'Lighting With Albedo', + ]; + + private compositeModeToggleList: Node[] = []; + private singleModeToggleList: Node[] = []; + private miscModeToggleList: Node[] = []; + private textComponentList: RichText[] = []; + private labelComponentList: Label[] = []; + private textContentList: string[] = []; + private hideButtonLabel: Label; + start() { + // get canvas resolution + const canvas = this.node.parent.getComponent(Canvas); + if (!canvas) { + console.error('debug-view-runtime-control should be child of Canvas'); + return; + } + + const uiTransform = this.node.parent.getComponent(UITransform); + const halfScreenWidth = uiTransform.width * 0.5; + const halfScreenHeight = uiTransform.height * 0.5; + + let x = -halfScreenWidth + halfScreenWidth * 0.1, y = halfScreenHeight - halfScreenHeight * 0.1; + const width = 200, height = 20; + + // new nodes + const miscNode = this.node.getChildByName('MiscMode'); + const buttonNode = instantiate(miscNode); + buttonNode.parent = this.node; + buttonNode.name = 'Buttons'; + const titleNode = instantiate(miscNode); + titleNode.parent = this.node; + titleNode.name = 'Titles'; + + // title + for (let i = 0; i < 2; i++) { + const newLabel = instantiate(this.EnableAllCompositeModeButton.getChildByName('Label')); + newLabel.setPosition(x + (i > 0 ? 50 + width * 2 : 150), y, 0.0); + newLabel.setScale(0.75, 0.75, 0.75); + newLabel.parent = titleNode; + const labelComponent = newLabel.getComponent(Label); + labelComponent.string = i ? '----------Composite Mode----------' : '----------Single Mode----------'; + labelComponent.color = Color.WHITE; + labelComponent.overflow = 0; + this.labelComponentList[this.labelComponentList.length] = labelComponent; + } + + y -= height; + // single + let currentRow = 0; + for (let i = 0; i < this.strSingle.length; i++, currentRow++) { + if (i === this.strSingle.length >> 1) { + x += width; + currentRow = 0; + } + const newNode = i ? instantiate(this.singleModeToggle) : this.singleModeToggle; + newNode.setPosition(x, y - height * currentRow, 0.0); + newNode.setScale(0.5, 0.5, 0.5); + newNode.parent = this.singleModeToggle.parent; + + const textComponent = newNode.getComponentInChildren(RichText); + textComponent.string = this.strSingle[i]; + this.textComponentList[this.textComponentList.length] = textComponent; + this.textContentList[this.textContentList.length] = textComponent.string; + + newNode.on(Toggle.EventType.TOGGLE, this.toggleSingleMode, this); + + this.singleModeToggleList[i] = newNode; + } + + x += width; + // buttons + this.EnableAllCompositeModeButton.setPosition(x + 15, y, 0.0); + this.EnableAllCompositeModeButton.setScale(0.5, 0.5, 0.5); + this.EnableAllCompositeModeButton.on(Button.EventType.CLICK, this.enableAllCompositeMode, this); + this.EnableAllCompositeModeButton.parent = buttonNode; + let labelComponent = this.EnableAllCompositeModeButton.getComponentInChildren(Label); + this.labelComponentList[this.labelComponentList.length] = labelComponent; + + const changeColorButton = instantiate(this.EnableAllCompositeModeButton); + changeColorButton.setPosition(x + 90, y, 0.0); + changeColorButton.setScale(0.5, 0.5, 0.5); + changeColorButton.on(Button.EventType.CLICK, this.changeTextColor, this); + changeColorButton.parent = buttonNode; + labelComponent = changeColorButton.getComponentInChildren(Label); + labelComponent.string = 'TextColor'; + this.labelComponentList[this.labelComponentList.length] = labelComponent; + + const HideButton = instantiate(this.EnableAllCompositeModeButton); + HideButton.setPosition(x + 200, y, 0.0); + HideButton.setScale(0.5, 0.5, 0.5); + HideButton.on(Button.EventType.CLICK, this.hideUI, this); + HideButton.parent = this.node.parent; + labelComponent = HideButton.getComponentInChildren(Label); + labelComponent.string = 'Hide UI'; + this.labelComponentList[this.labelComponentList.length] = labelComponent; + this.hideButtonLabel = labelComponent; + + // misc + y -= 40; + for (let i = 0; i < this.strMisc.length; i++) { + const newNode = instantiate(this.compositeModeToggle); + newNode.setPosition(x, y - height * i, 0.0); + newNode.setScale(0.5, 0.5, 0.5); + newNode.parent = miscNode; + + const textComponent = newNode.getComponentInChildren(RichText); + textComponent.string = this.strMisc[i]; + this.textComponentList[this.textComponentList.length] = textComponent; + this.textContentList[this.textContentList.length] = textComponent.string; + + const toggleComponent = newNode.getComponent(Toggle); + toggleComponent.isChecked = i ? true : false; + newNode.on(Toggle.EventType.TOGGLE, i ? this.toggleLightingWithAlbedo : this.toggleCSMColoration, this); + this.miscModeToggleList[i] = newNode; + } + + // composite + y -= 150; + for (let i = 0; i < this.strComposite.length; i++) { + const newNode = i ? instantiate(this.compositeModeToggle) : this.compositeModeToggle; + newNode.setPosition(x, y - height * i, 0.0); + newNode.setScale(0.5, 0.5, 0.5); + newNode.parent = this.compositeModeToggle.parent; + + const textComponent = newNode.getComponentInChildren(RichText); + textComponent.string = this.strComposite[i]; + this.textComponentList[this.textComponentList.length] = textComponent; + this.textContentList[this.textContentList.length] = textComponent.string; + + newNode.on(Toggle.EventType.TOGGLE, this.toggleCompositeMode, this); + + this.compositeModeToggleList[i] = newNode; + } + } + + isTextMatched(textUI, textDescription) : boolean { + let tempText = new String(textUI); + const findIndex = tempText.search('>'); + if (findIndex === -1) { + return textUI === textDescription; + } else { + tempText = tempText.substr(findIndex + 1); + tempText = tempText.substr(0, tempText.search('<')); + return tempText === textDescription; + } + } + toggleSingleMode(toggle: Toggle) { + const debugView = director.root!.debugView; + const textComponent = toggle.getComponentInChildren(RichText); + for (let i = 0; i < this.strSingle.length; i++) { + if (this.isTextMatched(textComponent.string, this.strSingle[i])) { + debugView.singleMode = i; + } + } + } + toggleCompositeMode(toggle: Toggle) { + const debugView = director.root!.debugView; + const textComponent = toggle.getComponentInChildren(RichText); + for (let i = 0; i < this.strComposite.length; i++) { + if (this.isTextMatched(textComponent.string, this.strComposite[i])) { + debugView.enableCompositeMode(i, toggle.isChecked); + } + } + } + toggleLightingWithAlbedo(toggle: Toggle) { + const debugView = director.root!.debugView; + debugView.lightingWithAlbedo = toggle.isChecked; + } + toggleCSMColoration(toggle: Toggle) { + const debugView = director.root!.debugView; + debugView.csmLayerColoration = toggle.isChecked; + } + enableAllCompositeMode(button: Button) { + const debugView = director.root!.debugView; + debugView.enableAllCompositeMode(true); + for (let i = 0; i < this.compositeModeToggleList.length; i++) { + const toggleComponent = this.compositeModeToggleList[i].getComponent(Toggle); + toggleComponent.isChecked = true; + } + + let toggleComponent = this.miscModeToggleList[0].getComponent(Toggle); + toggleComponent.isChecked = false; + debugView.csmLayerColoration = false; + toggleComponent = this.miscModeToggleList[1].getComponent(Toggle); + toggleComponent.isChecked = true; + debugView.lightingWithAlbedo = true; + } + hideUI(button: Button) { + const titleNode = this.node.getChildByName('Titles'); + const activeValue = !titleNode.active; + this.singleModeToggleList[0].parent.active = activeValue; + this.miscModeToggleList[0].parent.active = activeValue; + this.compositeModeToggleList[0].parent.active = activeValue; + this.EnableAllCompositeModeButton.parent.active = activeValue; + titleNode.active = activeValue; + this.hideButtonLabel.string = activeValue ? 'Hide UI' : 'Show UI'; + } + + private _currentColorIndex = 0; + private strColor: string[] = [ + '', + '', + '', + '', + '', + ]; + private color: Color[] = [ + Color.WHITE, + Color.BLACK, + Color.RED, + Color.GREEN, + Color.BLUE, + ]; + changeTextColor(button: Button) { + this._currentColorIndex++; + if (this._currentColorIndex >= this.strColor.length) { + this._currentColorIndex = 0; + } + for (let i = 0; i < this.textComponentList.length; i++) { + this.textComponentList[i].string = this.strColor[this._currentColorIndex] + this.textContentList[i] + '
'; + } + for (let i = 0; i < this.labelComponentList.length; i++) { + this.labelComponentList[i].color = this.color[this._currentColorIndex]; + } + } + + onLoad() { + } + update(deltaTime: number) { + } +} diff --git a/editor/assets/tools/debug-view-runtime-control.ts.meta b/editor/assets/tools/debug-view-runtime-control.ts.meta new file mode 100644 index 0000000000..100af74337 --- /dev/null +++ b/editor/assets/tools/debug-view-runtime-control.ts.meta @@ -0,0 +1,9 @@ +{ + "ver": "4.0.23", + "importer": "typescript", + "imported": true, + "uuid": "b2bd1fa7-8d7c-49c5-a158-df29a6d3a594", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/exports/2d-misc.ts b/editor/exports/2d-misc.ts new file mode 100644 index 0000000000..cf25d1076c --- /dev/null +++ b/editor/exports/2d-misc.ts @@ -0,0 +1 @@ +export { earcut } from '../../cocos/2d/assembler/graphics/webgl/earcut'; \ No newline at end of file diff --git a/editor/i18n/en/assets.js b/editor/i18n/en/assets.js index e309397de2..01887bb972 100644 --- a/editor/i18n/en/assets.js +++ b/editor/i18n/en/assets.js @@ -341,6 +341,22 @@ module.exports = { name: 'Ratio', title: 'Target Ratio', }, + preserveSurfaceCurvature: { + name: 'Surface Curvature', + title: 'Preserve Surface Curvature', + }, + preserveBorderEdges: { + name: 'Border Edges', + title: 'Preserve Border Edges', + }, + preserveUVSeamEdges: { + name: 'UV Seam Edges', + title: 'Preserve UV Seam Edges', + }, + preserveUVFoldoverEdges: { + name: 'UV Foldover Edges', + title: 'Preserve UV Foldover Edges', + }, enableSmartLink: { name: 'Smart Link', title: 'Enable Smart Link', diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 797e403048..d8dfe3d8b5 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -52,6 +52,11 @@ module.exports = { PageView: `${url}/${version}/manual/en/ui-system/components/editor/pageview.html`, UIStaticBatch: `${url}/${version}/manual/en/ui-system/components/editor/ui-static.html`, UIOpacity: `${url}/${version}/manual/en/ui-system/components/editor/ui-opacity.html`, + BoxCollider2D: `${url}/${version}/manual/en/physics-2d/physics-2d-collider.html`, + CircleCollider2D: `${url}/${version}/manual/en/physics-2d/physics-2d-collider.html`, + PolygonCollider2D: `${url}/${version}/manual/en/physics-2d/physics-2d-collider.html`, + RigidBody2D: `${url}/${version}/manual/en/physics-2d/physics-2d-rigid-body.html`, + Joint2D: `${url}/${version}/manual/en/physics-2d/physics-2d-joint.html`, BoxCollider: `${url}/${version}/manual/en/physics/physics-collider.html`, SphereCollider: `${url}/${version}/manual/en/physics/physics-component.html`, CapsuleCollider: `${url}/${version}/manual/en/physics/physics-component.html`, @@ -704,8 +709,9 @@ module.exports = { 'The alpha threshold.
The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold.
(Not supported Canvas Mode)', segements: 'The segements for ellipse mask', }, - physics: { + physics2d: { rigidbody: { + group: 'group', enabledContactListener: 'Should enabled contact listener. When a collision is trigger,
the collision callback will only be called when enabled contact listener.', bullet: 'Is this a fast moving body that should be prevented from tunneling through other moving bodies?', @@ -719,9 +725,12 @@ module.exports = { linearVelocity: "The linear velocity of the body's origin in world co-ordinates", angularVelocity: 'The angular velocity of the body.', fixedRotation: 'Should this body be prevented from rotating?', - awake: 'Is this body initially awake or sleeping?', + awakeOnLoad: 'Is this body initially awake?', }, - physics_collider: { + collider: { + group: 'Group', + editing: 'Whether to edit the collider', + threshold:'Specifies the minimum distance between the vertices of the generated map outline, the larger the value, the fewer points will be generated, adjustable according to requirements', density: 'The density', sensor: 'A sensor collider collects contact information but never generates a collision response', friction: 'The friction coefficient, usually in the range [0,1].', @@ -758,6 +767,37 @@ module.exports = { tag: 'Tag. If a node has several collider components,
you can judge which type of collider is collided according to the tag.', points: 'Polygon points', }, + joint: { + anchor: 'The anchor of the rigid body.', + connectedAnchor: 'The anchor of the connected rigid body.', + connectedBody: 'The rigid body to which the other end of the joint is attached.', + collideConnected: 'Should the two rigid bodies connected with this joint collide with each other?', + distance: 'The distance separating the two ends of the joint.', + frequency: 'The spring frequency.', + dampingRatio: 'The damping ratio.', + linearOffset: 'The linear offset from connected rigid body to rigid body.', + angularOffset: 'The angular offset from connected rigid body to rigid body.', + maxForce: 'The maximum force can be applied to rigid body.', + maxTorque: 'The maximum torque can be applied to rigid body.', + correctionFactor: 'The position correction factor in the range [0,1].', + mouseRegion: "The node used to register touch event.
If this is null, it will be the joint's node.", + target: 'The target point.
The mouse joint will move chosen rigid body to target point.', + localAxisA: 'The local joint axis relative to rigid body.', + enableLimit: 'Enable joint distance limit?', + enableMotor: 'Enable joint motor?', + lowerLimit: 'The lower joint limit.', + upperLimit: 'The upper joint limit.', + maxMotorForce: 'The maximum force can be applied to rigid body to reach the target motor speed.', + motorSpeed: 'The expected motor speed.', + referenceAngle: 'The reference angle.
An angle between bodies considered to be zero for the joint angle.', + lowerAngle: 'The lower angle.', + upperAngle: 'The upper angle.', + maxMotorTorque: 'The maximum torque can be applied to rigid body to reach the target motor speed.', + maxLength: 'The max length.', + autoCalcDistance:'Whether to automatically calculate the distance between two rigid bodies connected by a joint', + autoCalcAngle:'Automatically calculates the sliding direction based on the two rigid bodies connected', + autoCalcOffset:'Automatically calculate the angularOffset and linearOffset between two rigid bodies connected by a joint', + }, }, block_input_events: { brief_help: diff --git a/editor/i18n/zh/assets.js b/editor/i18n/zh/assets.js index eafa82a038..3fb591859a 100644 --- a/editor/i18n/zh/assets.js +++ b/editor/i18n/zh/assets.js @@ -92,18 +92,18 @@ module.exports = { frag: 'Fragment Shader', }, image: { - type: 'Type', - typeTip: 'Type', + type: '类型', + typeTip: '类型', // bakeOfflineMipmaps: 'Bake Offline Mipmaps', // bakeOfflineMipmapsTip: 'Bake Offline Mipmaps', - flipVertical: 'Flip Vertical', - flipVerticalTip: 'Flip Vertical', - fixAlphaTransparencyArtifacts: 'Fix Alpha Transparency Artifacts', + flipVertical: '垂直翻转', + flipVerticalTip: '垂直翻转', + fixAlphaTransparencyArtifacts: '消除透明伪影', fixAlphaTransparencyArtifactsTip: '为全透明像素填充相邻像素的颜色,防止纹理过滤引起的黑边问题。当使用 Alpha 透明通道时,请启用此功能。', - isRGBE: 'Is RGBE', - isRGBETip: 'Is RGBE', - flipGreenChannel: '翻转绿通道', + isRGBE: '作为 RGBE 格式', + isRGBETip: '作为 RGBE 格式', + flipGreenChannel: '翻转绿色通道', }, spriteFrame: { packable: 'Packable', @@ -291,7 +291,7 @@ module.exports = { '若不勾选,网格数据被提交到 GPU 后会被自动释放。
', }, meshOptimizer: { - name: 'Mesh Optimizer', + name: 'Mesh 优化', title: 'Mesh Optimizer', simplification: { name: 'Simplification', @@ -339,6 +339,22 @@ module.exports = { name: 'LOD 压缩比例', title: 'Target Ratio', }, + preserveSurfaceCurvature: { + name: '保留表面曲率', + title: 'Preserve Surface Curvature', + }, + preserveBorderEdges: { + name: '保留边界边', + title: 'Preserve Border Edges', + }, + preserveUVSeamEdges: { + name: '保留 UV 缝合边', + title: 'Preserve UV Seam Edges', + }, + preserveUVFoldoverEdges: { + name: '保留 UV 折叠边', + title: 'Preserve UV Foldover Edges', + }, enableSmartLink: { name: '防止破面', title: 'Smart Link', diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index cc173a87f6..b752e16b2f 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -52,6 +52,11 @@ module.exports = { PageView: `${url}/${version}/manual/zh/ui-system/components/editor/pageview.html`, UIStaticBatch: `${url}/${version}/manual/zh/ui-system/components/editor/ui-static.html`, UIOpacity: `${url}/${version}/manual/zh/ui-system/components/editor/ui-opacity.html`, + BoxCollider2D: `${url}/${version}/manual/zh/physics-2d/physics-2d-collider.html`, + CircleCollider2D: `${url}/${version}/manual/zh/physics-2d/physics-2d-collider.html`, + PolygonCollider2D: `${url}/${version}/manual/zh/physics-2d/physics-2d-collider.html`, + RigidBody2D: `${url}/${version}/manual/zh/physics-2d/physics-2d-rigid-body.html`, + Joint2D: `${url}/${version}/manual/zh/physics-2d/physics-2d-joint.html`, BoxCollider: `${url}/${version}/manual/zh/physics/physics-collider.html`, SphereCollider: `${url}/${version}/manual/zh/physics/physics-component.html`, CapsuleCollider: `${url}/${version}/manual/zh/physics/physics-component.html`, @@ -687,8 +692,9 @@ module.exports = { alphaThreshold: 'Alpha 阈值,只有当模板的像素的 Alpha 大于 Alpha Threshold 时,才会绘制内容(不支持 Canvas 模式)', segements: '椭圆遮罩的曲线细分数', }, - physics: { + physics2d: { rigidbody: { + group: '分组', enabledContactListener: '是否启用接触接听器。当 Collider 产生碰撞时,只有开启了接触接听器才会调用相应的回调函数', bullet: '这个刚体是否是一个快速移动的刚体,并且需要禁止穿过其他快速移动的刚体', type: '刚体类型:
Static(静态),
Kinematic(不受外力),
Dynamic(动态)和 Animated(通过设置线性速度和角速度驱动)', @@ -701,9 +707,12 @@ module.exports = { linearVelocity: '刚体在世界坐标下的线性速度', angularVelocity: '刚体的角速度', fixedRotation: '是否禁止此刚体进行旋转', - awake: '是否立刻唤醒此刚体', + awakeOnLoad: '是否在初始化时唤醒此刚体', }, - physics_collider: { + collider: { + group: '分组', + editing: '是否需要编辑此碰撞组件', + threshold:'指明生成贴图轮廓顶点间的最小距离,值越大则生成的点越少,可根据需求进行调节', density: '密度', sensor: '一个传感器类型的碰撞体会产生碰撞回调,但是不会发生物理碰撞效果。', friction: '摩擦系数,取值一般在 [0, 1] 之间', @@ -740,6 +749,37 @@ module.exports = { tag: '标签。当一个节点上有多个碰撞组件时,在发生碰撞后,可以使用此标签来判断是节点上的哪个碰撞组件被碰撞了。', points: '多边形顶点数组', }, + joint: { + anchor: '刚体的锚点。', + connectedAnchor: '关节另一端刚体的锚点。', + connectedBody: '关节另一端链接的刚体', + collideConnected: '链接到关节上的两个刚体是否应该相互碰撞?', + distance: '关节两端的距离', + frequency: '弹性系数。', + dampingRatio: '阻尼,表示关节变形后,恢复到初始状态受到的阻力。', + linearOffset: '关节另一端的刚体相对于起始端刚体的位置偏移量', + angularOffset: '关节另一端的刚体相对于起始端刚体的角度偏移量', + maxForce: '可以应用于刚体的最大的力值', + maxTorque: '可以应用于刚体的最大扭矩值', + correctionFactor: '位置矫正系数,范围为 [0, 1]', + mouseRegion: '用于注册触摸事件的节点。如果没有设置这个值,那么将会使用关节的节点来注册事件。', + target: '目标点,鼠标关节将会移动选中的刚体到指定的目标点', + localAxisA: '指定刚体可以移动的方向。', + enableLimit: '是否开启限制?', + enableMotor: '是否开启关节马达?', + lowerLimit: '刚体能够移动的最小值', + upperLimit: '刚体能够移动的最大值', + maxMotorForce: '可以施加到刚体的最大力。', + motorSpeed: '期望的马达速度。', + referenceAngle: '相对角度。两个物体之间角度为零时可以看作相等于关节角度', + lowerAngle: '角度的最低限制。', + upperAngle: '角度的最高限制。', + maxMotorTorque: '可以施加到刚体的最大扭矩。', + maxLength: '最大长度。', + autoCalcDistance:'是否自动计算关节连接的两个刚体间的距离', + autoCalcAngle:'根据连接的两个刚体自动计算滑动方向', + autoCalcOffset:'自动计算关节连接的两个刚体间的 angularOffset 和 linearOffset', + }, }, block_input_events: { brief_help: '该组件将拦截所有输入事件,防止输入穿透到屏幕下方的其它节点,一般用于屏幕上层 UI 的背景。', diff --git a/editor/inspector/assets/fbx/model.js b/editor/inspector/assets/fbx/model.js index 4a2392dd5c..f56967c4ed 100644 --- a/editor/inspector/assets/fbx/model.js +++ b/editor/inspector/assets/fbx/model.js @@ -95,6 +95,22 @@ exports.template = /* html */` + + + + + + + + + + + + + + + + @@ -165,6 +181,10 @@ exports.$ = { // simplifyOptions meshOptimizerSimplifyOptions: '.simplify-options', meshOptimizerTargetRatioSlider: '.meshOptimizer-targetRatio-slider', + meshOptimizerPreserveSurfaceCurvatureCheckbox: '.meshOptimizer-preserveSurfaceCurvature-checkbox', + meshOptimizerPreserveBorderEdgesCheckbox: '.meshOptimizer-preserveBorderEdges-checkbox', + meshOptimizerPreserveUVSeamEdgesCheckbox: '.meshOptimizer-preserveUVSeamEdges-checkbox', + meshOptimizerPreserveUVFoldoverEdgesCheckbox: '.meshOptimizer-preserveUVFoldoverEdges-checkbox', meshOptimizerEnableSmartLinkCheckbox: '.meshOptimizer-enableSmartLink-checkbox', meshOptimizerAgressivenessSlider: '.meshOptimizer-agressiveness-slider', meshOptimizerMaxIterationCountSlider: '.meshOptimizer-maxIterationCount-slider', @@ -555,6 +575,74 @@ const Elements = { updateElementReadonly.call(panel, panel.$.meshOptimizerEnableSmartLinkCheckbox); }, }, + preserveSurfaceCurvature: { + ready() { + const panel = this; + panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.preserveSurfaceCurvature', 'boolean')); + panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox.addEventListener('confirm', () => { + panel.dispatch('snapshot'); + }); + }, + update() { + const panel = this; + + panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.simplifyOptions.preserveSurfaceCurvature'); + + updateElementInvalid.call(panel, panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox, 'meshOptimizer.simplifyOptions.preserveSurfaceCurvature'); + updateElementReadonly.call(panel, panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox); + }, + }, + preserveBorderEdges: { + ready() { + const panel = this; + panel.$.meshOptimizerPreserveBorderEdgesCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.preserveBorderEdges', 'boolean')); + panel.$.meshOptimizerPreserveBorderEdgesCheckbox.addEventListener('confirm', () => { + panel.dispatch('snapshot'); + }); + }, + update() { + const panel = this; + + panel.$.meshOptimizerPreserveBorderEdgesCheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.simplifyOptions.preserveBorderEdges'); + + updateElementInvalid.call(panel, panel.$.meshOptimizerPreserveBorderEdgesCheckbox, 'meshOptimizer.simplifyOptions.preserveBorderEdges'); + updateElementReadonly.call(panel, panel.$.meshOptimizerPreserveBorderEdgesCheckbox); + }, + }, + preserveUVSeamEdges: { + ready() { + const panel = this; + panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.preserveUVSeamEdges', 'boolean')); + panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox.addEventListener('confirm', () => { + panel.dispatch('snapshot'); + }); + }, + update() { + const panel = this; + + panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.simplifyOptions.preserveUVSeamEdges'); + + updateElementInvalid.call(panel, panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox, 'meshOptimizer.simplifyOptions.preserveUVSeamEdges'); + updateElementReadonly.call(panel, panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox); + }, + }, + preserveUVFoldoverEdges: { + ready() { + const panel = this; + panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.preserveUVFoldoverEdges', 'boolean')); + panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox.addEventListener('confirm', () => { + panel.dispatch('snapshot'); + }); + }, + update() { + const panel = this; + + panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.simplifyOptions.preserveUVFoldoverEdges'); + + updateElementInvalid.call(panel, panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox, 'meshOptimizer.simplifyOptions.preserveUVFoldoverEdges'); + updateElementReadonly.call(panel, panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox); + }, + }, agressiveness: { ready() { const panel = this; @@ -566,7 +654,7 @@ const Elements = { update() { const panel = this; - panel.$.meshOptimizerAgressivenessSlider.value = getPropValue.call(panel, panel.meta.userData, 1, 'meshOptimizer.simplifyOptions.agressiveness'); + panel.$.meshOptimizerAgressivenessSlider.value = getPropValue.call(panel, panel.meta.userData, 7, 'meshOptimizer.simplifyOptions.agressiveness'); updateElementInvalid.call(panel, panel.$.meshOptimizerAgressivenessSlider, 'meshOptimizer.simplifyOptions.agressiveness'); updateElementReadonly.call(panel, panel.$.meshOptimizerAgressivenessSlider); @@ -583,7 +671,7 @@ const Elements = { update() { const panel = this; - panel.$.meshOptimizerMaxIterationCountSlider.value = getPropValue.call(panel, panel.meta.userData, 1, 'meshOptimizer.simplifyOptions.maxIterationCount'); + panel.$.meshOptimizerMaxIterationCountSlider.value = getPropValue.call(panel, panel.meta.userData, 100, 'meshOptimizer.simplifyOptions.maxIterationCount'); updateElementInvalid.call(panel, panel.$.meshOptimizerMaxIterationCountSlider, 'meshOptimizer.simplifyOptions.maxIterationCount'); updateElementReadonly.call(panel, panel.$.meshOptimizerMaxIterationCountSlider); diff --git a/editor/inspector/utils/assets.js b/editor/inspector/utils/assets.js index 3426ee0e93..ed8bea0d8f 100644 --- a/editor/inspector/utils/assets.js +++ b/editor/inspector/utils/assets.js @@ -76,7 +76,7 @@ exports.setPropValue = function(prop, type, event) { if (propNames.length > 1) { for (let i = 0; i < lastIndex; i++) { const propName = propNames[i]; - if (!target[propName]) { + if (!target[propName] || typeof target[propName] !== 'object') { target[propName] = {}; } target = target[propName]; diff --git a/exports/custom-pipeline.ts b/exports/custom-pipeline.ts index 5b120df554..477cb61978 100644 --- a/exports/custom-pipeline.ts +++ b/exports/custom-pipeline.ts @@ -1,6 +1,10 @@ +import { EDITOR } from 'internal:constants'; import { legacyCC } from '../cocos/core/global-exports'; import * as rendering from '../cocos/rendering/custom'; +import { macro } from './base'; export { rendering }; -legacyCC.rendering = rendering; +if (!EDITOR || macro.CUSTOM_PIPELINE_NAME !== '') { + legacyCC.rendering = rendering; +} diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 201188e535..99384ff3dc 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -1310,6 +1310,8 @@ cocos_source_files( cocos/renderer/pipeline/deferred/PostProcessStage.h cocos/renderer/pipeline/UIPhase.cpp cocos/renderer/pipeline/UIPhase.h + cocos/renderer/pipeline/DebugView.cpp + cocos/renderer/pipeline/DebugView.h cocos/renderer/pipeline/helper/Utils.h cocos/renderer/pipeline/helper/Utils.cpp cocos/renderer/pipeline/custom/BinaryArchive.h @@ -1341,18 +1343,20 @@ cocos_source_files( cocos/renderer/pipeline/custom/NativeExecutor.cpp cocos/renderer/pipeline/custom/NativeFactory.cpp cocos/renderer/pipeline/custom/NativeFwd.h - cocos/renderer/pipeline/custom/NativeLayoutGraph.cpp cocos/renderer/pipeline/custom/NativePipeline.cpp cocos/renderer/pipeline/custom/NativePipelineFwd.h cocos/renderer/pipeline/custom/NativePipelineGraphs.h cocos/renderer/pipeline/custom/NativePipelineTypes.cpp cocos/renderer/pipeline/custom/NativePipelineTypes.h + cocos/renderer/pipeline/custom/NativePools.cpp cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp cocos/renderer/pipeline/custom/NativeRenderGraph.cpp cocos/renderer/pipeline/custom/NativeRenderQueue.cpp cocos/renderer/pipeline/custom/NativeRenderingModule.cpp cocos/renderer/pipeline/custom/NativeTypes.cpp cocos/renderer/pipeline/custom/NativeTypes.h + cocos/renderer/pipeline/custom/NativeUtils.cpp + cocos/renderer/pipeline/custom/NativeUtils.h cocos/renderer/pipeline/custom/PrivateFwd.h cocos/renderer/pipeline/custom/PrivateTypes.cpp cocos/renderer/pipeline/custom/PrivateTypes.h @@ -1370,6 +1374,7 @@ cocos_source_files( cocos/renderer/pipeline/custom/RenderInterfaceFwd.h cocos/renderer/pipeline/custom/RenderInterfaceTypes.cpp cocos/renderer/pipeline/custom/RenderInterfaceTypes.h + cocos/renderer/pipeline/custom/RenderingModule.h ) if (USE_GEOMETRY_RENDERER) @@ -2775,19 +2780,12 @@ endif() ##### ar module if(USE_AR_MODULE) cocos_source_files( - cocos/xr/ar/ARModule.cpp cocos/xr/ar/ARModule.h - cocos/xr/ar/IARAPI.h cocos/renderer/pipeline/xr/ar/ARStage.cpp cocos/renderer/pipeline/xr/ar/ARStage.h cocos/renderer/pipeline/xr/ar/ARBackground.cpp cocos/renderer/pipeline/xr/ar/ARBackground.h ) - if(ANDROID OR IOS) - cocos_source_files( - cocos/xr/ar/ARLib.h - ) - endif() endif() ##### extensions diff --git a/native/cocos/2d/renderer/Batcher2d.cpp b/native/cocos/2d/renderer/Batcher2d.cpp index 3625d4ad68..5862a00bf8 100644 --- a/native/cocos/2d/renderer/Batcher2d.cpp +++ b/native/cocos/2d/renderer/Batcher2d.cpp @@ -231,7 +231,7 @@ CC_FORCE_INLINE void Batcher2d::handleModelDraw(RenderEntity* entity, RenderDraw bool isMask = entity->getIsMask(); if (isMask) { - //Mask Comp + // Mask Comp insertMaskBatch(entity); } else { entity->setEnumStencilStage(_stencilManager->getStencilStage()); @@ -295,7 +295,7 @@ CC_FORCE_INLINE void Batcher2d::handleSubNode(RenderEntity* entity, RenderDrawIn } } -CC_FORCE_INLINE void Batcher2d::handleDrawInfo(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node) { //NOLINT(misc-no-recursion) +CC_FORCE_INLINE void Batcher2d::handleDrawInfo(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node) { // NOLINT(misc-no-recursion) CC_ASSERT(entity); CC_ASSERT(drawInfo); RenderDrawInfoType drawInfoType = drawInfo->getEnumDrawInfoType(); @@ -380,7 +380,7 @@ void Batcher2d::generateBatchForMiddleware(RenderEntity* entity, RenderDrawInfo* auto* texture = drawInfo->getTexture(); auto* sampler = drawInfo->getSampler(); auto* meshBuffer = drawInfo->getMeshBuffer(); - //set meshbuffer offset + // set meshbuffer offset auto indexOffset = drawInfo->getIndexOffset(); auto indexCount = drawInfo->getIbCount(); indexOffset += indexCount; @@ -425,7 +425,7 @@ void Batcher2d::resetRenderStates() { _currDrawInfo = nullptr; } -gfx::DescriptorSet* Batcher2d::getDescriptorSet(gfx::Texture* texture, gfx::Sampler* sampler, gfx::DescriptorSetLayout* dsLayout) { +gfx::DescriptorSet* Batcher2d::getDescriptorSet(gfx::Texture* texture, gfx::Sampler* sampler, const gfx::DescriptorSetLayout* dsLayout) { ccstd::hash_t hash = 2; size_t textureHash; if (texture != nullptr) { @@ -522,7 +522,7 @@ void Batcher2d::reset() { } } } - //meshBuffer cannot clear because it is not transported at every frame. + // meshBuffer cannot clear because it is not transported at every frame. _currMeshBuffer = nullptr; _indexStart = 0; diff --git a/native/cocos/2d/renderer/Batcher2d.h b/native/cocos/2d/renderer/Batcher2d.h index 8aa875b91f..18acf6f050 100644 --- a/native/cocos/2d/renderer/Batcher2d.h +++ b/native/cocos/2d/renderer/Batcher2d.h @@ -137,7 +137,7 @@ private: void insertMaskBatch(RenderEntity* entity); void createClearModel(); - gfx::DescriptorSet* getDescriptorSet(gfx::Texture* texture, gfx::Sampler* sampler, gfx::DescriptorSetLayout* dsLayout); + gfx::DescriptorSet* getDescriptorSet(gfx::Texture* texture, gfx::Sampler* sampler, const gfx::DescriptorSetLayout* dsLayout); StencilManager* _stencilManager{nullptr}; diff --git a/native/cocos/2d/renderer/RenderDrawInfo.cpp b/native/cocos/2d/renderer/RenderDrawInfo.cpp index 4c05041e78..f376de0f97 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.cpp +++ b/native/cocos/2d/renderer/RenderDrawInfo.cpp @@ -136,7 +136,7 @@ gfx::InputAssembler* RenderDrawInfo::initIAInfo(gfx::Device* device) { return ia; } -void RenderDrawInfo::updateLocalDescriptorSet(Node* transform, gfx::DescriptorSetLayout* dsLayout) { +void RenderDrawInfo::updateLocalDescriptorSet(Node* transform, const gfx::DescriptorSetLayout* dsLayout) { if (_localDSBF == nullptr) { _localDSBF = new LocalDSBF(); auto* device = Root::getInstance()->getDevice(); diff --git a/native/cocos/2d/renderer/RenderDrawInfo.h b/native/cocos/2d/renderer/RenderDrawInfo.h index a0beea79ef..ee4ab7b2b4 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.h +++ b/native/cocos/2d/renderer/RenderDrawInfo.h @@ -218,7 +218,7 @@ public: void resetMeshIA(); inline gfx::DescriptorSet* getLocalDes() { return _localDSBF->ds; } - void updateLocalDescriptorSet(Node* transform, gfx::DescriptorSetLayout* dsLayout); + void updateLocalDescriptorSet(Node* transform, const gfx::DescriptorSetLayout* dsLayout); inline void resetDrawInfo() { destroy(); diff --git a/native/cocos/2d/renderer/UIModelProxy.cpp b/native/cocos/2d/renderer/UIModelProxy.cpp index 5d3e23ba75..11ae7af8d2 100644 --- a/native/cocos/2d/renderer/UIModelProxy.cpp +++ b/native/cocos/2d/renderer/UIModelProxy.cpp @@ -87,7 +87,7 @@ void UIModelProxy::uploadData() { for (size_t i = 0; i < drawInfos.size(); i++) { auto* drawInfo = drawInfos[i]; auto* ia = subModelList.at(i)->getInputAssembler(); - if (drawInfo->getVertexOffset() <= 0) continue; + if (drawInfo->getVertexOffset() <= 0 || drawInfo->getIndexOffset() <= 0) continue; gfx::BufferList vBuffers = ia->getVertexBuffers(); if (!vBuffers.empty()) { auto size = drawInfo->getVertexOffset() * _stride; diff --git a/native/cocos/audio/common/utils/tinysndfile.cpp b/native/cocos/audio/common/utils/tinysndfile.cpp index f881f958ee..ae302c6ee2 100644 --- a/native/cocos/audio/common/utils/tinysndfile.cpp +++ b/native/cocos/audio/common/utils/tinysndfile.cpp @@ -333,8 +333,8 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void * return handle; close: - free(handle); handle->callback.close(stream); + free(handle); return nullptr; } diff --git a/native/cocos/bindings/auto/jsb_2d_auto.cpp b/native/cocos/bindings/auto/jsb_2d_auto.cpp index 3ae50e93a1..6f6efc022d 100644 --- a/native/cocos/bindings/auto/jsb_2d_auto.cpp +++ b/native/cocos/bindings/auto/jsb_2d_auto.cpp @@ -1287,7 +1287,7 @@ static bool js_cc_RenderDrawInfo_updateLocalDescriptorSet(se::State& s) ok &= sevalue_to_native(args[1], &arg3, s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing arguments"); - (arg1)->updateLocalDescriptorSet(arg2,arg3); + (arg1)->updateLocalDescriptorSet(arg2,(cc::gfx::DescriptorSetLayout const *)arg3); return true; diff --git a/native/cocos/bindings/auto/jsb_ar_auto.cpp b/native/cocos/bindings/auto/jsb_ar_auto.cpp index d75c202908..7315517fc4 100644 --- a/native/cocos/bindings/auto/jsb_ar_auto.cpp +++ b/native/cocos/bindings/auto/jsb_ar_auto.cpp @@ -109,22 +109,6 @@ static bool js_cc_ar_ARModule_get_static(se::State& s) } SE_BIND_FUNC(js_cc_ar_ARModule_get_static) -static bool js_new_cc_ar_ARModule(se::State& s) // NOLINT(readability-identifier-naming) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - - cc::ar::ARModule *result; - result = (cc::ar::ARModule *)new cc::ar::ARModule(); - - - auto *ptr = JSB_MAKE_PRIVATE_OBJECT_WITH_INSTANCE(result); - s.thisObject()->setPrivateObject(ptr); - return true; -} -SE_BIND_CTOR(js_new_cc_ar_ARModule, __jsb_cc_ar_ARModule_class, js_delete_cc_ar_ARModule) - static bool js_delete_cc_ar_ARModule(se::State& s) { return true; @@ -137,7 +121,7 @@ static bool js_cc_ar_ARModule_config(se::State& s) const auto& args = s.args(); size_t argc = args.size(); cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; - int arg2 ; + uint32_t arg2 ; if(argc != 1) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); @@ -147,7 +131,8 @@ static bool js_cc_ar_ARModule_config(se::State& s) if (nullptr == arg1) return true; ok &= sevalue_to_native(args[0], &arg2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + (arg1)->config(arg2); @@ -161,7 +146,7 @@ static bool js_cc_ar_ARModule_getSupportMask(se::State& s) const auto& args = s.args(); size_t argc = args.size(); cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; - int result; + uint32_t result; if(argc != 0) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); @@ -169,7 +154,7 @@ static bool js_cc_ar_ARModule_getSupportMask(se::State& s) } arg1 = SE_THIS_OBJECT(s); if (nullptr == arg1) return true; - result = (int)(arg1)->getSupportMask(); + result = ((cc::ar::ARModule const *)arg1)->getSupportMask(); ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); @@ -178,17 +163,12 @@ static bool js_cc_ar_ARModule_getSupportMask(se::State& s) } SE_BIND_FUNC(js_cc_ar_ARModule_getSupportMask) -static bool js_cc_ar_ARModule_start(se::State& s) +static bool js_cc_ar_ARModule_start__SWIG_0(se::State& s) { CC_UNUSED bool ok = true; const auto& args = s.args(); - size_t argc = args.size(); cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; - if(argc != 0) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; - } arg1 = SE_THIS_OBJECT(s); if (nullptr == arg1) return true; (arg1)->start(); @@ -196,9 +176,52 @@ static bool js_cc_ar_ARModule_start(se::State& s) return true; } + +static bool js_cc_ar_ARModule_start__SWIG_1(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; + void *arg2 = (void *) NULL ; + void *arg3 = (void *) NULL ; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + ok &= sevalue_to_native(args[0], &arg2); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + ok &= sevalue_to_native(args[1], &arg3); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + (arg1)->start(arg2,arg3); + + + return true; +} + +static bool js_cc_ar_ARModule_start(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + + + if (argc == 0) { + ok = js_cc_ar_ARModule_start__SWIG_0(s); + if (ok) { + return true; + } + } + if (argc == 2) { + ok = js_cc_ar_ARModule_start__SWIG_1(s); + if (ok) { + return true; + } + } + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); + return false; +} SE_BIND_FUNC(js_cc_ar_ARModule_start) -static bool js_cc_ar_ARModule_onResume(se::State& s) +static bool js_cc_ar_ARModule_stop(se::State& s) { CC_UNUSED bool ok = true; const auto& args = s.args(); @@ -211,14 +234,72 @@ static bool js_cc_ar_ARModule_onResume(se::State& s) } arg1 = SE_THIS_OBJECT(s); if (nullptr == arg1) return true; - (arg1)->onResume(); + (arg1)->stop(); return true; } -SE_BIND_FUNC(js_cc_ar_ARModule_onResume) +SE_BIND_FUNC(js_cc_ar_ARModule_stop) -static bool js_cc_ar_ARModule_onPause(se::State& s) +static bool js_cc_ar_ARModule_resume__SWIG_0(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + (arg1)->resume(); + + + return true; +} + +static bool js_cc_ar_ARModule_resume__SWIG_1(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; + void *arg2 = (void *) NULL ; + void *arg3 = (void *) NULL ; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + ok &= sevalue_to_native(args[0], &arg2); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + ok &= sevalue_to_native(args[1], &arg3); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + (arg1)->resume(arg2,arg3); + + + return true; +} + +static bool js_cc_ar_ARModule_resume(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + + + if (argc == 0) { + ok = js_cc_ar_ARModule_resume__SWIG_0(s); + if (ok) { + return true; + } + } + if (argc == 2) { + ok = js_cc_ar_ARModule_resume__SWIG_1(s); + if (ok) { + return true; + } + } + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); + return false; +} +SE_BIND_FUNC(js_cc_ar_ARModule_resume) + +static bool js_cc_ar_ARModule_pause(se::State& s) { CC_UNUSED bool ok = true; const auto& args = s.args(); @@ -231,12 +312,12 @@ static bool js_cc_ar_ARModule_onPause(se::State& s) } arg1 = SE_THIS_OBJECT(s); if (nullptr == arg1) return true; - (arg1)->onPause(); + (arg1)->pause(); return true; } -SE_BIND_FUNC(js_cc_ar_ARModule_onPause) +SE_BIND_FUNC(js_cc_ar_ARModule_pause) static bool js_cc_ar_ARModule_update(se::State& s) { @@ -339,7 +420,7 @@ static bool js_cc_ar_ARModule_getCameraPose(se::State& s) const auto& args = s.args(); size_t argc = args.size(); cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; - Pose result; + cc::ar::Pose result; if(argc != 0) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); @@ -347,7 +428,7 @@ static bool js_cc_ar_ARModule_getCameraPose(se::State& s) } arg1 = SE_THIS_OBJECT(s); if (nullptr == arg1) return true; - result = ((cc::ar::ARModule const *)arg1)->getCameraPose(); + result = (arg1)->getCameraPose(); ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -365,7 +446,7 @@ static bool js_cc_ar_ARModule_getCameraViewMatrix(se::State& s) const auto& args = s.args(); size_t argc = args.size(); cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; - Matrix result; + cc::ar::Matrix result; if(argc != 0) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); @@ -373,7 +454,7 @@ static bool js_cc_ar_ARModule_getCameraViewMatrix(se::State& s) } arg1 = SE_THIS_OBJECT(s); if (nullptr == arg1) return true; - result = ((cc::ar::ARModule const *)arg1)->getCameraViewMatrix(); + result = (arg1)->getCameraViewMatrix(); ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -391,7 +472,7 @@ static bool js_cc_ar_ARModule_getCameraProjectionMatrix(se::State& s) const auto& args = s.args(); size_t argc = args.size(); cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; - Matrix result; + cc::ar::Matrix result; if(argc != 0) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); @@ -399,7 +480,7 @@ static bool js_cc_ar_ARModule_getCameraProjectionMatrix(se::State& s) } arg1 = SE_THIS_OBJECT(s); if (nullptr == arg1) return true; - result = ((cc::ar::ARModule const *)arg1)->getCameraProjectionMatrix(); + result = (arg1)->getCameraProjectionMatrix(); ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -417,7 +498,7 @@ static bool js_cc_ar_ARModule_getCameraTexCoords(se::State& s) const auto& args = s.args(); size_t argc = args.size(); cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; - TexCoords result; + cc::ar::TexCoords result; if(argc != 0) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); @@ -425,7 +506,7 @@ static bool js_cc_ar_ARModule_getCameraTexCoords(se::State& s) } arg1 = SE_THIS_OBJECT(s); if (nullptr == arg1) return true; - result = ((cc::ar::ARModule const *)arg1)->getCameraTexCoords(); + result = (arg1)->getCameraTexCoords(); ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -611,7 +692,7 @@ static bool js_cc_ar_ARModule_getCameraDepthBuffer(se::State& s) } arg1 = SE_THIS_OBJECT(s); if (nullptr == arg1) return true; - result = (uint8_t *)((cc::ar::ARModule const *)arg1)->getCameraDepthBuffer(); + result = (uint8_t *)(arg1)->getCameraDepthBuffer(); ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -695,7 +776,7 @@ static bool js_cc_ar_ARModule_getMainLightDirection(se::State& s) const auto& args = s.args(); size_t argc = args.size(); cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; - LightVal result; + cc::ar::LightVal result; if(argc != 0) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); @@ -721,7 +802,7 @@ static bool js_cc_ar_ARModule_getMainLightIntensity(se::State& s) const auto& args = s.args(); size_t argc = args.size(); cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; - LightVal result; + cc::ar::LightVal result; if(argc != 0) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); @@ -775,7 +856,7 @@ static bool js_cc_ar_ARModule_getAnchorPose(se::State& s) size_t argc = args.size(); cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; int arg2 ; - Pose result; + cc::ar::Pose result; if(argc != 1) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); @@ -786,7 +867,7 @@ static bool js_cc_ar_ARModule_getAnchorPose(se::State& s) ok &= sevalue_to_native(args[0], &arg2, s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing arguments"); - result = ((cc::ar::ARModule const *)arg1)->getAnchorPose(arg2); + result = (arg1)->getAnchorPose(arg2); ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -840,7 +921,7 @@ static bool js_cc_ar_ARModule_getHitResult(se::State& s) const auto& args = s.args(); size_t argc = args.size(); cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; - Pose result; + cc::ar::Pose result; if(argc != 0) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); @@ -848,7 +929,7 @@ static bool js_cc_ar_ARModule_getHitResult(se::State& s) } arg1 = SE_THIS_OBJECT(s); if (nullptr == arg1) return true; - result = ((cc::ar::ARModule const *)arg1)->getHitResult(); + result = (arg1)->getHitResult(); ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -954,30 +1035,6 @@ static bool js_cc_ar_ARModule_setPlaneDetectionMode(se::State& s) } SE_BIND_FUNC(js_cc_ar_ARModule_setPlaneDetectionMode) -static bool js_cc_ar_ARModule_setPlaneMaxTrackingNumber(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; - int arg2 ; - - if(argc != 1) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &arg2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - ((cc::ar::ARModule const *)arg1)->setPlaneMaxTrackingNumber(arg2); - - - return true; -} -SE_BIND_FUNC(js_cc_ar_ARModule_setPlaneMaxTrackingNumber) - static bool js_cc_ar_ARModule_enableSceneMesh(se::State& s) { CC_UNUSED bool ok = true; @@ -1046,33 +1103,6 @@ static bool js_cc_ar_ARModule_enableImageTracking(se::State& s) } SE_BIND_FUNC(js_cc_ar_ARModule_enableImageTracking) -static bool js_cc_ar_ARModule_addImageToLib(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::ar::ARModule *arg1 = (cc::ar::ARModule *) NULL ; - std::string *arg2 = 0 ; - std::string temp2 ; - - if(argc != 1) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &temp2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg2 = &temp2; - - ((cc::ar::ARModule const *)arg1)->addImageToLib((std::string const &)*arg2); - - - return true; -} -SE_BIND_FUNC(js_cc_ar_ARModule_addImageToLib) - static bool js_cc_ar_ARModule_addImageToLibWithSize(se::State& s) { CC_UNUSED bool ok = true; @@ -1203,6 +1233,22 @@ static bool js_cc_ar_ARModule_enableFaceTracking(se::State& s) } SE_BIND_FUNC(js_cc_ar_ARModule_enableFaceTracking) +static bool js_new_cc_ar_ARModule(se::State& s) // NOLINT(readability-identifier-naming) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + + cc::ar::ARModule *result; + result = (cc::ar::ARModule *)new cc::ar::ARModule(); + + + auto *ptr = JSB_MAKE_PRIVATE_OBJECT_WITH_INSTANCE(result); + s.thisObject()->setPrivateObject(ptr); + return true; +} +SE_BIND_CTOR(js_new_cc_ar_ARModule, __jsb_cc_ar_ARModule_class, js_delete_cc_ar_ARModule) + bool js_register_cc_ar_ARModule(se::Object* obj) { auto* cls = se::Class::create("ARModule", obj, nullptr, _SE(js_new_cc_ar_ARModule)); @@ -1211,8 +1257,9 @@ bool js_register_cc_ar_ARModule(se::Object* obj) { cls->defineFunction("config", _SE(js_cc_ar_ARModule_config)); cls->defineFunction("getSupportMask", _SE(js_cc_ar_ARModule_getSupportMask)); cls->defineFunction("start", _SE(js_cc_ar_ARModule_start)); - cls->defineFunction("onResume", _SE(js_cc_ar_ARModule_onResume)); - cls->defineFunction("onPause", _SE(js_cc_ar_ARModule_onPause)); + cls->defineFunction("stop", _SE(js_cc_ar_ARModule_stop)); + cls->defineFunction("resume", _SE(js_cc_ar_ARModule_resume)); + cls->defineFunction("pause", _SE(js_cc_ar_ARModule_pause)); cls->defineFunction("update", _SE(js_cc_ar_ARModule_update)); cls->defineFunction("getAPIState", _SE(js_cc_ar_ARModule_getAPIState)); cls->defineFunction("setCameraId", _SE(js_cc_ar_ARModule_setCameraId)); @@ -1241,11 +1288,9 @@ bool js_register_cc_ar_ARModule(se::Object* obj) { cls->defineFunction("getHitType", _SE(js_cc_ar_ARModule_getHitType)); cls->defineFunction("enablePlane", _SE(js_cc_ar_ARModule_enablePlane)); cls->defineFunction("setPlaneDetectionMode", _SE(js_cc_ar_ARModule_setPlaneDetectionMode)); - cls->defineFunction("setPlaneMaxTrackingNumber", _SE(js_cc_ar_ARModule_setPlaneMaxTrackingNumber)); cls->defineFunction("enableSceneMesh", _SE(js_cc_ar_ARModule_enableSceneMesh)); cls->defineFunction("endRequireSceneMesh", _SE(js_cc_ar_ARModule_endRequireSceneMesh)); cls->defineFunction("enableImageTracking", _SE(js_cc_ar_ARModule_enableImageTracking)); - cls->defineFunction("addImageToLib", _SE(js_cc_ar_ARModule_addImageToLib)); cls->defineFunction("addImageToLibWithSize", _SE(js_cc_ar_ARModule_addImageToLibWithSize)); cls->defineFunction("setImageMaxTrackingNumber", _SE(js_cc_ar_ARModule_setImageMaxTrackingNumber)); cls->defineFunction("enableObjectTracking", _SE(js_cc_ar_ARModule_enableObjectTracking)); diff --git a/native/cocos/bindings/auto/jsb_ar_auto.h b/native/cocos/bindings/auto/jsb_ar_auto.h index 27ac7f631b..65289da67a 100644 --- a/native/cocos/bindings/auto/jsb_ar_auto.h +++ b/native/cocos/bindings/auto/jsb_ar_auto.h @@ -35,7 +35,6 @@ #pragma once #include "bindings/jswrapper/SeApi.h" #include "bindings/manual/jsb_conversions.h" -#include "xr/ar/IARAPI.h" #include "xr/ar/ARModule.h" diff --git a/native/cocos/bindings/auto/jsb_assets_auto.cpp b/native/cocos/bindings/auto/jsb_assets_auto.cpp index 92015dbc29..2bc6d0a49e 100644 --- a/native/cocos/bindings/auto/jsb_assets_auto.cpp +++ b/native/cocos/bindings/auto/jsb_assets_auto.cpp @@ -16740,20 +16740,15 @@ static bool js_cc_IShaderInfo_descriptors_get(se::State& s) } SE_BIND_PROP_GET(js_cc_IShaderInfo_descriptors_get) -static bool js_cc_IShaderInfo_getSource(se::State& s) +static bool js_cc_IShaderInfo_getSource__SWIG_0(se::State& s) { CC_UNUSED bool ok = true; const auto& args = s.args(); - size_t argc = args.size(); cc::IShaderInfo *arg1 = (cc::IShaderInfo *) NULL ; ccstd::string *arg2 = 0 ; ccstd::string temp2 ; cc::IShaderSource *result = 0 ; - if(argc != 1) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; - } arg1 = SE_THIS_OBJECT(s); if (nullptr == arg1) return true; @@ -16770,6 +16765,55 @@ static bool js_cc_IShaderInfo_getSource(se::State& s) return true; } + +static bool js_cc_IShaderInfo_getSource__SWIG_1(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + cc::IShaderInfo *arg1 = (cc::IShaderInfo *) NULL ; + ccstd::string *arg2 = 0 ; + ccstd::string temp2 ; + cc::IShaderSource *result = 0 ; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + + ok &= sevalue_to_native(args[0], &temp2, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + arg2 = &temp2; + + result = (cc::IShaderSource *)(arg1)->getSource((ccstd::string const &)*arg2); + + ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + + + return true; +} + +static bool js_cc_IShaderInfo_getSource(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + + + if (argc == 1) { + ok = js_cc_IShaderInfo_getSource__SWIG_0(s); + if (ok) { + return true; + } + } + if (argc == 1) { + ok = js_cc_IShaderInfo_getSource__SWIG_1(s); + if (ok) { + return true; + } + } + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); + return false; +} SE_BIND_FUNC(js_cc_IShaderInfo_getSource) static bool js_new_cc_IShaderInfo(se::State& s) // NOLINT(readability-identifier-naming) diff --git a/native/cocos/bindings/auto/jsb_gi_auto.cpp b/native/cocos/bindings/auto/jsb_gi_auto.cpp index e5168230f7..5c60152c88 100644 --- a/native/cocos/bindings/auto/jsb_gi_auto.cpp +++ b/native/cocos/bindings/auto/jsb_gi_auto.cpp @@ -1413,6 +1413,29 @@ static bool js_cc_gi_LightProbesData_updateTetrahedrons(se::State& s) } SE_BIND_FUNC(js_cc_gi_LightProbesData_updateTetrahedrons) +static bool js_cc_gi_LightProbesData_hasCoefficients(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::gi::LightProbesData *arg1 = (cc::gi::LightProbesData *) NULL ; + bool result; + + if(argc != 0) { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; + } + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + result = (bool)((cc::gi::LightProbesData const *)arg1)->hasCoefficients(); + + ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); + + + return true; +} +SE_BIND_FUNC(js_cc_gi_LightProbesData_hasCoefficients) + static bool js_cc_gi_LightProbesData_getInterpolationSHCoefficients(se::State& s) { CC_UNUSED bool ok = true; @@ -1672,6 +1695,7 @@ bool js_register_cc_gi_LightProbesData(se::Object* obj) { cls->defineFunction("reset", _SE(js_cc_gi_LightProbesData_reset)); cls->defineFunction("updateProbes", _SE(js_cc_gi_LightProbesData_updateProbes)); cls->defineFunction("updateTetrahedrons", _SE(js_cc_gi_LightProbesData_updateTetrahedrons)); + cls->defineFunction("hasCoefficients", _SE(js_cc_gi_LightProbesData_hasCoefficients)); cls->defineFunction("getInterpolationSHCoefficients", _SE(js_cc_gi_LightProbesData_getInterpolationSHCoefficients)); cls->defineFunction("getInterpolationWeights", _SE(js_cc_gi_LightProbesData_getInterpolationWeights)); @@ -2428,6 +2452,46 @@ static bool js_cc_gi_LightProbeInfo_activate(se::State& s) } SE_BIND_FUNC(js_cc_gi_LightProbeInfo_activate) +static bool js_cc_gi_LightProbeInfo_onProbeBakeFinished(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::gi::LightProbeInfo *arg1 = (cc::gi::LightProbeInfo *) NULL ; + + if(argc != 0) { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; + } + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + (arg1)->onProbeBakeFinished(); + + + return true; +} +SE_BIND_FUNC(js_cc_gi_LightProbeInfo_onProbeBakeFinished) + +static bool js_cc_gi_LightProbeInfo_onProbeBakeCleared(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::gi::LightProbeInfo *arg1 = (cc::gi::LightProbeInfo *) NULL ; + + if(argc != 0) { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; + } + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + (arg1)->onProbeBakeCleared(); + + + return true; +} +SE_BIND_FUNC(js_cc_gi_LightProbeInfo_onProbeBakeCleared) + static bool js_cc_gi_LightProbeInfo_clearSHCoefficients(se::State& s) { CC_UNUSED bool ok = true; @@ -3204,6 +3268,8 @@ bool js_register_cc_gi_LightProbeInfo(se::Object* obj) { cls->defineProperty("data", _SE(js_cc_gi_LightProbeInfo_data_get), _SE(js_cc_gi_LightProbeInfo_data_set)); cls->defineFunction("activate", _SE(js_cc_gi_LightProbeInfo_activate)); + cls->defineFunction("onProbeBakeFinished", _SE(js_cc_gi_LightProbeInfo_onProbeBakeFinished)); + cls->defineFunction("onProbeBakeCleared", _SE(js_cc_gi_LightProbeInfo_onProbeBakeCleared)); cls->defineFunction("clearSHCoefficients", _SE(js_cc_gi_LightProbeInfo_clearSHCoefficients)); cls->defineFunction("isUniqueNode", _SE(js_cc_gi_LightProbeInfo_isUniqueNode)); cls->defineFunction("addNode", _SE(js_cc_gi_LightProbeInfo_addNode)); diff --git a/native/cocos/bindings/auto/jsb_pipeline_auto.cpp b/native/cocos/bindings/auto/jsb_pipeline_auto.cpp index 446b58a559..8ae4923ecc 100644 --- a/native/cocos/bindings/auto/jsb_pipeline_auto.cpp +++ b/native/cocos/bindings/auto/jsb_pipeline_auto.cpp @@ -130,6 +130,10 @@ using namespace cc; #define cc_pipeline_PipelineSceneData_lightProbes_get(self_) self_->getLightProbes() +#define cc_pipeline_PipelineSceneData_validPunctualLights_get(self_) self_->getValidPunctualLights() +#define cc_pipeline_PipelineSceneData_validPunctualLights_set(self_, val_) self_->setValidPunctualLights(val_) + + #define cc_pipeline_RenderStage__name_get(self_) self_->getName() #define cc_pipeline_RenderStage__name_set(self_, val_) self_->setName(val_) @@ -170,6 +174,18 @@ using namespace cc; #define cc_pipeline_RenderFlow__stages_set(self_, val_) self_->setStages(val_) +#define cc_pipeline_DebugView_singleMode_get(self_) self_->getSingleMode() +#define cc_pipeline_DebugView_singleMode_set(self_, val_) self_->setSingleMode(val_) + + +#define cc_pipeline_DebugView_lightingWithAlbedo_get(self_) self_->isLightingWithAlbedo() +#define cc_pipeline_DebugView_lightingWithAlbedo_set(self_, val_) self_->setLightingWithAlbedo(val_) + + +#define cc_pipeline_DebugView_csmLayerColoration_get(self_) self_->isCsmLayerColoration() +#define cc_pipeline_DebugView_csmLayerColoration_set(self_, val_) self_->setCsmLayerColoration(val_) + + se::Class* __jsb_cc_pipeline_SkinningJointCapacity_class = nullptr; se::Object* __jsb_cc_pipeline_SkinningJointCapacity_proto = nullptr; @@ -4379,6 +4395,7 @@ bool js_register_cc_pipeline_UBOGlobal(se::Object* obj) { cls->defineStaticProperty("DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET", nullptr, nullptr); cls->defineStaticProperty("DEBUG_VIEW_COMPOSITE_PACK_2_OFFSET", nullptr, nullptr); cls->defineStaticProperty("DEBUG_VIEW_COMPOSITE_PACK_3_OFFSET", nullptr, nullptr); + cls->defineStaticProperty("DEBUG_VIEW_COMPOSITE_PACK_4_OFFSET", nullptr, nullptr); cls->defineStaticProperty("COUNT", nullptr, nullptr); cls->defineStaticProperty("SIZE", nullptr, nullptr); cls->defineStaticProperty("BINDING", nullptr, nullptr); @@ -7863,7 +7880,7 @@ static bool js_cc_pipeline_RenderPipeline_genQuadVertexData(se::State& s) size_t argc = args.size(); cc::pipeline::RenderPipeline *arg1 = (cc::pipeline::RenderPipeline *) NULL ; cc::Vec4 *arg2 = 0 ; - float *arg3 = (float *) NULL ; + float *arg3 ; cc::Vec4 temp2 ; if(argc != 2) { @@ -9663,6 +9680,301 @@ bool js_register_cc_pipeline_RenderStage(se::Object* obj) { } +se::Class* __jsb_cc_pipeline_DebugView_class = nullptr; +se::Object* __jsb_cc_pipeline_DebugView_proto = nullptr; +SE_DECLARE_FINALIZE_FUNC(js_delete_cc_pipeline_DebugView) + +static bool js_new_cc_pipeline_DebugView(se::State& s) // NOLINT(readability-identifier-naming) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + + cc::pipeline::DebugView *result; + result = (cc::pipeline::DebugView *)new cc::pipeline::DebugView(); + + + auto *ptr = JSB_MAKE_PRIVATE_OBJECT_WITH_INSTANCE(result); + s.thisObject()->setPrivateObject(ptr); + return true; +} +SE_BIND_CTOR(js_new_cc_pipeline_DebugView, __jsb_cc_pipeline_DebugView_class, js_delete_cc_pipeline_DebugView) + +static bool js_delete_cc_pipeline_DebugView(se::State& s) +{ + return true; +} +SE_BIND_FINALIZE_FUNC(js_delete_cc_pipeline_DebugView) + +static bool js_cc_pipeline_DebugView_isCompositeModeEnabled(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::pipeline::DebugView *arg1 = (cc::pipeline::DebugView *) NULL ; + uint32_t arg2 ; + bool result; + + if(argc != 1) { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; + } + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + + ok &= sevalue_to_native(args[0], &arg2, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + result = (bool)((cc::pipeline::DebugView const *)arg1)->isCompositeModeEnabled(arg2); + + ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); + + + return true; +} +SE_BIND_FUNC(js_cc_pipeline_DebugView_isCompositeModeEnabled) + +static bool js_cc_pipeline_DebugView_enableCompositeMode(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::pipeline::DebugView *arg1 = (cc::pipeline::DebugView *) NULL ; + cc::pipeline::DebugViewCompositeType arg2 ; + bool arg3 ; + + if(argc != 2) { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); + return false; + } + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + + ok &= sevalue_to_native(args[0], &arg2, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + + ok &= sevalue_to_native(args[1], &arg3); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + (arg1)->enableCompositeMode(arg2,arg3); + + + return true; +} +SE_BIND_FUNC(js_cc_pipeline_DebugView_enableCompositeMode) + +static bool js_cc_pipeline_DebugView_enableAllCompositeMode(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::pipeline::DebugView *arg1 = (cc::pipeline::DebugView *) NULL ; + bool arg2 ; + + if(argc != 1) { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; + } + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + + ok &= sevalue_to_native(args[0], &arg2); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + (arg1)->enableAllCompositeMode(arg2); + + + return true; +} +SE_BIND_FUNC(js_cc_pipeline_DebugView_enableAllCompositeMode) + +static bool js_cc_pipeline_DebugView_isEnabled(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::pipeline::DebugView *arg1 = (cc::pipeline::DebugView *) NULL ; + bool result; + + if(argc != 0) { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; + } + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + result = (bool)((cc::pipeline::DebugView const *)arg1)->isEnabled(); + + ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); + + + return true; +} +SE_BIND_FUNC(js_cc_pipeline_DebugView_isEnabled) + +static bool js_cc_pipeline_DebugView_reset(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::pipeline::DebugView *arg1 = (cc::pipeline::DebugView *) NULL ; + + if(argc != 0) { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; + } + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + (arg1)->reset(); + + + return true; +} +SE_BIND_FUNC(js_cc_pipeline_DebugView_reset) + +static bool js_cc_pipeline_DebugView_singleMode_set(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::pipeline::DebugView *arg1 = (cc::pipeline::DebugView *) NULL ; + cc::pipeline::DebugViewSingleType arg2 ; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + + ok &= sevalue_to_native(args[0], &arg2, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + cc_pipeline_DebugView_singleMode_set(arg1,arg2); + + + return true; +} +SE_BIND_PROP_SET(js_cc_pipeline_DebugView_singleMode_set) + +static bool js_cc_pipeline_DebugView_singleMode_get(se::State& s) +{ + CC_UNUSED bool ok = true; + cc::pipeline::DebugView *arg1 = (cc::pipeline::DebugView *) NULL ; + cc::pipeline::DebugViewSingleType result; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + result = (cc::pipeline::DebugViewSingleType)cc_pipeline_DebugView_singleMode_get(arg1); + + ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + + + + return true; +} +SE_BIND_PROP_GET(js_cc_pipeline_DebugView_singleMode_get) + +static bool js_cc_pipeline_DebugView_lightingWithAlbedo_set(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::pipeline::DebugView *arg1 = (cc::pipeline::DebugView *) NULL ; + bool arg2 ; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + + ok &= sevalue_to_native(args[0], &arg2); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cc_pipeline_DebugView_lightingWithAlbedo_set(arg1,arg2); + + + return true; +} +SE_BIND_PROP_SET(js_cc_pipeline_DebugView_lightingWithAlbedo_set) + +static bool js_cc_pipeline_DebugView_lightingWithAlbedo_get(se::State& s) +{ + CC_UNUSED bool ok = true; + cc::pipeline::DebugView *arg1 = (cc::pipeline::DebugView *) NULL ; + bool result; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + result = (bool)cc_pipeline_DebugView_lightingWithAlbedo_get(arg1); + + ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); + + + return true; +} +SE_BIND_PROP_GET(js_cc_pipeline_DebugView_lightingWithAlbedo_get) + +static bool js_cc_pipeline_DebugView_csmLayerColoration_set(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::pipeline::DebugView *arg1 = (cc::pipeline::DebugView *) NULL ; + bool arg2 ; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + + ok &= sevalue_to_native(args[0], &arg2); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cc_pipeline_DebugView_csmLayerColoration_set(arg1,arg2); + + + return true; +} +SE_BIND_PROP_SET(js_cc_pipeline_DebugView_csmLayerColoration_set) + +static bool js_cc_pipeline_DebugView_csmLayerColoration_get(se::State& s) +{ + CC_UNUSED bool ok = true; + cc::pipeline::DebugView *arg1 = (cc::pipeline::DebugView *) NULL ; + bool result; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + result = (bool)cc_pipeline_DebugView_csmLayerColoration_get(arg1); + + ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); + + + return true; +} +SE_BIND_PROP_GET(js_cc_pipeline_DebugView_csmLayerColoration_get) + +bool js_register_cc_pipeline_DebugView(se::Object* obj) { + auto* cls = se::Class::create("DebugView", obj, nullptr, _SE(js_new_cc_pipeline_DebugView)); + + cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); + cls->defineProperty("singleMode", _SE(js_cc_pipeline_DebugView_singleMode_get), _SE(js_cc_pipeline_DebugView_singleMode_set)); + cls->defineProperty("lightingWithAlbedo", _SE(js_cc_pipeline_DebugView_lightingWithAlbedo_get), _SE(js_cc_pipeline_DebugView_lightingWithAlbedo_set)); + cls->defineProperty("csmLayerColoration", _SE(js_cc_pipeline_DebugView_csmLayerColoration_get), _SE(js_cc_pipeline_DebugView_csmLayerColoration_set)); + + cls->defineFunction("isCompositeModeEnabled", _SE(js_cc_pipeline_DebugView_isCompositeModeEnabled)); + cls->defineFunction("enableCompositeMode", _SE(js_cc_pipeline_DebugView_enableCompositeMode)); + cls->defineFunction("enableAllCompositeMode", _SE(js_cc_pipeline_DebugView_enableAllCompositeMode)); + cls->defineFunction("isEnabled", _SE(js_cc_pipeline_DebugView_isEnabled)); + cls->defineFunction("reset", _SE(js_cc_pipeline_DebugView_reset)); + + + + + cls->defineFinalizeFunction(_SE(js_delete_cc_pipeline_DebugView)); + + + cls->install(); + JSBClassType::registerClass(cls); + + __jsb_cc_pipeline_DebugView_proto = cls->getProto(); + __jsb_cc_pipeline_DebugView_class = cls; + se::ScriptEngine::getInstance()->clearException(); + return true; +} + + se::Class* __jsb_cc_pipeline_ForwardPipeline_class = nullptr; se::Object* __jsb_cc_pipeline_ForwardPipeline_proto = nullptr; SE_DECLARE_FINALIZE_FUNC(js_delete_cc_pipeline_ForwardPipeline) @@ -13550,31 +13862,6 @@ static bool js_cc_pipeline_PipelineSceneData_setShadowFramebuffer(se::State& s) } SE_BIND_FUNC(js_cc_pipeline_PipelineSceneData_setShadowFramebuffer) -static bool js_cc_pipeline_PipelineSceneData_getValidPunctualLights(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::pipeline::PipelineSceneData *arg1 = (cc::pipeline::PipelineSceneData *) NULL ; - ccstd::vector< cc::scene::Light const * > *result = 0 ; - - if(argc != 0) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = (ccstd::vector< cc::scene::Light const * > *) &((cc::pipeline::PipelineSceneData const *)arg1)->getValidPunctualLights(); - - ok &= nativevalue_to_se(*result, s.rval(), s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(*result, s.thisObject(), s.rval()); - - - return true; -} -SE_BIND_FUNC(js_cc_pipeline_PipelineSceneData_getValidPunctualLights) - static bool js_cc_pipeline_PipelineSceneData_getOctree(se::State& s) { CC_UNUSED bool ok = true; @@ -14060,6 +14347,47 @@ static bool js_cc_pipeline_PipelineSceneData_lightProbes_get(se::State& s) } SE_BIND_PROP_GET(js_cc_pipeline_PipelineSceneData_lightProbes_get) +static bool js_cc_pipeline_PipelineSceneData_validPunctualLights_set(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::pipeline::PipelineSceneData *arg1 = (cc::pipeline::PipelineSceneData *) NULL ; + ccstd::vector< cc::scene::Light const * > arg2 ; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + + ok &= sevalue_to_native(args[0], &arg2, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + cc_pipeline_PipelineSceneData_validPunctualLights_set(arg1,SWIG_STD_MOVE(arg2)); + + + return true; +} +SE_BIND_PROP_SET(js_cc_pipeline_PipelineSceneData_validPunctualLights_set) + +static bool js_cc_pipeline_PipelineSceneData_validPunctualLights_get(se::State& s) +{ + CC_UNUSED bool ok = true; + cc::pipeline::PipelineSceneData *arg1 = (cc::pipeline::PipelineSceneData *) NULL ; + ccstd::vector< cc::scene::Light const * > result; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + result = cc_pipeline_PipelineSceneData_validPunctualLights_get(arg1); + + ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + + + + return true; +} +SE_BIND_PROP_GET(js_cc_pipeline_PipelineSceneData_validPunctualLights_get) + bool js_register_cc_pipeline_PipelineSceneData(se::Object* obj) { auto* cls = se::Class::create("PipelineSceneData", obj, nullptr, _SE(js_new_cc_pipeline_PipelineSceneData)); @@ -14071,12 +14399,12 @@ bool js_register_cc_pipeline_PipelineSceneData(se::Object* obj) { cls->defineProperty("skybox", _SE(js_cc_pipeline_PipelineSceneData_skybox_get), nullptr); cls->defineProperty("shadows", _SE(js_cc_pipeline_PipelineSceneData_shadows_get), nullptr); cls->defineProperty("lightProbes", _SE(js_cc_pipeline_PipelineSceneData_lightProbes_get), nullptr); + cls->defineProperty("validPunctualLights", _SE(js_cc_pipeline_PipelineSceneData_validPunctualLights_get), _SE(js_cc_pipeline_PipelineSceneData_validPunctualLights_set)); cls->defineFunction("activate", _SE(js_cc_pipeline_PipelineSceneData_activate)); cls->defineFunction("destroy", _SE(js_cc_pipeline_PipelineSceneData_destroy)); cls->defineFunction("updatePipelineSceneData", _SE(js_cc_pipeline_PipelineSceneData_updatePipelineSceneData)); cls->defineFunction("setShadowFramebuffer", _SE(js_cc_pipeline_PipelineSceneData_setShadowFramebuffer)); - cls->defineFunction("getValidPunctualLights", _SE(js_cc_pipeline_PipelineSceneData_getValidPunctualLights)); cls->defineFunction("getOctree", _SE(js_cc_pipeline_PipelineSceneData_getOctree)); cls->defineFunction("getOcclusionQueryInputAssembler", _SE(js_cc_pipeline_PipelineSceneData_getOcclusionQueryInputAssembler)); cls->defineFunction("getOcclusionQueryPass", _SE(js_cc_pipeline_PipelineSceneData_getOcclusionQueryPass)); @@ -21401,6 +21729,7 @@ bool register_all_pipeline(se::Object* obj) { js_register_cc_pipeline_RenderFlow(ns); js_register_cc_pipeline_RenderStageInfo(ns); js_register_cc_pipeline_RenderStage(ns); + js_register_cc_pipeline_DebugView(ns); js_register_cc_pipeline_ForwardPipeline(ns); js_register_cc_pipeline_ForwardFlow(ns); js_register_cc_pipeline_ForwardStage(ns); diff --git a/native/cocos/bindings/auto/jsb_pipeline_auto.h b/native/cocos/bindings/auto/jsb_pipeline_auto.h index ec79ed056c..55777bf724 100644 --- a/native/cocos/bindings/auto/jsb_pipeline_auto.h +++ b/native/cocos/bindings/auto/jsb_pipeline_auto.h @@ -52,6 +52,7 @@ #include "renderer/pipeline/PipelineSceneData.h" #include "renderer/pipeline/BatchedBuffer.h" #include "renderer/pipeline/GeometryRenderer.h" +#include "renderer/pipeline/DebugView.h" #include "renderer/pipeline/reflection-probe/ReflectionProbeFlow.h" #include "renderer/pipeline/reflection-probe/ReflectionProbeStage.h" @@ -472,6 +473,11 @@ extern se::Object *__jsb_cc_pipeline_RenderStage_proto; // NOLINT extern se::Class * __jsb_cc_pipeline_RenderStage_class; // NOLINT +JSB_REGISTER_OBJECT_TYPE(cc::pipeline::DebugView); +extern se::Object *__jsb_cc_pipeline_DebugView_proto; // NOLINT +extern se::Class * __jsb_cc_pipeline_DebugView_class; // NOLINT + + JSB_REGISTER_OBJECT_TYPE(cc::pipeline::ForwardPipeline); extern se::Object *__jsb_cc_pipeline_ForwardPipeline_proto; // NOLINT extern se::Class * __jsb_cc_pipeline_ForwardPipeline_class; // NOLINT diff --git a/native/cocos/bindings/auto/jsb_render_auto.cpp b/native/cocos/bindings/auto/jsb_render_auto.cpp index e456080e40..7c977def91 100644 --- a/native/cocos/bindings/auto/jsb_render_auto.cpp +++ b/native/cocos/bindings/auto/jsb_render_auto.cpp @@ -106,15 +106,16 @@ using namespace cc::render; #define cc_render_RenderNode_name_set(self_, val_) self_->setName(val_) +#define cc_render_RasterPassBuilder_showStatistics_get(self_) self_->getShowStatistics() +#define cc_render_RasterPassBuilder_showStatistics_set(self_, val_) self_->setShowStatistics(val_) + + #define cc_render_SceneVisitor_pipelineSceneData_get(self_) self_->getPipelineSceneData() #define cc_render_SceneTask_taskType_get(self_) self_->getTaskType() -#define cc_render_Pipeline_layoutGraphBuilder_get(self_) self_->getLayoutGraphBuilder() - - se::Class* __jsb_cc_render_PipelineRuntime_class = nullptr; se::Object* __jsb_cc_render_PipelineRuntime_proto = nullptr; @@ -1710,6 +1711,7 @@ static bool js_cc_render_RasterPassBuilder_addQueue__SWIG_0(se::State& s) ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + s.rval().toObject()->getPrivateObject()->tryAllowDestroyInGC(); return true; @@ -1788,6 +1790,7 @@ static bool js_cc_render_RasterPassBuilder_addQueue__SWIG_1(se::State& s) ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + s.rval().toObject()->getPrivateObject()->tryAllowDestroyInGC(); return true; @@ -1817,6 +1820,43 @@ static bool js_cc_render_RasterPassBuilder_addQueue(se::State& s) } SE_BIND_FUNC(js_cc_render_RasterPassBuilder_addQueue) +static bool js_cc_render_RasterPassBuilder_showStatistics_set(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::render::RasterPassBuilder *arg1 = (cc::render::RasterPassBuilder *) NULL ; + bool arg2 ; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + + ok &= sevalue_to_native(args[0], &arg2); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cc_render_RasterPassBuilder_showStatistics_set(arg1,arg2); + + + return true; +} +SE_BIND_PROP_SET(js_cc_render_RasterPassBuilder_showStatistics_set) + +static bool js_cc_render_RasterPassBuilder_showStatistics_get(se::State& s) +{ + CC_UNUSED bool ok = true; + cc::render::RasterPassBuilder *arg1 = (cc::render::RasterPassBuilder *) NULL ; + bool result; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + result = (bool)cc_render_RasterPassBuilder_showStatistics_get(arg1); + + ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); + + + return true; +} +SE_BIND_PROP_GET(js_cc_render_RasterPassBuilder_showStatistics_get) + static bool js_delete_cc_render_RasterPassBuilder(se::State& s) { return true; @@ -1827,6 +1867,7 @@ bool js_register_cc_render_RasterPassBuilder(se::Object* obj) { auto* cls = se::Class::create("RasterPassBuilder", obj, __jsb_cc_render_Setter_proto, nullptr); cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); + cls->defineProperty("showStatistics", _SE(js_cc_render_RasterPassBuilder_showStatistics_get), _SE(js_cc_render_RasterPassBuilder_showStatistics_set)); cls->defineFunction("addRasterView", _SE(js_cc_render_RasterPassBuilder_addRasterView)); cls->defineFunction("addComputeView", _SE(js_cc_render_RasterPassBuilder_addComputeView)); @@ -2502,337 +2543,6 @@ bool js_register_cc_render_SceneTransversal(se::Object* obj) { } -se::Class* __jsb_cc_render_LayoutGraphBuilder_class = nullptr; -se::Object* __jsb_cc_render_LayoutGraphBuilder_proto = nullptr; -SE_DECLARE_FINALIZE_FUNC(js_delete_cc_render_LayoutGraphBuilder) - -static bool js_delete_cc_render_LayoutGraphBuilder(se::State& s) -{ - return true; -} -SE_BIND_FINALIZE_FUNC(js_delete_cc_render_LayoutGraphBuilder) - -static bool js_cc_render_LayoutGraphBuilder_clear(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::render::LayoutGraphBuilder *arg1 = (cc::render::LayoutGraphBuilder *) NULL ; - - if(argc != 0) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - (arg1)->clear(); - - - return true; -} -SE_BIND_FUNC(js_cc_render_LayoutGraphBuilder_clear) - -static bool js_cc_render_LayoutGraphBuilder_addRenderStage(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::render::LayoutGraphBuilder *arg1 = (cc::render::LayoutGraphBuilder *) NULL ; - ccstd::string *arg2 = 0 ; - ccstd::string temp2 ; - uint32_t result; - - if(argc != 1) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &temp2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg2 = &temp2; - - result = (arg1)->addRenderStage((ccstd::string const &)*arg2); - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - - return true; -} -SE_BIND_FUNC(js_cc_render_LayoutGraphBuilder_addRenderStage) - -static bool js_cc_render_LayoutGraphBuilder_addRenderPhase(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::render::LayoutGraphBuilder *arg1 = (cc::render::LayoutGraphBuilder *) NULL ; - ccstd::string *arg2 = 0 ; - uint32_t arg3 ; - ccstd::string temp2 ; - uint32_t result; - - if(argc != 2) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &temp2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg2 = &temp2; - - - ok &= sevalue_to_native(args[1], &arg3, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - - result = (arg1)->addRenderPhase((ccstd::string const &)*arg2,arg3); - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - - return true; -} -SE_BIND_FUNC(js_cc_render_LayoutGraphBuilder_addRenderPhase) - -static bool js_cc_render_LayoutGraphBuilder_addShader(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::render::LayoutGraphBuilder *arg1 = (cc::render::LayoutGraphBuilder *) NULL ; - ccstd::string *arg2 = 0 ; - uint32_t arg3 ; - ccstd::string temp2 ; - - if(argc != 2) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &temp2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg2 = &temp2; - - - ok &= sevalue_to_native(args[1], &arg3, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - - (arg1)->addShader((ccstd::string const &)*arg2,arg3); - - - return true; -} -SE_BIND_FUNC(js_cc_render_LayoutGraphBuilder_addShader) - -static bool js_cc_render_LayoutGraphBuilder_addDescriptorBlock(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::render::LayoutGraphBuilder *arg1 = (cc::render::LayoutGraphBuilder *) NULL ; - uint32_t arg2 ; - DescriptorBlockIndex *arg3 = 0 ; - DescriptorBlockFlattened *arg4 = 0 ; - DescriptorBlockIndex temp3 ; - DescriptorBlockFlattened temp4 ; - - if(argc != 3) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &arg2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - - - ok &= sevalue_to_native(args[1], &temp3, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg3 = &temp3; - - - ok &= sevalue_to_native(args[2], &temp4, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg4 = &temp4; - - (arg1)->addDescriptorBlock(arg2,(DescriptorBlockIndex const &)*arg3,(DescriptorBlockFlattened const &)*arg4); - - - return true; -} -SE_BIND_FUNC(js_cc_render_LayoutGraphBuilder_addDescriptorBlock) - -static bool js_cc_render_LayoutGraphBuilder_addUniformBlock(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::render::LayoutGraphBuilder *arg1 = (cc::render::LayoutGraphBuilder *) NULL ; - uint32_t arg2 ; - DescriptorBlockIndex *arg3 = 0 ; - ccstd::string *arg4 = 0 ; - gfx::UniformBlock *arg5 = 0 ; - DescriptorBlockIndex temp3 ; - ccstd::string temp4 ; - gfx::UniformBlock temp5 ; - - if(argc != 4) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 4); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &arg2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - - - ok &= sevalue_to_native(args[1], &temp3, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg3 = &temp3; - - - ok &= sevalue_to_native(args[2], &temp4, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg4 = &temp4; - - - ok &= sevalue_to_native(args[3], &temp5, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg5 = &temp5; - - (arg1)->addUniformBlock(arg2,(DescriptorBlockIndex const &)*arg3,(ccstd::string const &)*arg4,(gfx::UniformBlock const &)*arg5); - - - return true; -} -SE_BIND_FUNC(js_cc_render_LayoutGraphBuilder_addUniformBlock) - -static bool js_cc_render_LayoutGraphBuilder_reserveDescriptorBlock(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::render::LayoutGraphBuilder *arg1 = (cc::render::LayoutGraphBuilder *) NULL ; - uint32_t arg2 ; - DescriptorBlockIndex *arg3 = 0 ; - DescriptorBlockFlattened *arg4 = 0 ; - DescriptorBlockIndex temp3 ; - DescriptorBlockFlattened temp4 ; - - if(argc != 3) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &arg2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - - - ok &= sevalue_to_native(args[1], &temp3, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg3 = &temp3; - - - ok &= sevalue_to_native(args[2], &temp4, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg4 = &temp4; - - (arg1)->reserveDescriptorBlock(arg2,(DescriptorBlockIndex const &)*arg3,(DescriptorBlockFlattened const &)*arg4); - - - return true; -} -SE_BIND_FUNC(js_cc_render_LayoutGraphBuilder_reserveDescriptorBlock) - -static bool js_cc_render_LayoutGraphBuilder_compile(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::render::LayoutGraphBuilder *arg1 = (cc::render::LayoutGraphBuilder *) NULL ; - int result; - - if(argc != 0) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = (int)(arg1)->compile(); - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - - return true; -} -SE_BIND_FUNC(js_cc_render_LayoutGraphBuilder_compile) - -static bool js_cc_render_LayoutGraphBuilder_print(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::render::LayoutGraphBuilder *arg1 = (cc::render::LayoutGraphBuilder *) NULL ; - ccstd::string result; - - if(argc != 0) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = ((cc::render::LayoutGraphBuilder const *)arg1)->print(); - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - - - return true; -} -SE_BIND_FUNC(js_cc_render_LayoutGraphBuilder_print) - -bool js_register_cc_render_LayoutGraphBuilder(se::Object* obj) { - auto* cls = se::Class::create("LayoutGraphBuilder", obj, nullptr, nullptr); - - cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - - cls->defineFunction("clear", _SE(js_cc_render_LayoutGraphBuilder_clear)); - cls->defineFunction("addRenderStage", _SE(js_cc_render_LayoutGraphBuilder_addRenderStage)); - cls->defineFunction("addRenderPhase", _SE(js_cc_render_LayoutGraphBuilder_addRenderPhase)); - cls->defineFunction("addShader", _SE(js_cc_render_LayoutGraphBuilder_addShader)); - cls->defineFunction("addDescriptorBlock", _SE(js_cc_render_LayoutGraphBuilder_addDescriptorBlock)); - cls->defineFunction("addUniformBlock", _SE(js_cc_render_LayoutGraphBuilder_addUniformBlock)); - cls->defineFunction("reserveDescriptorBlock", _SE(js_cc_render_LayoutGraphBuilder_reserveDescriptorBlock)); - cls->defineFunction("compile", _SE(js_cc_render_LayoutGraphBuilder_compile)); - cls->defineFunction("print", _SE(js_cc_render_LayoutGraphBuilder_print)); - - - - - cls->defineFinalizeFunction(_SE(js_delete_cc_render_LayoutGraphBuilder)); - - - cls->install(); - JSBClassType::registerClass(cls); - - __jsb_cc_render_LayoutGraphBuilder_proto = cls->getProto(); - __jsb_cc_render_LayoutGraphBuilder_class = cls; - se::ScriptEngine::getInstance()->clearException(); - return true; -} - - se::Class* __jsb_cc_render_Pipeline_class = nullptr; se::Object* __jsb_cc_render_Pipeline_proto = nullptr; SE_DECLARE_FINALIZE_FUNC(js_delete_cc_render_Pipeline) @@ -3218,6 +2928,7 @@ static bool js_cc_render_Pipeline_addRasterPass__SWIG_0(se::State& s) ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + s.rval().toObject()->getPrivateObject()->tryAllowDestroyInGC(); return true; @@ -3655,6 +3366,7 @@ static bool js_cc_render_Pipeline_addRasterPass__SWIG_1(se::State& s) ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + s.rval().toObject()->getPrivateObject()->tryAllowDestroyInGC(); return true; @@ -3684,25 +3396,6 @@ static bool js_cc_render_Pipeline_addRasterPass(se::State& s) } SE_BIND_FUNC(js_cc_render_Pipeline_addRasterPass) -static bool js_cc_render_Pipeline_layoutGraphBuilder_get(se::State& s) -{ - CC_UNUSED bool ok = true; - cc::render::Pipeline *arg1 = (cc::render::Pipeline *) NULL ; - cc::render::LayoutGraphBuilder *result = 0 ; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = (cc::render::LayoutGraphBuilder *)cc_render_Pipeline_layoutGraphBuilder_get(arg1); - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - - return true; -} -SE_BIND_PROP_GET(js_cc_render_Pipeline_layoutGraphBuilder_get) - static bool js_delete_cc_render_Pipeline(se::State& s) { return true; @@ -3713,7 +3406,6 @@ bool js_register_cc_render_Pipeline(se::Object* obj) { auto* cls = se::Class::create("Pipeline", obj, __jsb_cc_render_PipelineRuntime_proto, nullptr); cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - cls->defineProperty("layoutGraphBuilder", _SE(js_cc_render_Pipeline_layoutGraphBuilder_get), nullptr); cls->defineFunction("beginSetup", _SE(js_cc_render_Pipeline_beginSetup)); cls->defineFunction("endSetup", _SE(js_cc_render_Pipeline_endSetup)); @@ -4065,7 +3757,6 @@ bool register_all_render(se::Object* obj) { js_register_cc_render_SceneVisitor(ns); js_register_cc_render_SceneTask(ns); js_register_cc_render_SceneTransversal(ns); - js_register_cc_render_LayoutGraphBuilder(ns); js_register_cc_render_Pipeline(ns); js_register_cc_render_PipelineBuilder(ns); js_register_cc_render_RenderingModule(ns); diff --git a/native/cocos/bindings/auto/jsb_render_auto.h b/native/cocos/bindings/auto/jsb_render_auto.h index 2db9143975..0ae1eedcc4 100644 --- a/native/cocos/bindings/auto/jsb_render_auto.h +++ b/native/cocos/bindings/auto/jsb_render_auto.h @@ -103,11 +103,6 @@ extern se::Object *__jsb_cc_render_SceneTransversal_proto; // NOLINT extern se::Class * __jsb_cc_render_SceneTransversal_class; // NOLINT -JSB_REGISTER_OBJECT_TYPE(cc::render::LayoutGraphBuilder); -extern se::Object *__jsb_cc_render_LayoutGraphBuilder_proto; // NOLINT -extern se::Class * __jsb_cc_render_LayoutGraphBuilder_class; // NOLINT - - JSB_REGISTER_OBJECT_TYPE(cc::render::Pipeline); extern se::Object *__jsb_cc_render_Pipeline_proto; // NOLINT extern se::Class * __jsb_cc_render_Pipeline_class; // NOLINT diff --git a/native/cocos/bindings/auto/jsb_scene_auto.cpp b/native/cocos/bindings/auto/jsb_scene_auto.cpp index a767ecd508..b44ecfaa0f 100644 --- a/native/cocos/bindings/auto/jsb_scene_auto.cpp +++ b/native/cocos/bindings/auto/jsb_scene_auto.cpp @@ -123,6 +123,9 @@ using namespace cc; #define cc_Root_cameraList_get(self_) self_->getCameraList() +#define cc_Root_debugView_get(self_) self_->getDebugView() + + #define cc_scene_RenderWindow_width_get(self_) self_->getWidth() @@ -828,6 +831,10 @@ using namespace cc; #define cc_scene_Model_reflectionProbeType_set(self_, val_) self_->setReflectionProbeType(val_) +#define cc_scene_Model_receiveDirLight_get(self_) self_->isReceiveDirLight() +#define cc_scene_Model_receiveDirLight_set(self_, val_) self_->setReceiveDirLight(val_) + + #define cc_scene_SubModel_passes_get(self_) self_->getPasses() #define cc_scene_SubModel_passes_set(self_, val_) self_->setPasses(val_) @@ -4768,274 +4775,6 @@ bool js_register_cc_SceneGlobals(se::Object* obj) { } -se::Class* __jsb_cc_DebugViewConfig_class = nullptr; -se::Object* __jsb_cc_DebugViewConfig_proto = nullptr; -SE_DECLARE_FINALIZE_FUNC(js_delete_cc_DebugViewConfig) - -static bool js_cc_DebugViewConfig_singleMode_set(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::DebugViewConfig *arg1 = (cc::DebugViewConfig *) NULL ; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &arg1->singleMode, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - - - - return true; -} -SE_BIND_PROP_SET(js_cc_DebugViewConfig_singleMode_set) - -static bool js_cc_DebugViewConfig_singleMode_get(se::State& s) -{ - CC_UNUSED bool ok = true; - cc::DebugViewConfig *arg1 = (cc::DebugViewConfig *) NULL ; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= nativevalue_to_se(arg1->singleMode, s.rval(), s.thisObject()); - - - return true; -} -SE_BIND_PROP_GET(js_cc_DebugViewConfig_singleMode_get) - -static bool js_cc_DebugViewConfig_compositeModeBitCount_set(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::DebugViewConfig *arg1 = (cc::DebugViewConfig *) NULL ; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &arg1->compositeModeBitCount, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - - - - return true; -} -SE_BIND_PROP_SET(js_cc_DebugViewConfig_compositeModeBitCount_set) - -static bool js_cc_DebugViewConfig_compositeModeBitCount_get(se::State& s) -{ - CC_UNUSED bool ok = true; - cc::DebugViewConfig *arg1 = (cc::DebugViewConfig *) NULL ; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= nativevalue_to_se(arg1->compositeModeBitCount, s.rval(), s.thisObject()); - - - return true; -} -SE_BIND_PROP_GET(js_cc_DebugViewConfig_compositeModeBitCount_get) - -static bool js_cc_DebugViewConfig_compositeModeValue_set(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::DebugViewConfig *arg1 = (cc::DebugViewConfig *) NULL ; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &arg1->compositeModeValue, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - - - - return true; -} -SE_BIND_PROP_SET(js_cc_DebugViewConfig_compositeModeValue_set) - -static bool js_cc_DebugViewConfig_compositeModeValue_get(se::State& s) -{ - CC_UNUSED bool ok = true; - cc::DebugViewConfig *arg1 = (cc::DebugViewConfig *) NULL ; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= nativevalue_to_se(arg1->compositeModeValue, s.rval(), s.thisObject()); - - - return true; -} -SE_BIND_PROP_GET(js_cc_DebugViewConfig_compositeModeValue_get) - -static bool js_cc_DebugViewConfig_lightingWithAlbedo_set(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::DebugViewConfig *arg1 = (cc::DebugViewConfig *) NULL ; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &arg1->lightingWithAlbedo); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - - - return true; -} -SE_BIND_PROP_SET(js_cc_DebugViewConfig_lightingWithAlbedo_set) - -static bool js_cc_DebugViewConfig_lightingWithAlbedo_get(se::State& s) -{ - CC_UNUSED bool ok = true; - cc::DebugViewConfig *arg1 = (cc::DebugViewConfig *) NULL ; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= nativevalue_to_se(arg1->lightingWithAlbedo, s.rval(), s.thisObject()); - - - return true; -} -SE_BIND_PROP_GET(js_cc_DebugViewConfig_lightingWithAlbedo_get) - -static bool js_cc_DebugViewConfig_csmLayerColoration_set(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::DebugViewConfig *arg1 = (cc::DebugViewConfig *) NULL ; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &arg1->csmLayerColoration); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - - - return true; -} -SE_BIND_PROP_SET(js_cc_DebugViewConfig_csmLayerColoration_set) - -static bool js_cc_DebugViewConfig_csmLayerColoration_get(se::State& s) -{ - CC_UNUSED bool ok = true; - cc::DebugViewConfig *arg1 = (cc::DebugViewConfig *) NULL ; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= nativevalue_to_se(arg1->csmLayerColoration, s.rval(), s.thisObject()); - - - return true; -} -SE_BIND_PROP_GET(js_cc_DebugViewConfig_csmLayerColoration_get) - -static bool js_new_cc_DebugViewConfig(se::State& s) // NOLINT(readability-identifier-naming) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - - cc::DebugViewConfig *result; - result = (cc::DebugViewConfig *)new cc::DebugViewConfig(); - - - auto *ptr = JSB_MAKE_PRIVATE_OBJECT_WITH_INSTANCE(result); - s.thisObject()->setPrivateObject(ptr); - return true; -} -SE_BIND_CTOR(js_new_cc_DebugViewConfig, __jsb_cc_DebugViewConfig_class, js_delete_cc_DebugViewConfig) - -static bool js_delete_cc_DebugViewConfig(se::State& s) -{ - return true; -} -SE_BIND_FINALIZE_FUNC(js_delete_cc_DebugViewConfig) - -template<> -bool sevalue_to_native(const se::Value &from, cc::DebugViewConfig * to, se::Object *ctx) -{ - assert(from.isObject()); - se::Object *json = from.toObject(); - auto* data = reinterpret_cast(json->getPrivateData()); - if (data) { - *to = *data; - return true; - } - se::Value field; - bool ok = true; - - json->getProperty("singleMode", &field, true); - if (!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->singleMode), ctx); - } - - - json->getProperty("compositeModeBitCount", &field, true); - if (!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->compositeModeBitCount), ctx); - } - - - json->getProperty("compositeModeValue", &field, true); - if (!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->compositeModeValue), ctx); - } - - - json->getProperty("lightingWithAlbedo", &field, true); - if (!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->lightingWithAlbedo), ctx); - } - - - json->getProperty("csmLayerColoration", &field, true); - if (!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->csmLayerColoration), ctx); - } - - - return ok; -} - - -bool js_register_cc_DebugViewConfig(se::Object* obj) { - auto* cls = se::Class::create("DebugViewConfig", obj, nullptr, _SE(js_new_cc_DebugViewConfig)); - - cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - cls->defineProperty("singleMode", _SE(js_cc_DebugViewConfig_singleMode_get), _SE(js_cc_DebugViewConfig_singleMode_set)); - cls->defineProperty("compositeModeBitCount", _SE(js_cc_DebugViewConfig_compositeModeBitCount_get), _SE(js_cc_DebugViewConfig_compositeModeBitCount_set)); - cls->defineProperty("compositeModeValue", _SE(js_cc_DebugViewConfig_compositeModeValue_get), _SE(js_cc_DebugViewConfig_compositeModeValue_set)); - cls->defineProperty("lightingWithAlbedo", _SE(js_cc_DebugViewConfig_lightingWithAlbedo_get), _SE(js_cc_DebugViewConfig_lightingWithAlbedo_set)); - cls->defineProperty("csmLayerColoration", _SE(js_cc_DebugViewConfig_csmLayerColoration_get), _SE(js_cc_DebugViewConfig_csmLayerColoration_set)); - - - - - - cls->defineFinalizeFunction(_SE(js_delete_cc_DebugViewConfig)); - - - cls->install(); - JSBClassType::registerClass(cls); - - __jsb_cc_DebugViewConfig_proto = cls->getProto(); - __jsb_cc_DebugViewConfig_class = cls; - se::ScriptEngine::getInstance()->clearException(); - return true; -} - - se::Class* __jsb_cc_Root_class = nullptr; se::Object* __jsb_cc_Root_proto = nullptr; SE_DECLARE_FINALIZE_FUNC(js_delete_cc_Root) @@ -5603,58 +5342,6 @@ static bool js_cc_Root_getBatcher2D(se::State& s) } SE_BIND_FUNC(js_cc_Root_getBatcher2D) -static bool js_cc_Root_setDebugViewConfig(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::Root *arg1 = (cc::Root *) NULL ; - cc::DebugViewConfig *arg2 = 0 ; - cc::DebugViewConfig temp2 ; - - if(argc != 1) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &temp2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg2 = &temp2; - - (arg1)->setDebugViewConfig((cc::DebugViewConfig const &)*arg2); - - - return true; -} -SE_BIND_FUNC(js_cc_Root_setDebugViewConfig) - -static bool js_cc_Root_getDebugViewConfig(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::Root *arg1 = (cc::Root *) NULL ; - cc::DebugViewConfig *result = 0 ; - - if(argc != 0) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = (cc::DebugViewConfig *) &((cc::Root const *)arg1)->getDebugViewConfig(); - - ok &= nativevalue_to_se(*result, s.rval(), s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(*result, s.thisObject(), s.rval()); - - - return true; -} -SE_BIND_FUNC(js_cc_Root_getDebugViewConfig) - static bool js_cc_Root_createRenderWindowFromSystemWindow__SWIG_0(se::State& s) { CC_UNUSED bool ok = true; @@ -6136,6 +5823,25 @@ static bool js_cc_Root_cameraList_get(se::State& s) } SE_BIND_PROP_GET(js_cc_Root_cameraList_get) +static bool js_cc_Root_debugView_get(se::State& s) +{ + CC_UNUSED bool ok = true; + cc::Root *arg1 = (cc::Root *) NULL ; + cc::pipeline::DebugView *result = 0 ; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + result = (cc::pipeline::DebugView *)cc_Root_debugView_get(arg1); + + ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + + + return true; +} +SE_BIND_PROP_GET(js_cc_Root_debugView_get) + bool js_register_cc_Root(se::Object* obj) { auto* cls = se::Class::create("Root", obj, nullptr, _SE(js_new_cc_Root)); @@ -6157,6 +5863,7 @@ bool js_register_cc_Root(se::Object* obj) { cls->defineProperty("pipeline", _SE(js_cc_Root_pipeline_get), nullptr); cls->defineProperty("customPipeline", _SE(js_cc_Root_customPipeline_get), nullptr); cls->defineProperty("cameraList", _SE(js_cc_Root_cameraList_get), nullptr); + cls->defineProperty("debugView", _SE(js_cc_Root_debugView_get), nullptr); cls->defineFunction("_initialize", _SE(js_cc_Root__initialize)); cls->defineFunction("destroy", _SE(js_cc_Root_destroy)); @@ -6176,8 +5883,6 @@ bool js_register_cc_Root(se::Object* obj) { cls->defineFunction("destroyLight", _SE(js_cc_Root_destroyLight)); cls->defineFunction("createCamera", _SE(js_cc_Root_createCamera)); cls->defineFunction("getBatcher2D", _SE(js_cc_Root_getBatcher2D)); - cls->defineFunction("setDebugViewConfig", _SE(js_cc_Root_setDebugViewConfig)); - cls->defineFunction("getDebugViewConfig", _SE(js_cc_Root_getDebugViewConfig)); cls->defineFunction("createRenderWindowFromSystemWindow", _SE(js_cc_Root_createRenderWindowFromSystemWindow)); @@ -15596,6 +15301,43 @@ static bool js_cc_scene_Model_reflectionProbeType_get(se::State& s) } SE_BIND_PROP_GET(js_cc_scene_Model_reflectionProbeType_get) +static bool js_cc_scene_Model_receiveDirLight_set(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::scene::Model *arg1 = (cc::scene::Model *) NULL ; + bool arg2 ; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + + ok &= sevalue_to_native(args[0], &arg2); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cc_scene_Model_receiveDirLight_set(arg1,arg2); + + + return true; +} +SE_BIND_PROP_SET(js_cc_scene_Model_receiveDirLight_set) + +static bool js_cc_scene_Model_receiveDirLight_get(se::State& s) +{ + CC_UNUSED bool ok = true; + cc::scene::Model *arg1 = (cc::scene::Model *) NULL ; + bool result; + + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + result = (bool)cc_scene_Model_receiveDirLight_get(arg1); + + ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); + + + return true; +} +SE_BIND_PROP_GET(js_cc_scene_Model_receiveDirLight_get) + bool js_register_cc_scene_Model(se::Object* obj) { auto* cls = se::Class::create("Model", obj, nullptr, _SE(js_new_cc_scene_Model)); @@ -15627,6 +15369,7 @@ bool js_register_cc_scene_Model(se::Object* obj) { cls->defineProperty("useLightProbe", _SE(js_cc_scene_Model_useLightProbe_get), _SE(js_cc_scene_Model_useLightProbe_set)); cls->defineProperty("bakeToReflectionProbe", _SE(js_cc_scene_Model_bakeToReflectionProbe_get), _SE(js_cc_scene_Model_bakeToReflectionProbe_set)); cls->defineProperty("reflectionProbeType", _SE(js_cc_scene_Model_reflectionProbeType_get), _SE(js_cc_scene_Model_reflectionProbeType_set)); + cls->defineProperty("receiveDirLight", _SE(js_cc_scene_Model_receiveDirLight_get), _SE(js_cc_scene_Model_receiveDirLight_set)); cls->defineFunction("destroy", _SE(js_cc_scene_Model_destroy)); cls->defineFunction("initSubModel", _SE(js_cc_scene_Model_initSubModel)); @@ -18286,6 +18029,52 @@ static bool js_cc_scene_Pass_getRootBlock(se::State& s) } SE_BIND_FUNC(js_cc_scene_Pass_getRootBlock) +static bool js_cc_scene_Pass_getPassID(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::scene::Pass *arg1 = (cc::scene::Pass *) NULL ; + uint32_t result; + + if(argc != 0) { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; + } + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + result = ((cc::scene::Pass const *)arg1)->getPassID(); + + ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); + + + return true; +} +SE_BIND_FUNC(js_cc_scene_Pass_getPassID) + +static bool js_cc_scene_Pass_getPhaseID(se::State& s) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + cc::scene::Pass *arg1 = (cc::scene::Pass *) NULL ; + uint32_t result; + + if(argc != 0) { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; + } + arg1 = SE_THIS_OBJECT(s); + if (nullptr == arg1) return true; + result = ((cc::scene::Pass const *)arg1)->getPhaseID(); + + ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); + + + return true; +} +SE_BIND_FUNC(js_cc_scene_Pass_getPhaseID) + static bool js_cc_scene_Pass__updatePassHash(se::State& s) { CC_UNUSED bool ok = true; @@ -18869,6 +18658,8 @@ bool js_register_cc_scene_Pass(se::Object* obj) { cls->defineFunction("getShaderVariant", _SE(js_cc_scene_Pass_getShaderVariant)); cls->defineFunction("getPassInfoFull", _SE(js_cc_scene_Pass_getPassInfoFull)); cls->defineFunction("getRootBlock", _SE(js_cc_scene_Pass_getRootBlock)); + cls->defineFunction("getPassID", _SE(js_cc_scene_Pass_getPassID)); + cls->defineFunction("getPhaseID", _SE(js_cc_scene_Pass_getPhaseID)); cls->defineFunction("_updatePassHash", _SE(js_cc_scene_Pass__updatePassHash)); cls->defineFunction("beginChangeStatesSilently", _SE(js_cc_scene_Pass_beginChangeStatesSilently)); cls->defineFunction("endChangeStatesSilently", _SE(js_cc_scene_Pass_endChangeStatesSilently)); @@ -26743,7 +26534,7 @@ static bool js_cc_ProgramLib_getTemplate(se::State& s) SE_PRECONDITION2(ok, false, "Error processing arguments"); arg2 = &temp2; - result = (cc::IProgramInfo *)(arg1)->getTemplate((ccstd::string const &)*arg2); + result = (cc::IProgramInfo *)((cc::ProgramLib const *)arg1)->getTemplate((ccstd::string const &)*arg2); ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -28340,7 +28131,6 @@ bool register_all_scene(se::Object* obj) { js_register_cc_Node_UserData(ns); js_register_cc_Scene(ns); js_register_cc_SceneGlobals(ns); - js_register_cc_DebugViewConfig(ns); js_register_cc_Root(ns); js_register_cc_scene_IMacroPatch(ns); js_register_cc_scene_Light(ns); diff --git a/native/cocos/bindings/auto/jsb_scene_auto.h b/native/cocos/bindings/auto/jsb_scene_auto.h index 4e03c2857e..9aa4886237 100644 --- a/native/cocos/bindings/auto/jsb_scene_auto.h +++ b/native/cocos/bindings/auto/jsb_scene_auto.h @@ -96,15 +96,6 @@ extern se::Object *__jsb_cc_SceneGlobals_proto; // NOLINT extern se::Class * __jsb_cc_SceneGlobals_class; // NOLINT -JSB_REGISTER_OBJECT_TYPE(cc::DebugViewConfig); -extern se::Object *__jsb_cc_DebugViewConfig_proto; // NOLINT -extern se::Class * __jsb_cc_DebugViewConfig_class; // NOLINT - - -template<> -bool sevalue_to_native(const se::Value &from, cc::DebugViewConfig * to, se::Object *ctx); - - JSB_REGISTER_OBJECT_TYPE(cc::Root); extern se::Object *__jsb_cc_Root_proto; // NOLINT extern se::Class * __jsb_cc_Root_class; // NOLINT diff --git a/native/cocos/bindings/jswrapper/HandleObject.cpp b/native/cocos/bindings/jswrapper/HandleObject.cpp index 73739aa65a..f040f99c41 100644 --- a/native/cocos/bindings/jswrapper/HandleObject.cpp +++ b/native/cocos/bindings/jswrapper/HandleObject.cpp @@ -37,6 +37,11 @@ HandleObject::HandleObject(Object *obj) } } +HandleObject::HandleObject(HandleObject &&o) noexcept{ + _obj = o._obj; + o._obj = nullptr; +} + HandleObject::~HandleObject() { if (_obj != nullptr) { _obj->unroot(); @@ -44,4 +49,10 @@ HandleObject::~HandleObject() { } } +HandleObject& HandleObject::operator=(HandleObject &&o) noexcept { + _obj = o._obj; + o._obj = nullptr; + return *this; +} + } // namespace se diff --git a/native/cocos/bindings/jswrapper/HandleObject.h b/native/cocos/bindings/jswrapper/HandleObject.h index 85dd2c259e..c8647b3eae 100644 --- a/native/cocos/bindings/jswrapper/HandleObject.h +++ b/native/cocos/bindings/jswrapper/HandleObject.h @@ -97,11 +97,11 @@ public: inline bool isEmpty() const { return (_obj == nullptr); } + HandleObject(HandleObject &&) noexcept; + HandleObject& operator=(HandleObject &&) noexcept; HandleObject(const HandleObject &) = delete; - void operator=(const HandleObject &) = delete; - HandleObject(HandleObject &&) = delete; - void operator=(HandleObject &&) = delete; + HandleObject& operator=(const HandleObject &) = delete; void *operator new(size_t size) = delete; void operator delete(void *, size_t) = delete; diff --git a/native/cocos/bindings/jswrapper/v8/Object.cpp b/native/cocos/bindings/jswrapper/v8/Object.cpp index 7cc1bbbd57..73a0e146b3 100644 --- a/native/cocos/bindings/jswrapper/v8/Object.cpp +++ b/native/cocos/bindings/jswrapper/v8/Object.cpp @@ -150,6 +150,13 @@ void Object::cleanup() { SE_ASSERT(NativePtrToObjectMap::size() == 0, "NativePtrToObjectMap should be empty!"); } +Object *Object::createProxyTarget(se::Object *proxy) { + SE_ASSERT(proxy->isProxy(), "parameter is not a Proxy object"); + v8::Local jsobj = proxy->getProxyTarget().As(); + Object *obj = Object::_createJSObject(nullptr, jsobj); + return obj; +} + Object *Object::createPlainObject() { v8::Local jsobj = v8::Object::New(__isolate); Object *obj = _createJSObject(nullptr, jsobj); @@ -564,6 +571,17 @@ bool Object::isTypedArray() const { return const_cast(this)->_obj.handle(__isolate)->IsTypedArray(); } +bool Object::isProxy() const { + return const_cast(this)->_obj.handle(__isolate)->IsProxy(); +} + +v8::Local Object::getProxyTarget() const { + v8::Local value = const_cast(this)->_obj.handle(__isolate); + CC_ASSERTF(value->IsProxy(), "Object is not a Proxy"); + v8::Proxy *proxy = v8::Proxy::Cast(*value); + return proxy->GetTarget(); +} + Object::TypedArrayType Object::getTypedArrayType() const { v8::Local value = const_cast(this)->_obj.handle(__isolate); TypedArrayType ret = TypedArrayType::NONE; @@ -794,8 +812,7 @@ bool Object::getArrayLength(uint32_t *length) const { CC_ASSERT(isArray()); CC_ASSERT_NOT_NULL(length); auto *thiz = const_cast(this); - - v8::Local v8Arr = v8::Local::Cast(thiz->_obj.handle(__isolate)); + auto v8Arr = v8::Local::Cast(thiz->_obj.handle(__isolate)); *length = v8Arr->Length(); return true; } diff --git a/native/cocos/bindings/jswrapper/v8/Object.h b/native/cocos/bindings/jswrapper/v8/Object.h index 0ec3119a40..80a834f0f2 100644 --- a/native/cocos/bindings/jswrapper/v8/Object.h +++ b/native/cocos/bindings/jswrapper/v8/Object.h @@ -177,6 +177,13 @@ public: */ static Object *createObjectWithConstructor(se::Object *constructor, const ValueArray &args); + /** + * Gets the Proxy Target object + * @param proxy The JavaScript Proxy object. + * @return The target JavaScript object of the parameter. + */ + static Object *createProxyTarget(se::Object *proxy); + /** * @brief Gets a se::Object from an existing native object pointer. * @param[in] ptr The native object pointer associated with the se::Object @@ -314,6 +321,11 @@ public: */ bool isTypedArray() const; + /** @brief Tests whether an object is a proxy object. + * @return true if object is a proxy object, otherwise false. + */ + bool isProxy() const; + /** * @brief Gets the type of a typed array object. * @return The type of a typed array object. @@ -656,6 +668,7 @@ private: ~Object() override; bool init(Class *cls, v8::Local obj); + v8::Local getProxyTarget() const; Class *_cls{nullptr}; ObjectWrap _obj; diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index 85afa4163e..b171e28331 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -195,17 +195,25 @@ seval_to_type(const se::Value &v, bool &ok) { // NOLINT(readability-identifier-n return v.toString(); } +inline se::HandleObject unwrapProxyObject(se::Object *obj) { + if(obj->isProxy()) { + return se::HandleObject(se::Object::createProxyTarget(obj)); + } + obj->incRef(); + return se::HandleObject(obj); +} + template typename std::enable_if::value && std::is_class::type>::value, bool>::type seval_to_std_vector(const se::Value &v, ccstd::vector *ret) { // NOLINT(readability-identifier-naming) CC_ASSERT_NOT_NULL(ret); CC_ASSERT(v.isObject()); - se::Object *obj = v.toObject(); - CC_ASSERT(obj->isArray()); + se::HandleObject array(unwrapProxyObject(v.toObject())); + CC_ASSERT(array->isArray()); bool ok = true; uint32_t len = 0; - ok = obj->getArrayLength(&len); + ok = array->getArrayLength(&len); if (!ok) { ret->clear(); return false; @@ -215,7 +223,7 @@ seval_to_std_vector(const se::Value &v, ccstd::vector *ret) { // NOLINT(reada se::Value tmp; for (uint32_t i = 0; i < len; ++i) { - ok = obj->getArrayElement(i, &tmp); + ok = array->getArrayElement(i, &tmp); if (!ok) { ret->clear(); return false; @@ -240,12 +248,12 @@ typename std::enable_if::value, bool>::type seval_to_std_vector(const se::Value &v, ccstd::vector *ret) { // NOLINT(readability-identifier-naming) CC_ASSERT_NOT_NULL(ret); CC_ASSERT(v.isObject()); - se::Object *obj = v.toObject(); - CC_ASSERT(obj->isArray()); + se::HandleObject array(unwrapProxyObject(v.toObject())); + CC_ASSERT(array->isArray()); bool ok = true; uint32_t len = 0; - ok = obj->getArrayLength(&len); + ok = array->getArrayLength(&len); if (!ok) { ret->clear(); return false; @@ -255,7 +263,7 @@ seval_to_std_vector(const se::Value &v, ccstd::vector *ret) { // NOLINT(reada se::Value tmp; for (uint32_t i = 0; i < len; ++i) { - ok = obj->getArrayElement(i, &tmp); + ok = array->getArrayElement(i, &tmp); if (!ok) { ret->clear(); return false; @@ -709,8 +717,8 @@ bool sevalue_to_native(const se::Value &from, ccstd::vector *to, se::Object * } CC_ASSERT(from.toObject()); - se::Object *array = from.toObject(); - + se::HandleObject array(unwrapProxyObject(from.toObject())); + if (array->isArray()) { uint32_t len = 0; array->getArrayLength(&len); diff --git a/native/cocos/bindings/manual/jsb_scene_manual.cpp b/native/cocos/bindings/manual/jsb_scene_manual.cpp index d01f04d57a..8459ca9899 100644 --- a/native/cocos/bindings/manual/jsb_scene_manual.cpp +++ b/native/cocos/bindings/manual/jsb_scene_manual.cpp @@ -265,6 +265,14 @@ static void registerLocalPositionRotationScaleUpdated(cc::Node *node, se::Object }); } +static void registerOnLightProbeBakingChanged(cc::Node *node, se::Object *jsObject) { + node->on( + [jsObject](cc::Node * /*emitter*/) { + se::AutoHandleScope hs; + se::ScriptEngine::getInstance()->callFunction(jsObject, "_onLightProbeBakingChanged", 0, nullptr); + }); +} + static bool js_scene_Node_registerListeners(se::State &s) // NOLINT(readability-identifier-naming) { auto *cobj = SE_THIS_OBJECT(s); @@ -405,6 +413,18 @@ static bool js_scene_Node_registerOnSiblingOrderChanged(se::State &s) // NOLINT( } SE_BIND_FUNC(js_scene_Node_registerOnSiblingOrderChanged) // NOLINT(readability-identifier-naming) +static bool js_scene_Node_registerOnLightProbeBakingChanged(se::State &s) // NOLINT(readability-identifier-naming) +{ + auto *cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + + auto *jsObject = s.thisObject(); + + registerOnLightProbeBakingChanged(cobj, jsObject); + return true; +} +SE_BIND_FUNC(js_scene_Node_registerOnLightProbeBakingChanged) // NOLINT(readability-identifier-naming) + static bool js_scene_Camera_screenPointToRay(void *nativeObject) // NOLINT(readability-identifier-naming) { auto *cobj = reinterpret_cast(nativeObject); @@ -828,6 +848,7 @@ bool register_all_scene_manual(se::Object *obj) // NOLINT(readability-identifier __jsb_cc_Node_proto->defineFunction("_registerOnChildRemoved", _SE(js_scene_Node_registerOnChildRemoved)); __jsb_cc_Node_proto->defineFunction("_registerOnChildAdded", _SE(js_scene_Node_registerOnChildAdded)); __jsb_cc_Node_proto->defineFunction("_registerOnSiblingOrderChanged", _SE(js_scene_Node_registerOnSiblingOrderChanged)); + __jsb_cc_Node_proto->defineFunction("_registerOnLightProbeBakingChanged", _SE(js_scene_Node_registerOnLightProbeBakingChanged)); se::Value jsbVal; obj->getProperty("jsb", &jsbVal); diff --git a/native/cocos/core/Root.cpp b/native/cocos/core/Root.cpp index 9edc74cb48..3a54b78f91 100644 --- a/native/cocos/core/Root.cpp +++ b/native/cocos/core/Root.cpp @@ -26,6 +26,7 @@ #include "2d/renderer/Batcher2d.h" #include "application/ApplicationManager.h" #include "bindings/event/EventDispatcher.h" +#include "pipeline/custom/RenderingModule.h" #include "platform/interfaces/modules/IScreen.h" #include "platform/interfaces/modules/ISystemWindow.h" #include "platform/interfaces/modules/ISystemWindowManager.h" @@ -92,6 +93,8 @@ void Root::initialize(gfx::Swapchain * /*swapchain*/) { uint32_t maxJoints = (_device->getCapabilities().maxVertexUniformVectors - usedUBOVectorCount) / 3; maxJoints = maxJoints < 256 ? maxJoints : 256; pipeline::localDescriptorSetLayoutResizeMaxJoints(maxJoints); + + _debugView = std::make_unique(); } render::Pipeline *Root::getCustomPipeline() const { @@ -161,6 +164,8 @@ void Root::destroy() { } _swapchains.clear(); + _debugView.reset(); + // TODO(minggo): // this.dataPoolManager.clear(); } @@ -316,8 +321,8 @@ bool Root::setRenderPipeline(pipeline::RenderPipeline *rppl /* = nullptr*/) { return false; } } else { - _pipelineRuntime = std::make_unique( - boost::container::pmr::get_default_resource()); + CC_ASSERT(!_pipelineRuntime); + _pipelineRuntime.reset(render::Factory::createPipeline()); if (!_pipelineRuntime->activate(_mainRenderWindow->getSwapchain())) { _pipelineRuntime->destroy(); _pipelineRuntime.reset(); diff --git a/native/cocos/core/Root.h b/native/cocos/core/Root.h index 306f2a40ad..faf2a0451b 100644 --- a/native/cocos/core/Root.h +++ b/native/cocos/core/Root.h @@ -29,6 +29,7 @@ #include "core/event/Event.h" #include "core/memop/Pool.h" #include "renderer/pipeline/RenderPipeline.h" +#include "renderer/pipeline/DebugView.h" #include "scene/DrawBatch2D.h" #include "scene/Light.h" #include "scene/Model.h" @@ -52,14 +53,6 @@ class Pipeline; } // namespace render class Batcher2d; -struct CC_DLL DebugViewConfig { - uint8_t singleMode; - uint8_t compositeModeBitCount; - uint32_t compositeModeValue; - bool lightingWithAlbedo; - bool csmLayerColoration; -}; - struct ISystemWindowInfo; class ISystemWindow; @@ -255,8 +248,7 @@ public: * @zh * 渲染调试数据 */ - inline void setDebugViewConfig(const DebugViewConfig &config) { _debugViewConfig = config; } - inline const DebugViewConfig &getDebugViewConfig() const { return _debugViewConfig; } + inline pipeline::DebugView *getDebugView() const { return _debugView.get(); } /** * @zh @@ -320,7 +312,7 @@ private: std::unique_ptr _pipelineRuntime; // IntrusivePtr _dataPoolMgr; ccstd::vector> _scenes; - DebugViewConfig _debugViewConfig; + std::unique_ptr _debugView; float _cumulativeTime{0.F}; float _frameTime{0.F}; float _fpsTime{0.F}; diff --git a/native/cocos/core/assets/EffectAsset.cpp b/native/cocos/core/assets/EffectAsset.cpp index 4d5070360d..9a74e9b171 100644 --- a/native/cocos/core/assets/EffectAsset.cpp +++ b/native/cocos/core/assets/EffectAsset.cpp @@ -23,9 +23,11 @@ ****************************************************************************/ #include "core/assets/EffectAsset.h" +#include "ProgramUtils.h" #include "cocos.h" #include "core/Root.h" #include "core/platform/Debug.h" +#include "cocos/renderer/pipeline/custom/RenderingModule.h" #include "engine/BaseEngine.h" #include "renderer/core/ProgramLib.h" @@ -164,7 +166,13 @@ EffectAsset *EffectAsset::get(const ccstd::string &name) { } void EffectAsset::onLoaded() { - ProgramLib::getInstance()->registerEffect(this); + auto *programLib = render::getProgramLibrary(); + if (programLib) { + render::addEffectDefaultProperties(*this); + programLib->addEffect(this); + } else { + ProgramLib::getInstance()->registerEffect(this); + } EffectAsset::registerAsset(this); #if !CC_EDITOR if (CC_CURRENT_ENGINE()->isInited()) { diff --git a/native/cocos/core/assets/EffectAsset.h b/native/cocos/core/assets/EffectAsset.h index cb535a94f2..ac0bf92436 100644 --- a/native/cocos/core/assets/EffectAsset.h +++ b/native/cocos/core/assets/EffectAsset.h @@ -374,6 +374,8 @@ struct IPassInfoFull final { // cjh } : public IPassInfo { // IPassInfoFull // generated part index_t passIndex{0}; + uint32_t passID = 0xFFFFFFFF; + uint32_t phaseID = 0xFFFFFFFF; MacroRecord defines; ccstd::optional stateOverrides; @@ -542,6 +544,12 @@ struct IShaderInfo { if (version == "glsl4") return &glsl4; return nullptr; } + IShaderSource *getSource(const ccstd::string &version) { + if (version == "glsl1") return &glsl1; + if (version == "glsl3") return &glsl3; + if (version == "glsl4") return &glsl4; + return nullptr; + } }; using IPreCompileInfoValueType = ccstd::variant, ccstd::vector, ccstd::vector>; diff --git a/native/cocos/core/builtin/DebugInfos.cpp b/native/cocos/core/builtin/DebugInfos.cpp index 097b9a147b..b7d789cd97 100644 --- a/native/cocos/core/builtin/DebugInfos.cpp +++ b/native/cocos/core/builtin/DebugInfos.cpp @@ -222,6 +222,7 @@ ccstd::unordered_map debugInfos = { { 4300, "Can not found the %s page." }, { 4301, "Can not add a page without UITransform." }, { 4302, "Can not set the scroll view content when it hasn't UITransform or its parent hasn't UITransform." }, +{ 4303, "The %s scrollBar on the '%s' node is not available, please check it." }, { 4400, "Invalid RichText img tag! The sprite frame name can't be found in the ImageAtlas!" }, { 4500, "Graphics: There is no model in %s." }, { 4600, "Script attached to '%s' is missing or invalid." }, @@ -459,6 +460,7 @@ ccstd::unordered_map debugInfos = { { 16101, "The effect('%s') you are looking for does not exist, please confirm the effect name in the editor. NOTE: Since 3.6, the name of the built-in effect has been changed to its name in the editor, please check it out. More information please refer to https://docs.cocos.com/creator/manual/en/shader/effect-inspector.html" }, { 16201, "The asset replacing failed, can not found override asset('%s') for '%s'" }, { 16301, "node '%s' doesn't have any ModelRenderer component, this component will not work. please add ModelRenderer component first" }, +{ 16302, "There is no reflection probe in the scene or no probe is near the current object. No reflection probe will take effect on this object. Please create a new reflection probe or move existing ones closer." }, }; }//namespace cc diff --git a/native/cocos/core/geometry/Intersect.cpp b/native/cocos/core/geometry/Intersect.cpp index e8f25a170e..406f4edd70 100644 --- a/native/cocos/core/geometry/Intersect.cpp +++ b/native/cocos/core/geometry/Intersect.cpp @@ -648,7 +648,7 @@ int aabbFrustum(const AABB &aabb, const Frustum &frustum) { int aabbFrustumCompletelyInside(const AABB &aabb, const Frustum &frustum) { for (const auto &plane : frustum.planes) { // frustum plane normal points to the inside - if (aabbPlane(aabb, *plane) == 0) { + if (aabbPlane(aabb, *plane) != 0) { return 0; } } // completely inside diff --git a/native/cocos/core/scene-graph/Node.h b/native/cocos/core/scene-graph/Node.h index e0d3f52eba..32aa151901 100644 --- a/native/cocos/core/scene-graph/Node.h +++ b/native/cocos/core/scene-graph/Node.h @@ -91,6 +91,7 @@ class Node : public CCObject { TARGET_EVENT_ARG3(LocalScaleUpdated, float, float, float) TARGET_EVENT_ARG10(LocalRTSUpdated, float, float, float, float, float, float, float, float, float, float) TARGET_EVENT_ARG1(EditorAttached, bool) + TARGET_EVENT_ARG0(LightProbeBakingChanged) DECLARE_TARGET_EVENT_END() public: class UserData : public RefCounted { diff --git a/native/cocos/engine/Engine.cpp b/native/cocos/engine/Engine.cpp index 4ff716cc21..03b96121de 100644 --- a/native/cocos/engine/Engine.cpp +++ b/native/cocos/engine/Engine.cpp @@ -37,6 +37,7 @@ #include "renderer/GFXDeviceManager.h" #include "renderer/core/ProgramLib.h" #include "renderer/pipeline/RenderPipeline.h" +#include "renderer/pipeline/custom/RenderingModule.h" #if CC_USE_AUDIO #include "cocos/audio/include/AudioEngine.h" @@ -191,6 +192,11 @@ void Engine::destroy() { delete _builtinResMgr; delete _programLib; + + if (cc::render::getRenderingModule()) { + cc::render::Factory::destroy(cc::render::getRenderingModule()); + } + CC_SAFE_DESTROY_AND_DELETE(_gfxDevice); delete _fs; _scheduler.reset(); @@ -225,9 +231,9 @@ void Engine::close() { // NOLINT cc::AudioEngine::stopAll(); #endif - //#if CC_USE_SOCKET - // cc::network::WebSocket::closeAllConnections(); - //#endif + // #if CC_USE_SOCKET + // cc::network::WebSocket::closeAllConnections(); + // #endif cc::DeferredReleasePool::clear(); _scheduler->removeAllFunctionsToBePerformedInCocosThread(); @@ -266,7 +272,7 @@ void Engine::tick() { // iOS/macOS use its own fps limitation algorithm. // Windows for Editor should not sleep,because Editor call tick function synchronously -#if (CC_PLATFORM == CC_PLATFORM_ANDROID || (CC_PLATFORM == CC_PLATFORM_WINDOWS && !defined(CC_EDITOR)) || CC_PLATFORM == CC_PLATFORM_OHOS) || (defined(CC_SERVER_MODE) && (CC_PLATFORM == CC_PLATFORM_MAC_OSX)) +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || (CC_PLATFORM == CC_PLATFORM_WINDOWS && !CC_EDITOR) || CC_PLATFORM == CC_PLATFORM_OHOS) || (defined(CC_SERVER_MODE) && (CC_PLATFORM == CC_PLATFORM_MAC_OSX)) if (dtNS < static_cast(_prefererredNanosecondsPerFrame)) { CC_PROFILE(EngineSleep); std::this_thread::sleep_for( diff --git a/native/cocos/gi/light-probe/LightProbe.cpp b/native/cocos/gi/light-probe/LightProbe.cpp index 85193c0fea..eccd049873 100644 --- a/native/cocos/gi/light-probe/LightProbe.cpp +++ b/native/cocos/gi/light-probe/LightProbe.cpp @@ -26,6 +26,7 @@ #include "LightProbe.h" #include "PolynomialSolver.h" #include "core/Root.h" +#include "core/scene-graph/Node.h" #include "core/scene-graph/Scene.h" #include "math/Math.h" #include "math/Utils.h" @@ -205,6 +206,15 @@ void LightProbeInfo::activate(Scene *scene, LightProbes *resource) { _resource->initialize(this); } +void LightProbeInfo::onProbeBakeFinished() { + onProbeBakingChanged(_scene); +} + +void LightProbeInfo::onProbeBakeCleared() { + clearSHCoefficients(); + onProbeBakingChanged(_scene); +} + void LightProbeInfo::clearSHCoefficients() { if (!_data) { return; @@ -293,6 +303,19 @@ void LightProbeInfo::update(bool updateTet) { } } +void LightProbeInfo::onProbeBakingChanged(Node *node) { // NOLINT(misc-no-recursion) + if (!node) { + return; + } + + node->emit(); + + const auto &children = node->getChildren(); + for (const auto &child: children) { + onProbeBakingChanged(child); + } +} + void LightProbeInfo::clearAllSHUBOs() { if (!_scene) { return; diff --git a/native/cocos/gi/light-probe/LightProbe.h b/native/cocos/gi/light-probe/LightProbe.h index bfb76e3dd9..349783387c 100644 --- a/native/cocos/gi/light-probe/LightProbe.h +++ b/native/cocos/gi/light-probe/LightProbe.h @@ -59,11 +59,11 @@ public: void updateProbes(ccstd::vector &points); void updateTetrahedrons(); + inline bool hasCoefficients() const { return !empty() && !_probes[0].coefficients.empty(); } bool getInterpolationSHCoefficients(int32_t tetIndex, const Vec4 &weights, ccstd::vector &coefficients) const; int32_t getInterpolationWeights(const Vec3 &position, int32_t tetIndex, Vec4 &weights) const; private: - inline bool hasCoefficients() const { return !empty() && !_probes[0].coefficients.empty(); } static Vec3 getTriangleBarycentricCoord(const Vec3 &p0, const Vec3 &p1, const Vec3 &p2, const Vec3 &position); void getBarycentricCoord(const Vec3 &position, const Tetrahedron &tetrahedron, Vec4 &weights) const; void getTetrahedronBarycentricCoord(const Vec3 &position, const Tetrahedron &tetrahedron, Vec4 &weights) const; @@ -137,6 +137,8 @@ public: ~LightProbeInfo() override = default; void activate(Scene *scene, LightProbes *resource); + void onProbeBakeFinished(); + void onProbeBakeCleared(); void clearSHCoefficients(); inline bool isUniqueNode() const { return _nodes.size() == 1; } bool addNode(Node *node); @@ -248,6 +250,7 @@ public: IntrusivePtr _data; private: + void onProbeBakingChanged(Node *node); void clearAllSHUBOs(); void resetAllTetraIndices(); diff --git a/native/cocos/math/Mat4.cpp b/native/cocos/math/Mat4.cpp index f31cbd4d88..4dbd1d604f 100644 --- a/native/cocos/math/Mat4.cpp +++ b/native/cocos/math/Mat4.cpp @@ -557,7 +557,7 @@ bool Mat4::decompose(Vec3 *scale, Quaternion *rotation, Vec3 *translation) const // In this case, we simply negate a single axis of the scale. float det = determinant(); if (det < 0) { - scaleZ = -scaleZ; + scaleX = -scaleX; } if (scale) { @@ -595,10 +595,10 @@ bool Mat4::decompose(Vec3 *scale, Quaternion *rotation, Vec3 *translation) const zaxis.z *= rn; // Now calculate the rotation from the resulting matrix (axes). - float trace = xaxis.x + yaxis.y + zaxis.z + 1.0F; + float trace = xaxis.x + yaxis.y + zaxis.z; - if (trace > MATH_EPSILON) { - float s = 0.5F / std::sqrt(trace); + if (trace > 0.0F) { + float s = 0.5F / std::sqrt(trace + 1.0F); rotation->w = 0.25F / s; rotation->x = (yaxis.z - zaxis.y) * s; rotation->y = (zaxis.x - xaxis.z) * s; diff --git a/native/cocos/platform/android/java/src/com/cocos/lib/CanvasRenderingContext2DImpl.java b/native/cocos/platform/android/java/src/com/cocos/lib/CanvasRenderingContext2DImpl.java index 7701ab4b6b..b6a0fe3a40 100644 --- a/native/cocos/platform/android/java/src/com/cocos/lib/CanvasRenderingContext2DImpl.java +++ b/native/cocos/platform/android/java/src/com/cocos/lib/CanvasRenderingContext2DImpl.java @@ -416,9 +416,13 @@ public class CanvasRenderingContext2DImpl { } private void configShadow(Paint paint) { - if (mShadowColorA > 0 && (Math.abs(mShadowOffsetX) > Float.MIN_VALUE || - Math.abs(mShadowOffsetY) > Float.MIN_VALUE || - mShadowBlur > Float.MIN_VALUE)) { + if (mShadowColorA > 0 && (Math.abs(mShadowOffsetX) > Float.MIN_VALUE || Math.abs(mShadowOffsetY) > Float.MIN_VALUE)) { + if (mShadowBlur < 0) { + return; + } + if (mShadowBlur < Float.MIN_VALUE) { + mShadowBlur = 0.001f;//If shadowBlur is 0, the shadow effect is not consistent with the web. + } paint.setShadowLayer(mShadowBlur, mShadowOffsetX, mShadowOffsetY, Color.argb(mShadowColorA, mShadowColorR, mShadowColorG, mShadowColorB)); } diff --git a/native/cocos/platform/android/java/src/com/cocos/lib/CocosEditBoxActivity.java b/native/cocos/platform/android/java/src/com/cocos/lib/CocosEditBoxActivity.java index 993f921be7..03b45ddddd 100644 --- a/native/cocos/platform/android/java/src/com/cocos/lib/CocosEditBoxActivity.java +++ b/native/cocos/platform/android/java/src/com/cocos/lib/CocosEditBoxActivity.java @@ -25,7 +25,9 @@ THE SOFTWARE. ****************************************************************************/ package com.cocos.lib; +import android.app.Activity; import android.content.Context; +import android.content.Intent; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; @@ -34,6 +36,7 @@ import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.shapes.RoundRectShape; +import android.os.Build; import android.os.Bundle; import android.text.Editable; import android.text.InputFilter; @@ -52,8 +55,7 @@ import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; -import android.app.Activity; -import android.content.Intent; +import android.widget.Toast; public class CocosEditBoxActivity extends Activity { @@ -83,6 +85,7 @@ public class CocosEditBoxActivity extends Activity { private float mLineWidth = 2f; private boolean keyboardVisible = false; private int mScreenHeight; + private boolean mCheckKeyboardShowNormally = false; public Cocos2dxEditText(Activity context){ super(context); @@ -185,6 +188,7 @@ public class CocosEditBoxActivity extends Activity { } private void setInputType(final String inputType, boolean isMultiLine){ + mCheckKeyboardShowNormally = false; if (inputType.contentEquals("text")) { if (isMultiLine) this.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE); @@ -197,8 +201,12 @@ public class CocosEditBoxActivity extends Activity { this.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); else if (inputType.contentEquals("phone")) this.setInputType(InputType.TYPE_CLASS_PHONE); - else if (inputType.contentEquals("password")) + else if (inputType.contentEquals("password")) { + if (Build.BRAND.equalsIgnoreCase("oppo")) { + mCheckKeyboardShowNormally = true; + } this.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + } else Log.e(TAG, "unknown input type " + inputType); } @@ -238,6 +246,9 @@ public class CocosEditBoxActivity extends Activity { keyboardVisible = true; } } else { + if (mCheckKeyboardShowNormally && !keyboardVisible) { + Toast.makeText(CocosEditBoxActivity.this, R.string.tip_disable_safe_input_type, Toast.LENGTH_SHORT).show(); + } if (keyboardVisible) { keyboardVisible = false; CocosEditBoxActivity.this.hide(); diff --git a/native/cocos/platform/android/libcocos2dx/src/main/res/values-zh-rCN/strings.xml b/native/cocos/platform/android/libcocos2dx/src/main/res/values-zh-rCN/strings.xml index 200317c177..0c0c2641ee 100644 --- a/native/cocos/platform/android/libcocos2dx/src/main/res/values-zh-rCN/strings.xml +++ b/native/cocos/platform/android/libcocos2dx/src/main/res/values-zh-rCN/strings.xml @@ -6,4 +6,5 @@ 搜索 前往 发送 + 请到系统设置关闭安全键盘 diff --git a/native/cocos/platform/android/libcocos2dx/src/main/res/values/strings.xml b/native/cocos/platform/android/libcocos2dx/src/main/res/values/strings.xml index d2a347be8d..97d607395f 100644 --- a/native/cocos/platform/android/libcocos2dx/src/main/res/values/strings.xml +++ b/native/cocos/platform/android/libcocos2dx/src/main/res/values/strings.xml @@ -6,4 +6,5 @@ Search Go Send + Please go to the system settings to turn off the security keyboard! diff --git a/native/cocos/platform/android/libcocosxr/src/com/cocos/lib/xr/CocosXRGLHelper.java b/native/cocos/platform/android/libcocosxr/src/com/cocos/lib/xr/CocosXRGLHelper.java index 6a79be134f..4bfabb184d 100644 --- a/native/cocos/platform/android/libcocosxr/src/com/cocos/lib/xr/CocosXRGLHelper.java +++ b/native/cocos/platform/android/libcocosxr/src/com/cocos/lib/xr/CocosXRGLHelper.java @@ -145,10 +145,10 @@ public class CocosXRGLHelper { + "precision mediump float; \n" + "in vec2 texCoord; \n" + "uniform samplerExternalOES texSampler2D; \n" - + "out vec4 gl_FragColor;\n" + + "out vec4 frag_color;\n" + "void main() \n" + "{ \n" - + " gl_FragColor = texture(texSampler2D, texCoord); \n" + + " frag_color = texture(texSampler2D, texCoord); \n" + "}"; float[] orthoQuadVertices = { -1.0f, -1.0f, 0.0f, 1.0f, diff --git a/native/cocos/platform/android/libcocosxr/src/com/cocos/lib/xr/CocosXRVideoManager.java b/native/cocos/platform/android/libcocosxr/src/com/cocos/lib/xr/CocosXRVideoManager.java index 6610cde6d7..640213c333 100644 --- a/native/cocos/platform/android/libcocosxr/src/com/cocos/lib/xr/CocosXRVideoManager.java +++ b/native/cocos/platform/android/libcocosxr/src/com/cocos/lib/xr/CocosXRVideoManager.java @@ -421,6 +421,7 @@ public class CocosXRVideoManager { for (Map.Entry entrySet : entrySets) { entrySet.getValue().onGLDestroy(); } + GLES30.glDeleteFramebuffers(1, new int[] {renderTargetFboId}, 0); EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT); EGL14.eglDestroySurface(eglDisplay, pBufferSurface); EGL14.eglDestroyContext(eglDisplay, eglContext); diff --git a/native/cocos/platform/ios/modules/Battery.mm b/native/cocos/platform/ios/modules/Battery.mm index 2ae8f139ff..0228ee2397 100644 --- a/native/cocos/platform/ios/modules/Battery.mm +++ b/native/cocos/platform/ios/modules/Battery.mm @@ -29,6 +29,8 @@ namespace cc { float Battery::getBatteryLevel() const { + // set batteryMonitoringEnabled value to YES otherwise batteryLevel is always -1 + [UIDevice currentDevice].batteryMonitoringEnabled = YES; return [UIDevice currentDevice].batteryLevel; } diff --git a/native/cocos/platform/mac/View.mm b/native/cocos/platform/mac/View.mm index 530da12820..b7ebaf897d 100644 --- a/native/cocos/platform/mac/View.mm +++ b/native/cocos/platform/mac/View.mm @@ -268,14 +268,46 @@ } - (void)sendMouseEvent:(int)button type:(cc::MouseEvent::Type)type event:(NSEvent *)event { - const NSRect contentRect = [self frame]; - const NSPoint pos = [event locationInWindow]; - _mouseEvent.windowId = [self getWindowId]; _mouseEvent.type = type; _mouseEvent.button = button; - _mouseEvent.x = pos.x; - _mouseEvent.y = contentRect.size.height - pos.y; + + auto *windowMgr = CC_GET_PLATFORM_INTERFACE(cc::SystemWindowManager); + auto *window = static_cast( windowMgr->getWindowFromNSWindow([self window])); + const NSRect contentRect = [self frame]; + if(!window->isPointerLock()) { + const NSPoint pos = [event locationInWindow]; + _mouseEvent.x = pos.x; + _mouseEvent.y = contentRect.size.height - pos.y; + } else { + if(type == cc::MouseEvent::Type::MOVE) { + // Out of window only happens when mouse is moved. + _mouseEvent.x = _mouseEvent.x + [event deltaX]; + _mouseEvent.y = _mouseEvent.y + [event deltaY]; + float xMin = 0, xMax = 0; + float yMin = 0, yMax = 0; + xMax = contentRect.size.width; + yMax = contentRect.size.height; + --xMax; + --yMax; + if (_mouseEvent.x > xMax) { + _mouseEvent.x = xMax; + } else if (_mouseEvent.x < xMin) { + _mouseEvent.x = xMin; + } + + if (_mouseEvent.y > yMax) { + _mouseEvent.y = yMax; + } else if (_mouseEvent.y < yMin) { + _mouseEvent.y = yMin; + } + } + auto mainDisplayId = CGMainDisplayID(); + float windowX = contentRect.origin.x; + float windowY = + CGDisplayPixelsHigh(mainDisplayId) - contentRect.origin.y - contentRect.size.height; + window->setLastMousePos(windowX + _mouseEvent.x, windowY + _mouseEvent.y); + } cc::events::Mouse::broadcast(_mouseEvent); } - (int)getWindowId { diff --git a/native/cocos/platform/mac/modules/SystemWindow.h b/native/cocos/platform/mac/modules/SystemWindow.h index 4bc284056f..2aeb273df7 100644 --- a/native/cocos/platform/mac/modules/SystemWindow.h +++ b/native/cocos/platform/mac/modules/SystemWindow.h @@ -57,8 +57,13 @@ public: */ void setCursorEnabled(bool value) override; void copyTextToClipboard(const std::string& text) override; - + + bool isPointerLock() const; + void setLastMousePos(float x, float y); private: + bool _pointerLock{false}; + float _lastMousePosX{0.0F}; + float _lastMousePosY{0.0F}; int32_t _width{0}; int32_t _height{0}; diff --git a/native/cocos/platform/mac/modules/SystemWindow.mm b/native/cocos/platform/mac/modules/SystemWindow.mm index 7e94853cca..242325c89d 100644 --- a/native/cocos/platform/mac/modules/SystemWindow.mm +++ b/native/cocos/platform/mac/modules/SystemWindow.mm @@ -43,7 +43,9 @@ SystemWindow::SystemWindow(uint32_t windowId, void *externalHandle) } } -SystemWindow::~SystemWindow() = default; +SystemWindow::~SystemWindow() { + setCursorEnabled(true); +} bool SystemWindow::createWindow(const char *title, int w, int h, int flags) { @@ -98,6 +100,22 @@ void SystemWindow::closeWindow() { } void SystemWindow::setCursorEnabled(bool value) { + CGError result; + if(value) { + result = CGAssociateMouseAndMouseCursorPosition(YES); + [NSCursor unhide]; + if(_pointerLock) { + CGPoint point = + CGPointMake((float)_lastMousePosX, _lastMousePosY); + CGWarpMouseCursorPosition(point); + } + _pointerLock = false; + } else { + result = CGAssociateMouseAndMouseCursorPosition(NO); + [NSCursor hide]; + _pointerLock = true; + } + CC_ASSERT(result == kCGErrorSuccess); } void SystemWindow::copyTextToClipboard(const std::string &text) { @@ -120,4 +138,13 @@ uint32_t SystemWindow::getWindowId() const { return _windowId; } +bool SystemWindow::isPointerLock() const { + return _pointerLock; +} + +void SystemWindow::setLastMousePos(float x, float y) { + _lastMousePosX = x; + _lastMousePosY = y; +} + } // namespace cc diff --git a/native/cocos/renderer/core/PassInstance.cpp b/native/cocos/renderer/core/PassInstance.cpp index 4a8cce8739..8c4e157e8e 100644 --- a/native/cocos/renderer/core/PassInstance.cpp +++ b/native/cocos/renderer/core/PassInstance.cpp @@ -1,8 +1,8 @@ /**************************************************************************** Copyright (c) 2021-2023 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 documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to @@ -22,16 +22,17 @@ THE SOFTWARE. ****************************************************************************/ -#include "renderer/core/PassInstance.h" -#include -#include "renderer/core/MaterialInstance.h" -#include "renderer/core/ProgramLib.h" -#include "renderer/pipeline/BatchedBuffer.h" -#include "renderer/pipeline/InstancedBuffer.h" +#include "cocos/renderer/core/PassInstance.h" +#include "cocos/renderer/core/MaterialInstance.h" +#include "cocos/renderer/core/ProgramLib.h" +#include "cocos/renderer/pipeline/BatchedBuffer.h" +#include "cocos/renderer/pipeline/InstancedBuffer.h" +#include "cocos/renderer/pipeline/custom/RenderingModule.h" namespace cc { -PassInstance::PassInstance(scene::Pass *parent, MaterialInstance *owner) : Super(parent->getRoot()), _parent(parent), _owner(owner) { +PassInstance::PassInstance(scene::Pass *parent, MaterialInstance *owner) +: Super(parent->getRoot()), _parent(parent), _owner(owner) { doInit(_parent->getPassInfoFull()); for (const auto &b : _shaderInfo->blocks) { scene::IBlockRef &block = _blocks[b.binding]; @@ -42,14 +43,30 @@ PassInstance::PassInstance(scene::Pass *parent, MaterialInstance *owner) : Super _rootBufferDirty = true; gfx::DescriptorSet *parentDescriptorSet = _parent->getDescriptorSet(); - for (const auto &samplerTexture : _shaderInfo->samplerTextures) { - for (uint32_t i = 0; i < samplerTexture.count; ++i) { - auto *sampler = parentDescriptorSet->getSampler(samplerTexture.binding, i); - auto *texture = parentDescriptorSet->getTexture(samplerTexture.binding, i); - _descriptorSet->bindSampler(samplerTexture.binding, sampler, i); - _descriptorSet->bindTexture(samplerTexture.binding, texture, i); + + auto *programLib = render::getProgramLibrary(); + if (programLib) { + const auto &set = _shaderInfo->descriptors.at( + static_cast(pipeline::SetIndex::MATERIAL)); + for (const auto &samplerTexture : set.samplerTextures) { + for (uint32_t i = 0; i < samplerTexture.count; ++i) { + auto *sampler = parentDescriptorSet->getSampler(samplerTexture.binding, i); + auto *texture = parentDescriptorSet->getTexture(samplerTexture.binding, i); + _descriptorSet->bindSampler(samplerTexture.binding, sampler, i); + _descriptorSet->bindTexture(samplerTexture.binding, texture, i); + } + } + } else { + for (const auto &samplerTexture : _shaderInfo->samplerTextures) { + for (uint32_t i = 0; i < samplerTexture.count; ++i) { + auto *sampler = parentDescriptorSet->getSampler(samplerTexture.binding, i); + auto *texture = parentDescriptorSet->getTexture(samplerTexture.binding, i); + _descriptorSet->bindSampler(samplerTexture.binding, sampler, i); + _descriptorSet->bindTexture(samplerTexture.binding, texture, i); + } } } + Super::tryCompile(); } diff --git a/native/cocos/renderer/core/ProgramLib.cpp b/native/cocos/renderer/core/ProgramLib.cpp index 4fef1f3ed4..36097092d4 100644 --- a/native/cocos/renderer/core/ProgramLib.cpp +++ b/native/cocos/renderer/core/ProgramLib.cpp @@ -37,47 +37,6 @@ namespace cc { namespace { -ccstd::string mapDefine(const IDefineInfo &info, const ccstd::optional &def) { - if (info.type == "boolean") { - return def.has_value() ? (macroRecordAsBool(def.value()) ? "1" : "0") : "0"; - } - if (info.type == "string") { - return def.has_value() ? macroRecordAsString(def.value()) : info.options.value()[0]; - } - if (info.type == "number") { - return def.has_value() ? macroRecordAsString(def.value()) : std::to_string(info.range.value()[0]); - } - CC_LOG_WARNING("unknown define type '%s', name: %s", info.type.c_str(), info.name.c_str()); - return "-1"; // should neven happen -} - -ccstd::vector prepareDefines(const MacroRecord &records, const ccstd::vector &defList) { - ccstd::vector macros{}; - for (const auto &tmp : defList) { - const auto &name = tmp.name; - auto it = records.find(name); - auto value = mapDefine(tmp, it == records.end() ? ccstd::nullopt : ccstd::optional(it->second)); - bool isDefault = it == records.end() || (ccstd::holds_alternative(it->second) && ccstd::get(it->second) == "0"); - macros.emplace_back(); - auto &info = macros.back(); - info.name = name; - info.value = value; - info.isDefault = isDefault; - } - return macros; -} - -ccstd::string getShaderInstanceName(const ccstd::string &name, const ccstd::vector ¯os) { - std::stringstream ret; - ret << name; - for (const auto &cur : macros) { - if (!cur.isDefault) { - ret << "|" << cur.name << cur.value; - } - } - return ret.str(); -} - void insertBuiltinBindings(const IProgramInfo &tmpl, ITemplateInfo &tmplInfo, const pipeline::DescriptorSetLayoutInfos &source, const ccstd::string &type, ccstd::vector *outBindings) { CC_ASSERT(type == "locals" || type == "globals"); @@ -144,32 +103,6 @@ int32_t getSize(const IBlockInfo &block) { return s; } -bool dependencyCheck(const ccstd::vector &dependencies, const MacroRecord &defines) { - for (const auto &d : dependencies) { // NOLINT(readability-use-anyofallof) - if (d[0] == '!') { // negative dependency - if (defines.find(d.substr(1)) != defines.end()) { - return false; - } - } else if (defines.count(d) == 0 ? true : !macroRecordAsBool(defines.at(d))) { - return false; - } - } - return true; -} - -ccstd::vector getActiveAttributes(const IProgramInfo &tmpl, const ITemplateInfo &tmplInfo, const MacroRecord &defines) { - ccstd::vector out{}; - const auto &attributes = tmpl.attributes; - const auto &gfxAttributes = tmplInfo.gfxAttributes; - for (auto i = 0; i < attributes.size(); i++) { - if (!dependencyCheck(attributes[i].defines, defines)) { - continue; - } - out.emplace_back(gfxAttributes[i]); - } - return out; -} - } // namespace const char *getDeviceShaderVersion(const gfx::Device *device) { @@ -214,6 +147,7 @@ void IProgramInfo::copyFrom(const IShaderInfo &o) { buffers = o.buffers; images = o.images; subpassInputs = o.subpassInputs; + descriptors = o.descriptors; } ProgramLib::ProgramLib() { @@ -245,15 +179,7 @@ void ProgramLib::registerEffect(EffectAsset *effect) { auto *tmpl = define(shader); tmpl->effectName = effect->getName(); } - - for (auto &tech : effect->_techniques) { - for (auto &pass : tech.passes) { - // grab default property declaration if there is none - if (pass.propertyIndex.has_value() && !pass.properties.has_value()) { - pass.properties = tech.passes[pass.propertyIndex.value()].properties; - } - } - } + render::addEffectDefaultProperties(*effect); } IProgramInfo *ProgramLib::define(IShaderInfo &shader) { @@ -429,7 +355,7 @@ IProgramInfo *ProgramLib::define(IShaderInfo &shader) { * @param name Target shader name */ -IProgramInfo *ProgramLib::getTemplate(const ccstd::string &name) { +const IProgramInfo *ProgramLib::getTemplate(const ccstd::string &name) const { auto it = _templates.find(name); return it != _templates.end() ? &it->second : nullptr; } @@ -540,7 +466,7 @@ gfx::Shader *ProgramLib::getGFXShader(gfx::Device *device, const ccstd::string & tmplInfo.pipelineLayout = device->createPipelineLayout(gfx::PipelineLayoutInfo{tmplInfo.setLayouts.get()}); } - ccstd::vector macroArray = prepareDefines(defines, tmpl.defines); + ccstd::vector macroArray = render::prepareDefines(defines, tmpl.defines); std::stringstream ss; ss << std::endl; for (const auto &m : macroArray) { @@ -559,9 +485,9 @@ gfx::Shader *ProgramLib::getGFXShader(gfx::Device *device, const ccstd::string & tmplInfo.shaderInfo.stages[1].source = prefix + src->frag; // strip out the active attributes only, instancing depend on this - tmplInfo.shaderInfo.attributes = getActiveAttributes(tmpl, tmplInfo, defines); + tmplInfo.shaderInfo.attributes = render::getActiveAttributes(tmpl, tmplInfo.gfxAttributes, defines); - tmplInfo.shaderInfo.name = getShaderInstanceName(name, macroArray); + tmplInfo.shaderInfo.name = render::getShaderInstanceName(name, macroArray); auto *shader = device->createShader(tmplInfo.shaderInfo); _cache[key] = shader; diff --git a/native/cocos/renderer/core/ProgramLib.h b/native/cocos/renderer/core/ProgramLib.h index 08756da5bb..c6b60569ec 100644 --- a/native/cocos/renderer/core/ProgramLib.h +++ b/native/cocos/renderer/core/ProgramLib.h @@ -101,7 +101,7 @@ public: * @param name Target shader name */ - IProgramInfo *getTemplate(const ccstd::string &name); + const IProgramInfo *getTemplate(const ccstd::string &name) const; /** * @en Gets the shader template info with its name diff --git a/native/cocos/renderer/core/ProgramUtils.cpp b/native/cocos/renderer/core/ProgramUtils.cpp index baffa4d8ae..d218d3fd55 100644 --- a/native/cocos/renderer/core/ProgramUtils.cpp +++ b/native/cocos/renderer/core/ProgramUtils.cpp @@ -163,6 +163,102 @@ ccstd::string getVariantKey(const IProgramInfo &tmpl, const MacroRecord &defines return ret; } +namespace { + +ccstd::string mapDefine(const IDefineInfo &info, const ccstd::optional &def) { + if (info.type == "boolean") { + return def.has_value() ? (macroRecordAsBool(def.value()) ? "1" : "0") : "0"; + } + if (info.type == "string") { + return def.has_value() ? macroRecordAsString(def.value()) : info.options.value()[0]; + } + if (info.type == "number") { + return def.has_value() ? macroRecordAsString(def.value()) : std::to_string(info.range.value()[0]); + } + CC_LOG_WARNING("unknown define type '%s', name: %s", info.type.c_str(), info.name.c_str()); + return "-1"; // should neven happen +} + +bool dependencyCheck(const ccstd::vector &dependencies, const MacroRecord &defines) { + for (const auto &d : dependencies) { // NOLINT(readability-use-anyofallof) + if (d[0] == '!') { // negative dependency + if (defines.find(d.substr(1)) != defines.end()) { + return false; + } + } else if (defines.count(d) == 0 ? true : !macroRecordAsBool(defines.at(d))) { + return false; + } + } + return true; +} + +template +ccstd::vector getActiveAttributesImpl( + const IProgramInfo &tmpl, + const Vector &gfxAttributes, const MacroRecord &defines) { + ccstd::vector out{}; + const auto &attributes = tmpl.attributes; + for (auto i = 0; i < attributes.size(); i++) { + if (!dependencyCheck(attributes[i].defines, defines)) { + continue; + } + out.emplace_back(gfxAttributes[i]); + } + return out; +} + +} // namespace + +ccstd::vector prepareDefines(const MacroRecord &records, const ccstd::vector &defList) { + ccstd::vector macros{}; + for (const auto &tmp : defList) { + const auto &name = tmp.name; + auto it = records.find(name); + auto value = mapDefine(tmp, it == records.end() ? ccstd::nullopt : ccstd::optional(it->second)); + bool isDefault = it == records.end() || (ccstd::holds_alternative(it->second) && ccstd::get(it->second) == "0"); + macros.emplace_back(); + auto &info = macros.back(); + info.name = name; + info.value = value; + info.isDefault = isDefault; + } + return macros; +} + +ccstd::vector getActiveAttributes( + const IProgramInfo &tmpl, + const ccstd::vector &gfxAttributes, const MacroRecord &defines) { + return getActiveAttributesImpl(tmpl, gfxAttributes, defines); +} + +ccstd::vector getActiveAttributes( + const IProgramInfo &tmpl, + const ccstd::pmr::vector &gfxAttributes, const MacroRecord &defines) { + return getActiveAttributesImpl(tmpl, gfxAttributes, defines); +} + +ccstd::string getShaderInstanceName(const ccstd::string &name, const ccstd::vector ¯os) { + std::stringstream ret; + ret << name; + for (const auto &cur : macros) { + if (!cur.isDefault) { + ret << "|" << cur.name << cur.value; + } + } + return ret.str(); +} + +void addEffectDefaultProperties(EffectAsset &effect) { + for (auto &tech : effect._techniques) { + for (auto &pass : tech.passes) { + // grab default property declaration if there is none + if (pass.propertyIndex.has_value() && !pass.properties.has_value()) { + pass.properties = tech.passes[pass.propertyIndex.value()].properties; + } + } + } +} + } // namespace render } // namespace cc diff --git a/native/cocos/renderer/core/ProgramUtils.h b/native/cocos/renderer/core/ProgramUtils.h index 74056194b2..e7f3402632 100644 --- a/native/cocos/renderer/core/ProgramUtils.h +++ b/native/cocos/renderer/core/ProgramUtils.h @@ -34,6 +34,21 @@ void populateMacros(IProgramInfo& tmpl); ccstd::unordered_map genHandles(const IProgramInfo& tmpl); ccstd::unordered_map genHandles(const gfx::ShaderInfo& tmpl); ccstd::string getVariantKey(const IProgramInfo& tmpl, const MacroRecord& defines); +ccstd::vector prepareDefines( + const MacroRecord& records, const ccstd::vector& defList); + +ccstd::vector getActiveAttributes( + const IProgramInfo& tmpl, + const ccstd::vector& gfxAttributes, const MacroRecord& defines); + +ccstd::vector getActiveAttributes( + const IProgramInfo& tmpl, + const ccstd::pmr::vector& gfxAttributes, const MacroRecord& defines); + +ccstd::string getShaderInstanceName( + const ccstd::string& name, const ccstd::vector& macros); + +void addEffectDefaultProperties(EffectAsset& effect); } // namespace render diff --git a/native/cocos/renderer/gfx-agent/DescriptorSetAgent.cpp b/native/cocos/renderer/gfx-agent/DescriptorSetAgent.cpp index 3eac95852e..48ba863ddb 100644 --- a/native/cocos/renderer/gfx-agent/DescriptorSetAgent.cpp +++ b/native/cocos/renderer/gfx-agent/DescriptorSetAgent.cpp @@ -50,7 +50,7 @@ DescriptorSetAgent::~DescriptorSetAgent() { void DescriptorSetAgent::doInit(const DescriptorSetInfo &info) { DescriptorSetInfo actorInfo; - actorInfo.layout = static_cast(info.layout)->getActor(); + actorInfo.layout = static_cast(info.layout)->getActor(); ENQUEUE_MESSAGE_2( DeviceAgent::getInstance()->getMessageQueue(), diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index b9254f1439..0070ce8b88 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -1419,7 +1419,7 @@ struct DescriptorSetLayoutInfo { }; struct DescriptorSetInfo { - DescriptorSetLayout *layout{nullptr}; + const DescriptorSetLayout *layout{nullptr}; EXPOSE_COPY_FN(DescriptorSetInfo) }; diff --git a/native/cocos/renderer/gfx-base/GFXDescriptorSet.h b/native/cocos/renderer/gfx-base/GFXDescriptorSet.h index 90f37b4ebe..f0f213ad6e 100644 --- a/native/cocos/renderer/gfx-base/GFXDescriptorSet.h +++ b/native/cocos/renderer/gfx-base/GFXDescriptorSet.h @@ -54,7 +54,7 @@ public: Texture *getTexture(uint32_t binding, uint32_t index) const; Sampler *getSampler(uint32_t binding, uint32_t index) const; - inline DescriptorSetLayout *getLayout() const { return _layout; } + inline const 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); } @@ -73,7 +73,7 @@ protected: uint32_t id = INVALID_OBJECT_ID; }; - DescriptorSetLayout *_layout = nullptr; + const DescriptorSetLayout *_layout = nullptr; ccstd::vector> _buffers; ccstd::vector> _textures; ccstd::vector> _samplers; diff --git a/native/cocos/renderer/gfx-base/GFXDevice.cpp b/native/cocos/renderer/gfx-base/GFXDevice.cpp index 8a63f30b56..148d1ece8c 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.cpp +++ b/native/cocos/renderer/gfx-base/GFXDevice.cpp @@ -158,14 +158,6 @@ DefaultResource::DefaultResource(Device *device) { BufferTextureCopy region = {0, 0, 0, {0, 0, 0}, {2, 2, 2}, {0, 0, 1}}; device->copyBuffersToTexture(&bufferData, _texture3D, ®ion, 1); } - if (device->getCapabilities().maxArrayTextureLayers >= 2) { - _texture1DArray = device->createTexture({TextureType::TEX1D_ARRAY, TextureUsageBit::STORAGE | TextureUsageBit::SAMPLED, - Format::RGBA8, 1, 1, TextureFlagBit::NONE, 2}); - BufferTextureCopy region = {0, 0, 0, {0, 0, 0}, {1, 1, 1}, {0, 0, 1}}; - device->copyBuffersToTexture(&bufferData, _texture1DArray, ®ion, 1); - region.texSubres.baseArrayLayer = 1; - device->copyBuffersToTexture(&bufferData, _texture1DArray, ®ion, 1); - } if (device->getCapabilities().maxArrayTextureLayers >= 2) { _texture2DArray = device->createTexture({TextureType::TEX2D_ARRAY, TextureUsageBit::STORAGE | TextureUsageBit::SAMPLED, Format::RGBA8, 2, 2, TextureFlagBit::NONE, 2}); @@ -176,7 +168,7 @@ DefaultResource::DefaultResource(Device *device) { } } -const Texture *DefaultResource::getTexture(TextureType type) const { +Texture *DefaultResource::getTexture(TextureType type) const { switch (type) { case TextureType::TEX2D: return _texture2D; @@ -184,8 +176,6 @@ const Texture *DefaultResource::getTexture(TextureType type) const { return _textureCube; case TextureType::TEX3D: return _texture3D; - case TextureType::TEX1D_ARRAY: - return _texture1DArray; case TextureType::TEX2D_ARRAY: return _texture2DArray; default: diff --git a/native/cocos/renderer/gfx-base/GFXDevice.h b/native/cocos/renderer/gfx-base/GFXDevice.h index dffb018ee5..5c993f72fa 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.h +++ b/native/cocos/renderer/gfx-base/GFXDevice.h @@ -196,12 +196,10 @@ public: ~DefaultResource() = default; - const Texture *getTexture(TextureType type) const; + Texture *getTexture(TextureType type) const; private: - IntrusivePtr _texture1D; IntrusivePtr _texture2D; - IntrusivePtr _texture1DArray; IntrusivePtr _texture2DArray; IntrusivePtr _textureCube; IntrusivePtr _texture3D; diff --git a/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.cpp b/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.cpp index a6a83dec4e..55b99ec13e 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.cpp @@ -43,7 +43,7 @@ GLES2DescriptorSet::~GLES2DescriptorSet() { } void GLES2DescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { - const GLES2GPUDescriptorSetLayout *gpuDescriptorSetLayout = static_cast(_layout)->gpuDescriptorSetLayout(); + const GLES2GPUDescriptorSetLayout *gpuDescriptorSetLayout = static_cast(_layout)->gpuDescriptorSetLayout(); const size_t descriptorCount = gpuDescriptorSetLayout->descriptorCount; const size_t bindingCount = gpuDescriptorSetLayout->bindings.size(); diff --git a/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.cpp b/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.cpp index ed76b77062..bc9128083f 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.cpp @@ -44,7 +44,7 @@ GLES3DescriptorSet::~GLES3DescriptorSet() { } void GLES3DescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { - const GLES3GPUDescriptorSetLayout *gpuDescriptorSetLayout = static_cast(_layout)->gpuDescriptorSetLayout(); + const GLES3GPUDescriptorSetLayout *gpuDescriptorSetLayout = static_cast(_layout)->gpuDescriptorSetLayout(); const size_t descriptorCount = gpuDescriptorSetLayout->descriptorCount; const size_t bindingCount = gpuDescriptorSetLayout->bindings.size(); diff --git a/native/cocos/renderer/gfx-metal/MTLBuffer.mm b/native/cocos/renderer/gfx-metal/MTLBuffer.mm index d9e618c290..f8cc2e2cbc 100644 --- a/native/cocos/renderer/gfx-metal/MTLBuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLBuffer.mm @@ -29,6 +29,7 @@ #include "MTLBuffer.h" #include "MTLCommandBuffer.h" #include "MTLDevice.h" +#include "MTLQueue.h" #include "MTLRenderCommandEncoder.h" #include "MTLUtils.h" #include "MTLGPUObjects.h" @@ -245,14 +246,7 @@ void CCMTLBuffer::update(const void *buffer, uint32_t size) { void CCMTLBuffer::updateMTLBuffer(const void *buffer, uint32_t /*offset*/, uint32_t size) { if (_gpuBuffer->mtlBuffer) { - CommandBuffer *cmdBuffer = CCMTLDevice::getInstance()->getCommandBuffer(); - cmdBuffer->begin(); - static_cast(cmdBuffer)->updateBuffer(this, buffer, size); -#if (CC_PLATFORM == CC_PLATFORM_MACOS) - if (_mtlResourceOptions == MTLResourceStorageModeManaged) { - [_gpuBuffer->mtlBuffer didModifyRange:NSMakeRange(0, _size)]; // Synchronize the managed buffer. - } -#endif + CCMTLDevice::getInstance()->writeBuffer(this, buffer, size); } } diff --git a/native/cocos/renderer/gfx-metal/MTLDescriptorSet.mm b/native/cocos/renderer/gfx-metal/MTLDescriptorSet.mm index 3452e23b25..1364da5db8 100644 --- a/native/cocos/renderer/gfx-metal/MTLDescriptorSet.mm +++ b/native/cocos/renderer/gfx-metal/MTLDescriptorSet.mm @@ -37,7 +37,7 @@ CCMTLDescriptorSet::CCMTLDescriptorSet() : DescriptorSet() { } void CCMTLDescriptorSet::doInit(const DescriptorSetInfo &info) { - const auto gpuDescriptorSetLayout = static_cast(_layout)->gpuDescriptorSetLayout(); + const auto gpuDescriptorSetLayout = static_cast(_layout)->gpuDescriptorSetLayout(); const auto descriptorCount = gpuDescriptorSetLayout->descriptorCount; const auto bindingCount = gpuDescriptorSetLayout->bindings.size(); diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.h b/native/cocos/renderer/gfx-metal/MTLDevice.h index 9aa87cabf9..5a28c9f6d2 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.h +++ b/native/cocos/renderer/gfx-metal/MTLDevice.h @@ -87,6 +87,10 @@ public: } } + CommandBuffer *transferCommandBuffer() const; + + void writeBuffer(Buffer *buffer, const void *data, uint32_t size); + protected: static CCMTLDevice *_instance; @@ -134,6 +138,7 @@ protected: ccstd::vector _swapchains; CCMTLGPUDeviceObject *_gpuDeviceObj = nullptr; + uint8_t _inFlightCount = 0; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index 13cc233ca6..b9d0af2ddd 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -73,6 +73,7 @@ CCMTLDevice::~CCMTLDevice() { bool CCMTLDevice::doInit(const DeviceInfo &info) { _gpuDeviceObj = ccnew CCMTLGPUDeviceObject; + _inFlightSemaphore = ccnew CCMTLSemaphore(3); _currentFrameIndex = 0; @@ -142,6 +143,11 @@ bool CCMTLDevice::doInit(const DeviceInfo &info) { QueryPoolInfo queryPoolInfo{QueryType::OCCLUSION, DEFAULT_MAX_QUERY_OBJECTS, true}; _queryPool = createQueryPool(queryPoolInfo); + + CommandBufferInfo transferCmdBuffInfo; + transferCmdBuffInfo.type = CommandBufferType::PRIMARY; + transferCmdBuffInfo.queue = _queue; + _gpuDeviceObj->_transferCmdBuffer = static_cast(createCommandBuffer(transferCmdBuffInfo)); CommandBufferInfo cmdBuffInfo; cmdBuffInfo.type = CommandBufferType::PRIMARY; @@ -157,6 +163,7 @@ bool CCMTLDevice::doInit(const DeviceInfo &info) { void CCMTLDevice::doDestroy() { + CC_SAFE_DESTROY_AND_DELETE(_gpuDeviceObj->_transferCmdBuffer); CC_SAFE_DELETE(_gpuDeviceObj); CC_SAFE_DESTROY_AND_DELETE(_queryPool) @@ -175,6 +182,7 @@ void CCMTLDevice::doDestroy() { CC_SAFE_DELETE(_gpuStagingBufferPools[i]); _gpuStagingBufferPools[i] = nullptr; } + _inFlightCount = 0; cc::gfx::mu::clearUtilResource(); @@ -224,6 +232,7 @@ void CCMTLDevice::present() { // present drawable { + ++_inFlightCount; id cmdBuffer = [queue->gpuQueueObj()->mtlCommandQueue commandBuffer]; [cmdBuffer enqueue]; @@ -247,6 +256,7 @@ void CCMTLDevice::onPresentCompleted(uint32_t index) { } } _inFlightSemaphore->signal(); + --_inFlightCount; } Queue *CCMTLDevice::createQueue() { @@ -324,6 +334,32 @@ void CCMTLDevice::copyTextureToBuffers(Texture *src, uint8_t *const *buffers, co static_cast(_cmdBuff)->copyTextureToBuffers(src, buffers, region, count); } +void CCMTLDevice::writeBuffer(Buffer* buffer, const void* data, uint32_t size) { + bool hasFrameInFlight = _inFlightCount; + auto* ccBuffer = static_cast(buffer); + id mtlBuffer = ccBuffer->getMTLBuffer(); + if(!hasFrameInFlight && mtlBuffer.storageMode != MTLStorageModePrivate) { + if(@available(macOS 10.15, *)) { + memcpy(mtlBuffer.contents, data, size); +#if (CC_PLATFORM == CC_PLATFORM_MACOS) + if (mtlBuffer.storageMode == MTLStorageModeManaged) { + [mtlBuffer didModifyRange:NSMakeRange(0, size)]; // Synchronize the managed buffer. + } +#endif + } + if(@available(iOS 11.0, *)) { + memcpy(mtlBuffer.contents, data, size); + } + } else { + CCMTLCommandBuffer* transferCmdBuffer = _gpuDeviceObj->_transferCmdBuffer; + transferCmdBuffer->updateBuffer(buffer, data, size); + } +} + +CommandBuffer* CCMTLDevice::transferCommandBuffer() const { + return _gpuDeviceObj ? _gpuDeviceObj->_transferCmdBuffer : nullptr; +} + void CCMTLDevice::getQueryPoolResults(QueryPool *queryPool) { CC_PROFILE(CCMTLDeviceGetQueryPoolResults); auto *mtlQueryPool = static_cast(queryPool); diff --git a/native/cocos/renderer/gfx-metal/MTLGPUObjects.h b/native/cocos/renderer/gfx-metal/MTLGPUObjects.h index 2ff17986a0..07f92ffff1 100644 --- a/native/cocos/renderer/gfx-metal/MTLGPUObjects.h +++ b/native/cocos/renderer/gfx-metal/MTLGPUObjects.h @@ -47,6 +47,7 @@ class CCMTLFramebuffer; class CCMTLInputAssembler; class CCMTLPipelineState; class CCMTLSemaphore; +class CCMTLCommandBuffer; namespace { constexpr size_t MegaBytesToBytes = 1024 * 1024; @@ -312,6 +313,7 @@ struct CCMTLGPUCommandBufferObject { }; struct CCMTLGPUDeviceObject { + CCMTLCommandBuffer* _transferCmdBuffer{nullptr}; }; struct CCMTLGPUQueryPool { diff --git a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm index 81af7360df..835a857142 100644 --- a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm +++ b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm @@ -145,6 +145,17 @@ bool CCMTLPipelineState::createMTLComputePipelineState() { } bool CCMTLPipelineState::createMTLDepthStencilState() { + const auto& colorAttachments = _renderPass->getColorAttachments(); + bool hasDS = std::any_of(colorAttachments.begin(), colorAttachments.end(), [](const ColorAttachment& attachemnt){ + return attachemnt.format == Format::DEPTH ||attachemnt.format == Format::DEPTH_STENCIL; + }); + hasDS |= _renderPass->getDepthStencilAttachment().format != Format::UNKNOWN; + + if(!hasDS) { + // default nil + return true; + } + MTLDepthStencilDescriptor *descriptor = [[MTLDepthStencilDescriptor alloc] init]; if (descriptor == nil) { CC_LOG_ERROR("CCMTLPipelineState: MTLDepthStencilDescriptor could not be allocated."); @@ -152,7 +163,6 @@ bool CCMTLPipelineState::createMTLDepthStencilState() { } descriptor.depthWriteEnabled = _depthStencilState.depthWrite != 0; - if (!_depthStencilState.depthTest) descriptor.depthCompareFunction = MTLCompareFunctionAlways; else diff --git a/native/cocos/renderer/gfx-metal/MTLQueue.mm b/native/cocos/renderer/gfx-metal/MTLQueue.mm index 49cfa4c250..d2f07f6cc1 100644 --- a/native/cocos/renderer/gfx-metal/MTLQueue.mm +++ b/native/cocos/renderer/gfx-metal/MTLQueue.mm @@ -73,6 +73,12 @@ void CCMTLQueue::submit(CommandBuffer *const *cmdBuffs, uint32_t count) { [mtlCmdBuffer commit]; cmdBuffer->reset(); } + CCMTLCommandBuffer* transferCmdBuffer = static_cast(CCMTLDevice::getInstance()->transferCommandBuffer()); + id mtlCmdBuffer = transferCmdBuffer->gpuCommandBufferObj()->mtlCommandBuffer; + if(mtlCmdBuffer) { + [mtlCmdBuffer commit]; + transferCmdBuffer->reset(); + } } } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.mm b/native/cocos/renderer/gfx-metal/MTLUtils.mm index 12333d0724..3d8cad6c4d 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.mm +++ b/native/cocos/renderer/gfx-metal/MTLUtils.mm @@ -404,9 +404,9 @@ CCMTLGPUPipelineState *getClearRenderPassPipelineState(CCMTLDevice *device, Rend pipelineInfo.renderPass = curPass; DepthStencilState dsState; - dsState.depthWrite = 0; - dsState.depthTest = 1; - dsState.depthFunc = ComparisonFunc::LESS_EQUAL; + dsState.depthWrite = curPass->getDepthStencilAttachment().format != Format::UNKNOWN; + dsState.depthTest = 0; + dsState.depthFunc = ComparisonFunc::ALWAYS; pipelineInfo.depthStencilState = dsState; PipelineState *pipelineState = device->createPipelineState(std::move(pipelineInfo)); @@ -1748,8 +1748,7 @@ void mu::clearRenderArea(CCMTLDevice *device, id render const auto &colorAttachments = renderPass->getColorAttachments(); const auto &depthStencilAttachment = renderPass->getDepthStencilAttachment(); - - [renderEncoder setViewport:(MTLViewport){0, 0, renderTargetWidth, renderTargetHeight}]; + [renderEncoder setViewport:(MTLViewport){0, 0, renderTargetWidth, renderTargetHeight, 0, 1}]; MTLScissorRect scissorArea = {static_cast(renderArea.x), static_cast(renderArea.y), static_cast(renderArea.width), static_cast(renderArea.height)}; #if defined(CC_DEBUG) && (CC_DEBUG > 0) scissorArea.width = MIN(scissorArea.width, renderTargetWidth - scissorArea.x); diff --git a/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp b/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp index 01196dffbd..b85bac174c 100644 --- a/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp +++ b/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp @@ -48,12 +48,12 @@ DescriptorSetValidator::~DescriptorSetValidator() { void DescriptorSetValidator::doInit(const DescriptorSetInfo &info) { CC_ASSERT(!isInited()); _inited = true; - CC_ASSERT(info.layout && static_cast(info.layout)->isInited()); + CC_ASSERT(info.layout && static_cast(info.layout)->isInited()); /////////// execute /////////// DescriptorSetInfo actorInfo; - actorInfo.layout = static_cast(info.layout)->getActor(); + actorInfo.layout = static_cast(info.layout)->getActor(); _actor->initialize(actorInfo); } diff --git a/native/cocos/renderer/gfx-validator/RenderPassValidator.cpp b/native/cocos/renderer/gfx-validator/RenderPassValidator.cpp index 439e518c96..48fcb8a7ac 100644 --- a/native/cocos/renderer/gfx-validator/RenderPassValidator.cpp +++ b/native/cocos/renderer/gfx-validator/RenderPassValidator.cpp @@ -52,17 +52,6 @@ void RenderPassValidator::doInit(const RenderPassInfo &info) { } } - for (auto &attachment : _colorAttachments) { - if (attachment.loadOp == LoadOp::LOAD && attachment.barrier->getInfo().prevAccesses == AccessFlagBit::NONE) { - // Attachment missing beginAccesses for LoadOp::LOAD. - CC_ABORT(); - } - } - if ((_depthStencilAttachment.depthLoadOp == LoadOp::LOAD || _depthStencilAttachment.stencilLoadOp == LoadOp::LOAD) && _depthStencilAttachment.barrier->getInfo().prevAccesses == AccessFlagBit::NONE) { - // Attachment missing beginAccesses for LoadOp::LOAD. - CC_ABORT(); - } - /////////// execute /////////// _actor->initialize(info); diff --git a/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp b/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp index 1821cfa9ab..727597846b 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp @@ -44,7 +44,7 @@ CCVKDescriptorSet::~CCVKDescriptorSet() { } void CCVKDescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { - CCVKGPUDescriptorSetLayout *gpuDescriptorSetLayout = static_cast(_layout)->gpuDescriptorSetLayout(); + CCVKGPUDescriptorSetLayout *gpuDescriptorSetLayout = static_cast(_layout)->gpuDescriptorSetLayout(); uint32_t bindingCount = utils::toUint(gpuDescriptorSetLayout->bindings.size()); uint32_t descriptorCount = gpuDescriptorSetLayout->descriptorCount; diff --git a/native/cocos/renderer/pipeline/DebugView.cpp b/native/cocos/renderer/pipeline/DebugView.cpp new file mode 100644 index 0000000000..33948e3753 --- /dev/null +++ b/native/cocos/renderer/pipeline/DebugView.cpp @@ -0,0 +1,67 @@ +/**************************************************************************** + Copyright (c) 2023 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 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. +****************************************************************************/ + +#include "DebugView.h" +#include "custom/RenderInterfaceTypes.h" +#include "RenderPipeline.h" +#include "core/Root.h" + +namespace cc { + +namespace pipeline { + +void DebugView::activate() { + _singleMode = DebugViewSingleType::NONE; + enableAllCompositeModeValue(true); + _lightingWithAlbedo = true; + _csmLayerColoration = false; +} + +void DebugView::updatePipeline() { + Root *root = Root::getInstance(); + auto *pipeline = root->getPipeline(); + + auto useDebugViewValue = static_cast(getType()); + + bool valueChanged = false; + auto iter = pipeline->getMacros().find("CC_USE_DEBUG_VIEW"); + if (iter != pipeline->getMacros().end()) { + const MacroValue ¯oValue = iter->second; + const int32_t *macroPtr = ccstd::get_if(¯oValue); + if (macroPtr != nullptr && (*macroPtr != useDebugViewValue)) { + pipeline->setValue("CC_USE_DEBUG_VIEW", useDebugViewValue); + valueChanged = true; + } + } else { + pipeline->setValue("CC_USE_DEBUG_VIEW", useDebugViewValue); + valueChanged = true; + } + + if (valueChanged) { + root->onGlobalPipelineStateChanged(); + } +} + +} // namespace pipeline +} // namespace cc diff --git a/native/cocos/renderer/pipeline/DebugView.h b/native/cocos/renderer/pipeline/DebugView.h new file mode 100644 index 0000000000..6fb4ba027a --- /dev/null +++ b/native/cocos/renderer/pipeline/DebugView.h @@ -0,0 +1,260 @@ +/* + Copyright (c) 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. +*/ + +#pragma once +#include "base/TypeDef.h" + +namespace cc { + +namespace pipeline { + +enum class RenderingDebugViewType { + NONE, + SINGLE, + COMPOSITE_AND_MISC, +}; + +/** + * @zh + * 渲染单项调试模式 + * @en + * Rendering single debug mode + * @readonly + */ +enum class DebugViewSingleType { + NONE, + VERTEX_COLOR, + VERTEX_NORMAL, + VERTEX_TANGENT, + WORLD_POS, + VERTEX_MIRROR, + FACE_SIDE, + UV0, + UV1, + UV_LIGHTMAP, + PROJ_DEPTH, + LINEAR_DEPTH, + + FRAGMENT_NORMAL, + FRAGMENT_TANGENT, + FRAGMENT_BINORMAL, + BASE_COLOR, + DIFFUSE_COLOR, + SPECULAR_COLOR, + TRANSPARENCY, + METALLIC, + ROUGHNESS, + SPECULAR_INTENSITY, + IOR, + + DIRECT_DIFFUSE, + DIRECT_SPECULAR, + DIRECT_ALL, + ENV_DIFFUSE, + ENV_SPECULAR, + ENV_ALL, + EMISSIVE, + LIGHT_MAP, + SHADOW, + AO, + + FRESNEL, + DIRECT_TRANSMIT_DIFFUSE, + DIRECT_TRANSMIT_SPECULAR, + ENV_TRANSMIT_DIFFUSE, + ENV_TRANSMIT_SPECULAR, + TRANSMIT_ALL, + DIRECT_TRT, + ENV_TRT, + TRT_ALL, + + FOG, +}; + +/** + * @zh + * 渲染组合调试模式 + * @en + * Rendering composite debug mode + * @readonly + */ +enum class DebugViewCompositeType { + DIRECT_DIFFUSE = 0, + DIRECT_SPECULAR, + ENV_DIFFUSE, + ENV_SPECULAR, + EMISSIVE, + LIGHT_MAP, + SHADOW, + AO, + + NORMAL_MAP, + FOG, + + TONE_MAPPING, + GAMMA_CORRECTION, + + FRESNEL, + TRANSMIT_DIFFUSE, + TRANSMIT_SPECULAR, + TRT, + + MAX_BIT_COUNT +}; + +/** + * @en Rendering debug view control class + * @zh 渲染调试控制类 + */ +// @ccclass('cc.DebugView') +// @help('i18n:cc.DebugView') +class DebugView final { +public: + DebugView() { + activate(); + } + ~DebugView() = default; + + /** + * @en Toggle rendering single debug mode. + * @zh 设置渲染单项调试模式。 + */ + inline DebugViewSingleType getSingleMode() const { return _singleMode; } + inline void setSingleMode(DebugViewSingleType val) { + _singleMode = val; + updatePipeline(); + } + + /** + * @en Toggle normal / pure lighting mode. + * @zh 切换正常光照和仅光照模式。 + */ + inline bool isLightingWithAlbedo() const { return _lightingWithAlbedo; } + inline void setLightingWithAlbedo(bool val) { + _lightingWithAlbedo = val; + updatePipeline(); + } + + /** + * @en Toggle CSM layer coloration mode. + * @zh 切换级联阴影染色调试模式。 + */ + inline bool isCsmLayerColoration() const { return _csmLayerColoration; } + inline void setCsmLayerColoration(bool val) { + _csmLayerColoration = val; + updatePipeline(); + } + + /** + * @en Whether enabled with specified rendering composite debug mode. + * @zh 获取指定的渲染组合调试模式是否开启。 + * @param Specified composite type. + */ + inline bool isCompositeModeEnabled (uint32_t val) const { + uint32_t mode = _compositeModeValue & (1 << val); + return mode != 0; + } + /** + * @en Toggle specified rendering composite debug mode. + * @zh 开关指定的渲染组合调试模式。 + * @param Specified composite type, enable or disable. + */ + inline void enableCompositeMode (DebugViewCompositeType val, bool enable) { + enableCompositeModeValue(val, enable); + updatePipeline(); + } + + /** + * @en Toggle all rendering composite debug mode. + * @zh 开关所有的渲染组合调试模式。 + */ + inline void enableAllCompositeMode (bool enable) { + enableAllCompositeModeValue(enable); + updatePipeline(); + } + + /** + * @en Get rendering debug view on / off state. + * @zh 查询当前是否开启了渲染调试模式。 + */ + inline bool isEnabled() const { + return getType() != RenderingDebugViewType::NONE; + } + + /** + * @en Disable all debug view modes, reset to standard rendering mode. + * @zh 关闭所有的渲染调试模式,恢复到正常渲染。 + */ + void reset () { + activate(); + updatePipeline(); + } + +protected: + void activate(); + void updatePipeline(); + +private: + inline void enableCompositeModeValue(DebugViewCompositeType val, bool enable) { + if (enable) { + _compositeModeValue |= (1 << static_cast(val)); + } else { + _compositeModeValue &= (~(1 << static_cast(val))); + } + } + + inline void enableAllCompositeModeValue(bool enable) { + for (int i = 0; i < static_cast(DebugViewCompositeType::MAX_BIT_COUNT); ++i) { + if (enable) { + _compositeModeValue |= (1 << i); + } else { + _compositeModeValue &= (~(1 << i)); + } + } + } + + inline RenderingDebugViewType getType () const { + if (_singleMode != DebugViewSingleType::NONE) { + return RenderingDebugViewType::SINGLE; + } else if (!_lightingWithAlbedo || _csmLayerColoration) { + return RenderingDebugViewType::COMPOSITE_AND_MISC; + } else { + for (int i = 0; i < static_cast(DebugViewCompositeType::MAX_BIT_COUNT); ++i) { + if (!isCompositeModeEnabled(i)) { + return RenderingDebugViewType::COMPOSITE_AND_MISC; + } + } + } + return RenderingDebugViewType::NONE; + } + +private: + DebugViewSingleType _singleMode{DebugViewSingleType::NONE}; + uint32_t _compositeModeValue{0}; + bool _lightingWithAlbedo{true}; + bool _csmLayerColoration{false}; +}; + +} // namespace pipeline +} // namespace cc diff --git a/native/cocos/renderer/pipeline/Define.cpp b/native/cocos/renderer/pipeline/Define.cpp index 89c9508024..8b0c81ca14 100644 --- a/native/cocos/renderer/pipeline/Define.cpp +++ b/native/cocos/renderer/pipeline/Define.cpp @@ -71,10 +71,11 @@ const gfx::UniformBlock UBOGlobal::LAYOUT = { {"cc_screenSize", gfx::Type::FLOAT4, 1}, {"cc_nativeSize", gfx::Type::FLOAT4, 1}, - {"cc_debug_view_mode", gfx::Type::FLOAT, 4}, - {"cc_debug_view_composite_pack_1", gfx::Type::FLOAT, 4}, - {"cc_debug_view_composite_pack_2", gfx::Type::FLOAT, 4}, - {"cc_debug_view_composite_pack_3", gfx::Type::FLOAT, 4}, + {"cc_debug_view_mode", gfx::Type::FLOAT4, 1}, + {"cc_debug_view_composite_pack_1", gfx::Type::FLOAT4, 1}, + {"cc_debug_view_composite_pack_2", gfx::Type::FLOAT4, 1}, + {"cc_debug_view_composite_pack_3", gfx::Type::FLOAT4, 1}, + {"cc_debug_view_composite_pack_4", gfx::Type::FLOAT4, 1}, }, 1, }; diff --git a/native/cocos/renderer/pipeline/Define.h b/native/cocos/renderer/pipeline/Define.h index fe50a00d31..87d905eb23 100644 --- a/native/cocos/renderer/pipeline/Define.h +++ b/native/cocos/renderer/pipeline/Define.h @@ -447,8 +447,9 @@ struct CC_DLL UBOGlobal { static constexpr uint32_t DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET = UBOGlobal::DEBUG_VIEW_MODE_OFFSET + 4; static constexpr uint32_t DEBUG_VIEW_COMPOSITE_PACK_2_OFFSET = UBOGlobal::DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET + 4; static constexpr uint32_t DEBUG_VIEW_COMPOSITE_PACK_3_OFFSET = UBOGlobal::DEBUG_VIEW_COMPOSITE_PACK_2_OFFSET + 4; + static constexpr uint32_t DEBUG_VIEW_COMPOSITE_PACK_4_OFFSET = UBOGlobal::DEBUG_VIEW_COMPOSITE_PACK_3_OFFSET + 4; - static constexpr uint32_t COUNT = UBOGlobal::DEBUG_VIEW_COMPOSITE_PACK_3_OFFSET + 4; + static constexpr uint32_t COUNT = UBOGlobal::DEBUG_VIEW_COMPOSITE_PACK_4_OFFSET + 4; static constexpr uint32_t SIZE = UBOGlobal::COUNT * 4; static constexpr uint32_t BINDING = static_cast(PipelineGlobalBindings::UBO_GLOBAL); diff --git a/native/cocos/renderer/pipeline/PipelineSceneData.h b/native/cocos/renderer/pipeline/PipelineSceneData.h index 48603ae1f5..41c97fbc41 100644 --- a/native/cocos/renderer/pipeline/PipelineSceneData.h +++ b/native/cocos/renderer/pipeline/PipelineSceneData.h @@ -64,6 +64,7 @@ public: inline const RenderObjectList &getRenderObjects() const { return _renderObjects; } inline void setRenderObjects(RenderObjectList &&ro) { _renderObjects = std::forward(ro); } inline const ccstd::vector &getValidPunctualLights() const { return _validPunctualLights; } + inline void setValidPunctualLights(ccstd::vector lights) { _validPunctualLights = std::move(lights); } inline bool isHDR() const { return _isHDR; } inline void setHDR(bool val) { _isHDR = val; } inline scene::Shadows *getShadows() const { return _shadow; } diff --git a/native/cocos/renderer/pipeline/PipelineUBO.cpp b/native/cocos/renderer/pipeline/PipelineUBO.cpp index c5c23b61d1..12d18a2f95 100644 --- a/native/cocos/renderer/pipeline/PipelineUBO.cpp +++ b/native/cocos/renderer/pipeline/PipelineUBO.cpp @@ -78,13 +78,12 @@ void PipelineUBO::updateGlobalUBOView(const scene::Camera *camera, ccstd::array< uboGlobalView[UBOGlobal::NATIVE_SIZE_OFFSET + 2] = 1.0F / uboGlobalView[UBOGlobal::NATIVE_SIZE_OFFSET]; uboGlobalView[UBOGlobal::NATIVE_SIZE_OFFSET + 3] = 1.0F / uboGlobalView[UBOGlobal::NATIVE_SIZE_OFFSET + 1]; - auto debugViewConfig = root->getDebugViewConfig(); - uboGlobalView[UBOGlobal::DEBUG_VIEW_MODE_OFFSET] = debugViewConfig.singleMode; - uboGlobalView[UBOGlobal::DEBUG_VIEW_MODE_OFFSET + 1] = debugViewConfig.lightingWithAlbedo; - uboGlobalView[UBOGlobal::DEBUG_VIEW_MODE_OFFSET + 2] = debugViewConfig.csmLayerColoration; - for (int i = 0; i < debugViewConfig.compositeModeBitCount; i++) { - uint32_t mode = debugViewConfig.compositeModeValue & (1 << i); - uboGlobalView[UBOGlobal::DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET + i] = mode ? 1.0 : 0.0; + auto *debugView = root->getDebugView(); + uboGlobalView[UBOGlobal::DEBUG_VIEW_MODE_OFFSET] = static_cast(debugView->getSingleMode()); + uboGlobalView[UBOGlobal::DEBUG_VIEW_MODE_OFFSET + 1] = debugView->isLightingWithAlbedo() ? 1.0F : 0.0F; + uboGlobalView[UBOGlobal::DEBUG_VIEW_MODE_OFFSET + 2] = debugView->isCsmLayerColoration() ? 1.0F : 0.0F; + for (int i = 0; i < static_cast(pipeline::DebugViewCompositeType::MAX_BIT_COUNT); ++i) { + uboGlobalView[UBOGlobal::DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET + i] = debugView->isCompositeModeEnabled(i) ? 1.0F : 0.0F; } } diff --git a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp index 0ed830e82b..85d6a14216 100644 --- a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp @@ -47,9 +47,7 @@ namespace cc { namespace pipeline { -RenderAdditiveLightQueue::RenderAdditiveLightQueue(RenderPipeline *pipeline) : _pipeline(pipeline), - _instancedQueue(ccnew RenderInstancedQueue), - _batchedQueue(ccnew RenderBatchedQueue) { +RenderAdditiveLightQueue::RenderAdditiveLightQueue(RenderPipeline *pipeline) : _pipeline(pipeline) { auto *device = gfx::Device::getInstance(); const auto alignment = device->getCapabilities().uboOffsetAlignment; _lightBufferStride = ((UBOForwardLight::SIZE + alignment - 1) / alignment) * alignment; @@ -67,25 +65,20 @@ RenderAdditiveLightQueue::RenderAdditiveLightQueue(RenderPipeline *pipeline) : _ _shadowUBO.fill(0.F); } -RenderAdditiveLightQueue ::~RenderAdditiveLightQueue() { - CC_SAFE_DELETE(_instancedQueue); - CC_SAFE_DELETE(_batchedQueue); -} - void RenderAdditiveLightQueue::recordCommandBuffer(gfx::Device *device, scene::Camera *camera, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer) { const uint32_t offset = _pipeline->getPipelineUBO()->getCurrentCameraUBOOffset(); - for (uint32_t i = 0; i < _instancedLightPass.lights.size(); ++i) { + for (uint32_t i = 0; i < _instancedQueues.size(); ++i) { const auto *light = _instancedLightPass.lights[i]; _dynamicOffsets[0] = _instancedLightPass.dynamicOffsets[i]; auto *globalDescriptorSet = _pipeline->getGlobalDSManager()->getOrCreateDescriptorSet(light); - _instancedQueue->recordCommandBuffer(device, renderPass, cmdBuffer, globalDescriptorSet, offset, &_dynamicOffsets); + _instancedQueues[i]->recordCommandBuffer(device, renderPass, cmdBuffer, globalDescriptorSet, offset, &_dynamicOffsets); } - for (size_t i = 0; i < _batchedLightPass.lights.size(); ++i) { + for (size_t i = 0; i < _batchedQueues.size(); ++i) { const auto *light = _batchedLightPass.lights[i]; _dynamicOffsets[0] = _batchedLightPass.dynamicOffsets[i]; auto *globalDescriptorSet = _pipeline->getGlobalDSManager()->getOrCreateDescriptorSet(light); - _batchedQueue->recordCommandBuffer(device, renderPass, cmdBuffer, globalDescriptorSet, offset, &_dynamicOffsets); + _batchedQueues[i]->recordCommandBuffer(device, renderPass, cmdBuffer, globalDescriptorSet, offset, &_dynamicOffsets); } const bool enableOcclusionQuery = _pipeline->isOcclusionQueryEnabled(); @@ -166,13 +159,23 @@ void RenderAdditiveLightQueue::gatherLightPasses(const scene::Camera *camera, gf _batchedLightPass.lights.emplace_back(light); _batchedLightPass.dynamicOffsets.emplace_back(_lightBufferStride * l); } - _instancedQueue->uploadBuffers(cmdBuffer); - _batchedQueue->uploadBuffers(cmdBuffer); + for (const auto &instancedQueue : _instancedQueues) { + instancedQueue->uploadBuffers(cmdBuffer); + } + for (const auto &batchedQueue : _batchedQueues) { + batchedQueue->uploadBuffers(cmdBuffer); + } } void RenderAdditiveLightQueue::clear() { - _instancedQueue->clear(); - _batchedQueue->clear(); + for (const auto &instancedQueue : _instancedQueues) { + instancedQueue->clear(); + } + _instancedQueues.clear(); + for (const auto &batchedQueue : _batchedQueues) { + batchedQueue->clear(); + } + _batchedQueues.clear(); for (auto lightPass : _lightPasses) { lightPass.dynamicOffsets.clear(); @@ -217,13 +220,19 @@ void RenderAdditiveLightQueue::addRenderQueue(scene::SubModel *subModel, const s auto *buffer = pass->getInstancedBuffer(i); buffer->merge(subModel, lightPassIdx); buffer->setDynamicOffset(0, _lightBufferStride); - _instancedQueue->add(buffer); + if (i >= _instancedQueues.size()) { + _instancedQueues.emplace_back(ccnew RenderInstancedQueue()); + } + _instancedQueues[i]->add(buffer); } break; case scene::BatchingSchemes::VB_MERGING: { auto *buffer = pass->getBatchedBuffer(i); buffer->merge(subModel, lightPassIdx, model); buffer->setDynamicOffset(0, _lightBufferStride); - _batchedQueue->add(buffer); + if (i >= _batchedQueues.size()) { + _batchedQueues.emplace_back(ccnew RenderBatchedQueue()); + } + _batchedQueues[i]->add(buffer); } break; case scene::BatchingSchemes::NONE: { lightPass.lights.emplace_back(light); diff --git a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h index a795863d2e..56b51a2346 100644 --- a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h +++ b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h @@ -54,7 +54,7 @@ struct AdditiveLightPass { class RenderAdditiveLightQueue final { public: explicit RenderAdditiveLightQueue(RenderPipeline *pipeline); - ~RenderAdditiveLightQueue(); + ~RenderAdditiveLightQueue() = default; void recordCommandBuffer(gfx::Device *device, scene::Camera *camera, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer); void gatherLightPasses(const scene::Camera *camera, gfx::CommandBuffer *cmdBuffer); @@ -77,10 +77,6 @@ private: // weak reference RenderPipeline *_pipeline{nullptr}; - // manage memory manually - RenderInstancedQueue *_instancedQueue{nullptr}; - // manage memory manually - RenderBatchedQueue *_batchedQueue{nullptr}; IntrusivePtr _lightBuffer; IntrusivePtr _firstLightBufferView; @@ -99,6 +95,10 @@ private: // weak reference ccstd::vector _validPunctualLights; + ccstd::vector> _instancedQueues; + + ccstd::vector> _batchedQueues; + ccstd::vector _lightPasses; ccstd::vector> _sortedPSOCIArray; diff --git a/native/cocos/renderer/pipeline/RenderBatchedQueue.h b/native/cocos/renderer/pipeline/RenderBatchedQueue.h index d98bfb2509..3a5747c0a3 100644 --- a/native/cocos/renderer/pipeline/RenderBatchedQueue.h +++ b/native/cocos/renderer/pipeline/RenderBatchedQueue.h @@ -24,6 +24,7 @@ #pragma once +#include "base/RefCounted.h" #include "base/std/container/unordered_set.h" #include "gfx-base/GFXDef.h" @@ -39,10 +40,10 @@ namespace pipeline { class BatchedBuffer; -class CC_DLL RenderBatchedQueue final { +class CC_DLL RenderBatchedQueue final : public RefCounted { public: RenderBatchedQueue() = default; - ~RenderBatchedQueue() = default; + ~RenderBatchedQueue() override = default; void clear(); void uploadBuffers(gfx::CommandBuffer *cmdBuff); diff --git a/native/cocos/renderer/pipeline/RenderInstancedQueue.h b/native/cocos/renderer/pipeline/RenderInstancedQueue.h index c01cd38be2..11dcf7c866 100644 --- a/native/cocos/renderer/pipeline/RenderInstancedQueue.h +++ b/native/cocos/renderer/pipeline/RenderInstancedQueue.h @@ -43,10 +43,10 @@ namespace pipeline { class InstancedBuffer; -class CC_DLL RenderInstancedQueue final { +class CC_DLL RenderInstancedQueue final : public RefCounted { public: RenderInstancedQueue() = default; - ~RenderInstancedQueue() = default; + ~RenderInstancedQueue() override = default; void recordCommandBuffer(gfx::Device *device, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer, gfx::DescriptorSet *ds = nullptr, uint32_t offset = 0, const ccstd::vector *dynamicOffsets = nullptr); void add(InstancedBuffer *instancedBuffer); diff --git a/native/cocos/renderer/pipeline/RenderPipeline.cpp b/native/cocos/renderer/pipeline/RenderPipeline.cpp index 21db853940..e3189d1f75 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.cpp +++ b/native/cocos/renderer/pipeline/RenderPipeline.cpp @@ -33,7 +33,6 @@ #include "PipelineStateManager.h" #include "PipelineUBO.h" #include "RenderFlow.h" -#include "RenderPipeline.h" #include "base/StringUtil.h" #include "base/std/hash/hash.h" #include "frame-graph/FrameGraph.h" @@ -42,6 +41,7 @@ #if CC_USE_DEBUG_RENDERER #include "profiler/DebugRenderer.h" #endif +#include "custom/NativeUtils.h" #include "scene/Camera.h" #include "scene/Skybox.h" @@ -291,31 +291,8 @@ void RenderPipeline::setShadingScale(float scale) { _pipelineSceneData->setShadingScale(scale); } -void RenderPipeline::genQuadVertexData(const Vec4 &viewport, float *vbData) { - auto minX = static_cast(viewport.x); - auto maxX = static_cast(viewport.x + viewport.z); - auto minY = static_cast(viewport.y); - auto maxY = static_cast(viewport.y + viewport.w); - if (_device->getCapabilities().screenSpaceSignY > 0) { - std::swap(minY, maxY); - } - int n = 0; - vbData[n++] = -1.0F; - vbData[n++] = -1.0F; - vbData[n++] = minX; // uv - vbData[n++] = maxY; - vbData[n++] = 1.0F; - vbData[n++] = -1.0F; - vbData[n++] = maxX; - vbData[n++] = maxY; - vbData[n++] = -1.0F; - vbData[n++] = 1.0F; - vbData[n++] = minX; - vbData[n++] = minY; - vbData[n++] = 1.0F; - vbData[n++] = 1.0F; - vbData[n++] = maxX; - vbData[n++] = minY; +void RenderPipeline::genQuadVertexData(const Vec4 &viewport, float vbData[16]) { + render::setupQuadVertexBuffer(*_device, viewport, vbData); } void RenderPipeline::generateConstantMacros() { diff --git a/native/cocos/renderer/pipeline/RenderPipeline.h b/native/cocos/renderer/pipeline/RenderPipeline.h index c8abdf8d03..5f2bdfba0b 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.h +++ b/native/cocos/renderer/pipeline/RenderPipeline.h @@ -110,7 +110,7 @@ public: gfx::Viewport getViewport(scene::Camera *camera); gfx::Rect getScissor(scene::Camera *camera); - void genQuadVertexData(const Vec4 &viewport, float *data); + void genQuadVertexData(const Vec4 &viewport, float data[16]); uint32_t getWidth() const { return _width; } uint32_t getHeight() const { return _height; } framegraph::FrameGraph &getFrameGraph() { return _fg; } diff --git a/native/cocos/renderer/pipeline/SceneCulling.cpp b/native/cocos/renderer/pipeline/SceneCulling.cpp index d2111d2ab8..6a5842dc8a 100644 --- a/native/cocos/renderer/pipeline/SceneCulling.cpp +++ b/native/cocos/renderer/pipeline/SceneCulling.cpp @@ -105,31 +105,40 @@ void shadowCulling(const RenderPipeline *pipeline, const scene::Camera *camera, layer->clearShadowObjects(); - for (size_t i = 0; i < csmLayers->getLayerObjects().size(); ++i) { - const auto *model = csmLayers->getLayerObjects()[i].model; + if (csmLayers->getLayerObjects().empty()) return; + + for (auto it = csmLayers->getLayerObjects().begin(); it != csmLayers->getLayerObjects().end();) { + const auto *model = it->model; if (!model || !model->isEnabled() || !model->getNode()) { + it = csmLayers->getLayerObjects().erase(it); continue; } const auto *node = model->getNode(); if (((visibility & node->getLayer()) != node->getLayer()) && !(visibility & static_cast(model->getVisFlags()))) { + it = csmLayers->getLayerObjects().erase(it); continue; } if (!model->getWorldBounds() || !model->isCastShadow()) { + it = csmLayers->getLayerObjects().erase(it); continue; } // frustum culling const bool accurate = model->getWorldBounds()->aabbFrustum(layer->getValidFrustum()); if (!accurate) { + ++it; continue; } layer->addShadowObject(genRenderObject(model, camera)); if (layer->getLevel() < static_cast(mainLight->getCSMLevel())) { if (mainLight->getCSMOptimizationMode() == scene::CSMOptimizationMode::REMOVE_DUPLICATES && aabbFrustumCompletelyInside(*model->getWorldBounds(), layer->getValidFrustum())) { - csmLayers->getLayerObjects().erase(csmLayers->getLayerObjects().begin() + static_cast(i)); - i--; + it = csmLayers->getLayerObjects().erase(it); + } else { + ++it; } + } else { + ++it; } } } diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp index dbfbd9323f..f8899fdc8c 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp @@ -89,7 +89,7 @@ RelationGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& alloc) : outEdges(rhs.outEdges, alloc), inEdges(rhs.inEdges, alloc) {} -FrameGraphDispatcher::FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& graphIn, LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept +FrameGraphDispatcher::FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& graphIn, const LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept : resourceAccessGraph(alloc), resourceGraph(resourceGraphIn), graph(graphIn), diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h index c528922111..2d085af91b 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h @@ -391,7 +391,7 @@ struct FrameGraphDispatcher { return {resourceAccessGraph.get_allocator().resource()}; } - FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& graphIn, LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept; + FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& graphIn, const LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept; FrameGraphDispatcher(FrameGraphDispatcher&& rhs) = delete; FrameGraphDispatcher(FrameGraphDispatcher const& rhs) = delete; FrameGraphDispatcher& operator=(FrameGraphDispatcher&& rhs) = delete; @@ -417,7 +417,7 @@ struct FrameGraphDispatcher { ResourceAccessGraph resourceAccessGraph; ResourceGraph& resourceGraph; const RenderGraph& graph; - LayoutGraphData& layoutGraph; + const LayoutGraphData& layoutGraph; boost::container::pmr::memory_resource* scratch{nullptr}; PmrFlatMap externalResMap; RelationGraph relationGraph; diff --git a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp index dfb096e9d0..a0b2a26797 100644 --- a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp +++ b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp @@ -177,7 +177,7 @@ bool isPassExecAdjecent(uint32_t passLID, uint32_t passRID) { return std::abs(static_cast(passLID) - static_cast(passRID)) <= 1; } -bool isStatusDependent(const AccessStatus &lhs, const AccessStatus &rhs); +bool isTransitionStatusDependent(const AccessStatus &lhs, const AccessStatus &rhs); template bool tryAddEdge(uint32_t srcVertex, uint32_t dstVertex, Graph &graph); @@ -304,14 +304,14 @@ void buildAccessGraph(const RenderGraph &renderGraph, const Graphs &graphs) { bool isExternal = pass.second.isExternal; bool needCulling = pass.second.needCulling; - if (isExternal && !needCulling) { - if (pass.first != resourceAccessGraph.presentPassID) { + if(pass.first != resourceAccessGraph.presentPassID) { + if (isExternal && !needCulling) { add_edge(pass.first, resourceAccessGraph.presentPassID, resourceAccessGraph); - } - } else { - // write into transient resources, culled - if constexpr (ENABLE_BRANCH_CULLING) { - branchCulling(pass.first, resourceAccessGraph); + } else { + // write into transient resources, culled + if constexpr (ENABLE_BRANCH_CULLING) { + branchCulling(pass.first, resourceAccessGraph); + } } } } @@ -454,7 +454,7 @@ struct BarrierVisitor : public boost::bfs_visitor<> { CC_ASSERT(fromIter != srcStatus.end()); CC_ASSERT(toIter != dstStatus.end()); - if (!isStatusDependent(*fromIter, *toIter)) { + if (!isTransitionStatusDependent(*fromIter, *toIter)) { continue; } @@ -587,7 +587,7 @@ struct BarrierVisitor : public boost::bfs_visitor<> { externalMap[resName].currStatus = resourcecAccess; externalMap[resName].currStatus.vertID = vert; - if (isStatusDependent(externalMap[resName].lastStatus, externalMap[resName].currStatus)) { + if (isTransitionStatusDependent(externalMap[resName].lastStatus, externalMap[resName].currStatus)) { barrierMap[vert].blockBarrier.frontBarriers.emplace_back(Barrier{ rescID, gfx::BarrierType::SPLIT_END, @@ -809,6 +809,7 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { } }; + // generate gfx barrier for (auto &passBarrierInfo : batchedBarriers) { auto &passBarrierNode = passBarrierInfo.second; genGFXBarrier(passBarrierNode.blockBarrier.frontBarriers); @@ -960,7 +961,7 @@ auto evaluateHeaviness(const RAG &rag, const ResourceGraph &rescGraph, ResourceA break; } } - return std::tie(forceAdjacent, score); + return std::make_tuple(forceAdjacent, score); }; void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, RelationGraph &relationGraph, const RelationGraph &relationGraphTc, const RelationVerts &lhsVerts, const RelationVerts &rhsVerts) { @@ -1374,12 +1375,11 @@ bool tryAddEdge(uint32_t srcVertex, uint32_t dstVertex, Graph &graph) { return false; } -bool isStatusDependent(const AccessStatus &lhs, const AccessStatus &rhs) { +bool isTransitionStatusDependent(const AccessStatus &lhs, const AccessStatus &rhs) { bool res = true; if (lhs.passType == rhs.passType && lhs.visibility == rhs.visibility && - lhs.access == gfx::MemoryAccessBit::READ_ONLY && - rhs.access == gfx::MemoryAccessBit::READ_ONLY && + lhs.access == rhs.access && lhs.usage == rhs.usage) { res = false; } @@ -1451,7 +1451,7 @@ auto getResourceStatus(PassType passType, const PmrString &name, gfx::MemoryAcce accesFlag = gfx::getAccessFlags(texUsage, memAccess, vis); } - return std::tie(vis, usage, accesFlag); + return std::make_tuple(vis, usage, accesFlag); } void addCopyAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status, const Range &range) { @@ -1539,7 +1539,9 @@ AccessVertex dependencyCheck(RAG &rag, AccessVertex curVertID, const ResourceGra } } if (isExternalPass) { - rag.leafPasses[curVertID] = LeafStatus{true, access == gfx::MemoryAccessBit::READ_ONLY && passType != PassType::PRESENT}; + // only external res will be manually record here, leaf pass with transient resource will be culled by default, + // those leaf passes with ALL read access on external(or with transients) res can be culled. + rag.leafPasses[curVertID].needCulling &= (access == gfx::MemoryAccessBit::READ_ONLY && passType != PassType::PRESENT); } trans.currStatus = {curVertID, visibility, access, passType, accessFlag, usage, Range{}}; lastVertID = trans.lastStatus.vertID; @@ -1555,7 +1557,8 @@ AccessVertex dependencyCheck(RAG &rag, AccessVertex curVertID, const ResourceGra if (rag.leafPasses.find(curVertID) != rag.leafPasses.end()) { // only write into externalRes counts if (isExternalPass) { - rag.leafPasses[curVertID] = LeafStatus{true, access == gfx::MemoryAccessBit::READ_ONLY && passType != PassType::PRESENT}; + // same as above + rag.leafPasses[curVertID].needCulling &= (access == gfx::MemoryAccessBit::READ_ONLY && passType != PassType::PRESENT); } } } else { diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphSerialization.h b/native/cocos/renderer/pipeline/custom/LayoutGraphSerialization.h index c7d2884456..8e86e9ef82 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphSerialization.h +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphSerialization.h @@ -199,6 +199,8 @@ inline void load(InputArchive& ar, DescriptorBlockData& v) { inline void save(OutputArchive& ar, const DescriptorSetLayoutData& v) { save(ar, v.slot); save(ar, v.capacity); + save(ar, v.uniformBlockCapacity); + save(ar, v.samplerTextureCapacity); save(ar, v.descriptorBlocks); save(ar, v.uniformBlocks); save(ar, v.bindingMap); @@ -207,6 +209,8 @@ inline void save(OutputArchive& ar, const DescriptorSetLayoutData& v) { inline void load(InputArchive& ar, DescriptorSetLayoutData& v) { load(ar, v.slot); load(ar, v.capacity); + load(ar, v.uniformBlockCapacity); + load(ar, v.samplerTextureCapacity); load(ar, v.descriptorBlocks); load(ar, v.uniformBlocks); load(ar, v.bindingMap); diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.cpp b/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.cpp index 824c09aebb..6b6a4671a2 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.cpp @@ -146,6 +146,8 @@ DescriptorSetLayoutData::DescriptorSetLayoutData(uint32_t slotIn, uint32_t capac DescriptorSetLayoutData::DescriptorSetLayoutData(DescriptorSetLayoutData&& rhs, const allocator_type& alloc) : slot(rhs.slot), capacity(rhs.capacity), + uniformBlockCapacity(rhs.uniformBlockCapacity), + samplerTextureCapacity(rhs.samplerTextureCapacity), descriptorBlocks(std::move(rhs.descriptorBlocks), alloc), uniformBlocks(std::move(rhs.uniformBlocks), alloc), bindingMap(std::move(rhs.bindingMap), alloc) {} @@ -232,7 +234,6 @@ LayoutGraphData::LayoutGraphData(const allocator_type& alloc) noexcept constantIndex(alloc), shaderLayoutIndex(alloc), effects(alloc), - constantMacros(alloc), pathIndex(alloc) {} LayoutGraphData::LayoutGraphData(LayoutGraphData&& rhs, const allocator_type& alloc) @@ -247,7 +248,7 @@ LayoutGraphData::LayoutGraphData(LayoutGraphData&& rhs, const allocator_type& al constantIndex(std::move(rhs.constantIndex), alloc), shaderLayoutIndex(std::move(rhs.shaderLayoutIndex), alloc), effects(std::move(rhs.effects), alloc), - constantMacros(std::move(rhs.constantMacros), alloc), + constantMacros(std::move(rhs.constantMacros)), pathIndex(std::move(rhs.pathIndex), alloc) {} // ContinuousContainer diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.h b/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.h index 89e7dd6bce..cf3911fe8a 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.h +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.h @@ -365,6 +365,8 @@ struct DescriptorSetLayoutData { uint32_t slot{0xFFFFFFFF}; uint32_t capacity{0}; + uint32_t uniformBlockCapacity{0}; + uint32_t samplerTextureCapacity{0}; ccstd::pmr::vector descriptorBlocks; ccstd::pmr::unordered_map uniformBlocks; PmrFlatMap bindingMap; @@ -704,7 +706,7 @@ struct LayoutGraphData { PmrFlatMap constantIndex; PmrFlatMap shaderLayoutIndex; PmrFlatMap effects; - ccstd::pmr::string constantMacros; + ccstd::string constantMacros; // Path PmrTransparentMap pathIndex; }; diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.cpp b/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.cpp index 3530961ca6..e76195f772 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.cpp +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.cpp @@ -26,12 +26,19 @@ #include "LayoutGraphUtils.h" #include #include +#include "LayoutGraphGraphs.h" +#include "LayoutGraphNames.h" +#include "LayoutGraphTypes.h" +#include "RenderCommonNames.h" +#include "RenderCommonTypes.h" #include "cocos/base/Log.h" +#include "cocos/base/StringUtil.h" #include "cocos/base/std/container/string.h" #include "cocos/renderer/gfx-base/GFXDef-common.h" -#include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" -#include "cocos/renderer/pipeline/custom/RenderCommonTypes.h" +#include "details/DebugUtils.h" +#include "details/GslUtils.h" #include "details/Map.h" +#include "details/Range.h" namespace cc { @@ -49,7 +56,7 @@ DescriptorBlockData& getDescriptorBlockData( iter = map.emplace( std::piecewise_construct, std::forward_as_tuple(index), - std::forward_as_tuple()) + std::forward_as_tuple(index.descriptorType, index.visibility, 0)) .first; return iter->second; @@ -241,6 +248,13 @@ void makeDescriptorSetLayoutData( } // increate total capacity capacity += block.capacity; + data.capacity += block.capacity; + if (index.descriptorType == DescriptorTypeOrder::UNIFORM_BUFFER || + index.descriptorType == DescriptorTypeOrder::DYNAMIC_UNIFORM_BUFFER) { + data.uniformBlockCapacity += block.capacity; + } else if (index.descriptorType == DescriptorTypeOrder::SAMPLER_TEXTURE) { + data.samplerTextureCapacity += block.capacity; + } data.descriptorBlocks.emplace_back(std::move(block)); } } @@ -267,16 +281,21 @@ void initializeDescriptorSetLayoutInfo( namespace { const ccstd::unordered_map DEFAULT_UNIFORM_COUNTS{ - {"cc_joints", pipeline::UBOSkinning::layout.members[0].count}, {"cc_lightPos", pipeline::UBOForwardLight::LIGHTS_PER_PASS}, {"cc_lightColor", pipeline::UBOForwardLight::LIGHTS_PER_PASS}, {"cc_lightSizeRangeAngle", pipeline::UBOForwardLight::LIGHTS_PER_PASS}, {"cc_lightDir", pipeline::UBOForwardLight::LIGHTS_PER_PASS}, }; +const TransparentSet DYNAMIC_UNIFORM_BLOCK{ + {"CCCamera"}, + {"CCForwardLight"}, + {"CCUILocal"}, +}; + } // namespace -uint32_t getSize(const ccstd::vector& blockMembers) { +uint32_t getUniformBlockSize(const ccstd::vector& blockMembers) { uint32_t prevSize = 0; for (const auto& m : blockMembers) { if (m.count) { @@ -288,11 +307,178 @@ uint32_t getSize(const ccstd::vector& blockMembers) { prevSize += getTypeSize(m.type) * iter->second; continue; } + if (m.name == "cc_joints") { + const auto sz = getTypeSize(m.type) * pipeline::UBOSkinning::layout.members[0].count; + CC_EXPECTS(sz == pipeline::UBOSkinning::size); + prevSize += sz; + continue; + } CC_LOG_ERROR("Invalid uniform count: %s", m.name.c_str()); } + CC_ENSURES(prevSize); return prevSize; } +bool isDynamicUniformBlock(std::string_view name) { + return DYNAMIC_UNIFORM_BLOCK.find(name) != DYNAMIC_UNIFORM_BLOCK.end(); +} + +gfx::DescriptorSet* getOrCreatePerPassDescriptorSet( + gfx::Device* device, + LayoutGraphData& lg, LayoutGraphData::vertex_descriptor vertID) { + auto& ppl = get(LayoutGraphData::Layout, lg, vertID); + auto iter = ppl.descriptorSets.find(UpdateFrequency::PER_PASS); + if (iter == ppl.descriptorSets.end()) { + return nullptr; + } + auto& data = iter->second; + if (!data.descriptorSet) { + if (!data.descriptorSetLayout) { + data.descriptorSetLayout = device->createDescriptorSetLayout(data.descriptorSetLayoutInfo); + } + CC_ENSURES(data.descriptorSetLayout); + data.descriptorSet = device->createDescriptorSet(gfx::DescriptorSetInfo{data.descriptorSetLayout.get()}); + } + CC_ENSURES(data.descriptorSet); + return data.descriptorSet; +} + +void generateConstantMacros( + gfx::Device* device, + ccstd::string& constantMacros, + bool clusterEnabled) { + constantMacros = StringUtil::format( + R"( +#define CC_DEVICE_SUPPORT_FLOAT_TEXTURE %d +#define CC_ENABLE_CLUSTERED_LIGHT_CULLING %d +#define CC_DEVICE_MAX_VERTEX_UNIFORM_VECTORS %d +#define CC_DEVICE_MAX_FRAGMENT_UNIFORM_VECTORS %d +#define CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT %d +#define CC_PLATFORM_ANDROID_AND_WEBGL 0 +#define CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES 0 +#define CC_JOINT_UNIFORM_CAPACITY %d + )", + hasAnyFlags(device->getFormatFeatures(gfx::Format::RGBA32F), + gfx::FormatFeature::RENDER_TARGET | gfx::FormatFeature::SAMPLED_TEXTURE), + clusterEnabled ? 1 : 0, + device->getCapabilities().maxVertexUniformVectors, + device->getCapabilities().maxFragmentUniformVectors, + device->hasFeature(gfx::Feature::INPUT_ATTACHMENT_BENEFIT), + pipeline::SkinningJointCapacity::jointUniformCapacity); +} + +namespace { + +ccstd::string getName(gfx::ShaderStageFlagBit stage) { + std::ostringstream oss; + int count = 0; + if (hasFlag(stage, gfx::ShaderStageFlagBit::VERTEX)) { + if (count++) { + oss << " | "; + } + oss << "Vertex"; + } + if (hasFlag(stage, gfx::ShaderStageFlagBit::CONTROL)) { + if (count++) { + oss << " | "; + } + oss << "Control"; + } + if (hasFlag(stage, gfx::ShaderStageFlagBit::EVALUATION)) { + if (count++) { + oss << " | "; + } + oss << "Evaluation"; + } + if (hasFlag(stage, gfx::ShaderStageFlagBit::GEOMETRY)) { + if (count++) { + oss << " | "; + } + oss << "Geometry"; + } + if (hasFlag(stage, gfx::ShaderStageFlagBit::FRAGMENT)) { + if (count++) { + oss << " | "; + } + oss << "Fragment"; + } + if (hasFlag(stage, gfx::ShaderStageFlagBit::COMPUTE)) { + if (count++) { + oss << " | "; + } + oss << "Compute"; + } + if (hasAllFlags(stage, gfx::ShaderStageFlagBit::ALL)) { + if (count++) { + oss << " | "; + } + oss << "All"; + } + return oss.str(); +} + +} // namespace + +void printLayoutGraphData( + const LayoutGraphData& lg, std::ostream& oss, + boost::container::pmr::memory_resource* scratch) { + ccstd::pmr::string space(scratch); + + oss << "\n"; + + for (const auto v : makeRange(vertices(lg))) { + if (parent(v, lg) != LayoutGraphData::null_vertex()) { + continue; + } + const auto& name = get(LayoutGraphData::Name, lg, v); + OSS << "\"" << name << "\": "; + + visit( + [&](auto tag) { + oss << getName(tag); + }, + tag(v, lg)); + + oss << " {\n"; + INDENT_BEG(); + const auto& info = get(LayoutGraphData::Layout, lg, v); + for (const auto& set : info.descriptorSets) { + OSS << "Set<" << getName(set.first) << "> {\n"; + { + INDENT(); + for (const auto& block : set.second.descriptorSetLayoutData.descriptorBlocks) { + OSS << "Block<" << getName(block.type) << ", " << getName(block.visibility) << "> {\n"; + { + INDENT(); + OSS << "capacity: " << block.capacity << ",\n"; + OSS << "count: " << block.descriptors.size() << ",\n"; + if (!block.descriptors.empty()) { + OSS << "Descriptors{ "; + int count = 0; + for (const auto& d : block.descriptors) { + if (count++) { + oss << ", "; + } + const auto& name = lg.valueNames.at(d.descriptorID.value); + oss << "\"" << name; + if (d.count != 1) { + oss << "[" << d.count << "]"; + } + oss << "\""; + } + oss << " }\n"; + } + } + OSS << "}\n"; + } + } + OSS << "}\n"; + } + INDENT_END(); + OSS << "}\n"; + } +} + } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h b/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h index e893e1e108..c1c92b8dcf 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h @@ -24,9 +24,11 @@ #pragma once #include +#include #include "cocos/core/assets/EffectAsset.h" #include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" #include "cocos/renderer/pipeline/custom/RenderCommonTypes.h" +#include "gfx-base/GFXDevice.h" namespace cc { @@ -47,7 +49,22 @@ void initializeDescriptorSetLayoutInfo( const DescriptorSetLayoutData& layoutData, gfx::DescriptorSetLayoutInfo& info); -uint32_t getSize(const ccstd::vector& blockMembers); +uint32_t getUniformBlockSize(const ccstd::vector& blockMembers); + +bool isDynamicUniformBlock(std::string_view name); + +gfx::DescriptorSet* getOrCreatePerPassDescriptorSet( + gfx::Device* device, + LayoutGraphData& lg, LayoutGraphData::vertex_descriptor vertID); + +void generateConstantMacros( + gfx::Device* device, + ccstd::string& constantMacros, + bool clusterEnabled); + +void printLayoutGraphData( + const LayoutGraphData& lg, std::ostream& oss, + boost::container::pmr::memory_resource* scratch); } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp index 63564d42b2..f5b166f36b 100644 --- a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp @@ -24,16 +24,24 @@ #include #include -#include #include "FGDispatcherGraphs.h" +#include "LayoutGraphGraphs.h" +#include "LayoutGraphTypes.h" +#include "LayoutGraphUtils.h" #include "NativePipelineFwd.h" #include "NativePipelineTypes.h" +#include "NativeUtils.h" +#include "PrivateTypes.h" #include "RenderGraphGraphs.h" #include "RenderGraphTypes.h" +#include "RenderingModule.h" #include "cocos/renderer/gfx-base/GFXBarrier.h" #include "cocos/renderer/gfx-base/GFXDef-common.h" +#include "cocos/renderer/gfx-base/GFXDescriptorSetLayout.h" #include "cocos/renderer/gfx-base/GFXDevice.h" +#include "cocos/renderer/pipeline/Define.h" #include "cocos/renderer/pipeline/InstancedBuffer.h" +#include "cocos/renderer/pipeline/PipelineStateManager.h" #include "cocos/scene/Model.h" #include "cocos/scene/Octree.h" #include "cocos/scene/Pass.h" @@ -49,47 +57,32 @@ namespace render { namespace { +constexpr uint32_t INVALID_ID = 0xFFFFFFFF; + struct RenderGraphVisitorContext { - RenderGraphVisitorContext( - NativeRenderContext& contextIn, - const RenderGraph& gIn, - ResourceGraph& resgIn, - const FrameGraphDispatcher& fgdIn, - const FrameGraphDispatcher::BarrierMap& barrierMapIn, - const ccstd::pmr::vector& validPassesIn, - gfx::Device* deviceIn, - cc::gfx::CommandBuffer* cmdBuffIn, - ccstd::pmr::unordered_map< - const scene::RenderScene*, - ccstd::pmr::unordered_map>& sceneQueuesIn, - PipelineRuntime* pplIn, - boost::container::pmr::memory_resource* scratchIn) - : context(contextIn), - g(gIn), - resourceGraph(resgIn), - fgd(fgdIn), - barrierMap(barrierMapIn), - validPasses(validPassesIn), - device(deviceIn), - cmdBuff(cmdBuffIn), - sceneQueues(sceneQueuesIn), - ppl(pplIn), - scratch(scratchIn) {} + RenderGraphVisitorContext(RenderGraphVisitorContext&&) = delete; + RenderGraphVisitorContext(RenderGraphVisitorContext const&) = delete; + RenderGraphVisitorContext& operator=(RenderGraphVisitorContext&&) = delete; + RenderGraphVisitorContext& operator=(RenderGraphVisitorContext const&) = delete; NativeRenderContext& context; + LayoutGraphData& lg; const RenderGraph& g; ResourceGraph& resourceGraph; const FrameGraphDispatcher& fgd; const FrameGraphDispatcher::BarrierMap& barrierMap; const ccstd::pmr::vector& validPasses; gfx::Device* device = nullptr; - cc::gfx::CommandBuffer* cmdBuff = nullptr; - boost::container::pmr::memory_resource* scratch = nullptr; - gfx::RenderPass* currentPass = nullptr; + gfx::CommandBuffer* cmdBuff = nullptr; ccstd::pmr::unordered_map< const scene::RenderScene*, ccstd::pmr::unordered_map>& sceneQueues; PipelineRuntime* ppl = nullptr; + ProgramLibrary* programLib = nullptr; + boost::container::pmr::memory_resource* scratch = nullptr; + gfx::RenderPass* currentPass = nullptr; + LayoutGraphData::vertex_descriptor currentPassLayoutID = LayoutGraphData::null_vertex(); + Mat4 currentProjMatrix{}; }; void clear(gfx::RenderPassInfo& info) { @@ -124,6 +117,9 @@ uint32_t getRasterPassInputCount(const RasterPass& pass) { uint32_t getRasterPassOutputCount(const RasterPass& pass) { uint32_t numOutputs = 0; for (const auto& [name, view] : pass.rasterViews) { + if (view.attachmentType != AttachmentType::RENDER_TARGET) { + continue; + } if (view.accessType == AccessType::READ_WRITE || view.accessType == AccessType::WRITE) { ++numOutputs; } @@ -142,51 +138,65 @@ uint32_t getRasterPassPreserveCount(const RasterPass& pass) { } PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( - RenderGraphVisitorContext& ctx, const RasterPass& pass) { + RenderGraphVisitorContext& ctx, const RasterPass& pass, + boost::container::pmr::memory_resource* scratch) { auto& resg = ctx.resourceGraph; + PersistentRenderPassAndFramebuffer data(pass.get_allocator()); - gfx::RenderPassInfo rpInfo; - uint32_t numDepthStencil = 0; - rpInfo.colorAttachments.resize(pass.rasterViews.size()); - data.clearColors.resize(pass.rasterViews.size()); + gfx::RenderPassInfo rpInfo{}; + gfx::FramebufferInfo fbInfo{ data.renderPass, }; fbInfo.colorTextures.reserve(pass.rasterViews.size()); if (pass.subpassGraph.subpasses.empty()) { + const auto numInputs = getRasterPassInputCount(pass); + const auto numColors = getRasterPassOutputCount(pass); + + // persistent cache + data.clearColors.reserve(numColors); + + // render pass + rpInfo.colorAttachments.reserve(numColors); + auto& subpass = rpInfo.subpasses.emplace_back(); - subpass.inputs.resize(getRasterPassInputCount(pass)); - subpass.colors.resize(getRasterPassOutputCount(pass)); - subpass.resolves.resize(getRasterPassResolveCount(pass)); - subpass.preserves.resize(getRasterPassPreserveCount(pass)); + subpass.inputs.reserve(numInputs); + subpass.colors.reserve(numColors); + subpass.resolves.reserve(getRasterPassResolveCount(pass)); + subpass.preserves.reserve(getRasterPassPreserveCount(pass)); auto numTotalAttachments = static_cast(pass.rasterViews.size()); - uint32_t slot = 0; - uint32_t rtvCount = 0; + + PmrFlatMap viewIndex(scratch); + for (const auto& [name, view] : pass.rasterViews) { + viewIndex.emplace(view.slotID, name); + } + uint32_t dsvCount = 0; - for (const auto& pair : pass.rasterViews) { - const auto& name = pair.first; - const auto& view = pair.second; + for (const auto& [slotID, name] : viewIndex) { + const auto& view = pass.rasterViews.at(name); const auto resID = vertex(name, ctx.resourceGraph); const auto& desc = get(ResourceGraph::DescTag{}, ctx.resourceGraph, resID); if (view.attachmentType == AttachmentType::RENDER_TARGET) { // RenderTarget - auto& rtv = rpInfo.colorAttachments[slot]; - rtv.format = desc.format; - rtv.sampleCount = desc.sampleCount; - rtv.loadOp = view.loadOp; - rtv.storeOp = view.storeOp; - rtv.barrier = nullptr; - rtv.isGeneralLayout = hasFlag(desc.textureFlags, gfx::TextureFlags::GENERAL_LAYOUT); + auto slot = static_cast(rpInfo.colorAttachments.size()); + auto& rtv = rpInfo.colorAttachments.emplace_back( + gfx::ColorAttachment{ + desc.format, + desc.sampleCount, + view.loadOp, + view.storeOp, + nullptr, + hasFlag(desc.textureFlags, gfx::TextureFlags::GENERAL_LAYOUT), + }); if (view.accessType != AccessType::WRITE) { // Input auto inputSlot = getRasterViewPassInputSlot(view); - subpass.inputs[inputSlot] = slot; + subpass.inputs.emplace_back(slot); } if (view.accessType != AccessType::READ) { // Output - auto outputSlot = rtvCount++; - subpass.colors[outputSlot] = slot; + subpass.colors.emplace_back(slot); } - data.clearColors[slot] = view.clearColor; + data.clearColors.emplace_back(view.clearColor); auto resID = findVertex(name, resg); visitObject( @@ -200,6 +210,7 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( CC_EXPECTS(false); }, [&](const ManagedTexture& tex) { + CC_EXPECTS(tex.texture); fbInfo.colorTextures.emplace_back(tex.texture); }, [&](const IntrusivePtr& res) { @@ -216,10 +227,10 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( [&](const RenderSwapchain& sc) { fbInfo.colorTextures.emplace_back(sc.swapchain->getColorTexture()); }); - - ++slot; + CC_ENSURES(rpInfo.colorAttachments.size() == subpass.colors.size()); + CC_ENSURES(rpInfo.colorAttachments.size() == data.clearColors.size()); + CC_ENSURES(rpInfo.colorAttachments.size() == fbInfo.colorTextures.size()); } else { // DepthStencil - ++numDepthStencil; auto& dsv = rpInfo.depthStencilAttachment; CC_EXPECTS(desc.format != gfx::Format::UNKNOWN); dsv.format = desc.format; @@ -241,6 +252,7 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( visitObject( resID, resg, [&](const ManagedTexture& tex) { + CC_EXPECTS(tex.texture); CC_EXPECTS(!fbInfo.depthStencilTexture); fbInfo.depthStencilTexture = tex.texture.get(); }, @@ -253,24 +265,31 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( }); } } - CC_EXPECTS(numDepthStencil <= 1); - if (numDepthStencil) { - CC_EXPECTS(rpInfo.colorAttachments.back().format == gfx::Format::UNKNOWN); - rpInfo.colorAttachments.pop_back(); - data.clearColors.pop_back(); - } } else { CC_EXPECTS(false); } + data.renderPass = ctx.device->createRenderPass(rpInfo); - if (!data.framebuffer) { - fbInfo.renderPass = data.renderPass; - data.framebuffer = ctx.device->createFramebuffer(fbInfo); - } + fbInfo.renderPass = data.renderPass; + data.framebuffer = ctx.device->createFramebuffer(fbInfo); + return data; } -gfx::BufferBarrierInfo getBufferBarrier(const cc::render::Barrier& barrier) { +PersistentRenderPassAndFramebuffer& fetchOrCreateFramebuffer( + RenderGraphVisitorContext& ctx, const RasterPass& pass, + boost::container::pmr::memory_resource* scratch) { + auto iter = ctx.resourceGraph.renderPasses.find(pass); + if (iter == ctx.resourceGraph.renderPasses.end()) { + bool added = false; + std::tie(iter, added) = ctx.resourceGraph.renderPasses.emplace( + pass, createPersistentRenderPassAndFramebuffer(ctx, pass, scratch)); + CC_ENSURES(added); + } + return iter->second; +} + +gfx::BufferBarrierInfo getBufferBarrier(const render::Barrier& barrier) { gfx::MemoryUsage memUsage = gfx::MemoryUsage::DEVICE; const auto& beginUsage = get(barrier.beginStatus.usage); @@ -293,42 +312,48 @@ gfx::BufferBarrierInfo getBufferBarrier(const cc::render::Barrier& barrier) { } std::pair getTextureBarrier( - const ResourceGraph& resg, ResourceGraph::vertex_descriptor resID, - const cc::render::Barrier& barrier) { - gfx::Texture* texture = nullptr; - visitObject( - resID, resg, - [&](const ManagedTexture& res) { - texture = res.texture.get(); - }, - [&](const IntrusivePtr& tex) { - texture = tex.get(); - }, - [&](const IntrusivePtr& fb) { - std::ignore = fb; - CC_EXPECTS(false); - }, - [&](const RenderSwapchain& sc) { - texture = sc.swapchain->getColorTexture(); - }, - [&](const auto& buffer) { - std::ignore = buffer; - CC_EXPECTS(false); - }); + ResourceGraph& resg, ResourceGraph::vertex_descriptor resID, + const render::Barrier& barrier) { + gfx::Texture* texture = resg.getTexture(resID); + CC_ENSURES(texture); const auto& desc = get(ResourceGraph::DescTag{}, resg, resID); - const auto& beginUsage = get(barrier.beginStatus.usage); - const auto& endUsage = get(barrier.endStatus.usage); + + const bool isExternal = barrier.endStatus.vertID == ResourceAccessGraph::null_vertex(); + + const auto barrierType = isExternal ? gfx::BarrierType::FULL : barrier.type; + const auto beginUsage = get(barrier.beginStatus.usage); + const auto endUsage = [&]() { + if (!isExternal) { + return get(barrier.endStatus.usage); + } + return gfx::TextureUsage::NONE; + }(); auto beginAccesFlags = gfx::getAccessFlags( beginUsage, barrier.beginStatus.access, barrier.beginStatus.visibility); - auto endAccessFlags = gfx::getAccessFlags( - endUsage, - barrier.endStatus.access, - barrier.endStatus.visibility); + auto endAccessFlags = [&]() { + if (!isExternal) { + return gfx::getAccessFlags( + endUsage, + barrier.endStatus.access, + barrier.endStatus.visibility); + } + auto& states = get(ResourceGraph::States, resg, resID); + if (holds(resID, resg)) { + states.states = gfx::AccessFlagBit::PRESENT; + return states.states; + } + states.states = + gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | + gfx::AccessFlagBit::VERTEX_SHADER_READ_TEXTURE | + gfx::AccessFlagBit::COMPUTE_SHADER_READ_TEXTURE; + + return states.states; + }(); CC_ENSURES(beginAccesFlags != gfx::INVALID_ACCESS_FLAGS); CC_ENSURES(endAccessFlags != gfx::INVALID_ACCESS_FLAGS); @@ -341,7 +366,7 @@ std::pair getTextureBarrier( gfx::TextureBarrierInfo{ beginAccesFlags, endAccessFlags, - barrier.type, + barrierType, textureRange.mipLevel, textureRange.levelCount, textureRange.firstSlice, @@ -359,9 +384,498 @@ struct RenderGraphFilter { const ccstd::pmr::vector* validPasses = nullptr; }; +void bindDescValue(gfx::DescriptorSet& desc, uint32_t binding, gfx::Buffer* value) { + desc.bindBuffer(binding, value); +} + +void bindDescValue(gfx::DescriptorSet& desc, uint32_t binding, gfx::Texture* value) { + desc.bindTexture(binding, value); +} + +void bindDescValue(gfx::DescriptorSet& desc, uint32_t binding, gfx::Sampler* value) { + desc.bindSampler(binding, value); +} + +template +void bindGlobalDesc(gfx::DescriptorSet& desc, uint32_t binding, T* value) { + bindDescValue(desc, binding, value); +} + +uint32_t getDescBinding(uint32_t descId, const DescriptorSetData& descData) { + const auto& layoutData = descData; + // find descriptor binding + for (const auto& block : layoutData.descriptorSetLayoutData.descriptorBlocks) { + for (uint32_t i = 0; i != block.descriptors.size(); ++i) { + if (descId == block.descriptors[i].descriptorID.value) { + return block.offset + i; + } + } + } + return 0xFFFFFFFF; +} + +void updateGlobal( + RenderGraphVisitorContext& ctx, + DescriptorSetData& descriptorSetData, + const RenderData& data, + bool isUpdate = false) { + const auto& constants = data.constants; + const auto& samplers = data.samplers; + const auto& textures = data.textures; + auto& device = *ctx.device; + auto& descriptorSet = *descriptorSetData.descriptorSet; + for (const auto& [key, value] : constants) { + const auto bindId = getDescBinding(key, descriptorSetData); + if (bindId == INVALID_ID) { + continue; + } + auto* buffer = descriptorSet.getBuffer(bindId); + bool haveBuff = true; + if (!buffer && !isUpdate) { + gfx::BufferInfo info{ + gfx::BufferUsageBit::UNIFORM | gfx::BufferUsageBit::TRANSFER_DST, + gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE, + static_cast(value.size()), + static_cast(value.size())}; + buffer = device.createBuffer(info); + haveBuff = false; + } + CC_ENSURES(buffer); + if (isUpdate) { + buffer->update(value.data()); + } + if (!haveBuff) { + bindGlobalDesc(descriptorSet, bindId, buffer); + } + } + for (const auto& [key, value] : textures) { + const auto bindId = getDescBinding(key, descriptorSetData); + if (bindId == INVALID_ID) { + continue; + } + auto* tex = descriptorSet.getTexture(bindId); + if (!tex || isUpdate) { + bindGlobalDesc(descriptorSet, bindId, value.get()); + } + } + for (const auto& [key, value] : samplers) { + const auto bindId = getDescBinding(key, descriptorSetData); + if (bindId == INVALID_ID) { + continue; + } + auto* sampler = descriptorSet.getSampler(bindId); + if (!sampler || isUpdate) { + bindGlobalDesc(descriptorSet, bindId, value.get()); + } + } +} + +void updateCpuUniformBuffer( + const LayoutGraphData& lg, + const RenderData& user, + const gfx::UniformBlock& uniformBlock, + bool bInit, + ccstd::pmr::vector& buffer) { + // calculate uniform block size + const auto bufferSize = uniformBlock.count * + getUniformBlockSize(uniformBlock.members); + // check pre-condition + CC_EXPECTS(buffer.size() == bufferSize); + + // reset buffer + if (bInit) { + std::fill(buffer.begin(), buffer.end(), 0); + } + + uint32_t offset = 0; + for (const auto& value : uniformBlock.members) { + CC_EXPECTS(value.count); + const auto typeSize = getTypeSize(value.type); + const auto totalSize = typeSize * value.count; + CC_ENSURES(typeSize); + CC_ENSURES(totalSize); + + const auto valueID = [&]() { + auto iter = lg.constantIndex.find(std::string_view{value.name}); + CC_EXPECTS(iter != lg.constantIndex.end()); + return iter->second.value; + }(); + + const auto iter2 = user.constants.find(valueID); + if (iter2 == user.constants.end() || iter2->second.empty()) { + if (bInit) { + if (value.type == gfx::Type::MAT4) { + // init matrix to identity + CC_EXPECTS(sizeof(Mat4) == typeSize); + const Mat4 id{}; + for (uint32_t i = 0; i != value.count; ++i) { + memcpy(buffer.data() + offset + i * typeSize, id.m, typeSize); + } + } + } + offset += totalSize; + continue; + } + const auto& source = iter2->second; + CC_EXPECTS(source.size() == totalSize); + CC_EXPECTS(offset + totalSize <= bufferSize); + memcpy(buffer.data() + offset, source.data(), + std::min(source.size(), totalSize)); // safe guard min + offset += totalSize; + } + CC_ENSURES(offset == bufferSize); +} + +void uploadUniformBuffer( + gfx::DescriptorSet* passSet, + uint32_t bindID, + UniformBlockResource& resource) { + auto* buffer = resource.bufferPool.allocateBuffer(); + CC_ENSURES(buffer); + buffer->update(resource.cpuBuffer.data(), + static_cast(resource.cpuBuffer.size())); + + CC_EXPECTS(passSet); + passSet->bindBuffer(bindID, buffer); +} + +void initPerPassDescriptorSet( + ResourceGraph& resg, + gfx::Device* device, + gfx::CommandBuffer* cmdBuff, + const gfx::DefaultResource& defaultResource, + const LayoutGraphData& lg, + const PmrFlatMap& resourceIndex, + const DescriptorSetData& set, + const RenderData& user, + LayoutGraphNodeResource& node) { + // update per pass resources + const auto& data = set.descriptorSetLayoutData; + + gfx::DescriptorSet* passSet = node.descriptorSetPool.allocateDescriptorSet(); + for (const auto& block : data.descriptorBlocks) { + CC_EXPECTS(block.descriptors.size() == block.capacity); + auto bindID = block.offset; + switch (block.type) { + case DescriptorTypeOrder::UNIFORM_BUFFER: { + for (const auto& d : block.descriptors) { + // get uniform block + const auto& uniformBlock = data.uniformBlocks.at(d.descriptorID); + + auto& resource = node.uniformBuffers.at(d.descriptorID); + updateCpuUniformBuffer(lg, user, uniformBlock, true, resource.cpuBuffer); + CC_ENSURES(resource.bufferPool.bufferSize == resource.cpuBuffer.size()); + + // upload gfx buffer + uploadUniformBuffer(passSet, bindID, resource); + + // increase slot + // TODO(zhouzhenglong): here binding will be refactored in the future + // current implementation is incorrect, and we assume d.count == 1 + CC_EXPECTS(d.count == 1); + bindID += d.count; + } + break; + } + case DescriptorTypeOrder::DYNAMIC_UNIFORM_BUFFER: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::SAMPLER_TEXTURE: { + CC_EXPECTS(passSet); + for (const auto& d : block.descriptors) { + CC_EXPECTS(d.count == 1); + CC_EXPECTS(d.type >= gfx::Type::SAMPLER1D && + d.type <= gfx::Type::SAMPLER_CUBE); + + auto iter = resourceIndex.find(d.descriptorID); + if (iter != resourceIndex.end()) { + // render graph textures + auto* texture = resg.getTexture(iter->second); + CC_ENSURES(texture); + passSet->bindTexture(bindID, texture); + } else { + // user provided textures + auto iter = user.textures.find(d.descriptorID.value); + if (iter != user.textures.end()) { + passSet->bindTexture(bindID, iter->second.get()); + } else { + // default textures + gfx::TextureType type{}; + switch (d.type) { + case gfx::Type::SAMPLER1D: + type = gfx::TextureType::TEX1D; + break; + case gfx::Type::SAMPLER1D_ARRAY: + type = gfx::TextureType::TEX1D_ARRAY; + break; + case gfx::Type::SAMPLER2D: + type = gfx::TextureType::TEX2D; + break; + case gfx::Type::SAMPLER2D_ARRAY: + type = gfx::TextureType::TEX2D_ARRAY; + break; + case gfx::Type::SAMPLER3D: + type = gfx::TextureType::TEX3D; + break; + case gfx::Type::SAMPLER_CUBE: + type = gfx::TextureType::CUBE; + break; + default: + break; + } + passSet->bindTexture(bindID, defaultResource.getTexture(type)); + } + } + bindID += d.count; + } + break; + } + case DescriptorTypeOrder::SAMPLER: + for (const auto& d : block.descriptors) { + CC_EXPECTS(d.count == 1); + auto iter = user.samplers.find(d.descriptorID.value); + if (iter != user.samplers.end()) { + passSet->bindSampler(bindID, iter->second.get()); + } else { + gfx::SamplerInfo info{}; + auto* sampler = device->getSampler(info); + passSet->bindSampler(bindID, sampler); + } + bindID += d.count; + } + break; + case DescriptorTypeOrder::TEXTURE: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::STORAGE_BUFFER: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::DYNAMIC_STORAGE_BUFFER: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::STORAGE_IMAGE: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::INPUT_ATTACHMENT: + // not supported yet + CC_EXPECTS(false); + break; + default: + CC_EXPECTS(false); + break; + } + } + passSet->update(); + cmdBuff->bindDescriptorSet(static_cast(pipeline::SetIndex::GLOBAL), passSet); +} + +void updatePerPassDescriptorSet( + gfx::CommandBuffer* cmdBuff, + const LayoutGraphData& lg, + const DescriptorSetData& set, + const RenderData& user, + LayoutGraphNodeResource& node) { + // update per pass resources + const auto& data = set.descriptorSetLayoutData; + + auto& prevSet = node.descriptorSetPool.getCurrentDescriptorSet(); + gfx::DescriptorSet* newSet = node.descriptorSetPool.allocateDescriptorSet(); + for (const auto& block : data.descriptorBlocks) { + CC_EXPECTS(block.descriptors.size() == block.capacity); + auto bindID = block.offset; + switch (block.type) { + case DescriptorTypeOrder::UNIFORM_BUFFER: { + for (const auto& d : block.descriptors) { + // get uniform block + const auto& uniformBlock = data.uniformBlocks.at(d.descriptorID); + + auto& resource = node.uniformBuffers.at(d.descriptorID); + updateCpuUniformBuffer(lg, user, uniformBlock, false, resource.cpuBuffer); + + // upload gfx buffer + uploadUniformBuffer(newSet, bindID, resource); + + // increase slot + // TODO(zhouzhenglong): here binding will be refactored in the future + // current implementation is incorrect, and we assume d.count == 1 + CC_EXPECTS(d.count == 1); + bindID += d.count; + } + break; + } + case DescriptorTypeOrder::DYNAMIC_UNIFORM_BUFFER: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::SAMPLER_TEXTURE: { + CC_EXPECTS(newSet); + for (const auto& d : block.descriptors) { + CC_EXPECTS(d.count == 1); + CC_EXPECTS(d.type >= gfx::Type::SAMPLER1D && + d.type <= gfx::Type::SAMPLER_CUBE); + auto iter = user.textures.find(d.descriptorID.value); + if (iter != user.textures.end()) { + newSet->bindTexture(bindID, iter->second.get()); + } else { + auto* prevTexture = prevSet.getTexture(bindID); + CC_ENSURES(prevTexture); + newSet->bindTexture(bindID, prevTexture); + } + bindID += d.count; + } + break; + } + case DescriptorTypeOrder::SAMPLER: + for (const auto& d : block.descriptors) { + CC_EXPECTS(d.count == 1); + auto iter = user.samplers.find(d.descriptorID.value); + if (iter != user.samplers.end()) { + newSet->bindSampler(bindID, iter->second.get()); + } else { + auto* prevSampler = prevSet.getSampler(bindID); + CC_ENSURES(prevSampler); + newSet->bindSampler(bindID, prevSampler); + } + bindID += d.count; + } + break; + case DescriptorTypeOrder::TEXTURE: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::STORAGE_BUFFER: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::DYNAMIC_STORAGE_BUFFER: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::STORAGE_IMAGE: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::INPUT_ATTACHMENT: + // not supported yet + CC_EXPECTS(false); + break; + default: + CC_EXPECTS(false); + break; + } + } + newSet->update(); + cmdBuff->bindDescriptorSet(static_cast(pipeline::SetIndex::GLOBAL), newSet); +} + +void updateCameraUniformBufferAndDescriptorSet( + RenderGraphVisitorContext& ctx, RenderGraph::vertex_descriptor sceneID) { + // update states + CC_EXPECTS(ctx.currentPassLayoutID != LayoutGraphData::null_vertex()); + const auto& passLayoutID = ctx.currentPassLayoutID; + auto& layout = get(LayoutGraphData::Layout, ctx.lg, passLayoutID); + auto iter = layout.descriptorSets.find(UpdateFrequency::PER_PASS); + if (iter != layout.descriptorSets.end()) { + auto& set = iter->second; + auto& node = ctx.context.layoutGraphResources.at(passLayoutID); + const auto& user = get(RenderGraph::Data, ctx.g, sceneID); // notice: sceneID + updatePerPassDescriptorSet(ctx.cmdBuff, ctx.lg, set, user, node); + } +} + +void submitUICommands( + gfx::RenderPass* renderPass, + uint32_t layoutPassID, + scene::Camera* camera, + gfx::CommandBuffer* cmdBuff) { + const auto& batches = camera->getScene()->getBatches(); + for (auto* batch : batches) { + if (!(camera->getVisibility() & batch->getVisFlags())) { + continue; + } + const auto& passes = batch->getPasses(); + for (size_t i = 0; i < batch->getShaders().size(); ++i) { + const scene::Pass* pass = passes[i]; + if (pass->getPassID() != layoutPassID) { + continue; + } + auto* shader = batch->getShaders()[i]; + auto* inputAssembler = batch->getInputAssembler(); + auto* ds = batch->getDescriptorSet(); + auto* pso = pipeline::PipelineStateManager::getOrCreatePipelineState( + pass, shader, inputAssembler, renderPass); + cmdBuff->bindPipelineState(pso); + cmdBuff->bindDescriptorSet( + static_cast(pipeline::SetIndex::MATERIAL), + pass->getDescriptorSet()); + cmdBuff->bindInputAssembler(inputAssembler); + cmdBuff->bindDescriptorSet( + static_cast(pipeline::SetIndex::LOCAL), ds); + cmdBuff->draw(inputAssembler); + } + } +} + +void submitProfilerCommands( + RenderGraphVisitorContext& ctx, + const RasterPass& rasterPass) { + const auto* profiler = ctx.ppl->getProfiler(); + if (!profiler || !profiler->isEnabled()) { + return; + } + auto* renderPass = ctx.currentPass; + auto* cmdBuff = ctx.cmdBuff; + const auto& submodel = profiler->getSubModels()[0]; + auto* pass = submodel->getPass(0); + auto* ia = submodel->getInputAssembler(); + auto* pso = pipeline::PipelineStateManager::getOrCreatePipelineState( + pass, submodel->getShader(0), ia, renderPass); + + // current pass + RenderData user(ctx.scratch); + NativeSetter setter(ctx.lg, user); + setter.setMat4("cc_matProj", ctx.currentProjMatrix); + + // profiler pass + gfx::Viewport profilerViewport{}; + gfx::Rect profilerScissor{}; + profilerViewport.width = profilerScissor.width = rasterPass.width; + profilerViewport.height = profilerScissor.height = rasterPass.height; + cmdBuff->setViewport(profilerViewport); + cmdBuff->setScissor(profilerScissor); + + cmdBuff->bindPipelineState(pso); + { + auto& layout = get(LayoutGraphData::Layout, ctx.lg, pass->getPassID()); + auto iter = layout.descriptorSets.find(UpdateFrequency::PER_PASS); + if (iter != layout.descriptorSets.end()) { + auto& set = iter->second; + auto& node = ctx.context.layoutGraphResources.at(pass->getPassID()); + PmrFlatMap resourceIndex(ctx.scratch); + initPerPassDescriptorSet( + ctx.resourceGraph, + ctx.device, ctx.cmdBuff, + *ctx.context.defaultResource, ctx.lg, + resourceIndex, set, user, node); + } else { + CC_EXPECTS(false); + // TODO(zhouzhenglong): set descriptor set to empty + } + } + cmdBuff->bindDescriptorSet(static_cast(pipeline::SetIndex::MATERIAL), pass->getDescriptorSet()); + cmdBuff->bindDescriptorSet(static_cast(pipeline::SetIndex::LOCAL), submodel->getDescriptorSet()); + cmdBuff->bindInputAssembler(ia); + cmdBuff->draw(ia); +} + struct RenderGraphVisitor : boost::dfs_visitor<> { void submitBarriers(const std::vector& barriers) const { - const auto& resg = ctx.resourceGraph; + auto& resg = ctx.resourceGraph; auto sz = barriers.size(); ccstd::pmr::vector buffers(ctx.scratch); ccstd::pmr::vector bufferBarriers(ctx.scratch); @@ -404,18 +918,28 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { textureBarriers.data(), textures.data(), static_cast(textureBarriers.size())); } void frontBarriers(RenderGraph::vertex_descriptor vertID) const { - auto iter = ctx.barrierMap.find(vertID + 1); - if (iter != ctx.barrierMap.end()) { - submitBarriers(iter->second.blockBarrier.frontBarriers); + auto iter = ctx.fgd.resourceAccessGraph.passIndex.find(vertID); + if (iter == ctx.fgd.resourceAccessGraph.passIndex.end()) { + return; + } + const auto& nodeID = iter->second; + auto iter2 = ctx.barrierMap.find(nodeID); + if (iter2 != ctx.barrierMap.end()) { + submitBarriers(iter2->second.blockBarrier.frontBarriers); } } void rearBarriers(RenderGraph::vertex_descriptor vertID) const { - auto iter = ctx.barrierMap.find(vertID + 1); - if (iter != ctx.barrierMap.end()) { - submitBarriers(iter->second.blockBarrier.rearBarriers); + auto iter = ctx.fgd.resourceAccessGraph.passIndex.find(vertID); + if (iter == ctx.fgd.resourceAccessGraph.passIndex.end()) { + return; + } + const auto& nodeID = iter->second; + auto iter2 = ctx.barrierMap.find(nodeID); + if (iter2 != ctx.barrierMap.end()) { + submitBarriers(iter2->second.blockBarrier.rearBarriers); } } - void begin(const RasterPass& pass) const { + void begin(const RasterPass& pass, RenderGraph::vertex_descriptor vertID) const { // viewport auto vp = pass.viewport; if (vp.width == 0 && vp.height == 0) { @@ -426,31 +950,56 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { gfx::Rect scissor{0, 0, vp.width, vp.height}; // render pass - auto iter = ctx.context.renderPasses.find(pass); - if (iter == ctx.context.renderPasses.end()) { - bool added = false; - std::tie(iter, added) = ctx.context.renderPasses.emplace( - pass, createPersistentRenderPassAndFramebuffer(ctx, pass)); - CC_ENSURES(added); + const auto& layoutName = get(RenderGraph::Layout, ctx.g, vertID); + const auto& layoutID = locate(LayoutGraphData::null_vertex(), layoutName, ctx.lg); + { + auto& res = fetchOrCreateFramebuffer(ctx, pass, ctx.scratch); + const auto& data = res; + auto* cmdBuff = ctx.cmdBuff; + + cmdBuff->beginRenderPass( + data.renderPass.get(), + data.framebuffer.get(), + scissor, data.clearColors.data(), + data.clearDepth, data.clearStencil); + + ctx.currentPass = data.renderPass.get(); + ctx.currentPassLayoutID = layoutID; } - ++iter->second.refCount; - const auto& data = iter->second; - auto* cmdBuff = ctx.cmdBuff; - cmdBuff->beginRenderPass( - data.renderPass.get(), - data.framebuffer.get(), - scissor, data.clearColors.data(), - data.clearDepth, data.clearStencil); + // get layout + auto& layout = get(LayoutGraphData::Layout, ctx.lg, layoutID); - ctx.currentPass = data.renderPass.get(); + // build pass resources + PmrFlatMap resourceIndex(ctx.scratch); + resourceIndex.reserve(pass.computeViews.size() * 2); + for (const auto& [resName, computeViews] : pass.computeViews) { + const auto resID = vertex(resName, ctx.resourceGraph); + for (const auto& computeView : computeViews) { + const auto& name = computeView.name; + CC_EXPECTS(!name.empty()); + const auto nameID = ctx.lg.attributeIndex.at(name); + resourceIndex.emplace(nameID, resID); + } + } // update states - // auto offset = ctx.ppl->getPipelineUBO()->getCurrentCameraUBOOffset(); - // cmdBuff->bindDescriptorSet(pipeline::globalSet, ctx.getDescriptorSet(), 1, &offset); + auto iter = layout.descriptorSets.find(UpdateFrequency::PER_PASS); + if (iter == layout.descriptorSets.end()) { + return; + } + auto& set = iter->second; + const auto& user = get(RenderGraph::Data, ctx.g, vertID); + auto& node = ctx.context.layoutGraphResources.at(layoutID); + initPerPassDescriptorSet( + ctx.resourceGraph, + ctx.device, ctx.cmdBuff, + *ctx.context.defaultResource, ctx.lg, + resourceIndex, set, user, node); } - void begin(const ComputePass& pass) const { // NOLINT(readability-convert-member-functions-to-static) + void begin(const ComputePass& pass, RenderGraph::vertex_descriptor vertID) const { // NOLINT(readability-convert-member-functions-to-static) std::ignore = pass; + std::ignore = vertID; for (const auto& [name, views] : pass.computeViews) { for (const auto& view : views) { if (view.clearFlags != gfx::ClearFlags::NONE) { @@ -459,35 +1008,43 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { } } } - void begin(const CopyPass& pass) const { // NOLINT(readability-convert-member-functions-to-static) + void begin(const CopyPass& pass, RenderGraph::vertex_descriptor vertID) const { // NOLINT(readability-convert-member-functions-to-static) std::ignore = pass; + std::ignore = vertID; for (const auto& copy : pass.copyPairs) { } } - void begin(const MovePass& pass) const { // NOLINT(readability-convert-member-functions-to-static) + void begin(const MovePass& pass, RenderGraph::vertex_descriptor vertID) const { // NOLINT(readability-convert-member-functions-to-static) std::ignore = pass; + std::ignore = vertID; // if fully optimized, move pass should have been removed from graph // here we just do copy for (const auto& copy : pass.movePairs) { } } - void begin(const PresentPass& pass) const { // NOLINT(readability-convert-member-functions-to-static) + void begin(const PresentPass& pass, RenderGraph::vertex_descriptor vertID) const { // NOLINT(readability-convert-member-functions-to-static) std::ignore = pass; + std::ignore = vertID; for (const auto& [name, present] : pass.presents) { // do presents } } - void begin(const RaytracePass& pass) const { // NOLINT(readability-convert-member-functions-to-static) + void begin(const RaytracePass& pass, RenderGraph::vertex_descriptor vertID) const { // NOLINT(readability-convert-member-functions-to-static) std::ignore = pass; + std::ignore = vertID; // not implemented yet CC_EXPECTS(false); } - void begin(const RenderQueue& pass) const { + void begin(const RenderQueue& pass, RenderGraph::vertex_descriptor vertID) const { // update uniform buffers and descriptor sets } - void begin(const SceneData& sceneData) const { - return; + void begin(const SceneData& sceneData, RenderGraph::vertex_descriptor sceneID) const { auto* camera = sceneData.camera; + CC_EXPECTS(camera); + if (camera) { // update camera data + updateCameraUniformBufferAndDescriptorSet(ctx, sceneID); + ctx.currentProjMatrix = camera->getMatProj(); + } const auto* scene = camera->getScene(); const auto& queues = ctx.sceneQueues.at(scene); const auto& queue = queues.at(camera); @@ -498,39 +1055,140 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { bDrawInstancing = true; } if (any(sceneData.flags & (SceneFlags::OPAQUE_OBJECT | SceneFlags::CUTOUT_OBJECT))) { - if (bDraw) { - queue.opaqueQueue.recordCommandBuffer( - ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); - } + queue.opaqueQueue.recordCommandBuffer( + ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); if (bDrawInstancing) { queue.opaqueInstancingQueue.recordCommandBuffer( ctx.currentPass, ctx.cmdBuff); } } if (any(sceneData.flags & SceneFlags::TRANSPARENT_OBJECT)) { - if (bDraw) { - queue.transparentQueue.recordCommandBuffer( - ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); - } + queue.transparentQueue.recordCommandBuffer( + ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); if (bDrawInstancing) { queue.transparentInstancingQueue.recordCommandBuffer( ctx.currentPass, ctx.cmdBuff); } } + if (any(sceneData.flags & SceneFlags::UI)) { + submitUICommands(ctx.currentPass, + ctx.currentPassLayoutID, camera, ctx.cmdBuff); + } } - void begin(const Blit& pass) const { + void begin(const Blit& blit, RenderGraph::vertex_descriptor vertID) const { + const auto& programLib = *dynamic_cast(ctx.programLib); + CC_EXPECTS(blit.material); + CC_EXPECTS(blit.material->getPasses()); + if (blit.camera) { + updateCameraUniformBufferAndDescriptorSet(ctx, vertID); + ctx.currentProjMatrix = blit.camera->getMatProj(); + } + // get pass + auto& pass = *blit.material->getPasses()->at(static_cast(blit.passID)); + // get shader + auto& shader = *pass.getShaderVariant(); + // get pso + auto* pso = pipeline::PipelineStateManager::getOrCreatePipelineState( + &pass, &shader, ctx.context.fullscreenQuad.quadIA.get(), ctx.currentPass); + if (!pso) { + return; + } + // update material ubo and descriptor set + pass.update(); + + // get or create program per-instance descriptor set + auto& node = ctx.context.layoutGraphResources.at(pass.getPhaseID()); + auto iter = node.programResources.find(std::string_view{shader.getName()}); + if (iter == node.programResources.end()) { + // make program resource + auto res = node.programResources.emplace( + std::piecewise_construct, + std::forward_as_tuple(shader.getName()), + std::forward_as_tuple()); + CC_ENSURES(res.second); + iter = res.first; + auto& instance = res.first->second; + + // make per-instance layout + IntrusivePtr instanceSetLayout = + &const_cast( + ctx.programLib->getLocalDescriptorSetLayout( + ctx.device, pass.getPhaseID(), shader.getName())); + + // init per-instance descriptor set pool + instance.descriptorSetPool.init(ctx.device, std::move(instanceSetLayout)); + + for (const auto& block : shader.getBlocks()) { + if (static_cast(block.set) != pipeline::SetIndex::LOCAL) { + continue; + } + const auto& name = block.name; + auto iter = ctx.lg.attributeIndex.find(std::string_view{name}); + CC_EXPECTS(iter != ctx.lg.attributeIndex.end()); + const auto attrID = iter->second; + auto sz = getUniformBlockSize(block.members); + const auto bDynamic = isDynamicUniformBlock(block.name); + instance.uniformBuffers[attrID].init(ctx.device, sz, bDynamic); + } + } + + // update per-instance buffer and descriptor set + const auto& data = programLib.localLayoutData; + auto& instance = iter->second; + auto* set = instance.descriptorSetPool.allocateDescriptorSet(); + CC_ENSURES(set); + for (const auto& block : shader.getBlocks()) { + if (static_cast(block.set) != pipeline::SetIndex::LOCAL) { + continue; + } + // find descriptor name ID + const auto& name = block.name; + auto iter = ctx.lg.attributeIndex.find(std::string_view{name}); + CC_EXPECTS(iter != ctx.lg.attributeIndex.end()); + const auto attrID = iter->second; + + // get uniformBuffer + auto& uniformBuffer = instance.uniformBuffers[attrID]; + CC_EXPECTS(uniformBuffer.cpuBuffer.size() == uniformBuffer.bufferPool.bufferSize); + + // fill cpu buffer + auto& cpuData = uniformBuffer.cpuBuffer; + if (false) { // NOLINT(readability-simplify-boolean-expr) + for (const auto& v : block.members) { + CC_LOG_INFO(v.name.c_str()); + } + } + + // create and upload buffer + auto* buffer = uniformBuffer.createFromCpuBuffer(); + + // set buffer descriptor + const auto binding = data.bindingMap.at(attrID); + set->bindBuffer(binding, buffer); + } + + // execution + ctx.cmdBuff->bindPipelineState(pso); + ctx.cmdBuff->bindDescriptorSet( + static_cast(pipeline::SetIndex::MATERIAL), pass.getDescriptorSet()); + ctx.cmdBuff->bindDescriptorSet( + static_cast(pipeline::SetIndex::LOCAL), set); + ctx.cmdBuff->bindInputAssembler(ctx.context.fullscreenQuad.quadIA.get()); + ctx.cmdBuff->draw(ctx.context.fullscreenQuad.quadIA.get()); } - void begin(const Dispatch& pass) const { + void begin(const Dispatch& pass, RenderGraph::vertex_descriptor vertID) const { } - void begin(const ccstd::pmr::vector& pass) const { + void begin(const ccstd::pmr::vector& pass, RenderGraph::vertex_descriptor vertID) const { } - void begin(const gfx::Viewport& pass) const { + void begin(const gfx::Viewport& pass, RenderGraph::vertex_descriptor vertID) const { } void end(const RasterPass& pass) const { - std::ignore = pass; - auto* cmdBuff = ctx.cmdBuff; - cmdBuff->endRenderPass(); + if (pass.showStatistics) { + submitProfilerCommands(ctx, pass); + } + ctx.cmdBuff->endRenderPass(); ctx.currentPass = nullptr; + ctx.currentPassLayoutID = LayoutGraphData::null_vertex(); } void end(const ComputePass& pass) const { } @@ -619,34 +1277,34 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { [&](const RasterPass& pass) { mountResources(pass); frontBarriers(vertID); - begin(pass); + begin(pass, vertID); }, [&](const ComputePass& pass) { mountResources(pass); frontBarriers(vertID); - begin(pass); + begin(pass, vertID); }, [&](const CopyPass& pass) { mountResources(pass); frontBarriers(vertID); - begin(pass); + begin(pass, vertID); }, [&](const MovePass& pass) { mountResources(pass); frontBarriers(vertID); - begin(pass); + begin(pass, vertID); }, [&](const PresentPass& pass) { frontBarriers(vertID); - begin(pass); + begin(pass, vertID); }, [&](const RaytracePass& pass) { mountResources(pass); frontBarriers(vertID); - begin(pass); + begin(pass, vertID); }, [&](const auto& queue) { - begin(queue); + begin(queue, vertID); }); } @@ -722,15 +1380,7 @@ struct RenderGraphContextCleaner { } RenderGraphContextCleaner(const RenderGraphContextCleaner&) = delete; RenderGraphContextCleaner& operator=(const RenderGraphContextCleaner&) = delete; - ~RenderGraphContextCleaner() noexcept { - for (auto iter = context.renderPasses.begin(); iter != context.renderPasses.end();) { - if (--iter->second.refCount == 0) { - iter = context.renderPasses.erase(iter); - } else { - ++iter; - } - } - } + ~RenderGraphContextCleaner() noexcept = default; NativeRenderContext& context; uint64_t prevFenceValue = 0; }; @@ -793,20 +1443,22 @@ float computeSortingDepth(const scene::Camera& camera, const scene::Model& model float depth = 0; if (model.getNode()) { const auto* node = model.getTransform(); - cc::Vec3 position; - cc::Vec3::subtract(node->getWorldPosition(), camera.getPosition(), &position); + Vec3 position; + Vec3::subtract(node->getWorldPosition(), camera.getPosition(), &position); depth = position.dot(camera.getForward()); } return depth; } void addRenderObject( + LayoutGraphData::vertex_descriptor shadowCasterlayoutID, const scene::Camera& camera, const scene::Model& model, NativeRenderQueue& queue) { const bool bDrawTransparent = any(queue.sceneFlags & SceneFlags::TRANSPARENT_OBJECT); bool bDrawOpaqueOrCutout = any(queue.sceneFlags & (SceneFlags::OPAQUE_OBJECT | SceneFlags::CUTOUT_OBJECT)); if (!bDrawTransparent && !bDrawOpaqueOrCutout) { bDrawOpaqueOrCutout = true; } + const bool bDrawShadowCaster = any(queue.sceneFlags & SceneFlags::SHADOW_CASTER); const auto& subModels = model.getSubModels(); const auto subModelCount = subModels.size(); @@ -818,6 +1470,7 @@ void addRenderObject( auto& pass = *passes[passIdx]; const bool bTransparent = isTransparent(pass); const bool bOpaqueOrCutout = !bTransparent; + const bool bShadowCaster = pass.getPhaseID() == shadowCasterlayoutID; if (!bDrawTransparent && bTransparent) { // skip transparent object @@ -829,6 +1482,17 @@ void addRenderObject( continue; } + // skip irrelavent passes + if (queue.layoutPassID != pass.getPassID()) { + continue; + } + + // skip shadow caster + if (!bDrawShadowCaster && bShadowCaster) { + continue; + } + + // add object to queue if (pass.getBatchingScheme() == scene::BatchingSchemes::INSTANCING) { auto& instancedBuffer = *pass.getInstancedBuffer(); instancedBuffer.merge(subModel, passIdx); @@ -850,6 +1514,7 @@ void addRenderObject( } void octreeCulling( + LayoutGraphData::vertex_descriptor shadowCasterlayoutID, const scene::Octree* octree, const scene::RenderScene* scene, const scene::Skybox* skyBox, @@ -871,7 +1536,7 @@ void octreeCulling( } const auto visibility = camera.getVisibility(); if (isInstanceVisible(model, visibility) && isPointInstanceAndNotSkybox(model, skyBox)) { - addRenderObject(camera, model, queue); + addRenderObject(shadowCasterlayoutID, camera, model, queue); } } @@ -885,11 +1550,12 @@ void octreeCulling( if (scene->isCulledByLod(&camera, &model)) { continue; } - addRenderObject(camera, model, queue); + addRenderObject(shadowCasterlayoutID, camera, model, queue); } } void frustumCulling( + LayoutGraphData::vertex_descriptor shadowCasterlayoutID, const scene::RenderScene* scene, const scene::Camera& camera, NativeRenderQueue& queue) { @@ -917,12 +1583,12 @@ void frustumCulling( const auto* modelWorldBounds = model.getWorldBounds(); // object has no volume if (!modelWorldBounds) { - addRenderObject(camera, model, queue); + addRenderObject(shadowCasterlayoutID, camera, model, queue); continue; } // frustum culling if (modelWorldBounds->aabbFrustum(camera.getFrustum())) { - addRenderObject(camera, model, queue); + addRenderObject(shadowCasterlayoutID, camera, model, queue); } } } @@ -930,6 +1596,7 @@ void frustumCulling( void mergeSceneFlags( const RenderGraph& rg, + const LayoutGraphData& lg, ccstd::pmr::unordered_map< const scene::RenderScene*, ccstd::pmr::unordered_map>& @@ -938,10 +1605,21 @@ void mergeSceneFlags( if (!holds(vertID, rg)) { continue; } + const auto queueID = parent(vertID, rg); + CC_ENSURES(queueID != RenderGraph::null_vertex()); + const auto passID = parent(queueID, rg); + CC_ENSURES(passID != RenderGraph::null_vertex()); + const auto& layoutName = get(RenderGraph::Layout, rg, passID); + CC_ENSURES(!layoutName.empty()); + const auto layoutID = locate(LayoutGraphData::null_vertex(), layoutName, lg); + CC_ENSURES(layoutID != LayoutGraphData::null_vertex()); + const auto& sceneData = get(SceneTag{}, vertID, rg); const auto* scene = sceneData.camera->getScene(); if (scene) { - sceneQueues[scene][sceneData.camera].sceneFlags |= sceneData.flags; + auto& queue = sceneQueues[scene][sceneData.camera]; + queue.sceneFlags |= sceneData.flags; + queue.layoutPassID = layoutID; } } } @@ -957,11 +1635,13 @@ void extendResourceLifetime(const NativeRenderQueue& queue, ResourceGroup& group } void buildRenderQueues( + LayoutGraphData::vertex_descriptor shadowCasterlayoutID, + const pipeline::PipelineSceneData& sceneData, NativeRenderContext& context, ccstd::pmr::unordered_map< const scene::RenderScene*, ccstd::pmr::unordered_map>& sceneQueues) { - const scene::Skybox* skyBox = nullptr; + const scene::Skybox* skybox = sceneData.getSkybox(); auto& group = context.resourceGroups[context.nextFenceValue]; @@ -972,10 +1652,27 @@ void buildRenderQueues( if (!camera->isCullingEnabled()) { continue; } + + // skybox + if (skybox && skybox->isEnabled() && + (static_cast(camera->getClearFlag()) & scene::Camera::SKYBOX_FLAG)) { + CC_EXPECTS(skybox->getModel()); + const auto& model = *skybox->getModel(); + const auto* node = model.getNode(); + float depth = 0; + if (node) { + Vec3 tempVec3{}; + tempVec3 = node->getWorldPosition() - camera->getPosition(); + depth = tempVec3.dot(camera->getForward()); + } + queue.opaqueQueue.add(model, depth, 0, 0); + } + + // culling if (octree && octree->isEnabled()) { - octreeCulling(octree, scene, skyBox, *camera, queue); + octreeCulling(shadowCasterlayoutID, octree, scene, skybox, *camera, queue); } else { - frustumCulling(scene, *camera, queue); + frustumCulling(shadowCasterlayoutID, scene, *camera, queue); } queue.sort(); @@ -991,14 +1688,15 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { auto& ppl = *this; auto* scratch = &ppl.unsyncPool; - // CC_LOG_INFO(rg.print(scratch).c_str()); + ppl.resourceGraph.validateSwapchains(); RenderGraphContextCleaner contextCleaner(ppl.nativeContext); ResourceCleaner cleaner(ppl.resourceGraph); + auto& lg = ppl.programLibrary->layoutGraph; FrameGraphDispatcher fgd( ppl.resourceGraph, rg, - ppl.layoutGraph, &ppl.unsyncPool, scratch); + lg, &ppl.unsyncPool, scratch); fgd.enableMemoryAliasing(false); fgd.enablePassReorder(false); fgd.setParalellWeight(0); @@ -1010,10 +1708,11 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { { // Mark all culled vertices RenderGraphCullVisitor visitor{{}, validPasses}; for (const auto& vertID : fgd.resourceAccessGraph.culledPasses) { - const auto passID = get(ResourceAccessGraph::PassID, fgd.resourceAccessGraph, vertID); - if (passID == RenderGraph::null_vertex()) { + const auto nodeID = get(ResourceAccessGraph::PassID, fgd.resourceAccessGraph, vertID); + if (nodeID == RenderGraph::null_vertex()) { continue; } + const auto passID = fgd.resourceAccessGraph.passIndex.at(nodeID); boost::depth_first_visit(graphView, passID, visitor, get(colors, rg)); } colors.clear(); @@ -1026,8 +1725,14 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { ccstd::pmr::unordered_map> sceneQueues(scratch); { - mergeSceneFlags(rg, sceneQueues); - buildRenderQueues(ppl.nativeContext, sceneQueues); + mergeSceneFlags(rg, lg, sceneQueues); + const auto shadowCasterLayoutID = locate("/default/shadow-caster", lg); + CC_ENSURES(shadowCasterLayoutID != LayoutGraphData::null_vertex()); + buildRenderQueues( + shadowCasterLayoutID, + *ppl.getPipelineSceneData(), + ppl.nativeContext, + sceneQueues); } // Execute all valid passes @@ -1048,14 +1753,16 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { } // submit commands - RenderGraphVisitorContext ctx( - ppl.nativeContext, rg, ppl.resourceGraph, + RenderGraphVisitorContext ctx{ + ppl.nativeContext, + lg, rg, ppl.resourceGraph, fgd, fgd.barrierMap, validPasses, ppl.device, submit.primaryCommandBuffer, sceneQueues, &ppl, - scratch); + programLibrary, + scratch}; RenderGraphVisitor visitor{{}, ctx}; boost::depth_first_search(fg, visitor, get(colors, rg)); diff --git a/native/cocos/renderer/pipeline/custom/NativeFactory.cpp b/native/cocos/renderer/pipeline/custom/NativeFactory.cpp index cfa0bd5d43..3e8c89ef30 100644 --- a/native/cocos/renderer/pipeline/custom/NativeFactory.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeFactory.cpp @@ -28,6 +28,7 @@ #include "LayoutGraphSerialization.h" #include "NativePipelineTypes.h" #include "RenderInterfaceTypes.h" +#include "RenderingModule.h" #include "details/GslUtils.h" #include "pipeline/custom/LayoutGraphTypes.h" #include "pipeline/custom/details/Pmr.h" @@ -39,12 +40,11 @@ namespace render { namespace { NativeRenderingModule* sRenderingModule = nullptr; +NativePipeline* sPipeline = nullptr; } // namespace RenderingModule* Factory::init(gfx::Device* deviceIn, const ccstd::vector& bufferIn) { - std::ignore = deviceIn; - std::shared_ptr ptr( allocatePmrUniquePtr( boost::container::pmr::get_default_resource())); @@ -54,6 +54,7 @@ RenderingModule* Factory::init(gfx::Device* deviceIn, const ccstd::vectorlayoutGraph); } + ptr->init(deviceIn); sRenderingModule = ccnew NativeRenderingModule(std::move(ptr)); return sRenderingModule; @@ -63,11 +64,31 @@ void Factory::destroy(RenderingModule* renderingModule) noexcept { auto* ptr = dynamic_cast(renderingModule); if (ptr) { ptr->programLibrary.reset(); + CC_EXPECTS(sRenderingModule == renderingModule); + sRenderingModule = nullptr; + sPipeline = nullptr; } } Pipeline* Factory::createPipeline() { - return ccnew NativePipeline(boost::container::pmr::get_default_resource()); + if (sPipeline) { + return sPipeline; + } + sPipeline = ccnew NativePipeline(boost::container::pmr::get_default_resource()); + CC_EXPECTS(sRenderingModule); + sRenderingModule->programLibrary->pipeline = sPipeline; + return sPipeline; +} + +ProgramLibrary* getProgramLibrary() { + if (!sRenderingModule) { + return nullptr; + } + return sRenderingModule->programLibrary.get(); +} + +RenderingModule* getRenderingModule() { + return sRenderingModule; } } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativeFwd.h b/native/cocos/renderer/pipeline/custom/NativeFwd.h index f4991e9cfa..6793b1776f 100644 --- a/native/cocos/renderer/pipeline/custom/NativeFwd.h +++ b/native/cocos/renderer/pipeline/custom/NativeFwd.h @@ -30,16 +30,14 @@ // clang-format off #pragma once #include "cocos/base/std/variant.h" -#include "cocos/renderer/core/ProgramLib.h" #include "cocos/renderer/pipeline/custom/LayoutGraphFwd.h" -#include "cocos/renderer/pipeline/custom/RenderInterfaceFwd.h" +#include "cocos/renderer/pipeline/custom/PrivateFwd.h" namespace cc { namespace render { struct ProgramInfo; -struct ProgramHost; struct ProgramGroup; } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativeLayoutGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeLayoutGraph.cpp deleted file mode 100644 index 26c5c95a5c..0000000000 --- a/native/cocos/renderer/pipeline/custom/NativeLayoutGraph.cpp +++ /dev/null @@ -1,334 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021-2023 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 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. -****************************************************************************/ - -#include "LayoutGraphGraphs.h" -#include "LayoutGraphNames.h" -#include "LayoutGraphTypes.h" -#include "NativePipelineGraphs.h" -#include "RenderCommonNames.h" -#include "cocos/renderer/gfx-base/GFXDevice.h" -#include "details/DebugUtils.h" -#include "details/GslUtils.h" -#include "details/Pmr.h" -#include "details/Range.h" - -namespace cc { - -namespace render { - -void NativeLayoutGraphBuilder::clear() { - *data = LayoutGraphData(data->get_allocator()); -} - -uint32_t NativeLayoutGraphBuilder::addRenderStage(const ccstd::string &name) { - return add_vertex(*data, RenderStageTag{}, name.c_str()); -} - -uint32_t NativeLayoutGraphBuilder::addRenderPhase(const ccstd::string &name, uint32_t parentID) { - return add_vertex(*data, RenderPhaseTag{}, name.c_str(), parentID); -} - -void NativeLayoutGraphBuilder::addShader(const ccstd::string &name, uint32_t parentPhaseID) { - auto res = data->shaderLayoutIndex.emplace(name.c_str(), parentPhaseID); - CC_ENSURES(res.second); -} - -void NativeLayoutGraphBuilder::addDescriptorBlock( - uint32_t nodeID, - const DescriptorBlockIndex &index, const DescriptorBlockFlattened &b) { - auto &g = *data; - auto &ppl = get(LayoutGraphData::Layout, g, nodeID); - - CC_EXPECTS(b.descriptorNames.size() == b.descriptors.size()); - CC_EXPECTS(b.uniformBlockNames.size() == b.uniformBlocks.size()); - DescriptorBlock block; - for (uint32_t i = 0; i != b.descriptorNames.size(); ++i) { - block.descriptors.emplace(b.descriptorNames[i], b.descriptors[i]); - } - for (uint32_t i = 0; i != b.uniformBlockNames.size(); ++i) { - block.uniformBlocks.emplace(b.uniformBlockNames[i], b.uniformBlocks[i]); - } - block.capacity = b.capacity; - block.count = b.count; - - CC_ASSERT(block.capacity); - auto &layout = ppl.descriptorSets[index.updateFrequency].descriptorSetLayoutData; - - // add block - layout.descriptorBlocks.emplace_back( - index.descriptorType, index.visibility, block.capacity); - - auto &dstBlock = layout.descriptorBlocks.back(); - dstBlock.offset = layout.capacity; - dstBlock.capacity = block.capacity; - for (const auto &pairD : block.descriptors) { - const auto &name = pairD.first; - const auto &d = pairD.second; - auto iter = g.attributeIndex.find(std::string_view{name}); - if (iter == g.attributeIndex.end()) { - auto attrID = gsl::narrow_cast(g.valueNames.size()); - g.valueNames.emplace_back(name); - bool added = false; - std::tie(iter, added) = g.attributeIndex.emplace( - std::piecewise_construct, - std::forward_as_tuple(name), - std::forward_as_tuple(NameLocalID{attrID})); - CC_ENSURES(added); - } - const auto &nameID = iter->second; - dstBlock.descriptors.emplace_back(nameID, gfx::Type::UNKNOWN, d.count); - } - // update layout - layout.capacity += block.capacity; -} - -void NativeLayoutGraphBuilder::addUniformBlock(uint32_t nodeID, const DescriptorBlockIndex &index, const ccstd::string &name, const gfx::UniformBlock &uniformBlock) { - auto &g = *data; - auto &ppl = get(LayoutGraphData::Layout, g, nodeID); - auto &layout = ppl.descriptorSets[index.updateFrequency].descriptorSetLayoutData; - auto iter = g.attributeIndex.find(std::string_view{name}); - if (iter == g.attributeIndex.end()) { - auto attrID = gsl::narrow_cast(g.valueNames.size()); - g.valueNames.emplace_back(name); - bool added = false; - std::tie(iter, added) = g.attributeIndex.emplace( - std::piecewise_construct, - std::forward_as_tuple(name), - std::forward_as_tuple(NameLocalID{attrID})); - CC_ENSURES(added); - } - const auto &nameID = iter->second; - layout.uniformBlocks.emplace(nameID, uniformBlock); -} - -namespace { - -gfx::DescriptorType getGfxType(DescriptorTypeOrder type) { - switch (type) { - case DescriptorTypeOrder::UNIFORM_BUFFER: - return gfx::DescriptorType::UNIFORM_BUFFER; - case DescriptorTypeOrder::DYNAMIC_UNIFORM_BUFFER: - return gfx::DescriptorType::DYNAMIC_UNIFORM_BUFFER; - case DescriptorTypeOrder::SAMPLER_TEXTURE: - return gfx::DescriptorType::SAMPLER_TEXTURE; - case DescriptorTypeOrder::SAMPLER: - return gfx::DescriptorType::SAMPLER; - case DescriptorTypeOrder::TEXTURE: - return gfx::DescriptorType::TEXTURE; - case DescriptorTypeOrder::STORAGE_BUFFER: - return gfx::DescriptorType::STORAGE_BUFFER; - case DescriptorTypeOrder::DYNAMIC_STORAGE_BUFFER: - return gfx::DescriptorType::DYNAMIC_STORAGE_BUFFER; - case DescriptorTypeOrder::STORAGE_IMAGE: - return gfx::DescriptorType::STORAGE_IMAGE; - case DescriptorTypeOrder::INPUT_ATTACHMENT: - return gfx::DescriptorType::INPUT_ATTACHMENT; - } - throw std::invalid_argument("DescriptorType not found"); -} - -IntrusivePtr createDescriptorSetLayout( - gfx::Device *device, const DescriptorSetLayoutData &layoutData) { - gfx::DescriptorSetLayoutInfo info; - - for (const auto &block : layoutData.descriptorBlocks) { - uint32_t slot = block.offset; - for (const auto &d : block.descriptors) { - gfx::DescriptorSetLayoutBinding binding; - binding.binding = slot; - binding.descriptorType = getGfxType(block.type); - binding.count = d.count; - binding.stageFlags = block.visibility; - binding.immutableSamplers = {}; - info.bindings.emplace_back(std::move(binding)); - slot += d.count; - } - } - - return {device->createDescriptorSetLayout(info)}; -} - -} // namespace - -void NativeLayoutGraphBuilder::reserveDescriptorBlock( - uint32_t nodeID, - const DescriptorBlockIndex &index, const DescriptorBlockFlattened &block) { - auto &g = *data; - auto &ppl = get(LayoutGraphData::Layout, g, nodeID); - - CC_ASSERT(block.capacity); - auto &layout = ppl.descriptorSets[index.updateFrequency].descriptorSetLayoutData; - - // add block - layout.descriptorBlocks.emplace_back( - index.descriptorType, index.visibility, block.capacity); - - auto &dstBlock = layout.descriptorBlocks.back(); - dstBlock.offset = layout.capacity; - dstBlock.capacity = block.capacity; - - // update layout - layout.capacity += block.capacity; -} - -int NativeLayoutGraphBuilder::compile() { - auto &g = *data; - // create descriptor sets - for (const auto v : makeRange(vertices(g))) { - auto &ppl = get(LayoutGraphData::Layout, g, v); - for (auto &levelPair : ppl.descriptorSets) { - auto &level = levelPair.second; - const auto &layoutData = level.descriptorSetLayoutData; - level.descriptorSetLayout = createDescriptorSetLayout(device, layoutData); - level.descriptorSet = device->createDescriptorSet( - gfx::DescriptorSetInfo{level.descriptorSetLayout.get()}); - } - } - -#ifdef _DEBUG - CC_LOG_DEBUG(print().c_str()); -#endif // _DEBUG - - return 0; -} - -namespace { - -ccstd::string getName(gfx::ShaderStageFlagBit stage) { - std::ostringstream oss; - int count = 0; - if (hasFlag(stage, gfx::ShaderStageFlagBit::VERTEX)) { - if (count++) { - oss << " | "; - } - oss << "Vertex"; - } - if (hasFlag(stage, gfx::ShaderStageFlagBit::CONTROL)) { - if (count++) { - oss << " | "; - } - oss << "Control"; - } - if (hasFlag(stage, gfx::ShaderStageFlagBit::EVALUATION)) { - if (count++) { - oss << " | "; - } - oss << "Evaluation"; - } - if (hasFlag(stage, gfx::ShaderStageFlagBit::GEOMETRY)) { - if (count++) { - oss << " | "; - } - oss << "Geometry"; - } - if (hasFlag(stage, gfx::ShaderStageFlagBit::FRAGMENT)) { - if (count++) { - oss << " | "; - } - oss << "Fragment"; - } - if (hasFlag(stage, gfx::ShaderStageFlagBit::COMPUTE)) { - if (count++) { - oss << " | "; - } - oss << "Compute"; - } - if (hasAllFlags(stage, gfx::ShaderStageFlagBit::ALL)) { - if (count++) { - oss << " | "; - } - oss << "All"; - } - return oss.str(); -} - -} // namespace - -ccstd::string NativeLayoutGraphBuilder::print() const { - std::ostringstream oss; - boost::container::pmr::unsynchronized_pool_resource pool( - boost::container::pmr::get_default_resource()); - ccstd::pmr::string space(&pool); - - oss << "\n"; - - auto &g = *data; - for (const auto v : makeRange(vertices(g))) { - if (parent(v, g) != LayoutGraphData::null_vertex()) { - continue; - } - const auto &name = get(LayoutGraphData::Name, g, v); - const auto &freq = get(LayoutGraphData::Update, g, v); - OSS << "\"" << name << "\": "; - - visit( - [&](auto tag) { - oss << getName(tag); - }, - tag(v, g)); - - oss << "<" << getName(freq) << "> {\n"; - INDENT_BEG(); - const auto &info = get(LayoutGraphData::Layout, g, v); - for (const auto &set : info.descriptorSets) { - OSS << "Set<" << getName(set.first) << "> {\n"; - { - INDENT(); - for (const auto &block : set.second.descriptorSetLayoutData.descriptorBlocks) { - OSS << "Block<" << getName(block.type) << ", " << getName(block.visibility) << "> {\n"; - { - INDENT(); - OSS << "capacity: " << block.capacity << ",\n"; - OSS << "count: " << block.descriptors.size() << ",\n"; - if (!block.descriptors.empty()) { - OSS << "Descriptors{ "; - int count = 0; - for (const auto &d : block.descriptors) { - if (count++) { - oss << ", "; - } - const auto &name = g.valueNames.at(d.descriptorID.value); - oss << "\"" << name; - if (d.count != 1) { - oss << "[" << d.count << "]"; - } - oss << "\""; - } - oss << " }\n"; - } - } - OSS << "}\n"; - } - } - OSS << "}\n"; - } - INDENT_END(); - OSS << "}\n"; - } - return oss.str(); -} - -} // namespace render - -} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp index 00a7fc84fd..7dd5098424 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp @@ -23,37 +23,39 @@ ****************************************************************************/ #include -#include #include -#include -#include -#include -#include #include "LayoutGraphFwd.h" #include "LayoutGraphGraphs.h" #include "LayoutGraphNames.h" #include "LayoutGraphTypes.h" +#include "LayoutGraphUtils.h" #include "NativePipelineFwd.h" #include "NativePipelineTypes.h" +#include "NativeUtils.h" #include "RenderCommonTypes.h" #include "RenderGraphGraphs.h" #include "RenderGraphTypes.h" #include "RenderInterfaceFwd.h" #include "RenderInterfaceTypes.h" +#include "RenderingModule.h" +#include "cocos/application/ApplicationManager.h" #include "cocos/base/Macros.h" #include "cocos/base/Ptr.h" #include "cocos/base/StringUtil.h" #include "cocos/base/std/container/string.h" +#include "cocos/core/Root.h" #include "cocos/math/Mat4.h" #include "cocos/renderer/gfx-base/GFXBuffer.h" #include "cocos/renderer/gfx-base/GFXDef-common.h" #include "cocos/renderer/gfx-base/GFXDescriptorSetLayout.h" #include "cocos/renderer/gfx-base/GFXDevice.h" +#include "cocos/renderer/gfx-base/GFXInputAssembler.h" #include "cocos/renderer/gfx-base/GFXSwapchain.h" #include "cocos/renderer/gfx-base/states/GFXSampler.h" #include "cocos/renderer/pipeline/Enum.h" #include "cocos/renderer/pipeline/GlobalDescriptorSetManager.h" #include "cocos/renderer/pipeline/PipelineSceneData.h" +#include "cocos/renderer/pipeline/PipelineStateManager.h" #include "cocos/renderer/pipeline/RenderPipeline.h" #include "cocos/scene/RenderScene.h" #include "cocos/scene/RenderWindow.h" @@ -76,11 +78,14 @@ SceneTask *NativeSceneTransversal::transverse(SceneVisitor *visitor) const { NativePipeline::NativePipeline(const allocator_type &alloc) noexcept : device(gfx::Device::getInstance()), globalDSManager(std::make_unique()), - layoutGraph(alloc), + programLibrary(dynamic_cast(getProgramLibrary())), pipelineSceneData(ccnew pipeline::PipelineSceneData()), // NOLINT - nativeContext(alloc), + nativeContext(std::make_unique(device), alloc), resourceGraph(alloc), - renderGraph(alloc) {} + renderGraph(alloc), + name(alloc) { + programLibrary->setPipeline(this); +} gfx::Device *NativePipeline::getDevice() const { return device; @@ -128,6 +133,9 @@ uint32_t NativePipeline::addRenderTexture(const ccstd::string &name, gfx::Format CC_ASSERT(renderWindow->getFramebuffer()->getColorTextures().size() == 1); CC_ASSERT(renderWindow->getFramebuffer()->getColorTextures().at(0)); + + desc.format = renderWindow->getFramebuffer()->getColorTextures()[0]->getFormat(); + return addVertex( SwapchainTag{}, std::forward_as_tuple(name.c_str()), @@ -209,6 +217,12 @@ void NativePipeline::updateRenderWindow(const ccstd::string &name, scene::Render }, [&](RenderSwapchain &sc) { CC_EXPECTS(renderWindow->getSwapchain()); + auto* newSwapchain = renderWindow->getSwapchain(); + if (sc.generation != newSwapchain->getGeneration()) { + resourceGraph.invalidatePersistentRenderPassAndFramebuffer( + sc.swapchain->getColorTexture()); + sc.generation = newSwapchain->getGeneration(); + } desc.width = renderWindow->getSwapchain()->getWidth(); desc.height = renderWindow->getSwapchain()->getHeight(); sc.swapchain = renderWindow->getSwapchain(); @@ -219,11 +233,36 @@ void NativePipeline::updateRenderWindow(const ccstd::string &name, scene::Render void NativePipeline::updateRenderTarget( const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) { // NOLINT(bugprone-easily-swappable-parameters) + auto resID = findVertex(ccstd::pmr::string(name, get_allocator()), resourceGraph); + if (resID == ResourceGraph::null_vertex()) { + return; + } + auto &desc = get(ResourceGraph::Desc, resourceGraph, resID); + + // update format + if (format == gfx::Format::UNKNOWN) { + format = desc.format; + } + visitObject( + resID, resourceGraph, + [&](ManagedTexture &tex) { + bool invalidate = + std::forward_as_tuple(desc.width, desc.height, desc.format) != + std::forward_as_tuple(width, height, format); + if (invalidate) { + desc.width = width; + desc.height = height; + desc.format = format; + resourceGraph.invalidatePersistentRenderPassAndFramebuffer(tex.texture.get()); + } + }, + [](const auto & /*res*/) {}); } void NativePipeline::updateDepthStencil( const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) { // NOLINT(bugprone-easily-swappable-parameters) + updateRenderTarget(name, width, height, format); } void NativePipeline::beginFrame() { @@ -232,6 +271,68 @@ void NativePipeline::beginFrame() { void NativePipeline::endFrame() { } +namespace { + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters) +void updateRasterPassConstants(uint32_t width, uint32_t height, Setter &setter) { + const auto &root = *Root::getInstance(); + const auto shadingWidth = static_cast(width); + const auto shadingHeight = static_cast(height); + setter.setVec4( + "cc_time", + Vec4( + root.getCumulativeTime(), + root.getFrameTime(), + static_cast(CC_CURRENT_ENGINE()->getTotalFrames()), + 0.0F)); + + setter.setVec4( + "cc_screenSize", + Vec4(shadingWidth, shadingHeight, 1.0F / shadingWidth, 1.0F / shadingHeight)); + setter.setVec4( + "cc_nativeSize", + Vec4(shadingWidth, shadingHeight, 1.0F / shadingWidth, 1.0F / shadingHeight)); +#if 0 + const auto *debugView = root.getDebugView(); + if (debugView) { + setter.setVec4( + "cc_debug_view_mode", + Vec4(static_cast(debugView->getSingleMode()), + debugView->isLightingWithAlbedo() ? 1.0F : 0.0F, + debugView->isCsmLayerColoration() ? 1.0F : 0.0F, + 0.0F)); + Vec4 debugPackVec{}; + for (auto i = static_cast(pipeline::DebugViewCompositeType::DIRECT_DIFFUSE); + i < static_cast(pipeline::DebugViewCompositeType::MAX_BIT_COUNT); ++i) { + const auto idx = i % 4; + (&debugPackVec.x)[idx] = debugView->isCompositeModeEnabled(i) ? 1.0F : 0.0F; + const auto packIdx = static_cast(floor(static_cast(i) / 4.0F)); + if (idx == 3) { + std::string name("cc_debug_view_composite_pack_"); + name.append(std::to_string(packIdx + 1)); + setter.setVec4(name, debugPackVec); + } + } + } else { + setter.setVec4("cc_debug_view_mode", Vec4(0.0F, 1.0F, 0.0F, 0.0F)); + Vec4 debugPackVec{}; + for (auto i = static_cast(pipeline::DebugViewCompositeType::DIRECT_DIFFUSE); + i < static_cast(pipeline::DebugViewCompositeType::MAX_BIT_COUNT); ++i) { + const auto idx = i % 4; + (&debugPackVec.x)[idx] = 1.0F; + const auto packIdx = static_cast(floor(i / 4.0)); + if (idx == 3) { + std::string name("cc_debug_view_composite_pack_"); + name.append(std::to_string(packIdx + 1)); + setter.setVec4(name, debugPackVec); + } + } + } +#endif +} + +} // namespace + RasterPassBuilder *NativePipeline::addRasterPass( uint32_t width, uint32_t height, // NOLINT(bugprone-easily-swappable-parameters) const ccstd::string &layoutName) { @@ -251,10 +352,13 @@ RasterPassBuilder *NativePipeline::addRasterPass( std::forward_as_tuple(std::move(pass)), renderGraph); - auto passLayoutID = locate(LayoutGraphData::null_vertex(), layoutName, layoutGraph); + auto passLayoutID = locate(LayoutGraphData::null_vertex(), layoutName, programLibrary->layoutGraph); CC_EXPECTS(passLayoutID != LayoutGraphData::null_vertex()); - return ccnew NativeRasterPassBuilder(&renderGraph, passID, &layoutGraph, passLayoutID); + auto *builder = ccnew NativeRasterPassBuilder(this, &renderGraph, passID, &programLibrary->layoutGraph, passLayoutID); + updateRasterPassConstants(width, height, *builder); + + return builder; } // NOLINTNEXTLINE @@ -269,9 +373,9 @@ ComputePassBuilder *NativePipeline::addComputePass(const ccstd::string &layoutNa std::forward_as_tuple(), renderGraph); - auto passLayoutID = locate(LayoutGraphData::null_vertex(), layoutName, layoutGraph); + auto passLayoutID = locate(LayoutGraphData::null_vertex(), layoutName, programLibrary->layoutGraph); - return ccnew NativeComputePassBuilder(&renderGraph, passID, &layoutGraph, passLayoutID); + return ccnew NativeComputePassBuilder(&renderGraph, passID, &programLibrary->layoutGraph, passLayoutID); } // NOLINTNEXTLINE @@ -335,14 +439,11 @@ SceneTransversal *NativePipeline::createSceneTransversal(const scene::Camera *ca return ccnew NativeSceneTransversal(camera, scene); } -LayoutGraphBuilder *NativePipeline::getLayoutGraphBuilder() { - return ccnew NativeLayoutGraphBuilder(device, &layoutGraph); -} - gfx::DescriptorSetLayout *NativePipeline::getDescriptorSetLayout(const ccstd::string &shaderName, UpdateFrequency freq) { - auto iter = layoutGraph.shaderLayoutIndex.find(std::string_view{shaderName}); - if (iter != layoutGraph.shaderLayoutIndex.end()) { - const auto &layouts = get(LayoutGraphData::Layout, layoutGraph, iter->second).descriptorSets; + const auto &lg = programLibrary->layoutGraph; + auto iter = lg.shaderLayoutIndex.find(std::string_view{shaderName}); + if (iter != lg.shaderLayoutIndex.end()) { + const auto &layouts = get(LayoutGraphData::Layout, lg, iter->second).descriptorSets; auto iter2 = layouts.find(freq); if (iter2 != layouts.end()) { return iter2->second.descriptorSetLayout.get(); @@ -363,33 +464,33 @@ const ccstd::vector &NativePipeline::getCommandBuffers() c namespace { -void generateConstantMacros( +void buildLayoutGraphNodeBuffer( gfx::Device *device, - ccstd::string &constantMacros, bool clusterEnabled) { - constantMacros = StringUtil::format( - R"( -#define CC_DEVICE_SUPPORT_FLOAT_TEXTURE %d -#define CC_ENABLE_CLUSTERED_LIGHT_CULLING %d -#define CC_DEVICE_MAX_VERTEX_UNIFORM_VECTORS %d -#define CC_DEVICE_MAX_FRAGMENT_UNIFORM_VECTORS %d -#define CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT %d -#define CC_PLATFORM_ANDROID_AND_WEBGL 0 -#define CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES 0 - )", - hasAnyFlags(device->getFormatFeatures(gfx::Format::RGBA32F), - gfx::FormatFeature::RENDER_TARGET | gfx::FormatFeature::SAMPLED_TEXTURE), - clusterEnabled ? 1 : 0, - device->getCapabilities().maxVertexUniformVectors, - device->getCapabilities().maxFragmentUniformVectors, - device->hasFeature(gfx::Feature::INPUT_ATTACHMENT_BENEFIT)); + const DescriptorSetLayoutData &data, + LayoutGraphNodeResource &node) { + for (const auto &[nameID, uniformBlock] : data.uniformBlocks) { + auto res = node.uniformBuffers.emplace( + std::piecewise_construct, + std::forward_as_tuple(nameID), + std::forward_as_tuple()); + CC_ENSURES(res.second); + auto &buffer = res.first->second; + CC_EXPECTS(uniformBlock.count); + const auto bufferSize = + getUniformBlockSize(uniformBlock.members) * uniformBlock.count; + + CC_ENSURES(bufferSize); + buffer.init(device, bufferSize, false); + } } } // namespace // NOLINTNEXTLINE bool NativePipeline::activate(gfx::Swapchain *swapchainIn) { + // setMacroInt("CC_PIPELINE_TYPE", 1); + swapchain = swapchainIn; - macros["CC_PIPELINE_TYPE"] = 0; globalDSManager->activate(device); pipelineSceneData->activate(device); #if CC_USE_DEBUG_RENDERER @@ -401,6 +502,101 @@ bool NativePipeline::activate(gfx::Swapchain *swapchainIn) { generateConstantMacros(device, constantMacros, false); _commandBuffers.resize(1, device->getCommandBuffer()); + + // reserve layout graph resource + const auto &lg = programLibrary->layoutGraph; + const auto numNodes = num_vertices(lg); + nativeContext.layoutGraphResources.reserve(numNodes); + + for (uint32_t i = 0; i != numNodes; ++i) { + auto &node = nativeContext.layoutGraphResources.emplace_back(); + const auto &layout = get(LayoutGraphData::Layout, lg, i); + if (holds(i, lg)) { + auto iter = layout.descriptorSets.find(UpdateFrequency::PER_PASS); + if (iter == layout.descriptorSets.end()) { + continue; + } + const auto &set = iter->second; + // reserve buffer + buildLayoutGraphNodeBuffer(device, set.descriptorSetLayoutData, node); + // reserve descriptor sets + node.descriptorSetPool.init(device, set.descriptorSetLayout); + } else { + auto iter = layout.descriptorSets.find(UpdateFrequency::PER_PHASE); + if (iter == layout.descriptorSets.end()) { + continue; + } + const auto &set = iter->second; + // reserve buffer + buildLayoutGraphNodeBuffer(device, set.descriptorSetLayoutData, node); + // reserve descriptor sets + node.descriptorSetPool.init(device, set.descriptorSetLayout); + } + } + + // create ia + { + CC_EXPECTS(device); + // create vertex buffer + const auto vbStride = sizeof(float) * 4; // 4 float per vertex + const auto vbSize = vbStride * 4; // 4 vertices + IntrusivePtr quadVB = device->createBuffer(gfx::BufferInfo{ + gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, + gfx::MemoryUsageBit::DEVICE | gfx::MemoryUsageBit::HOST, + vbSize, + vbStride}); + + CC_ENSURES(quadVB); + + // update vertex buffer + float vbData[16] = {}; + render::setupQuadVertexBuffer(*device, Vec4{0, 0, 1, 1}, vbData); + static_assert(sizeof(vbData) == 16 * 4); + CC_ENSURES(sizeof(vbData) == vbSize); + quadVB->update(vbData, sizeof(vbData)); + + // create index buffer + const auto ibStride = sizeof(uint16_t); + const auto ibSize = ibStride * 6; + + IntrusivePtr quadIB = device->createBuffer(gfx::BufferInfo{ + gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST, + gfx::MemoryUsageBit::DEVICE, + ibSize, + ibStride}); + + CC_ENSURES(quadIB); + + ccstd::vector indices(6); + indices[0] = 0; + indices[1] = 1; + indices[2] = 2; + indices[3] = 1; + indices[4] = 3; + indices[5] = 2; + + quadIB->update(indices.data(), + static_cast(indices.size() * sizeof(decltype(indices)::value_type))); + + // create input assembler + ccstd::vector attributes; + attributes.reserve(2); + attributes.emplace_back(gfx::Attribute{"a_position", gfx::Format::RG32F}); + attributes.emplace_back(gfx::Attribute{"a_texCoord", gfx::Format::RG32F}); + + ccstd::vector buffers; + buffers.emplace_back(quadVB.get()); + + IntrusivePtr quadIA = device->createInputAssembler( + gfx::InputAssemblerInfo{attributes, buffers, quadIB}); + CC_ENSURES(quadIA); + + // init fullscreenQuad + nativeContext.fullscreenQuad.quadIB = quadIB; + nativeContext.fullscreenQuad.quadVB = quadVB; + nativeContext.fullscreenQuad.quadIA = quadIA; + } + return true; } @@ -413,7 +609,7 @@ bool NativePipeline::destroy() noexcept { pipelineSceneData->destroy(); pipelineSceneData = {}; } - + pipeline::PipelineStateManager::destroyAll(); return true; } diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h b/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h index 6707f4da6e..3b2a7c392b 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h @@ -32,14 +32,12 @@ #include "cocos/base/std/variant.h" #include "cocos/renderer/pipeline/InstancedBuffer.h" #include "cocos/renderer/pipeline/custom/NativeFwd.h" -#include "cocos/renderer/pipeline/custom/PrivateFwd.h" #include "cocos/renderer/pipeline/custom/RenderGraphFwd.h" namespace cc { namespace render { -class NativeLayoutGraphBuilder; class NativeRasterQueueBuilder; class NativeRasterPassBuilder; class NativeComputeQueueBuilder; @@ -47,7 +45,6 @@ class NativeComputePassBuilder; class NativeMovePassBuilder; class NativeCopyPassBuilder; class NativeSceneTransversal; -struct PersistentRenderPassAndFramebuffer; struct RenderInstancingQueue; struct DrawInstance; struct RenderDrawQueue; @@ -55,11 +52,18 @@ struct NativeRenderQueue; class DefaultSceneVisitor; class DefaultForwardLightingTransversal; struct ResourceGroup; +struct BufferPool; +struct DescriptorSetPool; +struct UniformBlockResource; +struct ProgramResource; +struct LayoutGraphNodeResource; +struct QuadResource; struct NativeRenderContext; +class NativeProgramLibrary; class NativePipeline; class NativeProgramProxy; -class NativeProgramLibrary; class NativeRenderingModule; +class NativeSetter; } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp index 20afedbea8..b1d435a131 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp @@ -34,25 +34,6 @@ namespace cc { namespace render { -PersistentRenderPassAndFramebuffer::PersistentRenderPassAndFramebuffer(const allocator_type& alloc) noexcept -: clearColors(alloc) {} - -PersistentRenderPassAndFramebuffer::PersistentRenderPassAndFramebuffer(PersistentRenderPassAndFramebuffer&& rhs, const allocator_type& alloc) -: renderPass(std::move(rhs.renderPass)), - framebuffer(std::move(rhs.framebuffer)), - clearColors(std::move(rhs.clearColors), alloc), - clearDepth(rhs.clearDepth), - clearStencil(rhs.clearStencil), - refCount(rhs.refCount) {} - -PersistentRenderPassAndFramebuffer::PersistentRenderPassAndFramebuffer(PersistentRenderPassAndFramebuffer const& rhs, const allocator_type& alloc) -: renderPass(rhs.renderPass), - framebuffer(rhs.framebuffer), - clearColors(rhs.clearColors, alloc), - clearDepth(rhs.clearDepth), - clearStencil(rhs.clearStencil), - refCount(rhs.refCount) {} - RenderInstancingQueue::RenderInstancingQueue(const allocator_type& alloc) noexcept : batches(alloc), sortedBatches(alloc) {} @@ -80,19 +61,21 @@ NativeRenderQueue::NativeRenderQueue(const allocator_type& alloc) noexcept opaqueInstancingQueue(alloc), transparentInstancingQueue(alloc) {} -NativeRenderQueue::NativeRenderQueue(SceneFlags sceneFlagsIn, const allocator_type& alloc) noexcept +NativeRenderQueue::NativeRenderQueue(SceneFlags sceneFlagsIn, uint32_t layoutPassIDIn, const allocator_type& alloc) noexcept : opaqueQueue(alloc), transparentQueue(alloc), opaqueInstancingQueue(alloc), transparentInstancingQueue(alloc), - sceneFlags(sceneFlagsIn) {} + sceneFlags(sceneFlagsIn), + layoutPassID(layoutPassIDIn) {} NativeRenderQueue::NativeRenderQueue(NativeRenderQueue&& rhs, const allocator_type& alloc) : opaqueQueue(std::move(rhs.opaqueQueue), alloc), transparentQueue(std::move(rhs.transparentQueue), alloc), opaqueInstancingQueue(std::move(rhs.opaqueInstancingQueue), alloc), transparentInstancingQueue(std::move(rhs.transparentInstancingQueue), alloc), - sceneFlags(rhs.sceneFlags) {} + sceneFlags(rhs.sceneFlags), + layoutPassID(rhs.layoutPassID) {} DefaultSceneVisitor::DefaultSceneVisitor(const allocator_type& alloc) noexcept : name(alloc) {} @@ -103,13 +86,81 @@ DefaultForwardLightingTransversal::DefaultForwardLightingTransversal(const alloc ResourceGroup::ResourceGroup(const allocator_type& alloc) noexcept : instancingBuffers(alloc) {} -NativeRenderContext::NativeRenderContext(const allocator_type& alloc) noexcept -: renderPasses(alloc), - resourceGroups(alloc) {} +BufferPool::BufferPool(const allocator_type& alloc) noexcept +: currentBuffers(alloc), + currentBufferViews(alloc), + freeBuffers(alloc), + freeBufferViews(alloc) {} + +BufferPool::BufferPool(gfx::Device* deviceIn, uint32_t bufferSizeIn, bool dynamicIn, const allocator_type& alloc) noexcept // NOLINT +: device(deviceIn), + bufferSize(bufferSizeIn), + dynamic(dynamicIn), + currentBuffers(alloc), + currentBufferViews(alloc), + freeBuffers(alloc), + freeBufferViews(alloc) {} + +BufferPool::BufferPool(BufferPool&& rhs, const allocator_type& alloc) +: device(rhs.device), + bufferSize(rhs.bufferSize), + dynamic(rhs.dynamic), + currentBuffers(std::move(rhs.currentBuffers), alloc), + currentBufferViews(std::move(rhs.currentBufferViews), alloc), + freeBuffers(std::move(rhs.freeBuffers), alloc), + freeBufferViews(std::move(rhs.freeBufferViews), alloc) {} + +DescriptorSetPool::DescriptorSetPool(const allocator_type& alloc) noexcept +: currentDescriptorSets(alloc), + freeDescriptorSets(alloc) {} + +DescriptorSetPool::DescriptorSetPool(gfx::Device* deviceIn, IntrusivePtr setLayoutIn, const allocator_type& alloc) noexcept // NOLINT +: device(deviceIn), + setLayout(std::move(setLayoutIn)), + currentDescriptorSets(alloc), + freeDescriptorSets(alloc) {} + +DescriptorSetPool::DescriptorSetPool(DescriptorSetPool&& rhs, const allocator_type& alloc) +: device(rhs.device), + setLayout(std::move(rhs.setLayout)), + currentDescriptorSets(std::move(rhs.currentDescriptorSets), alloc), + freeDescriptorSets(std::move(rhs.freeDescriptorSets), alloc) {} + +UniformBlockResource::UniformBlockResource(const allocator_type& alloc) noexcept +: cpuBuffer(alloc), + bufferPool(alloc) {} + +UniformBlockResource::UniformBlockResource(UniformBlockResource&& rhs, const allocator_type& alloc) +: cpuBuffer(std::move(rhs.cpuBuffer), alloc), + bufferPool(std::move(rhs.bufferPool), alloc) {} + +ProgramResource::ProgramResource(const allocator_type& alloc) noexcept +: uniformBuffers(alloc), + descriptorSetPool(alloc) {} + +ProgramResource::ProgramResource(ProgramResource&& rhs, const allocator_type& alloc) +: uniformBuffers(std::move(rhs.uniformBuffers), alloc), + descriptorSetPool(std::move(rhs.descriptorSetPool), alloc) {} + +LayoutGraphNodeResource::LayoutGraphNodeResource(const allocator_type& alloc) noexcept +: uniformBuffers(alloc), + descriptorSetPool(alloc), + programResources(alloc) {} + +LayoutGraphNodeResource::LayoutGraphNodeResource(LayoutGraphNodeResource&& rhs, const allocator_type& alloc) +: uniformBuffers(std::move(rhs.uniformBuffers), alloc), + descriptorSetPool(std::move(rhs.descriptorSetPool), alloc), + programResources(std::move(rhs.programResources), alloc) {} + +NativeRenderContext::NativeRenderContext(std::unique_ptr defaultResourceIn, const allocator_type& alloc) noexcept +: defaultResource(std::move(defaultResourceIn)), + resourceGroups(alloc), + layoutGraphResources(alloc) {} NativeProgramLibrary::NativeProgramLibrary(const allocator_type& alloc) noexcept : layoutGraph(alloc), - phases(alloc) {} + phases(alloc), + localLayoutData(alloc) {} } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h index 85abd8eca1..eabe5a6214 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h @@ -38,7 +38,6 @@ #include "cocos/renderer/pipeline/InstancedBuffer.h" #include "cocos/renderer/pipeline/custom/NativePipelineFwd.h" #include "cocos/renderer/pipeline/custom/NativeTypes.h" -#include "cocos/renderer/pipeline/custom/PrivateTypes.h" #include "cocos/renderer/pipeline/custom/RenderGraphTypes.h" #include "cocos/renderer/pipeline/custom/details/Map.h" #include "cocos/renderer/pipeline/custom/details/Set.h" @@ -47,32 +46,12 @@ namespace cc { namespace render { -class NativeLayoutGraphBuilder final : public LayoutGraphBuilder { -public: - NativeLayoutGraphBuilder() = default; - NativeLayoutGraphBuilder(gfx::Device* deviceIn, LayoutGraphData* dataIn) noexcept - : device(deviceIn), - data(dataIn) {} - - void clear() override; - uint32_t addRenderStage(const ccstd::string &name) override; - uint32_t addRenderPhase(const ccstd::string &name, uint32_t parentID) override; - void addShader(const ccstd::string &name, uint32_t parentPhaseID) override; - void addDescriptorBlock(uint32_t nodeID, const DescriptorBlockIndex &index, const DescriptorBlockFlattened &block) override; - void addUniformBlock(uint32_t nodeID, const DescriptorBlockIndex &index, const ccstd::string &name, const gfx::UniformBlock &uniformBlock) override; - void reserveDescriptorBlock(uint32_t nodeID, const DescriptorBlockIndex &index, const DescriptorBlockFlattened &block) override; - int compile() override; - ccstd::string print() const override; - - gfx::Device* device{nullptr}; - LayoutGraphData* data{nullptr}; -}; - class NativeRasterQueueBuilder final : public RasterQueueBuilder { public: NativeRasterQueueBuilder() = default; - NativeRasterQueueBuilder(RenderGraph* renderGraphIn, uint32_t queueIDIn, const LayoutGraphData* layoutGraphIn) noexcept - : renderGraph(renderGraphIn), + NativeRasterQueueBuilder(const PipelineRuntime* pipelineRuntimeIn, RenderGraph* renderGraphIn, uint32_t queueIDIn, const LayoutGraphData* layoutGraphIn) noexcept + : pipelineRuntime(pipelineRuntimeIn), + renderGraph(renderGraphIn), layoutGraph(layoutGraphIn), queueID(queueIDIn) {} @@ -98,6 +77,7 @@ public: void clearRenderTarget(const ccstd::string &name, const gfx::Color &color) override; void setViewport(const gfx::Viewport &viewport) override; + const PipelineRuntime* pipelineRuntime{nullptr}; RenderGraph* renderGraph{nullptr}; const LayoutGraphData* layoutGraph{nullptr}; uint32_t queueID{RenderGraph::null_vertex()}; @@ -106,8 +86,9 @@ public: class NativeRasterPassBuilder final : public RasterPassBuilder { public: NativeRasterPassBuilder() = default; - NativeRasterPassBuilder(RenderGraph* renderGraphIn, uint32_t passIDIn, const LayoutGraphData* layoutGraphIn, uint32_t layoutIDIn) noexcept // NOLINT - : renderGraph(renderGraphIn), + NativeRasterPassBuilder(const PipelineRuntime* pipelineRuntimeIn, RenderGraph* renderGraphIn, uint32_t passIDIn, const LayoutGraphData* layoutGraphIn, uint32_t layoutIDIn) noexcept // NOLINT + : pipelineRuntime(pipelineRuntimeIn), + renderGraph(renderGraphIn), layoutGraph(layoutGraphIn), passID(passIDIn), layoutID(layoutIDIn) {} @@ -132,7 +113,10 @@ public: RasterQueueBuilder *addQueue(QueueHint hint) override; void setViewport(const gfx::Viewport &viewport) override; void setVersion(const ccstd::string &name, uint64_t version) override; + bool getShowStatistics() const override; + void setShowStatistics(bool enable) override; + const PipelineRuntime* pipelineRuntime{nullptr}; RenderGraph* renderGraph{nullptr}; const LayoutGraphData* layoutGraph{nullptr}; uint32_t passID{RenderGraph::null_vertex()}; @@ -247,29 +231,6 @@ public: const scene::RenderScene* scene{nullptr}; }; -struct PersistentRenderPassAndFramebuffer { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {clearColors.get_allocator().resource()}; - } - - PersistentRenderPassAndFramebuffer(const allocator_type& alloc) noexcept; // NOLINT - PersistentRenderPassAndFramebuffer(PersistentRenderPassAndFramebuffer&& rhs, const allocator_type& alloc); - PersistentRenderPassAndFramebuffer(PersistentRenderPassAndFramebuffer const& rhs, const allocator_type& alloc); - - PersistentRenderPassAndFramebuffer(PersistentRenderPassAndFramebuffer&& rhs) noexcept = default; - PersistentRenderPassAndFramebuffer(PersistentRenderPassAndFramebuffer const& rhs) = delete; - PersistentRenderPassAndFramebuffer& operator=(PersistentRenderPassAndFramebuffer&& rhs) = default; - PersistentRenderPassAndFramebuffer& operator=(PersistentRenderPassAndFramebuffer const& rhs) = default; - - IntrusivePtr renderPass; - IntrusivePtr framebuffer; - ccstd::pmr::vector clearColors; - float clearDepth{0}; - uint8_t clearStencil{0}; - int32_t refCount{1}; -}; - struct RenderInstancingQueue { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT @@ -297,7 +258,7 @@ struct RenderInstancingQueue { ccstd::pmr::vector sortedBatches; }; -struct alignas(32) DrawInstance { +struct DrawInstance { const scene::SubModel* subModel{nullptr}; uint32_t priority{0}; uint32_t hash{0}; @@ -338,7 +299,7 @@ struct NativeRenderQueue { } NativeRenderQueue(const allocator_type& alloc) noexcept; // NOLINT - NativeRenderQueue(SceneFlags sceneFlagsIn, const allocator_type& alloc) noexcept; + NativeRenderQueue(SceneFlags sceneFlagsIn, uint32_t layoutPassIDIn, const allocator_type& alloc) noexcept; NativeRenderQueue(NativeRenderQueue&& rhs, const allocator_type& alloc); NativeRenderQueue(NativeRenderQueue&& rhs) noexcept = default; @@ -353,6 +314,7 @@ struct NativeRenderQueue { RenderInstancingQueue opaqueInstancingQueue; RenderInstancingQueue transparentInstancingQueue; SceneFlags sceneFlags{SceneFlags::NONE}; + uint32_t layoutPassID{0xFFFFFFFF}; }; class DefaultSceneVisitor final : public SceneVisitor { @@ -406,13 +368,137 @@ struct ResourceGroup { PmrUnorderedSet> instancingBuffers; }; +struct BufferPool { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {currentBuffers.get_allocator().resource()}; + } + + BufferPool(const allocator_type& alloc) noexcept; // NOLINT + BufferPool(gfx::Device* deviceIn, uint32_t bufferSizeIn, bool dynamicIn, const allocator_type& alloc) noexcept; + BufferPool(BufferPool&& rhs, const allocator_type& alloc); + + BufferPool(BufferPool&& rhs) noexcept = default; + BufferPool(BufferPool const& rhs) = delete; + BufferPool& operator=(BufferPool&& rhs) = default; + BufferPool& operator=(BufferPool const& rhs) = delete; + void init(gfx::Device* deviceIn, uint32_t sz, bool bDynamic); + void syncResources(); + gfx::Buffer* allocateBuffer(); + + gfx::Device* device{nullptr}; + uint32_t bufferSize{0}; + bool dynamic{false}; + ccstd::pmr::vector> currentBuffers; + ccstd::pmr::vector> currentBufferViews; + ccstd::pmr::vector> freeBuffers; + ccstd::pmr::vector> freeBufferViews; +}; + +struct DescriptorSetPool { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {currentDescriptorSets.get_allocator().resource()}; + } + + DescriptorSetPool(const allocator_type& alloc) noexcept; // NOLINT + DescriptorSetPool(gfx::Device* deviceIn, IntrusivePtr setLayoutIn, const allocator_type& alloc) noexcept; + DescriptorSetPool(DescriptorSetPool&& rhs, const allocator_type& alloc); + + DescriptorSetPool(DescriptorSetPool&& rhs) noexcept = default; + DescriptorSetPool(DescriptorSetPool const& rhs) = delete; + DescriptorSetPool& operator=(DescriptorSetPool&& rhs) = default; + DescriptorSetPool& operator=(DescriptorSetPool const& rhs) = delete; + void init(gfx::Device* deviceIn, IntrusivePtr layout); + void syncDescriptorSets(); + const gfx::DescriptorSet& getCurrentDescriptorSet() const; + gfx::DescriptorSet& getCurrentDescriptorSet(); + gfx::DescriptorSet* allocateDescriptorSet(); + + gfx::Device* device{nullptr}; + IntrusivePtr setLayout; + ccstd::pmr::vector> currentDescriptorSets; + ccstd::pmr::vector> freeDescriptorSets; +}; + +struct UniformBlockResource { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {cpuBuffer.get_allocator().resource()}; + } + + UniformBlockResource(const allocator_type& alloc) noexcept; // NOLINT + UniformBlockResource(UniformBlockResource&& rhs, const allocator_type& alloc); + + UniformBlockResource(UniformBlockResource&& rhs) noexcept = default; + UniformBlockResource(UniformBlockResource const& rhs) = delete; + UniformBlockResource& operator=(UniformBlockResource&& rhs) = default; + UniformBlockResource& operator=(UniformBlockResource const& rhs) = delete; + void init(gfx::Device* deviceIn, uint32_t sz, bool bDynamic); + gfx::Buffer* createFromCpuBuffer(); + + ccstd::pmr::vector cpuBuffer; + BufferPool bufferPool; +}; + +struct ProgramResource { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {uniformBuffers.get_allocator().resource()}; + } + + ProgramResource(const allocator_type& alloc) noexcept; // NOLINT + ProgramResource(ProgramResource&& rhs, const allocator_type& alloc); + + ProgramResource(ProgramResource&& rhs) noexcept = default; + ProgramResource(ProgramResource const& rhs) = delete; + ProgramResource& operator=(ProgramResource&& rhs) = default; + ProgramResource& operator=(ProgramResource const& rhs) = delete; + void syncResources() noexcept; + + ccstd::pmr::unordered_map uniformBuffers; + DescriptorSetPool descriptorSetPool; +}; + +struct LayoutGraphNodeResource { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {uniformBuffers.get_allocator().resource()}; + } + + LayoutGraphNodeResource(const allocator_type& alloc) noexcept; // NOLINT + LayoutGraphNodeResource(LayoutGraphNodeResource&& rhs, const allocator_type& alloc); + + LayoutGraphNodeResource(LayoutGraphNodeResource&& rhs) noexcept = default; + LayoutGraphNodeResource(LayoutGraphNodeResource const& rhs) = delete; + LayoutGraphNodeResource& operator=(LayoutGraphNodeResource&& rhs) = default; + LayoutGraphNodeResource& operator=(LayoutGraphNodeResource const& rhs) = delete; + void syncResources() noexcept; + + PmrFlatMap uniformBuffers; + DescriptorSetPool descriptorSetPool; + PmrTransparentMap programResources; +}; + +struct QuadResource { + QuadResource() = default; + QuadResource(IntrusivePtr quadVBIn, IntrusivePtr quadIBIn, IntrusivePtr quadIAIn) noexcept // NOLINT + : quadVB(std::move(quadVBIn)), + quadIB(std::move(quadIBIn)), + quadIA(std::move(quadIAIn)) {} + + IntrusivePtr quadVB; + IntrusivePtr quadIB; + IntrusivePtr quadIA; +}; + struct NativeRenderContext { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT - return {renderPasses.get_allocator().resource()}; + return {resourceGroups.get_allocator().resource()}; } - NativeRenderContext(const allocator_type& alloc) noexcept; // NOLINT + NativeRenderContext(std::unique_ptr defaultResourceIn, const allocator_type& alloc) noexcept; NativeRenderContext(NativeRenderContext&& rhs) = delete; NativeRenderContext(NativeRenderContext const& rhs) = delete; NativeRenderContext& operator=(NativeRenderContext&& rhs) = delete; @@ -420,16 +506,59 @@ struct NativeRenderContext { void clearPreviousResources(uint64_t finishedFenceValue) noexcept; - ccstd::pmr::unordered_map renderPasses; + std::unique_ptr defaultResource; ccstd::pmr::map resourceGroups; + ccstd::pmr::vector layoutGraphResources; + QuadResource fullscreenQuad; uint64_t nextFenceValue{0}; }; +class NativeProgramLibrary final : public ProgramLibrary { +public: + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {layoutGraph.get_allocator().resource()}; + } + + NativeProgramLibrary(const allocator_type& alloc) noexcept; // NOLINT + + void addEffect(const EffectAsset *effectAsset) override; + void precompileEffect(gfx::Device *device, EffectAsset *effectAsset) override; + ccstd::string getKey(uint32_t phaseID, const ccstd::string &programName, const MacroRecord &defines) const override; + IntrusivePtr getPipelineLayout(gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) override; + const gfx::DescriptorSetLayout &getMaterialDescriptorSetLayout(gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) override; + const gfx::DescriptorSetLayout &getLocalDescriptorSetLayout(gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) override; + const IProgramInfo &getProgramInfo(uint32_t phaseID, const ccstd::string &programName) const override; + const gfx::ShaderInfo &getShaderInfo(uint32_t phaseID, const ccstd::string &programName) const override; + ProgramProxy *getProgramVariant(gfx::Device *device, uint32_t phaseID, const ccstd::string &name, MacroRecord &defines, const ccstd::pmr::string *key) override; + const ccstd::vector &getBlockSizes(uint32_t phaseID, const ccstd::string &programName) const override; + const Record &getHandleMap(uint32_t phaseID, const ccstd::string &programName) const override; + uint32_t getProgramID(uint32_t phaseID, const ccstd::pmr::string &programName) override; + uint32_t getDescriptorNameID(const ccstd::pmr::string &name) override; + const ccstd::pmr::string &getDescriptorName(uint32_t nameID) override; + + void init(gfx::Device* deviceIn); + void setPipeline(PipelineRuntime* pipelineIn); + void destroy(); + + LayoutGraphData layoutGraph; + PmrFlatMap phases; + boost::container::pmr::unsynchronized_pool_resource unsycPool; + bool mergeHighFrequency{false}; + bool fixedLocal{true}; + DescriptorSetLayoutData localLayoutData; + IntrusivePtr localDescriptorSetLayout; + IntrusivePtr emptyDescriptorSetLayout; + IntrusivePtr emptyPipelineLayout; + PipelineRuntime* pipeline{nullptr}; + gfx::Device* device{nullptr}; +}; + class NativePipeline final : public Pipeline { public: using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT - return {nativeContext.get_allocator().resource()}; + return {name.get_allocator().resource()}; } NativePipeline(const allocator_type& alloc) noexcept; // NOLINT @@ -480,7 +609,6 @@ public: CopyPassBuilder *addCopyPass() override; void presentAll() override; SceneTransversal *createSceneTransversal(const scene::Camera *camera, const scene::RenderScene *scene) override; - LayoutGraphBuilder *getLayoutGraphBuilder() override; gfx::DescriptorSetLayout *getDescriptorSetLayout(const ccstd::string &shaderName, UpdateFrequency freq) override; void executeRenderGraph(const RenderGraph& rg); @@ -494,11 +622,12 @@ public: MacroRecord macros; ccstd::string constantMacros; std::unique_ptr globalDSManager; + ccstd::pmr::string name; + NativeProgramLibrary* programLibrary; scene::Model* profiler{nullptr}; LightingMode lightingMode{LightingMode::DEFAULT}; IntrusivePtr pipelineSceneData; NativeRenderContext nativeContext; - LayoutGraphData layoutGraph; ResourceGraph resourceGraph; RenderGraph renderGraph; }; @@ -515,42 +644,6 @@ public: IntrusivePtr shader; }; -class NativeProgramLibrary final : public ProgramLibrary { -public: - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {layoutGraph.get_allocator().resource()}; - } - - NativeProgramLibrary(const allocator_type& alloc) noexcept; // NOLINT - - void addEffect(EffectAsset *effectAsset) override; - void precompileEffect(gfx::Device *device, EffectAsset *effectAsset) override; - ccstd::string getKey(uint32_t phaseID, const ccstd::pmr::string &programName, const MacroRecord &defines) const override; - const gfx::PipelineLayout &getPipelineLayout(gfx::Device *device, uint32_t phaseID, const ccstd::pmr::string &programName) override; - const gfx::DescriptorSetLayout &getMaterialDescriptorSetLayout(gfx::Device *device, uint32_t phaseID, const ccstd::pmr::string &programName) override; - const gfx::DescriptorSetLayout &getLocalDescriptorSetLayout(gfx::Device *device, uint32_t phaseID, const ccstd::pmr::string &programName) override; - const IProgramInfo &getProgramInfo(uint32_t phaseID, const ccstd::pmr::string &programName) const override; - const gfx::ShaderInfo &getShaderInfo(uint32_t phaseID, const ccstd::pmr::string &programName) const override; - ProgramProxy *getProgramVariant(gfx::Device *device, uint32_t phaseID, const ccstd::string &name, const MacroRecord &defines, const ccstd::pmr::string *key) const override; - const ccstd::pmr::vector &getBlockSizes(uint32_t phaseID, const ccstd::pmr::string &programName) const override; - const Record &getHandleMap(uint32_t phaseID, const ccstd::pmr::string &programName) const override; - uint32_t getProgramID(uint32_t phaseID, const ccstd::pmr::string &programName) override; - uint32_t getDescriptorNameID(const ccstd::pmr::string &name) override; - const ccstd::pmr::string &getDescriptorName(uint32_t nameID) override; - - void init(gfx::Device* device); - void destroy(); - - LayoutGraphData layoutGraph; - PmrFlatMap phases; - boost::container::pmr::unsynchronized_pool_resource unsycPool; - bool mergeHighFrequency{false}; - bool fixedLocal{true}; - IntrusivePtr emptyDescriptorSetLayout; - IntrusivePtr emptyPipelineLayout; -}; - class NativeRenderingModule final : public RenderingModule { public: NativeRenderingModule() = default; @@ -563,6 +656,37 @@ public: std::shared_ptr programLibrary; }; +class NativeSetter final : public Setter { +public: + NativeSetter(const LayoutGraphData& layoutGraphIn, RenderData& renderDataIn) noexcept + : layoutGraph(layoutGraphIn), + renderData(renderDataIn) {} + + ccstd::string getName() const override; + void setName(const ccstd::string &name) override; + + void setMat4(const ccstd::string &name, const Mat4 &mat) override; + void setQuaternion(const ccstd::string &name, const Quaternion &quat) override; + void setColor(const ccstd::string &name, const gfx::Color &color) override; + void setVec4(const ccstd::string &name, const Vec4 &vec) override; + void setVec2(const ccstd::string &name, const Vec2 &vec) override; + void setFloat(const ccstd::string &name, float v) override; + void setBuffer(const ccstd::string &name, gfx::Buffer *buffer) override; + void setTexture(const ccstd::string &name, gfx::Texture *texture) override; + void setReadWriteBuffer(const ccstd::string &name, gfx::Buffer *buffer) override; + void setReadWriteTexture(const ccstd::string &name, gfx::Texture *texture) override; + void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override; + + void setVec4ArraySize(const ccstd::string& name, uint32_t sz); + void setVec4ArrayElem(const ccstd::string& name, const cc::Vec4& vec, uint32_t id); + + void setMat4ArraySize(const ccstd::string& name, uint32_t sz); + void setMat4ArrayElem(const ccstd::string& name, const cc::Mat4& mat, uint32_t id); + + const LayoutGraphData& layoutGraph; + RenderData& renderData; +}; + } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativePools.cpp b/native/cocos/renderer/pipeline/custom/NativePools.cpp new file mode 100644 index 0000000000..f8de04f386 --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativePools.cpp @@ -0,0 +1,149 @@ +#include "NativePipelineTypes.h" +#include "details/GslUtils.h" + +namespace cc { + +namespace render { + +void BufferPool::init(gfx::Device* deviceIn, uint32_t sz, bool bDynamic) { + CC_EXPECTS(deviceIn); + CC_EXPECTS(sz); + CC_EXPECTS(!device); + CC_EXPECTS(bufferSize == 0); + + device = deviceIn; + bufferSize = sz; + dynamic = bDynamic; +} + +void BufferPool::syncResources() { + for (auto& buffer : currentBuffers) { + freeBuffers.emplace_back(std::move(buffer)); + } + currentBuffers.clear(); + + for (auto& bufferView : currentBufferViews) { + freeBufferViews.emplace_back(std::move(bufferView)); + } + currentBufferViews.clear(); +} + +gfx::Buffer* BufferPool::allocateBuffer() { + CC_EXPECTS(device); + CC_EXPECTS(bufferSize); + + gfx::Buffer* ptr = nullptr; + + if (freeBuffers.empty()) { + { + gfx::BufferInfo info{ + gfx::BufferUsageBit::UNIFORM | gfx::BufferUsageBit::TRANSFER_DST, + gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE, + bufferSize, + bufferSize}; + freeBuffers.emplace_back(device->createBuffer(info)); + } + + if (dynamic) { + gfx::BufferViewInfo info{ + freeBuffers.back().get(), + 0, bufferSize}; + freeBufferViews.emplace_back(device->createBuffer(info)); + } + } + { + CC_ENSURES(!freeBuffers.empty()); + auto& buffer = freeBuffers.back(); + ptr = buffer.get(); + CC_EXPECTS(buffer->getSize() == bufferSize); + currentBuffers.emplace_back(std::move(buffer)); + freeBuffers.pop_back(); + } + if (dynamic) { + CC_ENSURES(!freeBufferViews.empty()); + auto& bufferView = freeBufferViews.back(); + ptr = bufferView.get(); + CC_EXPECTS(bufferView->getSize() == bufferSize); + currentBufferViews.emplace_back(std::move(bufferView)); + freeBufferViews.pop_back(); + } + CC_ENSURES(ptr); + if (dynamic) { + CC_ENSURES(ptr->isBufferView()); + } else { + CC_ENSURES(!ptr->isBufferView()); + } + return ptr; +} + +void UniformBlockResource::init(gfx::Device* deviceIn, uint32_t sz, bool bDynamic) { + CC_EXPECTS(cpuBuffer.empty()); + cpuBuffer.resize(sz); + bufferPool.init(deviceIn, sz, bDynamic); +} + +gfx::Buffer* UniformBlockResource::createFromCpuBuffer() { + CC_EXPECTS(cpuBuffer.size() == bufferPool.bufferSize); + auto* bufferOrView = bufferPool.allocateBuffer(); + if (bufferPool.dynamic) { + auto* buffer = bufferPool.currentBuffers.back().get(); + buffer->update(cpuBuffer.data(), static_cast(cpuBuffer.size())); + } else { + bufferOrView->update(cpuBuffer.data(), static_cast(cpuBuffer.size())); + } + return bufferOrView; +} + +void DescriptorSetPool::init(gfx::Device* deviceIn, + IntrusivePtr layout) { + CC_EXPECTS(deviceIn); + CC_EXPECTS(layout); + CC_EXPECTS(!device); + CC_EXPECTS(!setLayout); + device = deviceIn; + setLayout = std::move(layout); +} + +void DescriptorSetPool::syncDescriptorSets() { + for (auto& set : currentDescriptorSets) { + freeDescriptorSets.emplace_back(std::move(set)); + } + currentDescriptorSets.clear(); +} + +gfx::DescriptorSet& DescriptorSetPool::getCurrentDescriptorSet() { + CC_EXPECTS(!currentDescriptorSets.empty()); + return *currentDescriptorSets.back(); +} + +const gfx::DescriptorSet& DescriptorSetPool::getCurrentDescriptorSet() const { + CC_EXPECTS(!currentDescriptorSets.empty()); + return *currentDescriptorSets.back(); +} + +gfx::DescriptorSet* DescriptorSetPool::allocateDescriptorSet() { + CC_EXPECTS(device); + CC_EXPECTS(setLayout); + + gfx::DescriptorSet* ptr = nullptr; + + if (freeDescriptorSets.empty()) { + freeDescriptorSets.emplace_back( + device->createDescriptorSet(gfx::DescriptorSetInfo{setLayout.get()})); + } + + { + CC_ENSURES(!freeDescriptorSets.empty()); + auto& set = freeDescriptorSets.back(); + ptr = set.get(); + CC_EXPECTS(set->getLayout() == setLayout); + currentDescriptorSets.emplace_back(std::move(set)); + freeDescriptorSets.pop_back(); + } + CC_ENSURES(ptr); + return ptr; +} + +} // namespace render + +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp b/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp index 732c30805f..2ef49ee96b 100644 --- a/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp @@ -23,14 +23,20 @@ THE SOFTWARE. ****************************************************************************/ +#include +#include #include +#include #include #include #include +#include +#include "LayoutGraphGraphs.h" #include "LayoutGraphUtils.h" #include "NativePipelineTypes.h" #include "ProgramLib.h" #include "ProgramUtils.h" +#include "base/Ptr.h" #include "cocos/base/Log.h" #include "cocos/core/assets/EffectAsset.h" #include "cocos/renderer/core/ProgramUtils.h" @@ -38,8 +44,12 @@ #include "cocos/renderer/pipeline/Define.h" #include "cocos/renderer/pipeline/custom/LayoutGraphGraphs.h" #include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" +#include "details/Range.h" #include "gfx-base/GFXDescriptorSetLayout.h" +#include "gfx-base/GFXShader.h" +#include "pipeline/custom/NativePipelineFwd.h" #include "pipeline/custom/PrivateTypes.h" +#include "pipeline/custom/RenderCommonTypes.h" #include "pipeline/custom/details/GslUtils.h" namespace cc { @@ -122,49 +132,61 @@ IProgramInfo makeProgramInfo(const ccstd::string &effectName, const IShaderInfo return programInfo; } -std::tuple getDescriptorNameAndType( - const pipeline::DescriptorSetLayoutInfos &source, - uint32_t binding) { +ccstd::pmr::vector> getDescriptorNameAndType( + const pipeline::DescriptorSetLayoutInfos &source, uint32_t binding, + boost::container::pmr::memory_resource *scratch) { + ccstd::pmr::vector> results(scratch); + for (const auto &[name, block] : source.blocks) { if (block.binding == binding) { - return {name, gfx::Type::UNKNOWN}; + results.emplace_back(std::tuple{name, gfx::Type::UNKNOWN}); } } for (const auto &[name, texture] : source.samplers) { if (texture.binding == binding) { - return {name, texture.type}; + results.emplace_back(std::tuple{name, texture.type}); } } for (const auto &[name, image] : source.storeImages) { if (image.binding == binding) { - return {name, image.type}; + results.emplace_back(std::tuple{name, image.type}); } } - return {"", gfx::Type::UNKNOWN}; + return results; } void makeLocalDescriptorSetLayoutData( LayoutGraphData &lg, const pipeline::DescriptorSetLayoutInfos &source, - DescriptorSetLayoutData &data) { + DescriptorSetLayoutData &data, + boost::container::pmr::memory_resource *scratch) { for (const auto &b : source.bindings) { - const auto [name, type] = getDescriptorNameAndType(source, b.binding); - const auto nameID = getOrCreateDescriptorID(lg, name); - const auto order = getDescriptorTypeOrder(b.descriptorType); + const auto &descriptors = getDescriptorNameAndType(source, b.binding, scratch); + CC_ENSURES(!descriptors.empty()); { + const auto &[name, type] = descriptors.front(); + const auto nameID = getOrCreateDescriptorID(lg, name); + const auto order = getDescriptorTypeOrder(b.descriptorType); auto &block = data.descriptorBlocks.emplace_back(order, b.stageFlags, b.count); block.offset = b.binding; block.descriptors.emplace_back(nameID, type, b.count); } - { - auto iter = data.bindingMap.find(nameID); - if (iter != data.bindingMap.end()) { - CC_LOG_ERROR("Duplicate descriptor name: %s", name.data()); + for (const auto &[name, type] : descriptors) { + const auto nameID = getOrCreateDescriptorID(lg, name); + { + auto iter = data.bindingMap.find(nameID); + if (iter != data.bindingMap.end()) { + CC_LOG_ERROR("Duplicate descriptor name: %s", name.data()); + } + data.bindingMap.emplace(nameID, b.binding); + } + { + auto iter = source.blocks.find(ccstd::string(name)); + if (iter != source.blocks.end()) { + data.uniformBlocks.emplace(nameID, iter->second); + } } - data.bindingMap.emplace(nameID, b.binding); } - const auto &v = source.blocks.at(ccstd::string(name)); - data.uniformBlocks.emplace(nameID, v); } } @@ -208,7 +230,7 @@ ShaderProgramData &buildProgramData( CC_ENSURES(res.second); auto &setData = res.first->second; auto &perInstance = setData.descriptorSetLayoutData; - makeLocalDescriptorSetLayoutData(lg, pipeline::localDescriptorSetLayout, perInstance); + makeLocalDescriptorSetLayoutData(lg, pipeline::localDescriptorSetLayout, perInstance, scratch); initializeDescriptorSetLayoutInfo( setData.descriptorSetLayoutData, setData.descriptorSetLayoutInfo); @@ -249,7 +271,7 @@ ShaderProgramData &buildProgramData( void populateMergedShaderInfo( const ccstd::pmr::vector &valueNames, const DescriptorSetLayoutData &layout, uint32_t set, - gfx::ShaderInfo &shaderInfo, ccstd::pmr::vector &blockSizes) { + gfx::ShaderInfo &shaderInfo, ccstd::vector &blockSizes) { for (const auto &descriptorBlock : layout.descriptorBlocks) { auto binding = descriptorBlock.offset; switch (descriptorBlock.type) { @@ -262,7 +284,7 @@ void populateMergedShaderInfo( continue; } const auto &uniformBlock = iter->second; - blockSizes.emplace_back(getSize(uniformBlock.members)); + blockSizes.emplace_back(getUniformBlockSize(uniformBlock.members)); shaderInfo.blocks.emplace_back( gfx::UniformBlock{ set, @@ -367,7 +389,7 @@ void populateGroupedShaderInfo( const DescriptorSetLayoutData &layout, const IDescriptorInfo &descriptorInfo, uint32_t set, gfx::ShaderInfo &shaderInfo, - ccstd::pmr::vector &blockSizes) { + ccstd::vector &blockSizes) { for (const auto &descriptorBlock : layout.descriptorBlocks) { const auto visibility = descriptorBlock.visibility; auto binding = descriptorBlock.offset; @@ -378,7 +400,7 @@ void populateGroupedShaderInfo( if (block.stageFlags != visibility) { continue; } - blockSizes.emplace_back(getSize(block.members)); + blockSizes.emplace_back(getUniformBlockSize(block.members)); shaderInfo.blocks.emplace_back( gfx::UniformBlock{ set, @@ -496,8 +518,8 @@ void populateGroupedShaderInfo( void populateLocalShaderInfo( const IDescriptorInfo &target, const pipeline::DescriptorSetLayoutInfos &source, - gfx::ShaderInfo &shaderInfo, ccstd::pmr::vector &blockSizes) { - const auto set = setIndex(UpdateFrequency::PER_INSTANCE); + gfx::ShaderInfo &shaderInfo, ccstd::vector &blockSizes) { + constexpr auto set = setIndex(UpdateFrequency::PER_INSTANCE); for (const auto &block : target.blocks) { auto blockIter = source.blocks.find(block.name); if (blockIter == source.blocks.end()) { @@ -517,7 +539,7 @@ void populateLocalShaderInfo( } const auto &binding = *pBinding; - blockSizes.emplace_back(getSize(block.members)); + blockSizes.emplace_back(getUniformBlockSize(block.members)); shaderInfo.blocks.emplace_back( gfx::UniformBlock{ set, @@ -556,6 +578,137 @@ void populateLocalShaderInfo( } } +uint32_t getIDescriptorSetLayoutInfoUniformBlockCapacity(const pipeline::DescriptorSetLayoutInfos &info) { + uint32_t capacity = 0; + for (const auto &binding : info.bindings) { + if (binding.descriptorType == gfx::DescriptorType::UNIFORM_BUFFER || + binding.descriptorType == gfx::DescriptorType::DYNAMIC_UNIFORM_BUFFER) { + capacity += binding.count; + } + } + return capacity; +} + +uint32_t getIDescriptorSetLayoutInfoSamplerTextureCapacity(const pipeline::DescriptorSetLayoutInfos &info) { + uint32_t capacity = 0; + for (const auto &binding : info.bindings) { + if (binding.descriptorType != gfx::DescriptorType::UNIFORM_BUFFER && + binding.descriptorType != gfx::DescriptorType::DYNAMIC_UNIFORM_BUFFER) { + capacity += binding.count; + } + } + return capacity; +} + +void setFlattenedUniformBlockBinding( + const std::array &setOffsets, + ccstd::vector &descriptors) { + for (auto &d : descriptors) { + d.flattened = setOffsets[d.set] + d.binding; + } +} + +template +void setFlattenedSamplerTextureBinding( + const std::array &setOffsets, + const std::array &uniformBlockCapacities, + ccstd::vector &descriptors) { + for (auto &d : descriptors) { + d.flattened = setOffsets[d.set] + d.binding - uniformBlockCapacities[d.set]; + } +} + +void calculateFlattenedBinding( + const std::array &descriptorSets, + const pipeline::DescriptorSetLayoutInfos *fixedInstanceDescriptorSetLayout, + gfx::ShaderInfo &shaderInfo) { + // Descriptors of UniformBlock starts from 0, and Descriptors of SamplerTexture starts from the end of UniformBlock. + std::array uniformBlockCapacities{}; + { + const auto passCapacity = + descriptorSets[static_cast(UpdateFrequency::PER_PASS)] + ? descriptorSets[static_cast(UpdateFrequency::PER_PASS)]->uniformBlockCapacity + : 0; + const auto phaseCapacity = + descriptorSets[static_cast(UpdateFrequency::PER_PHASE)] + ? descriptorSets[static_cast(UpdateFrequency::PER_PHASE)]->uniformBlockCapacity + : 0; + const auto batchCapacity = + descriptorSets[static_cast(UpdateFrequency::PER_BATCH)] + ? descriptorSets[static_cast(UpdateFrequency::PER_BATCH)]->uniformBlockCapacity + : 0; + const auto instanceCapacity = + fixedInstanceDescriptorSetLayout + ? getIDescriptorSetLayoutInfoUniformBlockCapacity(*fixedInstanceDescriptorSetLayout) + : (descriptorSets[static_cast(UpdateFrequency::PER_INSTANCE)] + ? descriptorSets[static_cast(UpdateFrequency::PER_INSTANCE)]->uniformBlockCapacity + : 0); + + // update uniform block capacities + uniformBlockCapacities[setIndex(UpdateFrequency::PER_PASS)] = passCapacity; + uniformBlockCapacities[setIndex(UpdateFrequency::PER_PHASE)] = phaseCapacity; + uniformBlockCapacities[setIndex(UpdateFrequency::PER_BATCH)] = batchCapacity; + uniformBlockCapacities[setIndex(UpdateFrequency::PER_INSTANCE)] = instanceCapacity; + + // calculate uniform block offsets + const auto passOffset = 0; + const auto phaseOffset = passOffset + passCapacity; + const auto instanceOffset = phaseOffset + phaseCapacity; + const auto batchOffset = instanceOffset + instanceCapacity; + + // save uniform block offsets by set index + std::array uniformBlockOffsets{}; + uniformBlockOffsets[setIndex(UpdateFrequency::PER_PASS)] = passOffset; + uniformBlockOffsets[setIndex(UpdateFrequency::PER_PHASE)] = phaseOffset; + uniformBlockOffsets[setIndex(UpdateFrequency::PER_BATCH)] = batchOffset; + uniformBlockOffsets[setIndex(UpdateFrequency::PER_INSTANCE)] = instanceOffset; + + // update flattened uniform block binding + setFlattenedUniformBlockBinding(uniformBlockOffsets, shaderInfo.blocks); + } + { + // calculate sampler texture capacities + const auto passCapacity = + descriptorSets[static_cast(UpdateFrequency::PER_PASS)] + ? descriptorSets[static_cast(UpdateFrequency::PER_PASS)]->samplerTextureCapacity + : 0; + const auto phaseCapacity = + descriptorSets[static_cast(UpdateFrequency::PER_PHASE)] + ? descriptorSets[static_cast(UpdateFrequency::PER_PHASE)]->samplerTextureCapacity + : 0; + const auto batchCapacity = + descriptorSets[static_cast(UpdateFrequency::PER_BATCH)] + ? descriptorSets[static_cast(UpdateFrequency::PER_BATCH)]->samplerTextureCapacity + : 0; + const auto instanceCapacity = + fixedInstanceDescriptorSetLayout + ? getIDescriptorSetLayoutInfoSamplerTextureCapacity(*fixedInstanceDescriptorSetLayout) + : (descriptorSets[static_cast(UpdateFrequency::PER_INSTANCE)] + ? descriptorSets[static_cast(UpdateFrequency::PER_INSTANCE)]->samplerTextureCapacity + : 0); + + // calculate sampler texture offsets + const auto passOffset = 0; + const auto phaseOffset = passOffset + passCapacity; + const auto instanceOffset = phaseOffset + phaseCapacity; + const auto batchOffset = instanceOffset + instanceCapacity; + + // save sampler texture offsets by set index + std::array samplerTextureOffsets{}; + samplerTextureOffsets[setIndex(UpdateFrequency::PER_PASS)] = passOffset; + samplerTextureOffsets[setIndex(UpdateFrequency::PER_PHASE)] = phaseOffset; + samplerTextureOffsets[setIndex(UpdateFrequency::PER_BATCH)] = batchOffset; + samplerTextureOffsets[setIndex(UpdateFrequency::PER_INSTANCE)] = instanceOffset; + + // update flattened sampler texture binding + setFlattenedSamplerTextureBinding(samplerTextureOffsets, uniformBlockCapacities, shaderInfo.samplerTextures); + setFlattenedSamplerTextureBinding(samplerTextureOffsets, uniformBlockCapacities, shaderInfo.samplers); + setFlattenedSamplerTextureBinding(samplerTextureOffsets, uniformBlockCapacities, shaderInfo.textures); + setFlattenedSamplerTextureBinding(samplerTextureOffsets, uniformBlockCapacities, shaderInfo.buffers); + setFlattenedSamplerTextureBinding(samplerTextureOffsets, uniformBlockCapacities, shaderInfo.images); + } +} + void makeShaderInfo( LayoutGraphData &lg, const PipelineLayoutData &passLayouts, // NOLINT(bugprone-easily-swappable-parameters) @@ -564,10 +717,13 @@ void makeShaderInfo( const ShaderProgramData *programData, bool fixedLocal, gfx::ShaderInfo &shaderInfo, - ccstd::pmr::vector &blockSizes) { + ccstd::vector &blockSizes) { + std::array descriptorSets{}; + const pipeline::DescriptorSetLayoutInfos *fixedInstanceDescriptorSetLayout = nullptr; { // pass auto iter = passLayouts.descriptorSets.find(UpdateFrequency::PER_PASS); if (iter != passLayouts.descriptorSets.end()) { + descriptorSets[static_cast(UpdateFrequency::PER_PASS)] = &iter->second.descriptorSetLayoutData; populateMergedShaderInfo( lg.valueNames, iter->second.descriptorSetLayoutData, setIndex(UpdateFrequency::PER_PASS), @@ -576,7 +732,8 @@ void makeShaderInfo( } { // phase auto iter = phaseLayouts.descriptorSets.find(UpdateFrequency::PER_PHASE); - if (iter != passLayouts.descriptorSets.end()) { + if (iter != phaseLayouts.descriptorSets.end()) { + descriptorSets[static_cast(UpdateFrequency::PER_PHASE)] = &iter->second.descriptorSetLayoutData; populateMergedShaderInfo( lg.valueNames, iter->second.descriptorSetLayoutData, setIndex(UpdateFrequency::PER_PHASE), @@ -589,6 +746,7 @@ void makeShaderInfo( if (programData) { auto iter = programData->layout.descriptorSets.find(UpdateFrequency::PER_BATCH); if (iter != programData->layout.descriptorSets.end()) { + descriptorSets[static_cast(UpdateFrequency::PER_BATCH)] = &iter->second.descriptorSetLayoutData; populateMergedShaderInfo( lg.valueNames, iter->second.descriptorSetLayoutData, setIndex(UpdateFrequency::PER_BATCH), @@ -597,6 +755,7 @@ void makeShaderInfo( } else { auto iter = phaseLayouts.descriptorSets.find(UpdateFrequency::PER_BATCH); if (iter != phaseLayouts.descriptorSets.end()) { + descriptorSets[static_cast(UpdateFrequency::PER_BATCH)] = &iter->second.descriptorSetLayoutData; populateGroupedShaderInfo( iter->second.descriptorSetLayoutData, batchInfo, setIndex(UpdateFrequency::PER_BATCH), @@ -609,6 +768,7 @@ void makeShaderInfo( static_cast(UpdateFrequency::PER_INSTANCE)); if (programData) { if (fixedLocal) { + fixedInstanceDescriptorSetLayout = &pipeline::localDescriptorSetLayout; populateLocalShaderInfo( instanceInfo, pipeline::localDescriptorSetLayout, shaderInfo, blockSizes); @@ -616,6 +776,7 @@ void makeShaderInfo( auto iter = programData->layout.descriptorSets.find( UpdateFrequency::PER_INSTANCE); if (iter != programData->layout.descriptorSets.end()) { + descriptorSets[static_cast(UpdateFrequency::PER_INSTANCE)] = &iter->second.descriptorSetLayoutData; populateMergedShaderInfo( lg.valueNames, iter->second.descriptorSetLayoutData, setIndex(UpdateFrequency::PER_INSTANCE), @@ -625,6 +786,7 @@ void makeShaderInfo( } else { auto iter = phaseLayouts.descriptorSets.find(UpdateFrequency::PER_INSTANCE); if (iter != phaseLayouts.descriptorSets.end()) { + descriptorSets[static_cast(UpdateFrequency::PER_INSTANCE)] = &iter->second.descriptorSetLayoutData; populateGroupedShaderInfo( iter->second.descriptorSetLayoutData, instanceInfo, setIndex(UpdateFrequency::PER_INSTANCE), @@ -632,11 +794,181 @@ void makeShaderInfo( } } } + calculateFlattenedBinding(descriptorSets, fixedInstanceDescriptorSetLayout, shaderInfo); + shaderInfo.stages.emplace_back(gfx::ShaderStage{gfx::ShaderStageFlagBit::VERTEX, ""}); + shaderInfo.stages.emplace_back(gfx::ShaderStage{gfx::ShaderStageFlagBit::FRAGMENT, ""}); +} + +std::pair findBinding( + const gfx::ShaderInfo &shaderInfo, std::string_view name) { + for (const auto &v : shaderInfo.blocks) { + if (v.name == name) { + return std::pair{v.set, v.binding}; + } + } + for (const auto &v : shaderInfo.buffers) { + if (v.name == name) { + return std::pair{v.set, v.binding}; + } + } + for (const auto &v : shaderInfo.samplerTextures) { + if (v.name == name) { + return std::pair{v.set, v.binding}; + } + } + for (const auto &v : shaderInfo.samplers) { + if (v.name == name) { + return std::pair{v.set, v.binding}; + } + } + for (const auto &v : shaderInfo.textures) { + if (v.name == name) { + return std::pair{v.set, v.binding}; + } + } + for (const auto &v : shaderInfo.images) { + if (v.name == name) { + return std::pair{v.set, v.binding}; + } + } + CC_EXPECTS(false); + return {}; +} + +void overwriteShaderSourceBinding( + const gfx::ShaderInfo &shaderInfo, + ccstd::string &source, + boost::container::pmr::memory_resource *scratch) { + // find first uniform + auto pos = source.find(" uniform "); + while (pos != ccstd::string::npos) { + // uniform statement is separated by ";{}"; + auto beg = source.find_last_of(";}", pos); + auto end = source.find_first_of(";{", pos); + if (beg == ccstd::string::npos) { + // if separator is not found, start from 0 + beg = 0; + } else { + // bypass last separator + beg += 1; + } + // uniform declaration is found + CC_EXPECTS(beg != ccstd::string::npos); + CC_EXPECTS(end != ccstd::string::npos); + CC_ENSURES(end > beg); + + // find uniform name + std::string_view name{}; + { + std::string_view decl(source.c_str() + beg, end - beg); + auto nameEnd = decl.size(); + for (; nameEnd-- > 0;) { + if (!std::isspace(decl[nameEnd])) { + break; + } + } + auto nameBeg = decl.find_last_of(' ', nameEnd); + nameBeg += 1; + nameEnd += 1; + // uniform name found + name = decl.substr(nameBeg, nameEnd - nameBeg); + } + CC_ENSURES(!name.empty()); + + // layout + std::ptrdiff_t offset = 0; + { + std::string_view prevLayout; + // find layout expression + auto layoutBeg = source.rfind("layout", pos); + auto layoutEnd = ccstd::string::npos; + if (layoutBeg == ccstd::string::npos || layoutBeg < beg) { + // layout not found + layoutBeg = ccstd::string::npos; + CC_ENSURES(layoutBeg == ccstd::string::npos); + CC_ENSURES(layoutEnd == ccstd::string::npos); + } else { + CC_EXPECTS(layoutBeg >= beg && layoutBeg <= end); + layoutEnd = source.find(')', layoutBeg) + 1; + CC_EXPECTS(layoutEnd != ccstd::string::npos); + CC_ENSURES(layoutBeg < layoutEnd && layoutEnd <= end); + prevLayout = std::string_view(source.c_str() + layoutBeg, layoutEnd - layoutBeg); + + // check layout expression is within uniform declaration + // prev layout expression is from layoutBeg to layoutEnd + CC_ENSURES(layoutBeg >= beg && layoutBeg <= end); + CC_ENSURES(layoutEnd >= layoutBeg && layoutEnd <= end); + } + + // find uniform set and binding + auto [set, binding] = findBinding(shaderInfo, name); + + // compose new layout expression + ccstd::pmr::string newLayout(scratch); + newLayout.reserve(32); + newLayout.append("layout(set = "); + newLayout.append(std::to_string(set)); + newLayout.append(", binding = "); + newLayout.append(std::to_string(binding)); + newLayout.append(")"); + + // replace layout expression + if (layoutBeg == ccstd::string::npos) { // layout not found + source.insert(pos, newLayout); + offset = static_cast(newLayout.size()); + } else { + // layout is found + source.erase(layoutBeg, prevLayout.size()); + source.insert(layoutBeg, newLayout); + // calculate string difference + offset = static_cast(newLayout.size()) - + static_cast(prevLayout.size()); + } + } + // offset end of uniform declaration, offset is caused by modification of layout + end += offset; + // find next uniform + pos = source.find(" uniform ", end); + auto exceptionPos = source.find(" uniform subpassInput ", end); + if (exceptionPos != ccstd::string::npos) { + while (pos == exceptionPos) { + end += strlen(" uniform subpassInput "); + pos = source.find(" uniform ", end); + exceptionPos = source.find(" uniform subpassInput ", end); + } + } + } +} + +void overwriteShaderProgramBinding( + gfx::Device *device, + const gfx::ShaderInfo &shaderInfo, IProgramInfo &programInfo, + boost::container::pmr::memory_resource *scratch) { + // get shader source to use + IShaderSource *src = &programInfo.glsl3; + const auto *deviceShaderVersion = getDeviceShaderVersion(device); + if (deviceShaderVersion) { + if (deviceShaderVersion != std::string_view{"glsl4"}) { + return; + } + src = programInfo.getSource(deviceShaderVersion); + } else { + CC_LOG_ERROR("Invalid GFX API!"); + } + CC_ENSURES(src); + + overwriteShaderSourceBinding(shaderInfo, src->vert, scratch); + overwriteShaderSourceBinding(shaderInfo, src->frag, scratch); } // overwrite IProgramInfo using gfx.ShaderInfo -void overwriteProgramBlockInfo(const gfx::ShaderInfo &shaderInfo, IProgramInfo &programInfo) { - const auto set = setIndex(UpdateFrequency::PER_BATCH); +void overwriteProgramBlockInfo( + gfx::Device *device, + const gfx::ShaderInfo &shaderInfo, IProgramInfo &programInfo, + boost::container::pmr::memory_resource *scratch) { + overwriteShaderProgramBinding(device, shaderInfo, programInfo, scratch); + + constexpr auto set = setIndex(UpdateFrequency::PER_BATCH); for (auto &block : programInfo.blocks) { auto found = false; for (const auto &src : shaderInfo.blocks) { @@ -691,10 +1023,10 @@ gfx::DescriptorSetLayout *getDescriptorSetLayout( gfx::DescriptorSetLayout *getProgramDescriptorSetLayout( gfx::Device *device, LayoutGraphData &lg, uint32_t phaseID, - const ccstd::pmr::string &programName, UpdateFrequency rate) { + const ccstd::string &programName, UpdateFrequency rate) { CC_EXPECTS(rate < UpdateFrequency::PER_PHASE); auto &phase = get(RenderPhaseTag{}, phaseID, lg); - const auto iter = phase.shaderIndex.find(programName); + const auto iter = phase.shaderIndex.find(std::string_view{programName}); if (iter == phase.shaderIndex.end()) { return nullptr; } @@ -753,7 +1085,7 @@ const gfx::DescriptorSetLayout &getOrCreateProgramDescriptorSetLayout( const NativeProgramLibrary &lib, gfx::Device *device, LayoutGraphData &lg, uint32_t phaseID, - const ccstd::pmr::string &programName, UpdateFrequency rate) { + std::string_view programName, UpdateFrequency rate) { CC_EXPECTS(rate < UpdateFrequency::PER_PHASE); auto &phase = get(RenderPhaseTag{}, phaseID, lg); const auto iter = phase.shaderIndex.find(programName); @@ -774,11 +1106,110 @@ const gfx::DescriptorSetLayout &getOrCreateProgramDescriptorSetLayout( return *layout.descriptorSetLayout; } +void populatePipelineLayoutInfo( + const NativeProgramLibrary &lib, + const PipelineLayoutData &layout, + UpdateFrequency rate, + gfx::PipelineLayoutInfo &info) { + auto iter = layout.descriptorSets.find(rate); + if (iter != layout.descriptorSets.end()) { + const auto &set = iter->second; + CC_EXPECTS(set.descriptorSetLayout); + info.setLayouts.emplace_back(set.descriptorSetLayout.get()); + } else { + info.setLayouts.emplace_back(lib.emptyDescriptorSetLayout.get()); + } +} + } // namespace -void NativeProgramLibrary::init(gfx::Device *device) { +void NativeProgramLibrary::init(gfx::Device *deviceIn) { + boost::container::pmr::memory_resource *scratch = &unsycPool; + device = deviceIn; emptyDescriptorSetLayout = device->createDescriptorSetLayout({}); emptyPipelineLayout = device->createPipelineLayout({}); + + if (false) { // NOLINT(readability-simplify-boolean-expr) + std::ostringstream oss; + printLayoutGraphData(layoutGraph, oss, scratch); + auto content = oss.str(); + std::istringstream iss(content); + std::string line; + while (std::getline(iss, line)) { + CC_LOG_INFO(line.c_str()); + } + } + + // update ubo + // tips: for compatibility with old version, when maxVertexUniformVectors is 128, maxJoints = 30 + uint maxJoints = (device->getCapabilities().maxVertexUniformVectors - 38) / 3; + maxJoints = maxJoints < 256 ? maxJoints : 256; + pipeline::SkinningJointCapacity::jointUniformCapacity = maxJoints; + pipeline::UBOSkinning::initLayout(maxJoints); + + // init layout graph + auto &lg = layoutGraph; + for (const auto v : makeRange(vertices(lg))) { + auto &layout = get(LayoutGraphData::Layout, lg, v); + for (auto &&[update, set] : layout.descriptorSets) { + if (set.descriptorSetLayout) { + CC_LOG_WARNING("descriptor set layout already initialized. It will be overwritten"); + } + initializeDescriptorSetLayoutInfo( + set.descriptorSetLayoutData, + set.descriptorSetLayoutInfo); + set.descriptorSetLayout = device->createDescriptorSetLayout(set.descriptorSetLayoutInfo); + CC_ENSURES(set.descriptorSetLayout); + set.descriptorSet = device->createDescriptorSet(gfx::DescriptorSetInfo{set.descriptorSetLayout.get()}); + CC_ENSURES(set.descriptorSet); + } + } + + for (const auto v : makeRange(vertices(lg))) { + if (!holds(v, lg)) { + continue; + } + const auto phaseID = v; + const auto passID = parent(phaseID, lg); + const auto &passLayout = get(LayoutGraphData::Layout, lg, passID); + const auto &phaseLayout = get(LayoutGraphData::Layout, lg, phaseID); + gfx::PipelineLayoutInfo info; + populatePipelineLayoutInfo(*this, passLayout, UpdateFrequency::PER_PASS, info); + populatePipelineLayoutInfo(*this, phaseLayout, UpdateFrequency::PER_PHASE, info); + populatePipelineLayoutInfo(*this, phaseLayout, UpdateFrequency::PER_BATCH, info); + populatePipelineLayoutInfo(*this, phaseLayout, UpdateFrequency::PER_INSTANCE, info); + auto &phase = get(RenderPhaseTag{}, phaseID, lg); + phase.pipelineLayout = device->createPipelineLayout(info); + } + + // init local descriptor set + { + const auto &localSetLayout = pipeline::localDescriptorSetLayout; + makeLocalDescriptorSetLayoutData(lg, localSetLayout, localLayoutData, scratch); + gfx::DescriptorSetLayoutInfo info{}; + initializeDescriptorSetLayoutInfo(localLayoutData, info); + localDescriptorSetLayout = device->createDescriptorSetLayout(info); + CC_ENSURES(localDescriptorSetLayout); + + uint32_t numUniformBuffers = 0; + for (const auto &block : localLayoutData.descriptorBlocks) { + if (block.type != DescriptorTypeOrder::UNIFORM_BUFFER && + block.type != DescriptorTypeOrder::DYNAMIC_UNIFORM_BUFFER) { + continue; + } + for (const auto &d : block.descriptors) { + numUniformBuffers += d.count; + } + } + CC_ENSURES(numUniformBuffers == 7); // 7 is currently max uniform binding + } + + // generate constant macros string + generateConstantMacros(device, lg.constantMacros, false); +} + +void NativeProgramLibrary::setPipeline(PipelineRuntime *pipelineIn) { + pipeline = pipelineIn; } void NativeProgramLibrary::destroy() { @@ -786,7 +1217,7 @@ void NativeProgramLibrary::destroy() { emptyPipelineLayout.reset(); } -void NativeProgramLibrary::addEffect(EffectAsset *effectAssetIn) { +void NativeProgramLibrary::addEffect(const EffectAsset *effectAssetIn) { auto &lg = layoutGraph; boost::container::pmr::memory_resource *scratch = &unsycPool; const auto &effect = *effectAssetIn; @@ -807,12 +1238,16 @@ void NativeProgramLibrary::addEffect(EffectAsset *effectAssetIn) { // programs auto iter = this->phases.find(phaseID); if (iter == this->phases.end()) { - iter = this->phases.emplace(std::piecewise_construct, - std::forward_as_tuple(phaseID), - std::forward_as_tuple()) + iter = this->phases.emplace( + std::piecewise_construct, + std::forward_as_tuple(phaseID), + std::forward_as_tuple()) .first; } auto &phasePrograms = iter->second.programInfos; + if (phasePrograms.find(std::string_view{srcShaderInfo.name}) != phasePrograms.end()) { + continue; + } auto alloc = phasePrograms.get_allocator(); // build program @@ -822,17 +1257,17 @@ void NativeProgramLibrary::addEffect(EffectAsset *effectAssetIn) { ShaderProgramData *programData = nullptr; if (!mergeHighFrequency) { auto &phase = get(RenderPhaseTag{}, phaseID, lg); - buildProgramData(programName, srcShaderInfo, lg, phase, fixedLocal, scratch); + programData = &buildProgramData(programName, srcShaderInfo, lg, phase, fixedLocal, scratch); } // shaderInfo and blockSizes gfx::ShaderInfo shaderInfo; - ccstd::pmr::vector blockSizes(alloc); + ccstd::vector blockSizes; makeShaderInfo(lg, passLayout, phaseLayout, srcShaderInfo, programData, fixedLocal, shaderInfo, blockSizes); // overwrite programInfo - overwriteProgramBlockInfo(shaderInfo, programInfo); + overwriteProgramBlockInfo(device, shaderInfo, programInfo, scratch); // handle map auto handleMap = genHandles(shaderInfo); @@ -870,7 +1305,7 @@ void NativeProgramLibrary::precompileEffect(gfx::Device *device, EffectAsset *ef } ccstd::string NativeProgramLibrary::getKey( - uint32_t phaseID, const ccstd::pmr::string &programName, + uint32_t phaseID, const ccstd::string &programName, const MacroRecord &defines) const { auto iter = phases.find(phaseID); if (iter == phases.end()) { @@ -878,7 +1313,7 @@ ccstd::string NativeProgramLibrary::getKey( return ""; } const auto &phase = iter->second; - auto iter2 = phase.programInfos.find(programName); + auto iter2 = phase.programInfos.find(std::string_view{programName}); if (iter2 == phase.programInfos.end()) { CC_LOG_ERROR("program not found"); return ""; @@ -887,29 +1322,29 @@ ccstd::string NativeProgramLibrary::getKey( return getVariantKey(info.programInfo, defines); } -const gfx::PipelineLayout &NativeProgramLibrary::getPipelineLayout( - gfx::Device *device, uint32_t phaseID, const ccstd::pmr::string &programName) { +IntrusivePtr NativeProgramLibrary::getPipelineLayout( + gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) { if (mergeHighFrequency) { CC_EXPECTS(phaseID != LayoutGraphData::null_vertex()); const auto &layout = get(RenderPhaseTag{}, phaseID, layoutGraph); - return *layout.pipelineLayout; + return layout.pipelineLayout; } auto &lg = layoutGraph; auto &phase = get(RenderPhaseTag{}, phaseID, lg); - const auto iter = phase.shaderIndex.find(programName); + const auto iter = phase.shaderIndex.find(std::string_view{programName}); if (iter == phase.shaderIndex.end()) { - return *emptyPipelineLayout; + return emptyPipelineLayout; } const auto programID = iter->second; auto &programData = phase.shaderPrograms.at(programID); if (programData.pipelineLayout) { - return *programData.pipelineLayout; + return programData.pipelineLayout; } // get pass const auto passID = parent(phaseID, lg); if (passID == LayoutGraphData::null_vertex()) { - return *emptyPipelineLayout; + return emptyPipelineLayout; } // create pipeline layout gfx::PipelineLayoutInfo info{}; @@ -932,11 +1367,11 @@ const gfx::PipelineLayout &NativeProgramLibrary::getPipelineLayout( info.setLayouts.emplace_back(instanceSet); } programData.pipelineLayout = device->createPipelineLayout(info); - return *programData.pipelineLayout; + return programData.pipelineLayout; } const gfx::DescriptorSetLayout &NativeProgramLibrary::getMaterialDescriptorSetLayout( - gfx::Device *device, uint32_t phaseID, const ccstd::pmr::string &programName) { + gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) { if (mergeHighFrequency) { CC_EXPECTS(phaseID != LayoutGraphData::null_vertex()); const auto passID = parent(phaseID, layoutGraph); @@ -948,44 +1383,61 @@ const gfx::DescriptorSetLayout &NativeProgramLibrary::getMaterialDescriptorSetLa } const gfx::DescriptorSetLayout &NativeProgramLibrary::getLocalDescriptorSetLayout( - gfx::Device *device, uint32_t phaseID, const ccstd::pmr::string &programName) { + gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) { if (mergeHighFrequency) { CC_EXPECTS(phaseID != LayoutGraphData::null_vertex()); const auto passID = parent(phaseID, layoutGraph); return getOrCreateDescriptorSetLayout( *this, layoutGraph, passID, phaseID, UpdateFrequency::PER_INSTANCE); } + if (fixedLocal) { + return *localDescriptorSetLayout; + } return getOrCreateProgramDescriptorSetLayout( *this, device, layoutGraph, phaseID, programName, UpdateFrequency::PER_INSTANCE); } const IProgramInfo &NativeProgramLibrary::getProgramInfo( - uint32_t phaseID, const ccstd::pmr::string &programName) const { + uint32_t phaseID, const ccstd::string &programName) const { const auto &group = phases.at(phaseID); - return group.programInfos.at(programName).programInfo; + auto iter = group.programInfos.find(std::string_view{programName}); + if (iter != group.programInfos.end()) { + return iter->second.programInfo; + } + throw std::invalid_argument("program not found"); } const gfx::ShaderInfo &NativeProgramLibrary::getShaderInfo( - uint32_t phaseID, const ccstd::pmr::string &programName) const { + uint32_t phaseID, const ccstd::string &programName) const { const auto &group = phases.at(phaseID); - return group.programInfos.at(programName).shaderInfo; + auto iter = group.programInfos.find(std::string_view{programName}); + if (iter != group.programInfos.end()) { + return iter->second.shaderInfo; + } + throw std::invalid_argument("program not found"); } ProgramProxy *NativeProgramLibrary::getProgramVariant( gfx::Device *device, uint32_t phaseID, const ccstd::string &name, - const MacroRecord &defines, const ccstd::pmr::string *key0) const { + MacroRecord &defines, const ccstd::pmr::string *key0) { + if (pipeline) { + for (const auto &it : pipeline->getMacros()) { + defines[it.first] = it.second; + } + } + auto iter = phases.find(phaseID); if (iter == phases.end()) { CC_LOG_ERROR("phase not found"); return nullptr; } - const auto &phase = iter->second; + auto &phase = iter->second; auto iter2 = phase.programInfos.find(std::string_view{name}); if (iter2 == phase.programInfos.end()) { CC_LOG_ERROR("program not found"); return nullptr; } - const auto &info = iter2->second; + auto &info = iter2->second; const auto &programInfo = info.programInfo; @@ -999,48 +1451,92 @@ ProgramProxy *NativeProgramLibrary::getProgramVariant( key = *key0; } - auto iter3 = phase.programHosts.find(key); - if (iter3 != phase.programHosts.end()) { - return new NativeProgramProxy(iter3->second.program); + auto iter3 = phase.programProxies.find(key); + if (iter3 != phase.programProxies.end()) { + return iter3->second.get(); } - std::ignore = device; - std::ignore = phaseID; - std::ignore = name; - std::ignore = defines; - std::ignore = key; - return nullptr; + // prepare defines + ccstd::vector macroArray = render::prepareDefines(defines, programInfo.defines); + std::stringstream ss; + ss << std::endl; + for (const auto &m : macroArray) { + ss << "#define " << m.name << " " << m.value << std::endl; + } + + std::string prefix; + prefix += layoutGraph.constantMacros; + prefix += programInfo.constantMacros + ss.str(); + + const IShaderSource *src = &programInfo.glsl3; + const auto *deviceShaderVersion = getDeviceShaderVersion(device); + if (deviceShaderVersion) { + src = programInfo.getSource(deviceShaderVersion); + } else { + CC_LOG_ERROR("Invalid GFX API!"); + } + info.shaderInfo.stages[0].source = prefix + src->vert; + info.shaderInfo.stages[1].source = prefix + src->frag; + + // strip out the active attributes only, instancing depend on this + info.shaderInfo.attributes = getActiveAttributes(programInfo, info.attributes, defines); + + info.shaderInfo.name = getShaderInstanceName(name, macroArray); + + IntrusivePtr shader = device->createShader(info.shaderInfo); + auto res = phase.programProxies.emplace( + key, + IntrusivePtr(new NativeProgramProxy(std::move(shader)))); + CC_ENSURES(res.second); + + return res.first->second.get(); } -const ccstd::pmr::vector &NativeProgramLibrary::getBlockSizes( - uint32_t phaseID, const ccstd::pmr::string &programName) const { - std::ignore = phaseID; - std::ignore = programName; - throw std::runtime_error("not implemented"); +const ccstd::vector &NativeProgramLibrary::getBlockSizes( + uint32_t phaseID, const ccstd::string &programName) const { + CC_EXPECTS(phaseID != LayoutGraphData::null_vertex()); + const auto &group = phases.at(phaseID); + auto iter = group.programInfos.find(std::string_view{programName}); + if (iter != group.programInfos.end()) { + return iter->second.blockSizes; + } + throw std::invalid_argument("program not found"); } const Record &NativeProgramLibrary::getHandleMap( - uint32_t phaseID, const ccstd::pmr::string &programName) const { - std::ignore = phaseID; - std::ignore = programName; - throw std::runtime_error("not implemented"); + uint32_t phaseID, const ccstd::string &programName) const { + CC_EXPECTS(phaseID != LayoutGraphData::null_vertex()); + const auto &group = phases.at(phaseID); + auto iter = group.programInfos.find(std::string_view{programName}); + if (iter != group.programInfos.end()) { + return iter->second.handleMap; + } + throw std::invalid_argument("program not found"); } uint32_t NativeProgramLibrary::getProgramID( uint32_t phaseID, const ccstd::pmr::string &programName) { - std::ignore = phaseID; - std::ignore = programName; - throw std::runtime_error("not implemented"); + CC_EXPECTS(phaseID != LayoutGraphData::null_vertex()); + const auto &phase = get(RenderPhaseTag{}, phaseID, layoutGraph); + auto iter = phase.shaderIndex.find(programName); + if (iter == phase.shaderIndex.end()) { + CC_LOG_ERROR("program not found"); + return LayoutGraphData::null_vertex(); + } + return iter->second; } uint32_t NativeProgramLibrary::getDescriptorNameID(const ccstd::pmr::string &name) { - std::ignore = name; - return 0xFFFFFFFF; + const auto iter = layoutGraph.attributeIndex.find(name); + if (iter == layoutGraph.attributeIndex.end()) { + CC_LOG_ERROR("descriptor name not found"); + return 0xFFFFFFFF; + } + return iter->second.value; } const ccstd::pmr::string &NativeProgramLibrary::getDescriptorName(uint32_t nameID) { - std::ignore = nameID; - throw std::runtime_error("not implemented"); + return layoutGraph.valueNames.at(static_cast(nameID)); } } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp index 2ab06e9d6d..62373a0541 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp @@ -28,18 +28,229 @@ #include "NativePipelineGraphs.h" #include "NativePipelineTypes.h" #include "RenderCommonNames.h" +#include "RenderCommonTypes.h" +#include "RenderGraphFwd.h" #include "RenderGraphGraphs.h" +#include "RenderGraphTypes.h" +#include "cocos/math/Utils.h" +#include "cocos/renderer/pipeline/Define.h" +#include "cocos/renderer/pipeline/PipelineUBO.h" +#include "cocos/scene/DirectionalLight.h" +#include "cocos/scene/Fog.h" +#include "cocos/scene/Skybox.h" +#include "cocos/scene/SpotLight.h" #include "details/DebugUtils.h" #include "details/GraphView.h" +#include "details/GslUtils.h" #include "gfx-base/GFXDef-common.h" -#include "pipeline/custom/RenderCommonTypes.h" -#include "pipeline/custom/RenderGraphFwd.h" -#include "pipeline/custom/RenderGraphTypes.h" +#include "gfx-base/GFXDevice.h" +#include "pipeline/PipelineSceneData.h" namespace cc { namespace render { +namespace { + +render::NameLocalID getNameID( + const PmrFlatMap &index, + std::string_view name) { + auto iter = index.find(name); + CC_EXPECTS(iter != index.end()); + return iter->second; +} + +void addMat4( + const LayoutGraphData &lg, std::string_view name, + const cc::Mat4 &v, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Mat4) == 16 * 4, "sizeof(Mat4) is not 64 bytes"); + data.constants[nameID.value].resize(sizeof(Mat4)); + memcpy(data.constants[nameID.value].data(), v.m, sizeof(v)); +} + +void setMat4ArrayElemImpl( + const LayoutGraphData &lg, std::string_view name, + const cc::Mat4 &v, uint32_t i, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Mat4) == 16 * 4, "sizeof(Mat4) is not 64 bytes"); + auto &dst = data.constants[nameID.value]; + CC_EXPECTS(sizeof(Mat4) * (i + 1) <= dst.size()); + memcpy(dst.data() + sizeof(Mat4) * i, v.m, sizeof(v)); +} + +void setMat4ArraySizeImpl( + const LayoutGraphData &lg, std::string_view name, + uint32_t sz, RenderData &data) { + CC_EXPECTS(sz); + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Mat4) == 16 * 4, "sizeof(Mat4) is not 64 bytes"); + data.constants[nameID.value].resize(sizeof(Mat4) * sz); +} + +void addQuaternion(const LayoutGraphData &lg, const ccstd::string &name, const Quaternion &quat, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Quaternion) == 4 * 4, "sizeof(Quaternion) is not 16 bytes"); + static_assert(std::is_trivially_copyable::value, "Quaternion is not trivially copyable"); + data.constants[nameID.value].resize(sizeof(Quaternion)); + memcpy(data.constants[nameID.value].data(), &quat, sizeof(quat)); +} + +void addColor(const LayoutGraphData &lg, const ccstd::string &name, const gfx::Color &color, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(gfx::Color) == 4 * 4, "sizeof(Color) is not 16 bytes"); + static_assert(std::is_trivially_copyable::value, "Color is not trivially copyable"); + data.constants[nameID.value].resize(sizeof(gfx::Color)); + memcpy(data.constants[nameID.value].data(), &color, sizeof(color)); +} + +void addVec4(const LayoutGraphData &lg, const ccstd::string &name, const Vec4 &vec, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Vec4) == 4 * 4, "sizeof(Vec4) is not 16 bytes"); + // static_assert(std::is_trivially_copyable::value, "Vec4 is not trivially copyable"); + data.constants[nameID.value].resize(sizeof(Vec4)); + memcpy(data.constants[nameID.value].data(), &vec.x, sizeof(vec)); +} + +void setVec4ArrayElemImpl(const LayoutGraphData &lg, const ccstd::string &name, + const Vec4 &vec, uint32_t i, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Vec4) == 4 * 4, "sizeof(Vec4) is not 16 bytes"); + // static_assert(std::is_trivially_copyable::value, "Vec4 is not trivially copyable"); + auto &dst = data.constants[nameID.value]; + CC_EXPECTS(sizeof(Vec4) * (i + 1) <= dst.size()); + memcpy(dst.data() + sizeof(Vec4) * i, &vec.x, sizeof(vec)); +} + +void setVec4ArraySizeImpl(const LayoutGraphData &lg, const ccstd::string &name, + uint32_t sz, RenderData &data) { + CC_EXPECTS(sz); + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Vec4) == 4 * 4, "sizeof(Vec4) is not 16 bytes"); + // static_assert(std::is_trivially_copyable::value, "Vec4 is not trivially copyable"); + data.constants[nameID.value].resize(sizeof(Vec4) * sz); +} + +void addVec2(const LayoutGraphData &lg, const ccstd::string &name, const Vec2 &vec, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Vec2) == 2 * 4, "sizeof(Vec2) is not 8 bytes"); + // static_assert(std::is_trivially_copyable::value, "Vec2 is not trivially copyable"); + data.constants[nameID.value].resize(sizeof(Vec2)); + memcpy(data.constants[nameID.value].data(), &vec.x, sizeof(vec)); +} + +void addFloat(const LayoutGraphData &lg, const ccstd::string &name, float v, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(float) == 4, "sizeof(float) is not 4 bytes"); + data.constants[nameID.value].resize(sizeof(float)); + memcpy(data.constants[nameID.value].data(), &v, sizeof(v)); +} + +void addBuffer(const LayoutGraphData &lg, const ccstd::string &name, gfx::Buffer *buffer, RenderData &data) { + auto nameID = getNameID(lg.attributeIndex, name); + data.buffers[nameID.value] = IntrusivePtr(buffer); +} + +void addTexture(const LayoutGraphData &lg, const ccstd::string &name, gfx::Texture *texture, RenderData &data) { + auto nameID = getNameID(lg.attributeIndex, name); + data.textures[nameID.value] = IntrusivePtr(texture); +} + +void addReadWriteBuffer(const LayoutGraphData &lg, const ccstd::string &name, gfx::Buffer *buffer, RenderData &data) { + auto nameID = getNameID(lg.attributeIndex, name); + data.buffers[nameID.value] = IntrusivePtr(buffer); +} + +void addReadWriteTexture(const LayoutGraphData &lg, const ccstd::string &name, gfx::Texture *texture, RenderData &data) { + auto nameID = getNameID(lg.attributeIndex, name); + data.textures[nameID.value] = IntrusivePtr(texture); +} + +void addSampler(const LayoutGraphData &lg, const ccstd::string &name, gfx::Sampler *sampler, RenderData &data) { + auto nameID = getNameID(lg.attributeIndex, name); + data.samplers[nameID.value].ptr = sampler; +} + +} // namespace + +ccstd::string NativeSetter::getName() const { + return {}; +} +void NativeSetter::setName(const ccstd::string &name) { + // noop +} + +void NativeSetter::setMat4(const ccstd::string &name, const Mat4 &mat) { + auto &data = renderData; + addMat4(layoutGraph, name, mat, data); +} + +void NativeSetter::setQuaternion(const ccstd::string &name, const Quaternion &quat) { + auto &data = renderData; + addQuaternion(layoutGraph, name, quat, data); +} + +void NativeSetter::setColor(const ccstd::string &name, const gfx::Color &color) { + auto &data = renderData; + addColor(layoutGraph, name, color, data); +} + +void NativeSetter::setVec4(const ccstd::string &name, const Vec4 &vec) { + auto &data = renderData; + addVec4(layoutGraph, name, vec, data); +} + +void NativeSetter::setVec2(const ccstd::string &name, const Vec2 &vec) { + auto &data = renderData; + addVec2(layoutGraph, name, vec, data); +} + +void NativeSetter::setFloat(const ccstd::string &name, float v) { + auto &data = renderData; + addFloat(layoutGraph, name, v, data); +} + +void NativeSetter::setBuffer(const ccstd::string &name, gfx::Buffer *buffer) { + auto &data = renderData; + addBuffer(layoutGraph, name, buffer, data); +} + +void NativeSetter::setTexture(const ccstd::string &name, gfx::Texture *texture) { + auto &data = renderData; + addTexture(layoutGraph, name, texture, data); +} + +void NativeSetter::setReadWriteBuffer(const ccstd::string &name, gfx::Buffer *buffer) { + auto &data = renderData; + addReadWriteBuffer(layoutGraph, name, buffer, data); +} + +void NativeSetter::setReadWriteTexture(const ccstd::string &name, gfx::Texture *texture) { + auto &data = renderData; + addReadWriteTexture(layoutGraph, name, texture, data); +} + +void NativeSetter::setSampler(const ccstd::string &name, gfx::Sampler *sampler) { + auto &data = renderData; + addSampler(layoutGraph, name, sampler, data); +} + +void NativeSetter::setVec4ArraySize(const ccstd::string &name, uint32_t sz) { + setVec4ArraySizeImpl(layoutGraph, name, sz, renderData); +} + +void NativeSetter::setVec4ArrayElem(const ccstd::string &name, const cc::Vec4 &vec, uint32_t id) { + setVec4ArrayElemImpl(layoutGraph, name, vec, id, renderData); +} + +void NativeSetter::setMat4ArraySize(const ccstd::string &name, uint32_t sz) { + setMat4ArraySizeImpl(layoutGraph, name, sz, renderData); +} + +void NativeSetter::setMat4ArrayElem(const ccstd::string &name, const cc::Mat4 &mat, uint32_t id) { + setMat4ArrayElemImpl(layoutGraph, name, mat, id, renderData); +} + ccstd::string NativeRasterPassBuilder::getName() const { return std::string(get(RenderGraph::Name, *renderGraph, passID)); } @@ -50,13 +261,18 @@ void NativeRasterPassBuilder::setName(const ccstd::string &name) { void NativeRasterPassBuilder::addRasterView(const ccstd::string &name, const RasterView &view) { auto &pass = get(RasterTag{}, passID, *renderGraph); - pass.rasterViews.emplace( + auto slotID = static_cast(pass.rasterViews.size()); + auto res = pass.rasterViews.emplace( std::piecewise_construct, std::forward_as_tuple(name.c_str()), std::forward_as_tuple(view)); + CC_ENSURES(res.second); + res.first->second.slotID = slotID; } void NativeRasterPassBuilder::addComputeView(const ccstd::string &name, const ComputeView &view) { + CC_EXPECTS(!name.empty()); + CC_EXPECTS(!view.name.empty()); auto &pass = get(RasterTag{}, passID, *renderGraph); auto iter = pass.computeViews.find(name.c_str()); if (iter == pass.computeViews.end()) { @@ -70,6 +286,16 @@ void NativeRasterPassBuilder::addComputeView(const ccstd::string &name, const Co iter->second.emplace_back(view); } +bool NativeRasterPassBuilder::getShowStatistics() const { + const auto &pass = get(RasterTag{}, passID, *renderGraph); + return pass.showStatistics; +} + +void NativeRasterPassBuilder::setShowStatistics(bool enable) { + auto &pass = get(RasterTag{}, passID, *renderGraph); + pass.showStatistics = enable; +} + ccstd::string NativeRasterQueueBuilder::getName() const { return std::string(get(RenderGraph::Name, *renderGraph, queueID)); } @@ -78,13 +304,397 @@ void NativeRasterQueueBuilder::setName(const ccstd::string &name) { get(RenderGraph::Name, *renderGraph, queueID) = std::string_view{name}; } -void NativeRasterQueueBuilder::addSceneOfCamera(scene::Camera *camera, LightInfo light, SceneFlags sceneFlags) { +namespace { + +uint8_t getCombineSignY(gfx::Device *device) { + // 0: vk, 1: metal, 2: none, 3: gl-like + static int8_t combineSignY{-1}; + if (combineSignY < 0) { + const float screenSpaceSignY = device->getCapabilities().screenSpaceSignY * 0.5F + 0.5F; + const float clipSpaceSignY = device->getCapabilities().clipSpaceSignY * 0.5F + 0.5F; + combineSignY = static_cast(screenSpaceSignY) << 1 | static_cast(clipSpaceSignY); + } + return static_cast(combineSignY); +} + +void setCameraUBOValues( + const scene::Camera &camera, + const pipeline::PipelineSceneData &cfg, + const scene::DirectionalLight *mainLight, + Setter &setter) { + CC_EXPECTS(camera.getNode()); + CC_EXPECTS(cfg.getSkybox()); + const auto &skybox = *cfg.getSkybox(); + const auto &shadingScale = cfg.getShadingScale(); + // Camera + setter.setMat4("cc_matView", camera.getMatView()); + setter.setMat4("cc_matViewInv", camera.getNode()->getWorldMatrix()); + setter.setMat4("cc_matProj", camera.getMatProj()); + setter.setMat4("cc_matProjInv", camera.getMatProjInv()); + setter.setMat4("cc_matViewProj", camera.getMatViewProj()); + setter.setMat4("cc_matViewProjInv", camera.getMatViewProjInv()); + setter.setVec4("cc_cameraPos", Vec4(camera.getPosition().x, + camera.getPosition().y, + camera.getPosition().z, + getCombineSignY(cc::gfx::Device::getInstance()))); + setter.setVec4("cc_surfaceTransform", Vec4(static_cast(camera.getSurfaceTransform()), + 0.0F, + cosf(static_cast(mathutils::toRadian(skybox.getRotationAngle()))), + sinf(static_cast(mathutils::toRadian(skybox.getRotationAngle()))))); + setter.setVec4("cc_screenScale", Vec4(cfg.getShadingScale(), + cfg.getShadingScale(), + 1.0F / cfg.getShadingScale(), + 1.0F / cfg.getShadingScale())); + setter.setVec4("cc_exposure", Vec4(camera.getExposure(), + 1.0F / camera.getExposure(), + cfg.isHDR() ? 1.0F : 0.0F, + 1.0F / scene::Camera::getStandardExposureValue())); + + if (mainLight) { + const auto &shadowInfo = *cfg.getShadows(); + const bool shadowEnable = (mainLight->isShadowEnabled() && + shadowInfo.getType() == scene::ShadowType::SHADOW_MAP); + setter.setVec4("cc_mainLitDir", Vec4(mainLight->getDirection().x, + mainLight->getDirection().y, + mainLight->getDirection().z, + shadowEnable)); + auto r = mainLight->getColor().x; + auto g = mainLight->getColor().y; + auto b = mainLight->getColor().z; + if (mainLight->isUseColorTemperature()) { + r *= mainLight->getColorTemperatureRGB().x; + g *= mainLight->getColorTemperatureRGB().y; + b *= mainLight->getColorTemperatureRGB().z; + } + auto w = mainLight->getIlluminance(); + if (cfg.isHDR()) { + w *= camera.getExposure(); + } + setter.setVec4("cc_mainLitColor", Vec4(r, g, b, w)); + } else { + setter.setVec4("cc_mainLitDir", Vec4(0, 0, 1, 0)); + setter.setVec4("cc_mainLitColor", Vec4(0, 0, 0, 0)); + } + + CC_EXPECTS(cfg.getAmbient()); + auto &ambient = *cfg.getAmbient(); + auto &skyColor = ambient.getSkyColor(); + if (cfg.isHDR()) { + skyColor.w = ambient.getSkyIllum() * camera.getExposure(); + } else { + skyColor.w = ambient.getSkyIllum(); + } + setter.setVec4("cc_ambientSky", Vec4(skyColor.x, skyColor.y, skyColor.z, skyColor.w)); + setter.setVec4("cc_ambientGround", Vec4(ambient.getGroundAlbedo().x, + ambient.getGroundAlbedo().y, + ambient.getGroundAlbedo().z, + skybox.getEnvmap() + ? static_cast(skybox.getEnvmap()->mipmapLevel()) + : 1.0F)); + + CC_EXPECTS(cfg.getFog()); + const auto &fog = *cfg.getFog(); + + const auto &colorTempRGB = fog.getColorArray(); + setter.setVec4("cc_fogColor", Vec4(colorTempRGB.x, colorTempRGB.y, colorTempRGB.z, colorTempRGB.z)); + setter.setVec4("cc_fogBase", Vec4(fog.getFogStart(), fog.getFogEnd(), fog.getFogDensity(), 0.0F)); + setter.setVec4("cc_fogAdd", Vec4(fog.getFogTop(), fog.getFogRange(), fog.getFogAtten(), 0.0F)); + setter.setVec4("cc_nearFar", Vec4(camera.getNearClip(), camera.getFarClip(), 0.0F, 0.0F)); + setter.setVec4("cc_viewPort", Vec4(camera.getViewport().x, + camera.getViewport().y, + shadingScale * static_cast(camera.getWindow()->getWidth()) * camera.getViewport().z, + shadingScale * static_cast(camera.getWindow()->getHeight()) * camera.getViewport().w)); +} + +void setShadowUBOLightView( + gfx::Device *device, + const pipeline::PipelineSceneData &sceneData, + const scene::Light &light, + uint32_t level, Setter &setter) { + const auto &shadowInfo = *sceneData.getShadows(); + const auto &csmLayers = *sceneData.getCSMLayers(); + const auto &packing = pipeline::supportsR32FloatTexture(device) ? 0.0F : 1.0F; + const auto &cap = device->getCapabilities(); + Vec4 vec4ShadowInfo{}; + + // ShadowMap + switch (light.getType()) { + case scene::LightType::DIRECTIONAL: { + const auto &mainLight = dynamic_cast(light); + if (shadowInfo.isEnabled() && mainLight.isShadowEnabled()) { + if (shadowInfo.getType() == scene::ShadowType::SHADOW_MAP) { + float near = 0.1; + float far = 0; + Mat4 matShadowView; + Mat4 matShadowProj; + Mat4 matShadowViewProj; + scene::CSMLevel levelCount{}; + if (mainLight.isShadowFixedArea() || mainLight.getCSMLevel() == scene::CSMLevel::LEVEL_1) { + matShadowView = csmLayers.getSpecialLayer()->getMatShadowView(); + matShadowProj = csmLayers.getSpecialLayer()->getMatShadowProj(); + matShadowViewProj = csmLayers.getSpecialLayer()->getMatShadowViewProj(); + if (mainLight.isShadowFixedArea()) { + near = mainLight.getShadowNear(); + far = mainLight.getShadowFar(); + levelCount = static_cast(0); + } else { + near = 0.1; + far = csmLayers.getSpecialLayer()->getShadowCameraFar(); + levelCount = scene::CSMLevel::LEVEL_1; + } + vec4ShadowInfo.set(0.0F, packing, mainLight.getShadowNormalBias(), 0); + setter.setVec4("cc_shadowLPNNInfo", vec4ShadowInfo); + } else { + const auto &layer = *csmLayers.getLayers()[level]; + matShadowView = layer.getMatShadowView(); + matShadowProj = layer.getMatShadowProj(); + matShadowViewProj = layer.getMatShadowViewProj(); + + near = layer.getSplitCameraNear(); + far = layer.getSplitCameraFar(); + levelCount = mainLight.getCSMLevel(); + } + setter.setMat4("cc_matLightView", matShadowView); + setter.setVec4("cc_shadowProjDepthInfo", Vec4(matShadowProj.m[10], matShadowProj.m[14], + matShadowProj.m[11], matShadowProj.m[15])); + setter.setVec4("cc_shadowProjInfo", Vec4(matShadowProj.m[00], matShadowProj.m[05], + 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05])); + setter.setMat4("cc_matLightViewProj", matShadowViewProj); + vec4ShadowInfo.set(near, far, 0, 1.0F - mainLight.getShadowSaturation()); + setter.setVec4("cc_shadowNFLSInfo", vec4ShadowInfo); + vec4ShadowInfo.set(0.0F, packing, mainLight.getShadowNormalBias(), static_cast(levelCount)); + setter.setVec4("cc_shadowLPNNInfo", vec4ShadowInfo); + vec4ShadowInfo.set(shadowInfo.getSize().x, shadowInfo.getSize().y, static_cast(mainLight.getShadowPcf()), mainLight.getShadowBias()); + setter.setVec4("cc_shadowWHPBInfo", vec4ShadowInfo); + } + } + break; + } + case scene::LightType::SPOT: { + const auto &spotLight = dynamic_cast(light); + if (shadowInfo.isEnabled() && spotLight.isShadowEnabled()) { + const auto &matShadowCamera = spotLight.getNode()->getWorldMatrix(); + const auto matShadowView = matShadowCamera.getInversed(); + setter.setMat4("cc_matLightView", matShadowView); + + Mat4 matShadowViewProj{}; + Mat4::createPerspective(spotLight.getAngle(), 1.0F, 0.001F, + spotLight.getRange(), true, + cap.clipSpaceMinZ, cap.clipSpaceSignY, 0, &matShadowViewProj); + matShadowViewProj.multiply(matShadowView); + setter.setMat4("cc_matLightViewProj", matShadowViewProj); + + const Vec4 shadowNFLSInfos(0.01F, spotLight.getRange(), 0.0F, 0.0F); + setter.setVec4("cc_shadowNFLSInfo", shadowNFLSInfos); + + const Vec4 shadowWHPBInfos( + shadowInfo.getSize().x, + shadowInfo.getSize().y, + spotLight.getShadowPcf(), + spotLight.getShadowBias()); + setter.setVec4("cc_shadowWHPBInfo", shadowWHPBInfos); + + const Vec4 shadowLPNNInfos(1.0F, packing, spotLight.getShadowNormalBias(), 0.0F); + setter.setVec4("cc_shadowLPNNInfo", shadowLPNNInfos); + } + break; + } + default: + break; + } + + const auto &data = shadowInfo.getShadowColor4f(); + setter.setColor("cc_shadowColor", gfx::Color{data[0], data[1], data[2], data[3]}); +} + +float getPCFRadius( + const scene::Shadows &shadowInfo, + const scene::DirectionalLight &mainLight) { + const auto &shadowMapSize = shadowInfo.getSize().x; + switch (mainLight.getShadowPcf()) { + case scene::PCFType::HARD: + return 0.0F; + case scene::PCFType::SOFT: + return 1.0F / (shadowMapSize * 0.5F); + case scene::PCFType::SOFT_2X: + return 2.0F / (shadowMapSize * 0.5F); + // case PCFType.SOFT_4X: + // return 3.0F / (shadowMapSize * 0.5F); + default: + break; + } + return 0.0F; +} + +void setShadowUBOView( + gfx::Device &device, + const pipeline::PipelineSceneData &sceneData, + const scene::DirectionalLight &mainLight, + NativeSetter &setter) { + const auto &shadowInfo = *sceneData.getShadows(); + const auto &csmLayers = *sceneData.getCSMLayers(); + const auto &csmSupported = sceneData.getCSMSupported(); + const auto &packing = pipeline::supportsR32FloatTexture(&device) ? 0.0F : 1.0F; + Vec4 vec4ShadowInfo{}; + if (shadowInfo.isEnabled()) { + if (shadowInfo.getType() == scene::ShadowType::SHADOW_MAP) { + if (mainLight.isShadowEnabled()) { + if (mainLight.isShadowFixedArea() || + mainLight.getCSMLevel() == scene::CSMLevel::LEVEL_1 || !csmSupported) { + // Shadow + const auto &matShadowView = csmLayers.getSpecialLayer()->getMatShadowView(); + const auto &matShadowProj = csmLayers.getSpecialLayer()->getMatShadowProj(); + const auto &matShadowViewProj = csmLayers.getSpecialLayer()->getMatShadowViewProj(); + const auto &near = mainLight.getShadowNear(); + const auto &far = mainLight.getShadowFar(); + + setter.setMat4("cc_matLightView", matShadowView); + setter.setVec4("cc_shadowProjDepthInfo", + Vec4(matShadowProj.m[10], matShadowProj.m[14], + matShadowProj.m[11], matShadowProj.m[15])); + + setter.setVec4("cc_shadowProjInfo", + Vec4(matShadowProj.m[00], matShadowProj.m[05], + 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05])); + setter.setMat4("cc_matLightViewProj", matShadowViewProj); + vec4ShadowInfo.set(near, far, 0, 1.0F - mainLight.getShadowSaturation()); + setter.setVec4("cc_shadowNFLSInfo", vec4ShadowInfo); + vec4ShadowInfo.set(0.0F, packing, mainLight.getShadowNormalBias(), 0); + setter.setVec4("cc_shadowLPNNInfo", vec4ShadowInfo); + } else { + { // CSM + const auto layerThreshold = getPCFRadius(shadowInfo, mainLight); + const auto numCascades = static_cast(mainLight.getCSMLevel()); + setter.setVec4ArraySize("cc_csmViewDir0", numCascades); + setter.setVec4ArraySize("cc_csmViewDir1", numCascades); + setter.setVec4ArraySize("cc_csmViewDir2", numCascades); + setter.setVec4ArraySize("cc_csmAtlas", numCascades); + setter.setMat4ArraySize("cc_matCSMViewProj", numCascades); + setter.setVec4ArraySize("cc_csmProjDepthInfo", numCascades); + setter.setVec4ArraySize("cc_csmProjInfo", numCascades); + + Vec4 csmSplitsInfo{}; + for (uint32_t i = 0; i < numCascades; ++i) { + const auto &layer = *csmLayers.getLayers()[i]; + + const auto &matShadowView = layer.getMatShadowView(); + vec4ShadowInfo.set(matShadowView.m[0], matShadowView.m[4], matShadowView.m[8], layerThreshold); + setter.setVec4ArrayElem("cc_csmViewDir0", vec4ShadowInfo, i); + vec4ShadowInfo.set(matShadowView.m[1], matShadowView.m[5], matShadowView.m[9], 0.0F); + setter.setVec4ArrayElem("cc_csmViewDir1", vec4ShadowInfo, i); + vec4ShadowInfo.set(matShadowView.m[2], matShadowView.m[6], matShadowView.m[0], 0.0F); + setter.setVec4ArrayElem("cc_csmViewDir2", vec4ShadowInfo, i); + + const auto &csmAtlas = layer.getCSMAtlas(); + setter.setVec4ArrayElem("cc_csmAtlas", csmAtlas, i); + + const auto &matShadowViewProj = layer.getMatShadowViewProj(); + setter.setMat4ArrayElem("cc_matCSMViewProj", matShadowViewProj, i); + + const auto &matShadowProj = layer.getMatShadowProj(); + setter.setVec4ArrayElem( + "cc_csmProjDepthInfo", + Vec4(matShadowProj.m[10], matShadowProj.m[14], + matShadowProj.m[11], matShadowProj.m[15]), + i); + + setter.setVec4ArrayElem( + "cc_csmProjInfo", + Vec4(matShadowProj.m[00], matShadowProj.m[05], + 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05]), + i); + + (&csmSplitsInfo.x)[i] = layer.getSplitCameraFar() / mainLight.getShadowDistance(); + } + setter.setVec4("cc_csmSplitsInfo", csmSplitsInfo); + } + { // Shadow + vec4ShadowInfo.set(0, 0, 0, 1.0F - mainLight.getShadowSaturation()); + setter.setVec4("cc_shadowNFLSInfo", vec4ShadowInfo); + vec4ShadowInfo.set( + 0.0F, packing, + mainLight.getShadowNormalBias(), + static_cast(mainLight.getCSMLevel())); + setter.setVec4("cc_shadowLPNNInfo", vec4ShadowInfo); + } + } + { // Shadow + vec4ShadowInfo.set( + shadowInfo.getSize().x, shadowInfo.getSize().y, + static_cast(mainLight.getShadowPcf()), mainLight.getShadowBias()); + setter.setVec4("cc_shadowWHPBInfo", vec4ShadowInfo); + } + } + } else { + Vec3 tempVec3 = shadowInfo.getNormal().getNormalized(); + setter.setVec4( + "cc_planarNDInfo", + Vec4(tempVec3.x, tempVec3.y, tempVec3.z, -shadowInfo.getDistance())); + } + { + const auto &data = shadowInfo.getShadowColor4f(); + setter.setColor("cc_shadowColor", gfx::Color{data[0], data[1], data[2], data[3]}); + } + } +} + +void setTextureUBOView( + gfx::Device &device, + const pipeline::PipelineSceneData &sceneData, + Setter &setter) { + const auto &skybox = *sceneData.getSkybox(); + if (skybox.getReflectionMap()) { + auto &texture = *skybox.getReflectionMap()->getGFXTexture(); + auto *sampler = device.getSampler(skybox.getReflectionMap()->getSamplerInfo()); + setter.setTexture("cc_environment", &texture); + setter.setSampler("cc_environment", sampler); + } else { + const auto *envmap = + skybox.getEnvmap() + ? skybox.getEnvmap() + : BuiltinResMgr::getInstance()->get("default-cube-texture"); + if (envmap) { + auto *texture = envmap->getGFXTexture(); + auto *sampler = device.getSampler(envmap->getSamplerInfo()); + setter.setTexture("cc_environment", texture); + setter.setSampler("cc_environment", sampler); + } + } + const auto *diffuseMap = + skybox.getDiffuseMap() + ? skybox.getDiffuseMap() + : BuiltinResMgr::getInstance()->get("default-cube-texture"); + if (diffuseMap) { + auto *texture = diffuseMap->getGFXTexture(); + auto *sampler = device.getSampler(diffuseMap->getSamplerInfo()); + setter.setTexture("cc_diffuseMap", texture); + setter.setSampler("cc_diffuseMap", sampler); + } + gfx::SamplerInfo samplerPointInfo{ + gfx::Filter::POINT, + gfx::Filter::POINT, + gfx::Filter::NONE, + gfx::Address::CLAMP, + gfx::Address::CLAMP, + gfx::Address::CLAMP}; + auto *pointSampler = device.getSampler(samplerPointInfo); + setter.setSampler("cc_shadowMap", pointSampler); + setter.setTexture("cc_shadowMap", BuiltinResMgr::getInstance()->get("default-texture")->getGFXTexture()); + setter.setSampler("cc_spotShadowMap", pointSampler); + setter.setTexture("cc_spotShadowMap", BuiltinResMgr::getInstance()->get("default-texture")->getGFXTexture()); +} + +} // namespace + +void NativeRasterQueueBuilder::addSceneOfCamera( + scene::Camera *camera, LightInfo light, SceneFlags sceneFlags) { std::string_view name = "Camera"; + auto *pLight = light.light.get(); SceneData scene(renderGraph->get_allocator()); scene.name = name; scene.flags = sceneFlags; scene.camera = camera; - scene.light = std::move(light); + scene.light = light; auto sceneID = addVertex( SceneTag{}, std::forward_as_tuple(name), @@ -94,6 +704,34 @@ void NativeRasterQueueBuilder::addSceneOfCamera(scene::Camera *camera, LightInfo std::forward_as_tuple(std::move(scene)), *renderGraph, queueID); CC_ENSURES(sceneID != RenderGraph::null_vertex()); + + auto &data = get(RenderGraph::Data, *renderGraph, sceneID); + NativeSetter setter{*layoutGraph, data}; + + setCameraUBOValues( + *camera, + *pipelineRuntime->getPipelineSceneData(), + camera->getScene()->getMainLight(), setter); + + if (any(sceneFlags & SceneFlags::SHADOW_CASTER)) { + if (pLight) { + setShadowUBOLightView( + pipelineRuntime->getDevice(), + *pipelineRuntime->getPipelineSceneData(), + *pLight, light.level, setter); + } + } else { + const auto *pDirLight = camera->getScene()->getMainLight(); + if (pDirLight) { + setShadowUBOView(*pipelineRuntime->getDevice(), + *pipelineRuntime->getPipelineSceneData(), + *pDirLight, setter); + } + } + setTextureUBOView( + *pipelineRuntime->getDevice(), + *pipelineRuntime->getPipelineSceneData(), + setter); } void NativeRasterQueueBuilder::addScene(const ccstd::string &name, SceneFlags sceneFlags) { @@ -139,6 +777,28 @@ void NativeRasterQueueBuilder::addCameraQuad( std::forward_as_tuple(material, passID, sceneFlags, camera), *renderGraph, queueID); CC_ENSURES(drawID != RenderGraph::null_vertex()); + + auto &data = get(RenderGraph::Data, *renderGraph, drawID); + NativeSetter setter{*layoutGraph, data}; + + setCameraUBOValues( + *camera, + *pipelineRuntime->getPipelineSceneData(), + camera->getScene()->getMainLight(), setter); + + if (any(sceneFlags & SceneFlags::SHADOW_CASTER)) { + } else { + const auto *pDirLight = camera->getScene()->getMainLight(); + if (pDirLight) { + setShadowUBOView(*pipelineRuntime->getDevice(), + *pipelineRuntime->getPipelineSceneData(), + *pDirLight, setter); + } + } + setTextureUBOView( + *pipelineRuntime->getDevice(), + *pipelineRuntime->getPipelineSceneData(), + setter); } void NativeRasterQueueBuilder::clearRenderTarget(const ccstd::string &name, const gfx::Color &color) { @@ -168,91 +828,6 @@ void NativeRasterQueueBuilder::setViewport(const gfx::Viewport &viewport) { CC_ENSURES(viewportID != RenderGraph::null_vertex()); } -namespace { - -render::NameLocalID getNameID( - const PmrFlatMap &index, - std::string_view name) { - auto iter = index.find(name); - CC_EXPECTS(iter != index.end()); - return iter->second; -} - -void addMat4( - const LayoutGraphData &lg, std::string_view name, - const cc::Mat4 &v, RenderData &data) { - auto nameID = getNameID(lg.constantIndex, name); - static_assert(sizeof(Mat4) == 16 * 4, "sizeof(Mat4) is not 64 bytes"); - data.constants[nameID.value].resize(sizeof(Mat4)); - memcpy(data.constants[nameID.value].data(), v.m, sizeof(v)); -} - -void addQuaternion(const LayoutGraphData &lg, const ccstd::string &name, const Quaternion &quat, RenderData &data) { - auto nameID = getNameID(lg.constantIndex, name); - static_assert(sizeof(Quaternion) == 4 * 4, "sizeof(Quaternion) is not 16 bytes"); - static_assert(std::is_trivially_copyable::value, "Quaternion is not trivially copyable"); - data.constants[nameID.value].resize(sizeof(Quaternion)); - memcpy(data.constants[nameID.value].data(), &quat, sizeof(quat)); -} - -void addColor(const LayoutGraphData &lg, const ccstd::string &name, const gfx::Color &color, RenderData &data) { - auto nameID = getNameID(lg.constantIndex, name); - static_assert(sizeof(gfx::Color) == 4 * 4, "sizeof(Color) is not 16 bytes"); - static_assert(std::is_trivially_copyable::value, "Color is not trivially copyable"); - data.constants[nameID.value].resize(sizeof(gfx::Color)); - memcpy(data.constants[nameID.value].data(), &color, sizeof(color)); -} - -void addVec4(const LayoutGraphData &lg, const ccstd::string &name, const Vec4 &vec, RenderData &data) { - auto nameID = getNameID(lg.constantIndex, name); - static_assert(sizeof(Vec4) == 4 * 4, "sizeof(Vec4) is not 16 bytes"); - // static_assert(std::is_trivially_copyable::value, "Vec4 is not trivially copyable"); - data.constants[nameID.value].resize(sizeof(Vec4)); - memcpy(data.constants[nameID.value].data(), &vec.x, sizeof(vec)); -} - -void addVec2(const LayoutGraphData &lg, const ccstd::string &name, const Vec2 &vec, RenderData &data) { - auto nameID = getNameID(lg.constantIndex, name); - static_assert(sizeof(Vec2) == 2 * 4, "sizeof(Vec2) is not 8 bytes"); - // static_assert(std::is_trivially_copyable::value, "Vec2 is not trivially copyable"); - data.constants[nameID.value].resize(sizeof(Vec2)); - memcpy(data.constants[nameID.value].data(), &vec.x, sizeof(vec)); -} - -void addFloat(const LayoutGraphData &lg, const ccstd::string &name, float v, RenderData &data) { - auto nameID = getNameID(lg.constantIndex, name); - static_assert(sizeof(float) == 4, "sizeof(float) is not 4 bytes"); - data.constants[nameID.value].resize(sizeof(float)); - memcpy(data.constants[nameID.value].data(), &v, sizeof(v)); -} - -void addBuffer(const LayoutGraphData &lg, const ccstd::string &name, gfx::Buffer *buffer, RenderData &data) { - auto nameID = getNameID(lg.attributeIndex, name); - data.buffers[nameID.value] = IntrusivePtr(buffer); -} - -void addTexture(const LayoutGraphData &lg, const ccstd::string &name, gfx::Texture *texture, RenderData &data) { - auto nameID = getNameID(lg.attributeIndex, name); - data.textures[nameID.value] = IntrusivePtr(texture); -} - -void addReadWriteBuffer(const LayoutGraphData &lg, const ccstd::string &name, gfx::Buffer *buffer, RenderData &data) { - auto nameID = getNameID(lg.attributeIndex, name); - data.buffers[nameID.value] = IntrusivePtr(buffer); -} - -void addReadWriteTexture(const LayoutGraphData &lg, const ccstd::string &name, gfx::Texture *texture, RenderData &data) { - auto nameID = getNameID(lg.attributeIndex, name); - data.textures[nameID.value] = IntrusivePtr(texture); -} - -void addSampler(const LayoutGraphData &lg, const ccstd::string &name, gfx::Sampler *sampler, RenderData &data) { - auto nameID = getNameID(lg.attributeIndex, name); - data.samplers[nameID.value].ptr = sampler; -} - -} // namespace - void NativeRasterQueueBuilder::setMat4(const ccstd::string &name, const Mat4 &mat) { auto &data = get(RenderGraph::Data, *renderGraph, queueID); addMat4(*layoutGraph, name, mat, data); @@ -319,7 +894,7 @@ RasterQueueBuilder *NativeRasterPassBuilder::addQueue(QueueHint hint) { std::forward_as_tuple(hint), *renderGraph, passID); - return new NativeRasterQueueBuilder(renderGraph, queueID, layoutGraph); + return new NativeRasterQueueBuilder(pipelineRuntime, renderGraph, queueID, layoutGraph); } void NativeRasterPassBuilder::setViewport(const gfx::Viewport &viewport) { @@ -475,6 +1050,8 @@ void NativeComputePassBuilder::setName(const ccstd::string &name) { } void NativeComputePassBuilder::addComputeView(const ccstd::string &name, const ComputeView &view) { + CC_EXPECTS(!name.empty()); + CC_EXPECTS(!view.name.empty()); auto &pass = get(ComputeTag{}, passID, *renderGraph); auto iter = pass.computeViews.find(name.c_str()); if (iter == pass.computeViews.end()) { diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderingModule.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderingModule.cpp index 09001e9514..110f994473 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderingModule.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeRenderingModule.cpp @@ -23,20 +23,22 @@ ****************************************************************************/ #include "NativePipelineTypes.h" +#include "details/GslUtils.h" +#include "LayoutGraphGraphs.h" namespace cc { namespace render { uint32_t NativeRenderingModule::getPassID(const ccstd::string &name) const { - std::ignore = name; - return LayoutGraphData::null_vertex(); + CC_EXPECTS(programLibrary); + return locate(LayoutGraphData::null_vertex(), name, programLibrary->layoutGraph); } uint32_t NativeRenderingModule::getPhaseID(uint32_t passID, const ccstd::string &name) const { - std::ignore = passID; - std::ignore = name; - return LayoutGraphData::null_vertex(); + CC_EXPECTS(programLibrary); + CC_EXPECTS(passID != LayoutGraphData::null_vertex()); + return locate(passID, name, programLibrary->layoutGraph); } } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp index 08c3333be0..3c2444666a 100644 --- a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp @@ -40,6 +40,23 @@ ResourceGroup::~ResourceGroup() noexcept { } } +void ProgramResource::syncResources() noexcept { + for (auto&& [nameID, buffer] : uniformBuffers) { + buffer.bufferPool.syncResources(); + } + descriptorSetPool.syncDescriptorSets(); +} + +void LayoutGraphNodeResource::syncResources() noexcept { + for (auto&& [nameID, buffer] : uniformBuffers) { + buffer.bufferPool.syncResources(); + } + descriptorSetPool.syncDescriptorSets(); + for (auto&& [programName, programResource] : programResources) { + programResource.syncResources(); + } +} + void NativeRenderContext::clearPreviousResources(uint64_t finishedFenceValue) noexcept { for (auto iter = resourceGroups.begin(); iter != resourceGroups.end();) { if (iter->first <= finishedFenceValue) { @@ -48,6 +65,9 @@ void NativeRenderContext::clearPreviousResources(uint64_t finishedFenceValue) no break; } } + for (auto& node : layoutGraphResources) { + node.syncResources(); + } } namespace { @@ -138,6 +158,27 @@ gfx::TextureInfo getTextureInfo(const ResourceDesc& desc, bool bCube = false) { } // namespace +bool ManagedTexture::checkResource(const ResourceDesc& desc) const { + if (!texture) { + return false; + } + const auto& info = texture->getInfo(); + return desc.width == info.width && desc.height == info.height && desc.format == info.format; +} + +void ResourceGraph::validateSwapchains() { + bool swapchainInvalidated = false; + for (auto& sc : swapchains) { + if (sc.generation != sc.swapchain->getGeneration()) { + swapchainInvalidated = true; + sc.generation = sc.swapchain->getGeneration(); + } + } + if (swapchainInvalidated) { + renderPasses.clear(); + } +} + void ResourceGraph::mount(gfx::Device* device, vertex_descriptor vertID) { std::ignore = device; auto& resg = *this; @@ -156,49 +197,98 @@ void ResourceGraph::mount(gfx::Device* device, vertex_descriptor vertID) { buffer.fenceValue = nextFenceValue; }, [&](ManagedTexture& texture) { - if (!texture.texture) { + if (!texture.checkResource(desc)) { auto info = getTextureInfo(desc); texture.texture = device->createTexture(info); } CC_ENSURES(texture.texture); texture.fenceValue = nextFenceValue; }, - [&](const IntrusivePtr& pass) { + [&](const IntrusivePtr& buffer) { + CC_EXPECTS(buffer); + std::ignore = buffer; }, - [&](const IntrusivePtr& pass) { + [&](const IntrusivePtr& texture) { + CC_EXPECTS(texture); + std::ignore = texture; }, - [&](const IntrusivePtr& pass) { + [&](const IntrusivePtr& fb) { + CC_EXPECTS(fb); + std::ignore = fb; }, [&](const RenderSwapchain& queue) { + CC_EXPECTS(queue.swapchain); + std::ignore = queue; }); } void ResourceGraph::unmount(uint64_t completedFenceValue) { auto& resg = *this; for (const auto& vertID : makeRange(vertices(resg))) { - visitObject( - vertID, resg, - [&](const ManagedResource& resource) { - // to be removed - }, - [&](ManagedBuffer& buffer) { - if (buffer.fenceValue <= completedFenceValue) { - buffer.buffer.reset(); - } - }, - [&](ManagedTexture& texture) { - if (texture.fenceValue <= completedFenceValue) { - texture.texture.reset(); - } - }, - [&](const IntrusivePtr& pass) { - }, - [&](const IntrusivePtr& pass) { - }, - [&](const IntrusivePtr& pass) { - }, - [&](const RenderSwapchain& queue) { - }); + // here msvc has strange behaviour when using visitObject + // we use if-else instead. + if (holds(vertID, resg)) { + auto& buffer = get(ManagedBufferTag{}, vertID, resg); + if (buffer.buffer && buffer.fenceValue <= completedFenceValue) { + buffer.buffer.reset(); + } + } else if (holds(vertID, resg)) { + auto& texture = get(ManagedTextureTag{}, vertID, resg); + if (texture.texture && texture.fenceValue <= completedFenceValue) { + invalidatePersistentRenderPassAndFramebuffer(texture.texture.get()); + texture.texture.reset(); + } + } + } +} + +gfx::Texture* ResourceGraph::getTexture(vertex_descriptor resID) { + gfx::Texture* texture = nullptr; + visitObject( + resID, *this, + [&](const ManagedTexture& res) { + texture = res.texture.get(); + }, + [&](const IntrusivePtr& tex) { + texture = tex.get(); + }, + [&](const IntrusivePtr& fb) { + std::ignore = fb; + CC_EXPECTS(false); + }, + [&](const RenderSwapchain& sc) { + texture = sc.swapchain->getColorTexture(); + }, + [&](const auto& buffer) { + std::ignore = buffer; + CC_EXPECTS(false); + }); + CC_ENSURES(texture); + + return texture; +} + +void ResourceGraph::invalidatePersistentRenderPassAndFramebuffer(gfx::Texture* pTexture) { + if (!pTexture) { + return; + } + for (auto iter = renderPasses.begin(); iter != renderPasses.end();) { + const auto& pass = iter->second; + bool bErase = false; + for (const auto& color : pass.framebuffer->getColorTextures()) { + if (color == pTexture) { + bErase = true; + break; + } + } + if (pass.framebuffer->getDepthStencilTexture() == pTexture) { + bErase = true; + } + if (bErase) { + iter = renderPasses.erase(iter); + } else { + ++iter; + } } } diff --git a/native/cocos/renderer/pipeline/custom/NativeTypes.cpp b/native/cocos/renderer/pipeline/custom/NativeTypes.cpp index 719f69e79a..f0d21eea6a 100644 --- a/native/cocos/renderer/pipeline/custom/NativeTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeTypes.cpp @@ -35,41 +35,40 @@ namespace cc { namespace render { ProgramInfo::ProgramInfo(const allocator_type& alloc) noexcept -: attributes(alloc), - blockSizes(alloc) {} +: attributes(alloc) {} -ProgramInfo::ProgramInfo(IProgramInfo programInfoIn, gfx::ShaderInfo shaderInfoIn, ccstd::pmr::vector attributesIn, ccstd::pmr::vector blockSizesIn, Record handleMapIn, const allocator_type& alloc) noexcept +ProgramInfo::ProgramInfo(IProgramInfo programInfoIn, gfx::ShaderInfo shaderInfoIn, ccstd::pmr::vector attributesIn, ccstd::vector blockSizesIn, Record handleMapIn, const allocator_type& alloc) noexcept : programInfo(std::move(programInfoIn)), shaderInfo(std::move(shaderInfoIn)), attributes(std::move(attributesIn), alloc), - blockSizes(std::move(blockSizesIn), alloc), + blockSizes(std::move(blockSizesIn)), handleMap(std::move(handleMapIn)) {} ProgramInfo::ProgramInfo(ProgramInfo&& rhs, const allocator_type& alloc) : programInfo(std::move(rhs.programInfo)), shaderInfo(std::move(rhs.shaderInfo)), attributes(std::move(rhs.attributes), alloc), - blockSizes(std::move(rhs.blockSizes), alloc), + blockSizes(std::move(rhs.blockSizes)), handleMap(std::move(rhs.handleMap)) {} ProgramInfo::ProgramInfo(ProgramInfo const& rhs, const allocator_type& alloc) : programInfo(rhs.programInfo), shaderInfo(rhs.shaderInfo), attributes(rhs.attributes, alloc), - blockSizes(rhs.blockSizes, alloc), + blockSizes(rhs.blockSizes), handleMap(rhs.handleMap) {} ProgramGroup::ProgramGroup(const allocator_type& alloc) noexcept : programInfos(alloc), - programHosts(alloc) {} + programProxies(alloc) {} ProgramGroup::ProgramGroup(ProgramGroup&& rhs, const allocator_type& alloc) : programInfos(std::move(rhs.programInfos), alloc), - programHosts(std::move(rhs.programHosts), alloc) {} + programProxies(std::move(rhs.programProxies), alloc) {} ProgramGroup::ProgramGroup(ProgramGroup const& rhs, const allocator_type& alloc) : programInfos(rhs.programInfos, alloc), - programHosts(rhs.programHosts, alloc) {} + programProxies(rhs.programProxies, alloc) {} } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativeTypes.h b/native/cocos/renderer/pipeline/custom/NativeTypes.h index 9e029847ec..3d3eae733a 100644 --- a/native/cocos/renderer/pipeline/custom/NativeTypes.h +++ b/native/cocos/renderer/pipeline/custom/NativeTypes.h @@ -29,15 +29,13 @@ */ // clang-format off #pragma once -#include "cocos/base/Ptr.h" #include "cocos/base/std/container/string.h" #include "cocos/base/std/hash/hash.h" -#include "cocos/renderer/core/ProgramLib.h" #include "cocos/renderer/gfx-base/GFXRenderPass.h" #include "cocos/renderer/pipeline/GlobalDescriptorSetManager.h" #include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" #include "cocos/renderer/pipeline/custom/NativeFwd.h" -#include "cocos/renderer/pipeline/custom/RenderInterfaceTypes.h" +#include "cocos/renderer/pipeline/custom/PrivateTypes.h" #include "cocos/renderer/pipeline/custom/details/Map.h" namespace cc { @@ -51,7 +49,7 @@ struct ProgramInfo { } ProgramInfo(const allocator_type& alloc) noexcept; // NOLINT - ProgramInfo(IProgramInfo programInfoIn, gfx::ShaderInfo shaderInfoIn, ccstd::pmr::vector attributesIn, ccstd::pmr::vector blockSizesIn, Record handleMapIn, const allocator_type& alloc) noexcept; + ProgramInfo(IProgramInfo programInfoIn, gfx::ShaderInfo shaderInfoIn, ccstd::pmr::vector attributesIn, ccstd::vector blockSizesIn, Record handleMapIn, const allocator_type& alloc) noexcept; ProgramInfo(ProgramInfo&& rhs, const allocator_type& alloc); ProgramInfo(ProgramInfo const& rhs, const allocator_type& alloc); @@ -63,18 +61,10 @@ struct ProgramInfo { IProgramInfo programInfo; gfx::ShaderInfo shaderInfo; ccstd::pmr::vector attributes; - ccstd::pmr::vector blockSizes; + ccstd::vector blockSizes; Record handleMap; }; -struct ProgramHost { - ProgramHost() = default; - ProgramHost(IntrusivePtr programIn) noexcept // NOLINT - : program(std::move(programIn)) {} - - IntrusivePtr program; -}; - struct ProgramGroup { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT @@ -90,8 +80,8 @@ struct ProgramGroup { ProgramGroup& operator=(ProgramGroup&& rhs) = default; ProgramGroup& operator=(ProgramGroup const& rhs) = default; - PmrFlatMap programInfos; - PmrFlatMap programHosts; + PmrTransparentMap programInfos; + PmrFlatMap> programProxies; }; } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativeUtils.cpp b/native/cocos/renderer/pipeline/custom/NativeUtils.cpp new file mode 100644 index 0000000000..a581071153 --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeUtils.cpp @@ -0,0 +1,35 @@ +#include "NativeUtils.h" +#include "cocos/renderer/gfx-base/GFXDevice.h" + +namespace cc { +namespace render { + +void setupQuadVertexBuffer(gfx::Device& device, const Vec4& viewport, float vbData[16]) { + auto minX = static_cast(viewport.x); + auto maxX = static_cast(viewport.x + viewport.z); + auto minY = static_cast(viewport.y); + auto maxY = static_cast(viewport.y + viewport.w); + if (device.getCapabilities().screenSpaceSignY > 0) { + std::swap(minY, maxY); + } + int n = 0; + vbData[n++] = -1.0F; + vbData[n++] = -1.0F; + vbData[n++] = minX; // uv + vbData[n++] = maxY; + vbData[n++] = 1.0F; + vbData[n++] = -1.0F; + vbData[n++] = maxX; + vbData[n++] = maxY; + vbData[n++] = -1.0F; + vbData[n++] = 1.0F; + vbData[n++] = minX; + vbData[n++] = minY; + vbData[n++] = 1.0F; + vbData[n++] = 1.0F; + vbData[n++] = maxX; + vbData[n++] = minY; +} + +} // namespace render +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeUtils.h b/native/cocos/renderer/pipeline/custom/NativeUtils.h new file mode 100644 index 0000000000..17c728fde1 --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeUtils.h @@ -0,0 +1,13 @@ +#pragma once +#include "cocos/math/Vec4.h" + +namespace cc { +namespace gfx { +class Device; +} +namespace render { + +void setupQuadVertexBuffer(gfx::Device& device, const Vec4& viewport, float vbData[16]); + +} // namespace render +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/PrivateTypes.h b/native/cocos/renderer/pipeline/custom/PrivateTypes.h index bced606672..d8c6b49372 100644 --- a/native/cocos/renderer/pipeline/custom/PrivateTypes.h +++ b/native/cocos/renderer/pipeline/custom/PrivateTypes.h @@ -60,21 +60,21 @@ public: ProgramLibrary& operator=(ProgramLibrary const& rhs) = delete; virtual ~ProgramLibrary() noexcept = default; - virtual void addEffect(EffectAsset *effectAsset) = 0; + virtual void addEffect(const EffectAsset *effectAsset) = 0; virtual void precompileEffect(gfx::Device *device, EffectAsset *effectAsset) = 0; - virtual ccstd::string getKey(uint32_t phaseID, const ccstd::pmr::string &programName, const MacroRecord &defines) const = 0; - virtual const gfx::PipelineLayout &getPipelineLayout(gfx::Device *device, uint32_t phaseID, const ccstd::pmr::string &programName) = 0; - virtual const gfx::DescriptorSetLayout &getMaterialDescriptorSetLayout(gfx::Device *device, uint32_t phaseID, const ccstd::pmr::string &programName) = 0; - virtual const gfx::DescriptorSetLayout &getLocalDescriptorSetLayout(gfx::Device *device, uint32_t phaseID, const ccstd::pmr::string &programName) = 0; - virtual const IProgramInfo &getProgramInfo(uint32_t phaseID, const ccstd::pmr::string &programName) const = 0; - virtual const gfx::ShaderInfo &getShaderInfo(uint32_t phaseID, const ccstd::pmr::string &programName) const = 0; - virtual ProgramProxy *getProgramVariant(gfx::Device *device, uint32_t phaseID, const ccstd::string &name, const MacroRecord &defines, const ccstd::pmr::string *key) const = 0; - virtual const ccstd::pmr::vector &getBlockSizes(uint32_t phaseID, const ccstd::pmr::string &programName) const = 0; - virtual const Record &getHandleMap(uint32_t phaseID, const ccstd::pmr::string &programName) const = 0; + virtual ccstd::string getKey(uint32_t phaseID, const ccstd::string &programName, const MacroRecord &defines) const = 0; + virtual IntrusivePtr getPipelineLayout(gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) = 0; + virtual const gfx::DescriptorSetLayout &getMaterialDescriptorSetLayout(gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) = 0; + virtual const gfx::DescriptorSetLayout &getLocalDescriptorSetLayout(gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) = 0; + virtual const IProgramInfo &getProgramInfo(uint32_t phaseID, const ccstd::string &programName) const = 0; + virtual const gfx::ShaderInfo &getShaderInfo(uint32_t phaseID, const ccstd::string &programName) const = 0; + virtual ProgramProxy *getProgramVariant(gfx::Device *device, uint32_t phaseID, const ccstd::string &name, MacroRecord &defines, const ccstd::pmr::string *key) = 0; + virtual const ccstd::vector &getBlockSizes(uint32_t phaseID, const ccstd::string &programName) const = 0; + virtual const Record &getHandleMap(uint32_t phaseID, const ccstd::string &programName) const = 0; virtual uint32_t getProgramID(uint32_t phaseID, const ccstd::pmr::string &programName) = 0; virtual uint32_t getDescriptorNameID(const ccstd::pmr::string &name) = 0; virtual const ccstd::pmr::string &getDescriptorName(uint32_t nameID) = 0; - ProgramProxy *getProgramVariant(gfx::Device *device, uint32_t phaseID, const ccstd::string &name, const MacroRecord &defines) const { + ProgramProxy *getProgramVariant(gfx::Device *device, uint32_t phaseID, const ccstd::string &name, MacroRecord &defines) { return getProgramVariant(device, phaseID, name, defines, nullptr); } }; diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp b/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp index 674463fa9d..2d060aa901 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp @@ -59,6 +59,9 @@ bool nativevalue_to_se(const cc::render::RasterView &from, se::Value &to, se::Ob nativevalue_to_se(from.clearColor, tmp, ctx); obj->setProperty("clearColor", tmp); + nativevalue_to_se(from.slotID, tmp, ctx); + obj->setProperty("slotID", tmp); + to.setObject(obj); return true; } @@ -262,6 +265,10 @@ bool sevalue_to_native(const se::Value &from, cc::render if(!field.isNullOrUndefined()) { ok &= sevalue_to_native(field, &(to->clearColor), ctx); } + obj->getProperty("slotID", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->slotID), ctx); + } return ok; } diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h b/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h index a1432dc7e5..6ad04371ff 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h @@ -45,6 +45,7 @@ inline void save(OutputArchive& ar, const RasterView& v) { save(ar, v.storeOp); save(ar, v.clearFlags); save(ar, v.clearColor); + save(ar, v.slotID); } inline void load(InputArchive& ar, RasterView& v) { @@ -55,6 +56,7 @@ inline void load(InputArchive& ar, RasterView& v) { load(ar, v.storeOp); load(ar, v.clearFlags); load(ar, v.clearColor); + load(ar, v.slotID); } inline void save(OutputArchive& ar, const ComputeView& v) { diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp index 9408292582..6841ebe77b 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp @@ -53,7 +53,8 @@ RasterView::RasterView(RasterView&& rhs, const allocator_type& alloc) loadOp(rhs.loadOp), storeOp(rhs.storeOp), clearFlags(rhs.clearFlags), - clearColor(rhs.clearColor) {} + clearColor(rhs.clearColor), + slotID(rhs.slotID) {} RasterView::RasterView(RasterView const& rhs, const allocator_type& alloc) : slotName(rhs.slotName, alloc), @@ -62,7 +63,8 @@ RasterView::RasterView(RasterView const& rhs, const allocator_type& alloc) loadOp(rhs.loadOp), storeOp(rhs.storeOp), clearFlags(rhs.clearFlags), - clearColor(rhs.clearColor) {} + clearColor(rhs.clearColor), + slotID(rhs.slotID) {} ComputeView::ComputeView(const allocator_type& alloc) noexcept : name(alloc) {} diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h index 3120ea2147..4408e1b8de 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h @@ -212,6 +212,7 @@ struct RasterView { gfx::StoreOp storeOp{gfx::StoreOp::STORE}; gfx::ClearFlagBit clearFlags{gfx::ClearFlagBit::ALL}; gfx::Color clearColor; + uint32_t slotID{0}; }; inline bool operator==(const RasterView& lhs, const RasterView& rhs) noexcept { diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphFwd.h b/native/cocos/renderer/pipeline/custom/RenderGraphFwd.h index 83f631cac1..fa0c927b64 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphFwd.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphFwd.h @@ -45,6 +45,10 @@ struct ResourceStates; struct ManagedBuffer; struct ManagedTexture; struct ManagedResource; +struct RasterSubpass; +struct SubpassGraph; +struct RasterPass; +struct PersistentRenderPassAndFramebuffer; struct ManagedTag; struct ManagedBufferTag; struct ManagedTextureTag; @@ -54,9 +58,6 @@ struct FramebufferTag; struct SwapchainTag; struct SamplerTag; struct ResourceGraph; -struct RasterSubpass; -struct SubpassGraph; -struct RasterPass; struct ComputePass; struct CopyPass; struct MovePass; diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphGraphs.h b/native/cocos/renderer/pipeline/custom/RenderGraphGraphs.h index a5a7fc1b2e..aaf97f7d55 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphGraphs.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphGraphs.h @@ -40,6 +40,212 @@ namespace cc { namespace render { +// IncidenceGraph +inline SubpassGraph::vertex_descriptor +source(const SubpassGraph::edge_descriptor& e, const SubpassGraph& /*g*/) noexcept { + return e.source; +} + +inline SubpassGraph::vertex_descriptor +target(const SubpassGraph::edge_descriptor& e, const SubpassGraph& /*g*/) noexcept { + return e.target; +} + +inline std::pair +out_edges(SubpassGraph::vertex_descriptor u, const SubpassGraph& g) noexcept { // NOLINT + return std::make_pair( + SubpassGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).begin(), u), + SubpassGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).end(), u)); +} + +inline SubpassGraph::degree_size_type +out_degree(SubpassGraph::vertex_descriptor u, const SubpassGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getOutEdgeList(u).size()); +} + +inline std::pair +edge(SubpassGraph::vertex_descriptor u, SubpassGraph::vertex_descriptor v, const SubpassGraph& g) noexcept { + const auto& outEdgeList = g.getOutEdgeList(u); + auto iter = std::find(outEdgeList.begin(), outEdgeList.end(), SubpassGraph::OutEdge(v)); + bool hasEdge = (iter != outEdgeList.end()); + return {SubpassGraph::edge_descriptor(u, v), hasEdge}; +} + +// BidirectionalGraph(Directed) +inline std::pair +in_edges(SubpassGraph::vertex_descriptor u, const SubpassGraph& g) noexcept { // NOLINT + return std::make_pair( + SubpassGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).begin(), u), + SubpassGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).end(), u)); +} + +inline SubpassGraph::degree_size_type +in_degree(SubpassGraph::vertex_descriptor u, const SubpassGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getInEdgeList(u).size()); +} + +inline SubpassGraph::degree_size_type +degree(SubpassGraph::vertex_descriptor u, const SubpassGraph& g) noexcept { + return in_degree(u, g) + out_degree(u, g); +} + +// AdjacencyGraph +inline std::pair +adjacent_vertices(SubpassGraph::vertex_descriptor u, const SubpassGraph& g) noexcept { // NOLINT + auto edges = out_edges(u, g); + return std::make_pair(SubpassGraph::adjacency_iterator(edges.first, &g), SubpassGraph::adjacency_iterator(edges.second, &g)); +} + +// VertexListGraph +inline std::pair +vertices(const SubpassGraph& g) noexcept { + return std::make_pair(const_cast(g).getVertexList().begin(), const_cast(g).getVertexList().end()); +} + +inline SubpassGraph::vertices_size_type +num_vertices(const SubpassGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getVertexList().size()); +} + +// EdgeListGraph +inline std::pair +edges(const SubpassGraph& g0) noexcept { + auto& g = const_cast(g0); + return std::make_pair( + SubpassGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().begin(), g.getVertexList().end(), g), + SubpassGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().end(), g.getVertexList().end(), g)); +} + +inline SubpassGraph::edges_size_type +num_edges(const SubpassGraph& g) noexcept { // NOLINT + SubpassGraph::edges_size_type numEdges = 0; + + auto range = vertices(g); + for (auto iter = range.first; iter != range.second; ++iter) { + numEdges += out_degree(*iter, g); + } + return numEdges; +} + +// MutableGraph(Edge) +inline std::pair +add_edge( // NOLINT + SubpassGraph::vertex_descriptor u, + SubpassGraph::vertex_descriptor v, SubpassGraph& g) { + auto& outEdgeList = g.getOutEdgeList(u); + outEdgeList.emplace_back(v); + + auto& inEdgeList = g.getInEdgeList(v); + inEdgeList.emplace_back(u); + + return std::make_pair(SubpassGraph::edge_descriptor(u, v), true); +} + +inline void remove_edge(SubpassGraph::vertex_descriptor u, SubpassGraph::vertex_descriptor v, SubpassGraph& g) noexcept { // NOLINT + auto& s = g._vertices[u]; + auto& t = g._vertices[v]; + s.outEdges.erase(std::remove(s.outEdges.begin(), s.outEdges.end(), SubpassGraph::OutEdge(v)), s.outEdges.end()); + t.inEdges.erase(std::remove(t.inEdges.begin(), t.inEdges.end(), SubpassGraph::InEdge(u)), t.inEdges.end()); +} + +inline void remove_edge(SubpassGraph::out_edge_iterator outIter, SubpassGraph& g) noexcept { // NOLINT + auto e = *outIter; + const auto u = source(e, g); + const auto v = target(e, g); + auto& s = g._vertices[u]; + auto& t = g._vertices[v]; + auto inIter = std::find(t.inEdges.begin(), t.inEdges.end(), SubpassGraph::InEdge(u)); + CC_EXPECTS(inIter != t.inEdges.end()); + t.inEdges.erase(inIter); + s.outEdges.erase(outIter.base()); +} + +inline void remove_edge(SubpassGraph::edge_descriptor e, SubpassGraph& g) noexcept { // NOLINT + const auto u = source(e, g); + const auto v = target(e, g); + auto& s = g._vertices[u]; + auto outIter = std::find(s.outEdges.begin(), s.outEdges.end(), SubpassGraph::OutEdge(v)); + CC_EXPECTS(outIter != s.outEdges.end()); + remove_edge(SubpassGraph::out_edge_iterator(outIter, u), g); +} + +// MutableGraph(Vertex) +inline void clear_out_edges(SubpassGraph::vertex_descriptor u, SubpassGraph& g) noexcept { // NOLINT + // Bidirectional (OutEdges) + auto& outEdgeList = g.getOutEdgeList(u); + auto outEnd = outEdgeList.end(); + for (auto iter = outEdgeList.begin(); iter != outEnd; ++iter) { + auto& inEdgeList = g.getInEdgeList((*iter).get_target()); + // eraseFromIncidenceList + impl::sequenceEraseIf(inEdgeList, [u](const auto& e) { + return e.get_target() == u; + }); + } + outEdgeList.clear(); +} + +inline void clear_in_edges(SubpassGraph::vertex_descriptor u, SubpassGraph& g) noexcept { // NOLINT + // Bidirectional (InEdges) + auto& inEdgeList = g.getInEdgeList(u); + auto inEnd = inEdgeList.end(); + for (auto iter = inEdgeList.begin(); iter != inEnd; ++iter) { + auto& outEdgeList = g.getOutEdgeList((*iter).get_target()); + // eraseFromIncidenceList + impl::sequenceEraseIf(outEdgeList, [u](const auto& e) { + return e.get_target() == u; + }); + } + inEdgeList.clear(); +} + +inline void clear_vertex(SubpassGraph::vertex_descriptor u, SubpassGraph& g) noexcept { // NOLINT + clear_out_edges(u, g); + clear_in_edges(u, g); +} + +inline void remove_vertex(SubpassGraph::vertex_descriptor u, SubpassGraph& g) noexcept { // NOLINT + impl::removeVectorVertex(const_cast(g), u, SubpassGraph::directed_category{}); + + // remove components + g.names.erase(g.names.begin() + static_cast(u)); + g.subpasses.erase(g.subpasses.begin() + static_cast(u)); +} + +// MutablePropertyGraph(Vertex) +template +inline SubpassGraph::vertex_descriptor +addVertex(Component0&& c0, Component1&& c1, SubpassGraph& g) { + auto v = gsl::narrow_cast(g._vertices.size()); + + g._vertices.emplace_back(); + g.names.emplace_back(std::forward(c0)); + g.subpasses.emplace_back(std::forward(c1)); + + return v; +} + +template +inline SubpassGraph::vertex_descriptor +addVertex(std::piecewise_construct_t /*tag*/, Component0&& c0, Component1&& c1, SubpassGraph& g) { + auto v = gsl::narrow_cast(g._vertices.size()); + + g._vertices.emplace_back(); + + std::apply( + [&](auto&&... args) { + g.names.emplace_back(std::forward(args)...); + }, + std::forward(c0)); + + std::apply( + [&](auto&&... args) { + g.subpasses.emplace_back(std::forward(args)...); + }, + std::forward(c1)); + + return v; +} + // IncidenceGraph inline ResourceGraph::vertex_descriptor source(const ResourceGraph::edge_descriptor& e, const ResourceGraph& /*g*/) noexcept { @@ -505,212 +711,6 @@ addVertex(Tag tag, Component0&& c0, Component1&& c1, Component2&& c2, Component3 return v; } -// IncidenceGraph -inline SubpassGraph::vertex_descriptor -source(const SubpassGraph::edge_descriptor& e, const SubpassGraph& /*g*/) noexcept { - return e.source; -} - -inline SubpassGraph::vertex_descriptor -target(const SubpassGraph::edge_descriptor& e, const SubpassGraph& /*g*/) noexcept { - return e.target; -} - -inline std::pair -out_edges(SubpassGraph::vertex_descriptor u, const SubpassGraph& g) noexcept { // NOLINT - return std::make_pair( - SubpassGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).begin(), u), - SubpassGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).end(), u)); -} - -inline SubpassGraph::degree_size_type -out_degree(SubpassGraph::vertex_descriptor u, const SubpassGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getOutEdgeList(u).size()); -} - -inline std::pair -edge(SubpassGraph::vertex_descriptor u, SubpassGraph::vertex_descriptor v, const SubpassGraph& g) noexcept { - const auto& outEdgeList = g.getOutEdgeList(u); - auto iter = std::find(outEdgeList.begin(), outEdgeList.end(), SubpassGraph::OutEdge(v)); - bool hasEdge = (iter != outEdgeList.end()); - return {SubpassGraph::edge_descriptor(u, v), hasEdge}; -} - -// BidirectionalGraph(Directed) -inline std::pair -in_edges(SubpassGraph::vertex_descriptor u, const SubpassGraph& g) noexcept { // NOLINT - return std::make_pair( - SubpassGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).begin(), u), - SubpassGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).end(), u)); -} - -inline SubpassGraph::degree_size_type -in_degree(SubpassGraph::vertex_descriptor u, const SubpassGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getInEdgeList(u).size()); -} - -inline SubpassGraph::degree_size_type -degree(SubpassGraph::vertex_descriptor u, const SubpassGraph& g) noexcept { - return in_degree(u, g) + out_degree(u, g); -} - -// AdjacencyGraph -inline std::pair -adjacent_vertices(SubpassGraph::vertex_descriptor u, const SubpassGraph& g) noexcept { // NOLINT - auto edges = out_edges(u, g); - return std::make_pair(SubpassGraph::adjacency_iterator(edges.first, &g), SubpassGraph::adjacency_iterator(edges.second, &g)); -} - -// VertexListGraph -inline std::pair -vertices(const SubpassGraph& g) noexcept { - return std::make_pair(const_cast(g).getVertexList().begin(), const_cast(g).getVertexList().end()); -} - -inline SubpassGraph::vertices_size_type -num_vertices(const SubpassGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getVertexList().size()); -} - -// EdgeListGraph -inline std::pair -edges(const SubpassGraph& g0) noexcept { - auto& g = const_cast(g0); - return std::make_pair( - SubpassGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().begin(), g.getVertexList().end(), g), - SubpassGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().end(), g.getVertexList().end(), g)); -} - -inline SubpassGraph::edges_size_type -num_edges(const SubpassGraph& g) noexcept { // NOLINT - SubpassGraph::edges_size_type numEdges = 0; - - auto range = vertices(g); - for (auto iter = range.first; iter != range.second; ++iter) { - numEdges += out_degree(*iter, g); - } - return numEdges; -} - -// MutableGraph(Edge) -inline std::pair -add_edge( // NOLINT - SubpassGraph::vertex_descriptor u, - SubpassGraph::vertex_descriptor v, SubpassGraph& g) { - auto& outEdgeList = g.getOutEdgeList(u); - outEdgeList.emplace_back(v); - - auto& inEdgeList = g.getInEdgeList(v); - inEdgeList.emplace_back(u); - - return std::make_pair(SubpassGraph::edge_descriptor(u, v), true); -} - -inline void remove_edge(SubpassGraph::vertex_descriptor u, SubpassGraph::vertex_descriptor v, SubpassGraph& g) noexcept { // NOLINT - auto& s = g._vertices[u]; - auto& t = g._vertices[v]; - s.outEdges.erase(std::remove(s.outEdges.begin(), s.outEdges.end(), SubpassGraph::OutEdge(v)), s.outEdges.end()); - t.inEdges.erase(std::remove(t.inEdges.begin(), t.inEdges.end(), SubpassGraph::InEdge(u)), t.inEdges.end()); -} - -inline void remove_edge(SubpassGraph::out_edge_iterator outIter, SubpassGraph& g) noexcept { // NOLINT - auto e = *outIter; - const auto u = source(e, g); - const auto v = target(e, g); - auto& s = g._vertices[u]; - auto& t = g._vertices[v]; - auto inIter = std::find(t.inEdges.begin(), t.inEdges.end(), SubpassGraph::InEdge(u)); - CC_EXPECTS(inIter != t.inEdges.end()); - t.inEdges.erase(inIter); - s.outEdges.erase(outIter.base()); -} - -inline void remove_edge(SubpassGraph::edge_descriptor e, SubpassGraph& g) noexcept { // NOLINT - const auto u = source(e, g); - const auto v = target(e, g); - auto& s = g._vertices[u]; - auto outIter = std::find(s.outEdges.begin(), s.outEdges.end(), SubpassGraph::OutEdge(v)); - CC_EXPECTS(outIter != s.outEdges.end()); - remove_edge(SubpassGraph::out_edge_iterator(outIter, u), g); -} - -// MutableGraph(Vertex) -inline void clear_out_edges(SubpassGraph::vertex_descriptor u, SubpassGraph& g) noexcept { // NOLINT - // Bidirectional (OutEdges) - auto& outEdgeList = g.getOutEdgeList(u); - auto outEnd = outEdgeList.end(); - for (auto iter = outEdgeList.begin(); iter != outEnd; ++iter) { - auto& inEdgeList = g.getInEdgeList((*iter).get_target()); - // eraseFromIncidenceList - impl::sequenceEraseIf(inEdgeList, [u](const auto& e) { - return e.get_target() == u; - }); - } - outEdgeList.clear(); -} - -inline void clear_in_edges(SubpassGraph::vertex_descriptor u, SubpassGraph& g) noexcept { // NOLINT - // Bidirectional (InEdges) - auto& inEdgeList = g.getInEdgeList(u); - auto inEnd = inEdgeList.end(); - for (auto iter = inEdgeList.begin(); iter != inEnd; ++iter) { - auto& outEdgeList = g.getOutEdgeList((*iter).get_target()); - // eraseFromIncidenceList - impl::sequenceEraseIf(outEdgeList, [u](const auto& e) { - return e.get_target() == u; - }); - } - inEdgeList.clear(); -} - -inline void clear_vertex(SubpassGraph::vertex_descriptor u, SubpassGraph& g) noexcept { // NOLINT - clear_out_edges(u, g); - clear_in_edges(u, g); -} - -inline void remove_vertex(SubpassGraph::vertex_descriptor u, SubpassGraph& g) noexcept { // NOLINT - impl::removeVectorVertex(const_cast(g), u, SubpassGraph::directed_category{}); - - // remove components - g.names.erase(g.names.begin() + static_cast(u)); - g.subpasses.erase(g.subpasses.begin() + static_cast(u)); -} - -// MutablePropertyGraph(Vertex) -template -inline SubpassGraph::vertex_descriptor -addVertex(Component0&& c0, Component1&& c1, SubpassGraph& g) { - auto v = gsl::narrow_cast(g._vertices.size()); - - g._vertices.emplace_back(); - g.names.emplace_back(std::forward(c0)); - g.subpasses.emplace_back(std::forward(c1)); - - return v; -} - -template -inline SubpassGraph::vertex_descriptor -addVertex(std::piecewise_construct_t /*tag*/, Component0&& c0, Component1&& c1, SubpassGraph& g) { - auto v = gsl::narrow_cast(g._vertices.size()); - - g._vertices.emplace_back(); - - std::apply( - [&](auto&&... args) { - g.names.emplace_back(std::forward(args)...); - }, - std::forward(c0)); - - std::apply( - [&](auto&&... args) { - g.subpasses.emplace_back(std::forward(args)...); - }, - std::forward(c1)); - - return v; -} - // IncidenceGraph inline RenderGraph::vertex_descriptor source(const RenderGraph::edge_descriptor& e, const RenderGraph& /*g*/) noexcept { @@ -932,6 +932,83 @@ numReferences(const RenderGraph& g) noexcept { namespace boost { +// Vertex Index +template <> +struct property_map { + using const_type = identity_property_map; + using type = identity_property_map; +}; + +// Vertex Component +template <> +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentPropertyMap< + read_write_property_map_tag, + const cc::render::SubpassGraph, + const ccstd::pmr::vector, + std::string_view, + const ccstd::pmr::string&>; + using type = cc::render::impl::VectorVertexComponentPropertyMap< + read_write_property_map_tag, + cc::render::SubpassGraph, + ccstd::pmr::vector, + std::string_view, + ccstd::pmr::string&>; +}; + +// Vertex Name +template <> +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentPropertyMap< + read_write_property_map_tag, + const cc::render::SubpassGraph, + const ccstd::pmr::vector, + std::string_view, + const ccstd::pmr::string&>; + using type = cc::render::impl::VectorVertexComponentPropertyMap< + read_write_property_map_tag, + cc::render::SubpassGraph, + ccstd::pmr::vector, + std::string_view, + ccstd::pmr::string&>; +}; + +// Vertex Component +template <> +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + const cc::render::SubpassGraph, + const ccstd::pmr::vector, + cc::render::RasterSubpass, + const cc::render::RasterSubpass&>; + using type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + cc::render::SubpassGraph, + ccstd::pmr::vector, + cc::render::RasterSubpass, + cc::render::RasterSubpass&>; +}; + +// Vertex ComponentMember +template +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentMemberPropertyMap< + lvalue_property_map_tag, + const cc::render::SubpassGraph, + const ccstd::pmr::vector, + T, + const T&, + T cc::render::RasterSubpass::*>; + using type = cc::render::impl::VectorVertexComponentMemberPropertyMap< + lvalue_property_map_tag, + cc::render::SubpassGraph, + ccstd::pmr::vector, + T, + T&, + T cc::render::RasterSubpass::*>; +}; + // Vertex Index template <> struct property_map { @@ -1098,83 +1175,6 @@ struct property_map; }; -// Vertex Index -template <> -struct property_map { - using const_type = identity_property_map; - using type = identity_property_map; -}; - -// Vertex Component -template <> -struct property_map { - using const_type = cc::render::impl::VectorVertexComponentPropertyMap< - read_write_property_map_tag, - const cc::render::SubpassGraph, - const ccstd::pmr::vector, - std::string_view, - const ccstd::pmr::string&>; - using type = cc::render::impl::VectorVertexComponentPropertyMap< - read_write_property_map_tag, - cc::render::SubpassGraph, - ccstd::pmr::vector, - std::string_view, - ccstd::pmr::string&>; -}; - -// Vertex Name -template <> -struct property_map { - using const_type = cc::render::impl::VectorVertexComponentPropertyMap< - read_write_property_map_tag, - const cc::render::SubpassGraph, - const ccstd::pmr::vector, - std::string_view, - const ccstd::pmr::string&>; - using type = cc::render::impl::VectorVertexComponentPropertyMap< - read_write_property_map_tag, - cc::render::SubpassGraph, - ccstd::pmr::vector, - std::string_view, - ccstd::pmr::string&>; -}; - -// Vertex Component -template <> -struct property_map { - using const_type = cc::render::impl::VectorVertexComponentPropertyMap< - lvalue_property_map_tag, - const cc::render::SubpassGraph, - const ccstd::pmr::vector, - cc::render::RasterSubpass, - const cc::render::RasterSubpass&>; - using type = cc::render::impl::VectorVertexComponentPropertyMap< - lvalue_property_map_tag, - cc::render::SubpassGraph, - ccstd::pmr::vector, - cc::render::RasterSubpass, - cc::render::RasterSubpass&>; -}; - -// Vertex ComponentMember -template -struct property_map { - using const_type = cc::render::impl::VectorVertexComponentMemberPropertyMap< - lvalue_property_map_tag, - const cc::render::SubpassGraph, - const ccstd::pmr::vector, - T, - const T&, - T cc::render::RasterSubpass::*>; - using type = cc::render::impl::VectorVertexComponentMemberPropertyMap< - lvalue_property_map_tag, - cc::render::SubpassGraph, - ccstd::pmr::vector, - T, - T&, - T cc::render::RasterSubpass::*>; -}; - // Vertex Index template <> struct property_map { @@ -1292,6 +1292,105 @@ namespace cc { namespace render { +// Vertex Index +inline boost::property_map::const_type +get(boost::vertex_index_t /*tag*/, const SubpassGraph& /*g*/) noexcept { + return {}; +} + +inline boost::property_map::type +get(boost::vertex_index_t /*tag*/, SubpassGraph& /*g*/) noexcept { + return {}; +} + +inline impl::ColorMap +get(ccstd::pmr::vector& colors, const SubpassGraph& /*g*/) noexcept { + return {colors}; +} + +// Vertex Component +inline typename boost::property_map::const_type +get(SubpassGraph::NameTag /*tag*/, const SubpassGraph& g) noexcept { + return {g.names}; +} + +inline typename boost::property_map::type +get(SubpassGraph::NameTag /*tag*/, SubpassGraph& g) noexcept { + return {g.names}; +} + +// Vertex Name +inline boost::property_map::const_type +get(boost::vertex_name_t /*tag*/, const SubpassGraph& g) noexcept { + return {g.names}; +} + +// Vertex Component +inline typename boost::property_map::const_type +get(SubpassGraph::SubpassTag /*tag*/, const SubpassGraph& g) noexcept { + return {g.subpasses}; +} + +inline typename boost::property_map::type +get(SubpassGraph::SubpassTag /*tag*/, SubpassGraph& g) noexcept { + return {g.subpasses}; +} + +// Vertex ComponentMember +template +inline typename boost::property_map::const_type +get(T RasterSubpass::*memberPointer, const SubpassGraph& g) noexcept { + return {g.subpasses, memberPointer}; +} + +template +inline typename boost::property_map::type +get(T RasterSubpass::*memberPointer, SubpassGraph& g) noexcept { + return {g.subpasses, memberPointer}; +} + +// Vertex Constant Getter +template +inline decltype(auto) +get(Tag tag, const SubpassGraph& g, SubpassGraph::vertex_descriptor v) noexcept { + return get(get(tag, g), v); +} + +// Vertex Mutable Getter +template +inline decltype(auto) +get(Tag tag, SubpassGraph& g, SubpassGraph::vertex_descriptor v) noexcept { + return get(get(tag, g), v); +} + +// Vertex Setter +template +inline void put( + Tag tag, SubpassGraph& g, + SubpassGraph::vertex_descriptor v, + Args&&... args) { + put(get(tag, g), v, std::forward(args)...); +} + +// MutableGraph(Vertex) +inline SubpassGraph::vertex_descriptor +add_vertex(SubpassGraph& g, ccstd::pmr::string&& name) { // NOLINT + return addVertex( + std::piecewise_construct, + std::forward_as_tuple(std::move(name)), // names + std::forward_as_tuple(), // subpasses + g); +} + +inline SubpassGraph::vertex_descriptor +add_vertex(SubpassGraph& g, const char* name) { // NOLINT + return addVertex( + std::piecewise_construct, + std::forward_as_tuple(name), // names + std::forward_as_tuple(), // subpasses + g); +} + // Vertex Index inline boost::property_map::const_type get(boost::vertex_index_t /*tag*/, const ResourceGraph& /*g*/) noexcept { @@ -2230,105 +2329,6 @@ add_vertex(ResourceGraph& g, Tag t, const char* name) { // NOLINT g); } -// Vertex Index -inline boost::property_map::const_type -get(boost::vertex_index_t /*tag*/, const SubpassGraph& /*g*/) noexcept { - return {}; -} - -inline boost::property_map::type -get(boost::vertex_index_t /*tag*/, SubpassGraph& /*g*/) noexcept { - return {}; -} - -inline impl::ColorMap -get(ccstd::pmr::vector& colors, const SubpassGraph& /*g*/) noexcept { - return {colors}; -} - -// Vertex Component -inline typename boost::property_map::const_type -get(SubpassGraph::NameTag /*tag*/, const SubpassGraph& g) noexcept { - return {g.names}; -} - -inline typename boost::property_map::type -get(SubpassGraph::NameTag /*tag*/, SubpassGraph& g) noexcept { - return {g.names}; -} - -// Vertex Name -inline boost::property_map::const_type -get(boost::vertex_name_t /*tag*/, const SubpassGraph& g) noexcept { - return {g.names}; -} - -// Vertex Component -inline typename boost::property_map::const_type -get(SubpassGraph::SubpassTag /*tag*/, const SubpassGraph& g) noexcept { - return {g.subpasses}; -} - -inline typename boost::property_map::type -get(SubpassGraph::SubpassTag /*tag*/, SubpassGraph& g) noexcept { - return {g.subpasses}; -} - -// Vertex ComponentMember -template -inline typename boost::property_map::const_type -get(T RasterSubpass::*memberPointer, const SubpassGraph& g) noexcept { - return {g.subpasses, memberPointer}; -} - -template -inline typename boost::property_map::type -get(T RasterSubpass::*memberPointer, SubpassGraph& g) noexcept { - return {g.subpasses, memberPointer}; -} - -// Vertex Constant Getter -template -inline decltype(auto) -get(Tag tag, const SubpassGraph& g, SubpassGraph::vertex_descriptor v) noexcept { - return get(get(tag, g), v); -} - -// Vertex Mutable Getter -template -inline decltype(auto) -get(Tag tag, SubpassGraph& g, SubpassGraph::vertex_descriptor v) noexcept { - return get(get(tag, g), v); -} - -// Vertex Setter -template -inline void put( - Tag tag, SubpassGraph& g, - SubpassGraph::vertex_descriptor v, - Args&&... args) { - put(get(tag, g), v, std::forward(args)...); -} - -// MutableGraph(Vertex) -inline SubpassGraph::vertex_descriptor -add_vertex(SubpassGraph& g, ccstd::pmr::string&& name) { // NOLINT - return addVertex( - std::piecewise_construct, - std::forward_as_tuple(std::move(name)), // names - std::forward_as_tuple(), // subpasses - g); -} - -inline SubpassGraph::vertex_descriptor -add_vertex(SubpassGraph& g, const char* name) { // NOLINT - return addVertex( - std::piecewise_construct, - std::forward_as_tuple(name), // names - std::forward_as_tuple(), // subpasses - g); -} - // Vertex Index inline boost::property_map::const_type get(boost::vertex_index_t /*tag*/, const RenderGraph& /*g*/) noexcept { diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp index dfabba9653..76fa619ff4 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp @@ -34,82 +34,6 @@ namespace cc { namespace render { -ResourceGraph::ResourceGraph(const allocator_type& alloc) noexcept -: _vertices(alloc), - names(alloc), - descs(alloc), - traits(alloc), - states(alloc), - samplerInfo(alloc), - resources(alloc), - managedBuffers(alloc), - managedTextures(alloc), - buffers(alloc), - textures(alloc), - framebuffers(alloc), - swapchains(alloc), - valueIndex(alloc) {} - -ResourceGraph::ResourceGraph(ResourceGraph&& rhs, const allocator_type& alloc) -: _vertices(std::move(rhs._vertices), alloc), - names(std::move(rhs.names), alloc), - descs(std::move(rhs.descs), alloc), - traits(std::move(rhs.traits), alloc), - states(std::move(rhs.states), alloc), - samplerInfo(std::move(rhs.samplerInfo), alloc), - resources(std::move(rhs.resources), alloc), - managedBuffers(std::move(rhs.managedBuffers), alloc), - managedTextures(std::move(rhs.managedTextures), alloc), - buffers(std::move(rhs.buffers), alloc), - textures(std::move(rhs.textures), alloc), - framebuffers(std::move(rhs.framebuffers), alloc), - swapchains(std::move(rhs.swapchains), alloc), - valueIndex(std::move(rhs.valueIndex), alloc), - nextFenceValue(rhs.nextFenceValue), - version(rhs.version) {} - -ResourceGraph::ResourceGraph(ResourceGraph const& rhs, const allocator_type& alloc) -: _vertices(rhs._vertices, alloc), - names(rhs.names, alloc), - descs(rhs.descs, alloc), - traits(rhs.traits, alloc), - states(rhs.states, alloc), - samplerInfo(rhs.samplerInfo, alloc), - resources(rhs.resources, alloc), - managedBuffers(rhs.managedBuffers, alloc), - managedTextures(rhs.managedTextures, alloc), - buffers(rhs.buffers, alloc), - textures(rhs.textures, alloc), - framebuffers(rhs.framebuffers, alloc), - swapchains(rhs.swapchains, alloc), - valueIndex(rhs.valueIndex, alloc), - nextFenceValue(rhs.nextFenceValue), - version(rhs.version) {} - -// ContinuousContainer -void ResourceGraph::reserve(vertices_size_type sz) { - _vertices.reserve(sz); - names.reserve(sz); - descs.reserve(sz); - traits.reserve(sz); - states.reserve(sz); - samplerInfo.reserve(sz); -} - -ResourceGraph::Vertex::Vertex(const allocator_type& alloc) noexcept -: outEdges(alloc), - inEdges(alloc) {} - -ResourceGraph::Vertex::Vertex(Vertex&& rhs, const allocator_type& alloc) -: outEdges(std::move(rhs.outEdges), alloc), - inEdges(std::move(rhs.inEdges), alloc), - handle(std::move(rhs.handle)) {} - -ResourceGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& alloc) -: outEdges(rhs.outEdges, alloc), - inEdges(rhs.inEdges, alloc), - handle(rhs.handle) {} - RasterSubpass::RasterSubpass(const allocator_type& alloc) noexcept : rasterViews(alloc), computeViews(alloc) {} @@ -170,7 +94,8 @@ RasterPass::RasterPass(RasterPass&& rhs, const allocator_type& alloc) height(rhs.height), viewport(rhs.viewport), versionName(std::move(rhs.versionName), alloc), - version(rhs.version) {} + version(rhs.version), + showStatistics(rhs.showStatistics) {} RasterPass::RasterPass(RasterPass const& rhs, const allocator_type& alloc) : rasterViews(rhs.rasterViews, alloc), @@ -180,7 +105,71 @@ RasterPass::RasterPass(RasterPass const& rhs, const allocator_type& alloc) height(rhs.height), viewport(rhs.viewport), versionName(rhs.versionName, alloc), - version(rhs.version) {} + version(rhs.version), + showStatistics(rhs.showStatistics) {} + +PersistentRenderPassAndFramebuffer::PersistentRenderPassAndFramebuffer(const allocator_type& alloc) noexcept +: clearColors(alloc) {} + +PersistentRenderPassAndFramebuffer::PersistentRenderPassAndFramebuffer(IntrusivePtr renderPassIn, IntrusivePtr framebufferIn, const allocator_type& alloc) noexcept +: renderPass(std::move(renderPassIn)), + framebuffer(std::move(framebufferIn)), + clearColors(alloc) {} + +PersistentRenderPassAndFramebuffer::PersistentRenderPassAndFramebuffer(PersistentRenderPassAndFramebuffer&& rhs, const allocator_type& alloc) +: renderPass(std::move(rhs.renderPass)), + framebuffer(std::move(rhs.framebuffer)), + clearColors(std::move(rhs.clearColors), alloc), + clearDepth(rhs.clearDepth), + clearStencil(rhs.clearStencil) {} + +PersistentRenderPassAndFramebuffer::PersistentRenderPassAndFramebuffer(PersistentRenderPassAndFramebuffer const& rhs, const allocator_type& alloc) +: renderPass(rhs.renderPass), + framebuffer(rhs.framebuffer), + clearColors(rhs.clearColors, alloc), + clearDepth(rhs.clearDepth), + clearStencil(rhs.clearStencil) {} + +ResourceGraph::ResourceGraph(const allocator_type& alloc) noexcept +: _vertices(alloc), + names(alloc), + descs(alloc), + traits(alloc), + states(alloc), + samplerInfo(alloc), + resources(alloc), + managedBuffers(alloc), + managedTextures(alloc), + buffers(alloc), + textures(alloc), + framebuffers(alloc), + swapchains(alloc), + valueIndex(alloc), + renderPasses(alloc) {} + +// ContinuousContainer +void ResourceGraph::reserve(vertices_size_type sz) { + _vertices.reserve(sz); + names.reserve(sz); + descs.reserve(sz); + traits.reserve(sz); + states.reserve(sz); + samplerInfo.reserve(sz); +} + +ResourceGraph::Vertex::Vertex(const allocator_type& alloc) noexcept +: outEdges(alloc), + inEdges(alloc) {} + +ResourceGraph::Vertex::Vertex(Vertex&& rhs, const allocator_type& alloc) +: outEdges(std::move(rhs.outEdges), alloc), + inEdges(std::move(rhs.inEdges), alloc), + handle(std::move(rhs.handle)) {} + +ResourceGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& alloc) +: outEdges(rhs.outEdges, alloc), + inEdges(rhs.inEdges, alloc), + handle(rhs.handle) {} ComputePass::ComputePass(const allocator_type& alloc) noexcept : computeViews(alloc) {} diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h index a4868dcc5d..127ce2b017 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h @@ -41,6 +41,7 @@ #include "cocos/math/Geometry.h" #include "cocos/renderer/gfx-base/GFXBuffer.h" #include "cocos/renderer/gfx-base/GFXFramebuffer.h" +#include "cocos/renderer/gfx-base/GFXRenderPass.h" #include "cocos/renderer/gfx-base/GFXSwapchain.h" #include "cocos/renderer/gfx-base/GFXTexture.h" #include "cocos/renderer/gfx-base/states/GFXSampler.h" @@ -89,6 +90,7 @@ struct RenderSwapchain { gfx::Swapchain* swapchain{nullptr}; uint32_t currentID{0}; uint32_t numBackBuffers{0}; + uint32_t generation{0xFFFFFFFF}; }; struct ResourceStates { @@ -109,6 +111,8 @@ struct ManagedTexture { ManagedTexture(IntrusivePtr textureIn) noexcept // NOLINT : texture(std::move(textureIn)) {} + bool checkResource(const ResourceDesc &desc) const; + IntrusivePtr texture; uint64_t fenceValue{0}; }; @@ -117,176 +121,6 @@ struct ManagedResource { uint32_t unused{0}; }; -struct ManagedTag {}; -struct ManagedBufferTag {}; -struct ManagedTextureTag {}; -struct PersistentBufferTag {}; -struct PersistentTextureTag {}; -struct FramebufferTag {}; -struct SwapchainTag {}; -struct SamplerTag {}; - -struct ResourceGraph { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {_vertices.get_allocator().resource()}; - } - - inline boost::container::pmr::memory_resource* resource() const noexcept { - return get_allocator().resource(); - } - - ResourceGraph(const allocator_type& alloc) noexcept; // NOLINT - ResourceGraph(ResourceGraph&& rhs, const allocator_type& alloc); - ResourceGraph(ResourceGraph const& rhs, const allocator_type& alloc); - - ResourceGraph(ResourceGraph&& rhs) noexcept = default; - ResourceGraph(ResourceGraph const& rhs) = delete; - ResourceGraph& operator=(ResourceGraph&& rhs) = default; - ResourceGraph& operator=(ResourceGraph const& rhs) = default; - - // Graph - using directed_category = boost::bidirectional_tag; - using vertex_descriptor = uint32_t; - using edge_descriptor = impl::EdgeDescriptor; - using edge_parallel_category = boost::allow_parallel_edge_tag; - struct traversal_category // NOLINT - : virtual boost::incidence_graph_tag, - virtual boost::bidirectional_graph_tag, - virtual boost::adjacency_graph_tag, - virtual boost::vertex_list_graph_tag, - virtual boost::edge_list_graph_tag {}; - - constexpr static vertex_descriptor null_vertex() noexcept { // NOLINT - return std::numeric_limits::max(); - } - - // IncidenceGraph - using OutEdge = impl::StoredEdge; - using out_edge_iterator = impl::OutEdgeIter< - ccstd::pmr::vector::iterator, - vertex_descriptor, edge_descriptor, int32_t>; - using degree_size_type = uint32_t; - - // BidirectionalGraph - using InEdge = impl::StoredEdge; - using in_edge_iterator = impl::InEdgeIter< - ccstd::pmr::vector::iterator, - vertex_descriptor, edge_descriptor, int32_t>; - - // AdjacencyGraph - using adjacency_iterator = boost::adjacency_iterator_generator< - ResourceGraph, vertex_descriptor, out_edge_iterator>::type; - - // VertexListGraph - using vertex_iterator = boost::integer_range::iterator; - using vertices_size_type = uint32_t; - - // VertexList help functions - inline ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) noexcept { - return _vertices[v].outEdges; - } - inline const ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) const noexcept { - return _vertices[v].outEdges; - } - - inline ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) noexcept { - return _vertices[v].inEdges; - } - inline const ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) const noexcept { - return _vertices[v].inEdges; - } - - inline boost::integer_range getVertexList() const noexcept { - return {0, static_cast(_vertices.size())}; - } - - inline vertex_descriptor getCurrentID() const noexcept { - return static_cast(_vertices.size()); - } - - inline ccstd::pmr::vector colors(boost::container::pmr::memory_resource* mr) const { - return ccstd::pmr::vector(_vertices.size(), mr); - } - - // EdgeListGraph - using edge_iterator = impl::DirectedEdgeIterator; - using edges_size_type = uint32_t; - - // PolymorphicGraph - using VertexTag = ccstd::variant; - using VertexValue = ccstd::variant*, IntrusivePtr*, IntrusivePtr*, RenderSwapchain*>; - using VertexConstValue = ccstd::variant*, const IntrusivePtr*, const IntrusivePtr*, const RenderSwapchain*>; - using VertexHandle = ccstd::variant< - impl::ValueHandle, - impl::ValueHandle, - impl::ValueHandle, - impl::ValueHandle, - impl::ValueHandle, - impl::ValueHandle, - impl::ValueHandle>; - - void mount(gfx::Device* device, vertex_descriptor vertID); - void unmount(uint64_t completedFenceValue); - - // ContinuousContainer - void reserve(vertices_size_type sz); - - // Members - struct Vertex { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {outEdges.get_allocator().resource()}; - } - - Vertex(const allocator_type& alloc) noexcept; // NOLINT - Vertex(Vertex&& rhs, const allocator_type& alloc); - Vertex(Vertex const& rhs, const allocator_type& alloc); - - Vertex(Vertex&& rhs) noexcept = default; - Vertex(Vertex const& rhs) = delete; - Vertex& operator=(Vertex&& rhs) = default; - Vertex& operator=(Vertex const& rhs) = default; - - ccstd::pmr::vector outEdges; - ccstd::pmr::vector inEdges; - VertexHandle handle; - }; - - struct NameTag { - } static constexpr Name{}; // NOLINT - struct DescTag { - } static constexpr Desc{}; // NOLINT - struct TraitsTag { - } static constexpr Traits{}; // NOLINT - struct StatesTag { - } static constexpr States{}; // NOLINT - struct SamplerTag { - } static constexpr Sampler{}; // NOLINT - - // Vertices - ccstd::pmr::vector _vertices; - // Components - ccstd::pmr::vector names; - ccstd::pmr::vector descs; - ccstd::pmr::vector traits; - ccstd::pmr::vector states; - ccstd::pmr::vector samplerInfo; - // PolymorphicGraph - ccstd::pmr::vector resources; - ccstd::pmr::vector managedBuffers; - ccstd::pmr::vector managedTextures; - ccstd::pmr::vector> buffers; - ccstd::pmr::vector> textures; - ccstd::pmr::vector> framebuffers; - ccstd::pmr::vector swapchains; - // UuidGraph - PmrUnorderedStringMap valueIndex; - // Members - uint64_t nextFenceValue{0}; - uint64_t version{0}; -}; - struct RasterSubpass { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT @@ -469,17 +303,212 @@ struct RasterPass { gfx::Viewport viewport; ccstd::pmr::string versionName; uint64_t version{0}; + bool showStatistics{false}; }; inline bool operator==(const RasterPass& lhs, const RasterPass& rhs) noexcept { - return std::forward_as_tuple(lhs.rasterViews, lhs.computeViews, lhs.subpassGraph, lhs.width, lhs.height, lhs.versionName, lhs.version) == - std::forward_as_tuple(rhs.rasterViews, rhs.computeViews, rhs.subpassGraph, rhs.width, rhs.height, rhs.versionName, rhs.version); + return std::forward_as_tuple(lhs.rasterViews, lhs.computeViews, lhs.subpassGraph, lhs.width, lhs.height) == + std::forward_as_tuple(rhs.rasterViews, rhs.computeViews, rhs.subpassGraph, rhs.width, rhs.height); } inline bool operator!=(const RasterPass& lhs, const RasterPass& rhs) noexcept { return !(lhs == rhs); } +struct PersistentRenderPassAndFramebuffer { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {clearColors.get_allocator().resource()}; + } + + PersistentRenderPassAndFramebuffer(const allocator_type& alloc) noexcept; // NOLINT + PersistentRenderPassAndFramebuffer(IntrusivePtr renderPassIn, IntrusivePtr framebufferIn, const allocator_type& alloc) noexcept; + PersistentRenderPassAndFramebuffer(PersistentRenderPassAndFramebuffer&& rhs, const allocator_type& alloc); + PersistentRenderPassAndFramebuffer(PersistentRenderPassAndFramebuffer const& rhs, const allocator_type& alloc); + + PersistentRenderPassAndFramebuffer(PersistentRenderPassAndFramebuffer&& rhs) noexcept = default; + PersistentRenderPassAndFramebuffer(PersistentRenderPassAndFramebuffer const& rhs) = delete; + PersistentRenderPassAndFramebuffer& operator=(PersistentRenderPassAndFramebuffer&& rhs) = default; + PersistentRenderPassAndFramebuffer& operator=(PersistentRenderPassAndFramebuffer const& rhs) = default; + + IntrusivePtr renderPass; + IntrusivePtr framebuffer; + ccstd::pmr::vector clearColors; + float clearDepth{0}; + uint8_t clearStencil{0}; +}; + +struct ManagedTag {}; +struct ManagedBufferTag {}; +struct ManagedTextureTag {}; +struct PersistentBufferTag {}; +struct PersistentTextureTag {}; +struct FramebufferTag {}; +struct SwapchainTag {}; +struct SamplerTag {}; + +struct ResourceGraph { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {_vertices.get_allocator().resource()}; + } + + inline boost::container::pmr::memory_resource* resource() const noexcept { + return get_allocator().resource(); + } + + ResourceGraph(const allocator_type& alloc) noexcept; // NOLINT + ResourceGraph(ResourceGraph&& rhs) = delete; + ResourceGraph(ResourceGraph const& rhs) = delete; + ResourceGraph& operator=(ResourceGraph&& rhs) = delete; + ResourceGraph& operator=(ResourceGraph const& rhs) = delete; + + // Graph + using directed_category = boost::bidirectional_tag; + using vertex_descriptor = uint32_t; + using edge_descriptor = impl::EdgeDescriptor; + using edge_parallel_category = boost::allow_parallel_edge_tag; + struct traversal_category // NOLINT + : virtual boost::incidence_graph_tag, + virtual boost::bidirectional_graph_tag, + virtual boost::adjacency_graph_tag, + virtual boost::vertex_list_graph_tag, + virtual boost::edge_list_graph_tag {}; + + constexpr static vertex_descriptor null_vertex() noexcept { // NOLINT + return std::numeric_limits::max(); + } + + // IncidenceGraph + using OutEdge = impl::StoredEdge; + using out_edge_iterator = impl::OutEdgeIter< + ccstd::pmr::vector::iterator, + vertex_descriptor, edge_descriptor, int32_t>; + using degree_size_type = uint32_t; + + // BidirectionalGraph + using InEdge = impl::StoredEdge; + using in_edge_iterator = impl::InEdgeIter< + ccstd::pmr::vector::iterator, + vertex_descriptor, edge_descriptor, int32_t>; + + // AdjacencyGraph + using adjacency_iterator = boost::adjacency_iterator_generator< + ResourceGraph, vertex_descriptor, out_edge_iterator>::type; + + // VertexListGraph + using vertex_iterator = boost::integer_range::iterator; + using vertices_size_type = uint32_t; + + // VertexList help functions + inline ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) noexcept { + return _vertices[v].outEdges; + } + inline const ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) const noexcept { + return _vertices[v].outEdges; + } + + inline ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) noexcept { + return _vertices[v].inEdges; + } + inline const ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) const noexcept { + return _vertices[v].inEdges; + } + + inline boost::integer_range getVertexList() const noexcept { + return {0, static_cast(_vertices.size())}; + } + + inline vertex_descriptor getCurrentID() const noexcept { + return static_cast(_vertices.size()); + } + + inline ccstd::pmr::vector colors(boost::container::pmr::memory_resource* mr) const { + return ccstd::pmr::vector(_vertices.size(), mr); + } + + // EdgeListGraph + using edge_iterator = impl::DirectedEdgeIterator; + using edges_size_type = uint32_t; + + // PolymorphicGraph + using VertexTag = ccstd::variant; + using VertexValue = ccstd::variant*, IntrusivePtr*, IntrusivePtr*, RenderSwapchain*>; + using VertexConstValue = ccstd::variant*, const IntrusivePtr*, const IntrusivePtr*, const RenderSwapchain*>; + using VertexHandle = ccstd::variant< + impl::ValueHandle, + impl::ValueHandle, + impl::ValueHandle, + impl::ValueHandle, + impl::ValueHandle, + impl::ValueHandle, + impl::ValueHandle>; + + void validateSwapchains(); + void mount(gfx::Device* device, vertex_descriptor vertID); + void unmount(uint64_t completedFenceValue); + gfx::Texture* getTexture(vertex_descriptor resID); + void invalidatePersistentRenderPassAndFramebuffer(gfx::Texture* pTexture); + + // ContinuousContainer + void reserve(vertices_size_type sz); + + // Members + struct Vertex { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {outEdges.get_allocator().resource()}; + } + + Vertex(const allocator_type& alloc) noexcept; // NOLINT + Vertex(Vertex&& rhs, const allocator_type& alloc); + Vertex(Vertex const& rhs, const allocator_type& alloc); + + Vertex(Vertex&& rhs) noexcept = default; + Vertex(Vertex const& rhs) = delete; + Vertex& operator=(Vertex&& rhs) = default; + Vertex& operator=(Vertex const& rhs) = default; + + ccstd::pmr::vector outEdges; + ccstd::pmr::vector inEdges; + VertexHandle handle; + }; + + struct NameTag { + } static constexpr Name{}; // NOLINT + struct DescTag { + } static constexpr Desc{}; // NOLINT + struct TraitsTag { + } static constexpr Traits{}; // NOLINT + struct StatesTag { + } static constexpr States{}; // NOLINT + struct SamplerTag { + } static constexpr Sampler{}; // NOLINT + + // Vertices + ccstd::pmr::vector _vertices; + // Components + ccstd::pmr::vector names; + ccstd::pmr::vector descs; + ccstd::pmr::vector traits; + ccstd::pmr::vector states; + ccstd::pmr::vector samplerInfo; + // PolymorphicGraph + ccstd::pmr::vector resources; + ccstd::pmr::vector managedBuffers; + ccstd::pmr::vector managedTextures; + ccstd::pmr::vector> buffers; + ccstd::pmr::vector> textures; + ccstd::pmr::vector> framebuffers; + ccstd::pmr::vector swapchains; + // UuidGraph + PmrUnorderedStringMap valueIndex; + // Members + ccstd::pmr::unordered_map renderPasses; + uint64_t nextFenceValue{0}; + uint64_t version{0}; +}; + struct ComputePass { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT @@ -939,8 +968,6 @@ inline hash_t hash::operator()(const cc::render::RasterP hash_combine(seed, val.subpassGraph); hash_combine(seed, val.width); hash_combine(seed, val.height); - hash_combine(seed, val.versionName); - hash_combine(seed, val.version); return seed; } diff --git a/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h b/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h index cf08c7b96e..711b5ab3aa 100644 --- a/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h +++ b/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h @@ -52,7 +52,6 @@ class CopyPassBuilder; class SceneVisitor; class SceneTask; class SceneTransversal; -class LayoutGraphBuilder; class Pipeline; class PipelineBuilder; class RenderingModule; diff --git a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h index f8ca5ea2b1..df572e3553 100644 --- a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h @@ -173,6 +173,8 @@ public: virtual RasterQueueBuilder *addQueue(QueueHint hint) = 0; virtual void setViewport(const gfx::Viewport &viewport) = 0; virtual void setVersion(const ccstd::string &name, uint64_t version) = 0; + virtual bool getShowStatistics() const = 0; + virtual void setShowStatistics(bool enable) = 0; RasterQueueBuilder *addQueue() { return addQueue(QueueHint::NONE); } @@ -253,26 +255,6 @@ public: virtual SceneTask *transverse(SceneVisitor *visitor) const = 0; }; -class LayoutGraphBuilder { -public: - LayoutGraphBuilder() noexcept = default; - LayoutGraphBuilder(LayoutGraphBuilder&& rhs) = delete; - LayoutGraphBuilder(LayoutGraphBuilder const& rhs) = delete; - LayoutGraphBuilder& operator=(LayoutGraphBuilder&& rhs) = delete; - LayoutGraphBuilder& operator=(LayoutGraphBuilder const& rhs) = delete; - virtual ~LayoutGraphBuilder() noexcept = default; - - virtual void clear() = 0; - virtual uint32_t addRenderStage(const ccstd::string &name) = 0; - virtual uint32_t addRenderPhase(const ccstd::string &name, uint32_t parentID) = 0; - virtual void addShader(const ccstd::string &name, uint32_t parentPhaseID) = 0; - virtual void addDescriptorBlock(uint32_t nodeID, const DescriptorBlockIndex &index, const DescriptorBlockFlattened &block) = 0; - virtual void addUniformBlock(uint32_t nodeID, const DescriptorBlockIndex &index, const ccstd::string &name, const gfx::UniformBlock &uniformBlock) = 0; - virtual void reserveDescriptorBlock(uint32_t nodeID, const DescriptorBlockIndex &index, const DescriptorBlockFlattened &block) = 0; - virtual int compile() = 0; - virtual ccstd::string print() const = 0; -}; - class Pipeline : public PipelineRuntime { public: Pipeline() noexcept = default; @@ -294,7 +276,6 @@ public: virtual CopyPassBuilder *addCopyPass() = 0; virtual void presentAll() = 0; virtual SceneTransversal *createSceneTransversal(const scene::Camera *camera, const scene::RenderScene *scene) = 0; - virtual LayoutGraphBuilder *getLayoutGraphBuilder() = 0; virtual gfx::DescriptorSetLayout *getDescriptorSetLayout(const ccstd::string &shaderName, UpdateFrequency freq) = 0; uint32_t addRenderTarget(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height) { return addRenderTarget(name, format, width, height, ResourceResidency::MANAGED); diff --git a/native/cocos/renderer/pipeline/custom/RenderingModule.h b/native/cocos/renderer/pipeline/custom/RenderingModule.h new file mode 100644 index 0000000000..4acff013a7 --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/RenderingModule.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2021-2023 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 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. +****************************************************************************/ + +#pragma once +#include "cocos/renderer/pipeline/custom/PrivateTypes.h" + +namespace cc { + +namespace render { + +ProgramLibrary* getProgramLibrary(); +RenderingModule* getRenderingModule(); + +} // namespace render + +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/details/PathUtils.h b/native/cocos/renderer/pipeline/custom/details/PathUtils.h index f5c6c32a1f..e455672918 100644 --- a/native/cocos/renderer/pipeline/custom/details/PathUtils.h +++ b/native/cocos/renderer/pipeline/custom/details/PathUtils.h @@ -44,14 +44,6 @@ inline void cleanPath(std::basic_string, Allocato CC_EXPECTS(!str.empty()); CC_EXPECTS(boost::algorithm::starts_with(str, std::string_view(slash))); CC_EXPECTS(str.find(doubleSlash) == string_t::npos); - CC_EXPECTS([&]() { // NOLINT - bool valid = true; - for (uint8_t c : str) { - if (c < uint8_t('.')) - valid = false; - } - return valid; - }()); { // remove all /./ constexpr CharT current[] = {'/', '.', '/', '\0'}; diff --git a/native/cocos/renderer/pipeline/xr/ar/ARBackground.cpp b/native/cocos/renderer/pipeline/xr/ar/ARBackground.cpp index 4c22a484b4..e0a14cb144 100644 --- a/native/cocos/renderer/pipeline/xr/ar/ARBackground.cpp +++ b/native/cocos/renderer/pipeline/xr/ar/ARBackground.cpp @@ -341,7 +341,7 @@ void ARBackground::render(cc::scene::Camera *camera, gfx::RenderPass *renderPass } #endif - const auto data = armodule->getCameraTexCoords(); + auto data = armodule->getCameraTexCoords(); #if CC_PLATFORM == CC_PLATFORM_ANDROID if (apiState > 1) { float vertices[] = {-1, -1, data[2], data[3], diff --git a/native/cocos/scene/Ambient.cpp b/native/cocos/scene/Ambient.cpp index 0322bd1ec7..080b833d0a 100644 --- a/native/cocos/scene/Ambient.cpp +++ b/native/cocos/scene/Ambient.cpp @@ -1,8 +1,8 @@ /**************************************************************************** Copyright (c) 2021-2023 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 documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to @@ -157,6 +157,11 @@ Vec4 &Ambient::getSkyColor() { return isHDR ? _skyColorHDR : _skyColorLDR; } +const Vec4 &Ambient::getSkyColor() const { + const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); + return isHDR ? _skyColorHDR : _skyColorLDR; +} + void Ambient::setSkyColor(const Vec4 &color) { const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); if (isHDR) { diff --git a/native/cocos/scene/Ambient.h b/native/cocos/scene/Ambient.h index 6c9f91d228..05c1b0a27f 100644 --- a/native/cocos/scene/Ambient.h +++ b/native/cocos/scene/Ambient.h @@ -1,8 +1,8 @@ /**************************************************************************** Copyright (c) 2021-2023 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 documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to @@ -59,6 +59,7 @@ public: */ Vec4 &getSkyColor(); + const Vec4 &getSkyColor() const; void setSkyColor(const Vec4 &color); /** @@ -168,9 +169,9 @@ public: void activate(Ambient *resource); - //cjh JSB need to bind the property, so need to make it public - // @serializable - // @formerlySerializedAs('_skyColor')); + // cjh JSB need to bind the property, so need to make it public + // @serializable + // @formerlySerializedAs('_skyColor')); Vec4 _skyColorHDR{0.2F, 0.5F, 0.8F, 1.F}; // @serializable // @formerlySerializedAs('_skyIllum') diff --git a/native/cocos/scene/LODGroup.cpp b/native/cocos/scene/LODGroup.cpp index ebf336a7b4..28a9240686 100644 --- a/native/cocos/scene/LODGroup.cpp +++ b/native/cocos/scene/LODGroup.cpp @@ -73,9 +73,9 @@ float LODGroup::getScreenUsagePercentage(const Camera *camera) const { float LODGroup::distanceToScreenUsagePercentage(const Camera *camera, float distance, float size) { if (camera->getProjectionType() == CameraProjection::PERSPECTIVE) { - return static_cast((size * camera->getMatProj().m[5]) / (distance * 2.0)); // note: matProj.m11 is 1 / tan(fov / 2.0) + return static_cast((size * fabs(camera->getMatProj().m[5])) / (distance * 2.0)); // note: matProj.m11 is 1 / tan(fov / 2.0) } - return static_cast(size * camera->getMatProj().m[5] * 0.5); + return static_cast(size * fabs(camera->getMatProj().m[5]) * 0.5); } float LODGroup::getWorldSpaceSize() const { diff --git a/native/cocos/scene/Model.cpp b/native/cocos/scene/Model.cpp index e2496e091e..816d0db8e9 100644 --- a/native/cocos/scene/Model.cpp +++ b/native/cocos/scene/Model.cpp @@ -63,6 +63,7 @@ const cc::gfx::SamplerInfo LIGHTMAP_SAMPLER_WITH_MIP_HASH{ const ccstd::vector SHADOW_MAP_PATCHES{{"CC_RECEIVE_SHADOW", true}}; const ccstd::vector LIGHT_PROBE_PATCHES{{"CC_USE_LIGHT_PROBE", true}}; const ccstd::string CC_USE_REFLECTION_PROBE = "CC_USE_REFLECTION_PROBE"; +const ccstd::string CC_RECEIVE_DIRECTIONAL_LIGHT = "CC_RECEIVE_DIRECTIONAL_LIGHT"; const ccstd::vector STATIC_LIGHTMAP_PATHES{{"CC_USE_LIGHTMAP", 1}}; const ccstd::vector STATIONARY_LIGHTMAP_PATHES{{"CC_USE_LIGHTMAP", 2}}; } // namespace @@ -451,6 +452,7 @@ ccstd::vector Model::getMacroPatches(index_t subModelIndex) { } } } + patches.push_back({CC_RECEIVE_DIRECTIONAL_LIGHT, _receiveDirLight}); return patches; } diff --git a/native/cocos/scene/Model.h b/native/cocos/scene/Model.h index 7d12f90498..0b885785b3 100644 --- a/native/cocos/scene/Model.h +++ b/native/cocos/scene/Model.h @@ -187,6 +187,11 @@ public: inline float getShadowNormalBias() const { return _shadowBias.y; } inline uint32_t getPriority() const { return _priority; } inline void setPriority(uint32_t value) { _priority = value; } + inline bool isReceiveDirLight() const { return _receiveDirLight; } + inline void setReceiveDirLight(bool value) { + _receiveDirLight = value; + onMacroPatchesStateChanged(); + } // For JS inline void setCalledFromJS(bool v) { _isCalledFromJS = v; } @@ -209,10 +214,11 @@ protected: Type _type{Type::DEFAULT}; Layers::Enum _visFlags{Layers::Enum::NONE}; + int32_t _reflectionProbeType{0}; + int32_t _tetrahedronIndex{-1}; uint32_t _descriptorSetCount{1}; uint32_t _priority{0}; uint32_t _updateStamp{0}; - Float32Array _localSHData; OctreeNode *_octreeNode{nullptr}; RenderScene *_scene{nullptr}; @@ -227,13 +233,6 @@ protected: IntrusivePtr _modelBounds; IntrusivePtr _lightmap; - int32_t _tetrahedronIndex{-1}; - Vec3 _lastWorldBoundCenter{INFINITY, INFINITY, INFINITY}; - bool _useLightProbe = false; - - bool _bakeToReflectionProbe{true}; - int32_t _reflectionProbeType{0}; - bool _enabled{false}; bool _castShadow{false}; bool _receiveShadow{false}; @@ -241,9 +240,14 @@ protected: bool _inited{false}; bool _localDataUpdated{false}; bool _worldBoundsDirty{true}; + bool _useLightProbe = false; + bool _bakeToReflectionProbe{true}; + bool _receiveDirLight{true}; // For JS bool _isCalledFromJS{false}; + Vec3 _lastWorldBoundCenter{INFINITY, INFINITY, INFINITY}; + Vec4 _shadowBias; Vec4 _lightmapUVParam; @@ -251,6 +255,8 @@ protected: // CallbacksInvoker _eventProcessor; ccstd::vector> _subModels; + Float32Array _localSHData; + private: CC_DISALLOW_COPY_MOVE_ASSIGN(Model); }; diff --git a/native/cocos/scene/Pass.cpp b/native/cocos/scene/Pass.cpp index 7ea68c06fe..74972a9128 100644 --- a/native/cocos/scene/Pass.cpp +++ b/native/cocos/scene/Pass.cpp @@ -25,10 +25,13 @@ #include "scene/Pass.h" #include "base/std/hash/hash.h" #include "cocos/bindings/jswrapper/SeApi.h" +#include "cocos/renderer/pipeline/custom/RenderingModule.h" #include "core/Root.h" #include "core/assets/TextureBase.h" #include "core/builtin/BuiltinResMgr.h" #include "core/platform/Debug.h" +#include "gfx-base/GFXDevice.h" +#include "pipeline/custom/details/GslUtils.h" #include "renderer/core/PassUtils.h" #include "renderer/core/ProgramLib.h" #include "renderer/gfx-base/GFXDef.h" @@ -43,6 +46,8 @@ namespace scene { namespace { +constexpr uint32_t INVALID_ID = 0xFFFFFFFF; + ccstd::hash_t serializeBlendState(const gfx::BlendState &bs) { ccstd::hash_t hashValue{2}; ccstd::hash_combine(hashValue, bs.isA2C); @@ -134,8 +139,15 @@ ccstd::hash_t Pass::getPassHash(Pass *pass) { ccstd::hash_combine(hashValue, serializeDepthStencilState(pass->_depthStencilState)); ccstd::hash_combine(hashValue, serializeRasterizerState(pass->_rs)); - const ccstd::string &shaderKey = ProgramLib::getInstance()->getKey(pass->getProgram(), pass->getDefines()); - ccstd::hash_range(hashValue, shaderKey.begin(), shaderKey.end()); + const auto *programLib = render::getProgramLibrary(); + if (programLib) { + const auto &shaderKey = programLib->getKey(pass->_phaseID, pass->getProgram(), pass->getDefines()); + ccstd::hash_combine(hashValue, pass->_phaseID); + ccstd::hash_range(hashValue, shaderKey.begin(), shaderKey.end()); + } else { + const ccstd::string &shaderKey = ProgramLib::getInstance()->getKey(pass->getProgram(), pass->getDefines()); + ccstd::hash_range(hashValue, shaderKey.begin(), shaderKey.end()); + } return hashValue; } @@ -402,27 +414,53 @@ void Pass::resetTexture(const ccstd::string &name, uint32_t index) { } void Pass::resetUBOs() { - for (auto &u : _shaderInfo->blocks) { + auto updateBuffer = [&](const IBlockInfo &u) { uint32_t ofs = 0; - for (auto &cur : u.members) { + for (const auto &cur : u.members) { const auto &block = _blocks[u.binding]; const auto &info = _properties[cur.name]; const auto &givenDefault = info.value; - const auto &value = (givenDefault.has_value() ? ccstd::get>(givenDefault.value()) : getDefaultFloatArrayFromType(cur.type)); + const auto &value = + (givenDefault.has_value() + ? ccstd::get>(givenDefault.value()) + : getDefaultFloatArrayFromType(cur.type)); const uint32_t size = (gfx::getTypeSize(cur.type) >> 2) * cur.count; for (size_t k = 0; (k + value.size()) <= size; k += value.size()) { std::copy(value.begin(), value.end(), block.data + ofs + k); } ofs += size; } + }; + auto *programLib = render::getProgramLibrary(); + if (programLib) { + const auto &set = _shaderInfo->descriptors.at( + static_cast(pipeline::SetIndex::MATERIAL)); + for (const auto &block : set.blocks) { + updateBuffer(block); + } + } else { + for (const auto &u : _shaderInfo->blocks) { + updateBuffer(u); + } + _rootBufferDirty = true; } - _rootBufferDirty = true; } void Pass::resetTextures() { - for (auto &u : _shaderInfo->samplerTextures) { - for (int32_t j = 0; j < u.count; j++) { - resetTexture(u.name, j); + auto *programLib = render::getProgramLibrary(); + if (programLib) { + const auto &set = _shaderInfo->descriptors.at( + static_cast(pipeline::SetIndex::MATERIAL)); + for (const auto &combined : set.samplerTextures) { + for (int32_t j = 0; j < combined.count; j++) { + resetTexture(combined.name, j); + } + } + } else { + for (const auto &u : _shaderInfo->samplerTextures) { + for (int32_t j = 0; j < u.count; j++) { + resetTexture(u.name, j); + } } } } @@ -433,13 +471,25 @@ bool Pass::tryCompile() { } syncBatchingScheme(); - auto *shader = ProgramLib::getInstance()->getGFXShader(_device, _programName, _defines, _root->getPipeline()); - if (!shader) { - CC_LOG_WARNING("create shader %s failed", _programName.c_str()); - return false; + auto *programLib = render::getProgramLibrary(); + if (programLib) { + auto *shaderProxy = programLib->getProgramVariant(_device, _phaseID, _programName, _defines); + if (!shaderProxy) { + CC_LOG_WARNING("create shader %s failed", _programName.c_str()); + return false; + } + _shader = shaderProxy->getShader(); + _pipelineLayout = programLib->getPipelineLayout(_device, _phaseID, _programName); + } else { + auto *shader = ProgramLib::getInstance()->getGFXShader(_device, _programName, _defines, _root->getPipeline()); + if (!shader) { + CC_LOG_WARNING("create shader %s failed", _programName.c_str()); + return false; + } + _shader = shader; + _pipelineLayout = ProgramLib::getInstance()->getTemplateInfo(_programName)->pipelineLayout; } - _shader = shader; - _pipelineLayout = ProgramLib::getInstance()->getTemplateInfo(_programName)->pipelineLayout; + _hash = Pass::getPassHash(this); return true; } @@ -472,7 +522,16 @@ gfx::Shader *Pass::getShaderVariant(const ccstd::vector &patches) { _defines[patch.name] = patch.value; } - auto *shader = ProgramLib::getInstance()->getGFXShader(_device, _programName, _defines, pipeline); + gfx::Shader *shader = nullptr; + auto *programLib = render::getProgramLibrary(); + if (programLib) { + const auto *program = programLib->getProgramVariant(_device, _phaseID, _programName, _defines); + if (program) { + shader = program->getShader(); + } + } else { + shader = ProgramLib::getInstance()->getGFXShader(_device, _programName, _defines, pipeline); + } for (const auto &patch : patches) { auto iter = _defines.find(patch.name); @@ -511,6 +570,9 @@ IPassInfoFull Pass::getPassInfoFull() const { ret.dynamicStates = _dynamicStates; ret.phase = _phaseString; + ret.passID = _passID; + ret.phaseID = _phaseID; + return ret; } @@ -526,6 +588,35 @@ void Pass::doInit(const IPassInfoFull &info, bool /*copyDefines*/ /* = false */) auto *programLib = ProgramLib::getInstance(); _priority = pipeline::RenderPriority::DEFAULT; _stage = pipeline::RenderPassStage::DEFAULT; + auto *programLib2 = render::getProgramLibrary(); + if (programLib2) { + const auto *rendering = render::getRenderingModule(); + CC_EXPECTS(rendering); + if (info.phaseID != 0xFFFFFFFF) { + _passID = info.passID; + _phaseID = info.phaseID; + } else { + if (info.pass) { + _passID = rendering->getPassID(*info.pass); + } else { + _passID = rendering->getPassID("default"); + } + CC_ENSURES(_passID != 0xFFFFFFFF); + if (info.phase) { + _phaseID = rendering->getPhaseID(_passID, *info.phase); + } else { + _phaseID = rendering->getPhaseID(_passID, "default"); + } + } + if (_passID == INVALID_ID) { + CC_LOG_ERROR("Invalid pass ID"); + return; + } + if (_phaseID == INVALID_ID) { + CC_LOG_ERROR("Invalid phase ID"); + return; + } + } _phaseString = "default"; _phase = pipeline::getPhaseID(_phaseString); _primitive = gfx::PrimitiveMode::TRIANGLE_LIST; @@ -534,11 +625,18 @@ void Pass::doInit(const IPassInfoFull &info, bool /*copyDefines*/ /* = false */) _propertyIndex = info.propertyIndex.has_value() ? info.propertyIndex.value() : info.passIndex; _programName = info.program; _defines = info.defines; // cjh c++ always does copy by assignment. copyDefines ? ({ ...info.defines }) : info.defines; - _shaderInfo = programLib->getTemplate(info.program); + // init shader info + if (programLib2) { + CC_EXPECTS(_phaseID != INVALID_ID); + _shaderInfo = &programLib2->getProgramInfo(_phaseID, _programName); + } else { + _shaderInfo = programLib->getTemplate(info.program); + } if (info.properties.has_value()) { _properties = info.properties.value(); } - // + + // init gfx gfx::Device *device = _device; Pass::fillPipelineInfo(this, info); if (info.stateOverrides.has_value()) { @@ -547,63 +645,45 @@ void Pass::doInit(const IPassInfoFull &info, bool /*copyDefines*/ /* = false */) // init descriptor set gfx::DescriptorSetInfo dsInfo; - dsInfo.layout = programLib->getDescriptorSetLayout(_device, info.program); + if (programLib2) { + CC_EXPECTS(_phaseID != INVALID_ID); + dsInfo.layout = &programLib2->getMaterialDescriptorSetLayout( + _device, _phaseID, _programName); + } else { + dsInfo.layout = programLib->getDescriptorSetLayout(_device, info.program); + } _descriptorSet = _device->createDescriptorSet(dsInfo); // calculate total size required const auto &blocks = _shaderInfo->blocks; - const auto *tmplInfo = programLib->getTemplateInfo(info.program); - const ccstd::vector &blockSizes = tmplInfo->blockSizes; - const auto &handleMap = tmplInfo->handleMap; - - const auto alignment = device->getCapabilities().uboOffsetAlignment; - ccstd::vector startOffsets; - startOffsets.reserve(blocks.size()); - uint32_t lastSize = 0; - uint32_t lastOffset = 0; - for (size_t i = 0; i < blocks.size(); i++) { - const auto &size = blockSizes[i]; - startOffsets.emplace_back(lastOffset); - lastOffset += static_cast(std::ceil(static_cast(size) / static_cast(alignment))) * alignment; - lastSize = size; - } - - // create gfx buffer resource - uint32_t totalSize = !startOffsets.empty() ? (startOffsets[startOffsets.size() - 1] + lastSize) : 0; - if (totalSize > 0) { - gfx::BufferInfo bufferInfo; - bufferInfo.usage = gfx::BufferUsageBit::UNIFORM | gfx::BufferUsageBit::TRANSFER_DST; - bufferInfo.memUsage = gfx::MemoryUsageBit::DEVICE; - // https://bugs.chromium.org/p/chromium/issues/detail?id=988988 - bufferInfo.size = static_cast(std::ceil(static_cast(totalSize) / 16.F)) * 16; - _rootBuffer = device->createBuffer(bufferInfo); - _rootBlock = ccnew ArrayBuffer(totalSize); - } - - gfx::BufferViewInfo bufferViewInfo; - - // create buffer views - for (size_t i = 0, count = 0; i < blocks.size(); i++) { - int32_t binding = blocks[i].binding; - int32_t size = blockSizes[i]; - bufferViewInfo.buffer = _rootBuffer; - bufferViewInfo.offset = startOffsets[count++]; - bufferViewInfo.range = static_cast(std::ceil(static_cast(size) / 16.F)) * 16; - if (binding >= _buffers.size()) { - _buffers.resize(binding + 1); + const auto *tmplInfo = + programLib2 + ? nullptr + : programLib->getTemplateInfo(info.program); + const auto &blockSizes = [&]() -> const auto & { + if (programLib2) { + return programLib2->getBlockSizes(_phaseID, _programName); } - auto *bufferView = device->createBuffer(bufferViewInfo); - _buffers[binding] = bufferView; - // non-builtin UBO data pools, note that the effect compiler - // guarantees these bindings to be consecutive, starting from 0 and non-array-typed - if (binding >= _blocks.size()) { - _blocks.resize(binding + 1); - } - _blocks[binding].data = reinterpret_cast(const_cast(_rootBlock->getData()) + bufferViewInfo.offset); - _blocks[binding].count = size / 4; - _blocks[binding].offset = bufferViewInfo.offset / 4; - _descriptorSet->bindBuffer(binding, bufferView); + return tmplInfo->blockSizes; } + (); + const auto &handleMap = [&]() -> const auto & { + if (programLib2) { + CC_EXPECTS(_phaseID != INVALID_ID); + return programLib2->getHandleMap(_phaseID, _programName); + } + return tmplInfo->handleMap; + } + (); + + // build uniform blocks + if (programLib2) { + const auto &shaderInfo = programLib2->getShaderInfo(_phaseID, _programName); + buildMaterialUniformBlocks(shaderInfo.blocks, blockSizes); + } else { + buildUniformBlocks(blocks, blockSizes); + } + // store handles _propertyHandleMap = handleMap; auto &directHandleMap = _propertyHandleMap; @@ -620,6 +700,117 @@ void Pass::doInit(const IPassInfoFull &info, bool /*copyDefines*/ /* = false */) utils::mergeToMap(directHandleMap, indirectHandleMap); } +namespace { + +void calculateTotalSize( + gfx::Device *device, const uint32_t lastSize, + IntrusivePtr &rootBuffer, + IntrusivePtr &rootBlock, + ccstd::vector &startOffsets) { + uint32_t totalSize = !startOffsets.empty() ? (startOffsets[startOffsets.size() - 1] + lastSize) : 0; + if (totalSize > 0) { + gfx::BufferInfo bufferInfo; + bufferInfo.usage = gfx::BufferUsageBit::UNIFORM | gfx::BufferUsageBit::TRANSFER_DST; + bufferInfo.memUsage = gfx::MemoryUsageBit::DEVICE; + // https://bugs.chromium.org/p/chromium/issues/detail?id=988988 + bufferInfo.size = static_cast(std::ceil(static_cast(totalSize) / 16.F)) * 16; + rootBuffer = device->createBuffer(bufferInfo); + rootBlock = ccnew ArrayBuffer(totalSize); + } +} + +} // namespace + +void Pass::buildUniformBlock( + uint32_t binding, int32_t size, + gfx::BufferViewInfo &bufferViewInfo, + ccstd::vector &startOffsets, + size_t &count) { + bufferViewInfo.buffer = _rootBuffer; + bufferViewInfo.offset = startOffsets[count++]; + bufferViewInfo.range = static_cast(std::ceil(static_cast(size) / 16.F)) * 16; + if (binding >= _buffers.size()) { + _buffers.resize(binding + 1); + } + auto *bufferView = _device->createBuffer(bufferViewInfo); + _buffers[binding] = bufferView; + // non-builtin UBO data pools, note that the effect compiler + // guarantees these bindings to be consecutive, starting from 0 and non-array-typed + if (binding >= _blocks.size()) { + _blocks.resize(binding + 1); + } + _blocks[binding].data = reinterpret_cast(const_cast(_rootBlock->getData()) + bufferViewInfo.offset); + _blocks[binding].count = size / 4; + _blocks[binding].offset = bufferViewInfo.offset / 4; + _descriptorSet->bindBuffer(binding, bufferView); +} + +void Pass::buildMaterialUniformBlocks( + const ccstd::vector &blocks, + const ccstd::vector &blockSizes) { + gfx::Device *device = _device; + const auto alignment = device->getCapabilities().uboOffsetAlignment; + ccstd::vector startOffsets; + startOffsets.reserve(blocks.size()); + uint32_t lastSize = 0; + uint32_t lastOffset = 0; + for (size_t i = 0; i < blocks.size(); i++) { + const auto &block = blocks[i]; + if (static_cast(block.set) != pipeline::SetIndex::MATERIAL) { + continue; + } + const auto &size = blockSizes[i]; + startOffsets.emplace_back(lastOffset); + lastOffset += static_cast(std::ceil(static_cast(size) / static_cast(alignment))) * alignment; + lastSize = size; + } + + // create gfx buffer resource + if (lastSize != 0) { + calculateTotalSize(device, lastSize, _rootBuffer, _rootBlock, startOffsets); + } + + // create buffer views + gfx::BufferViewInfo bufferViewInfo{}; + for (size_t i = 0, count = 0; i < blocks.size(); i++) { + const auto &block = blocks[i]; + if (static_cast(block.set) != pipeline::SetIndex::MATERIAL) { + continue; + } + const auto binding = block.binding; + int32_t size = blockSizes[i]; + buildUniformBlock(binding, size, bufferViewInfo, startOffsets, count); + } +} + +void Pass::buildUniformBlocks( + const ccstd::vector &blocks, + const ccstd::vector &blockSizes) { + gfx::Device *device = _device; + const auto alignment = device->getCapabilities().uboOffsetAlignment; + ccstd::vector startOffsets; + startOffsets.reserve(blocks.size()); + uint32_t lastSize = 0; + uint32_t lastOffset = 0; + for (size_t i = 0; i < blocks.size(); i++) { + const auto &size = blockSizes[i]; + startOffsets.emplace_back(lastOffset); + lastOffset += static_cast(std::ceil(static_cast(size) / static_cast(alignment))) * alignment; + lastSize = size; + } + + // create gfx buffer resource + calculateTotalSize(device, lastSize, _rootBuffer, _rootBlock, startOffsets); + + // create buffer views + gfx::BufferViewInfo bufferViewInfo; + for (size_t i = 0, count = 0; i < blocks.size(); i++) { + const auto binding = blocks[i].binding; + int32_t size = blockSizes[i]; + buildUniformBlock(binding, size, bufferViewInfo, startOffsets, count); + } +} + void Pass::syncBatchingScheme() { auto iter = _defines.find("USE_INSTANCING"); if (iter != _defines.end()) { @@ -643,6 +834,8 @@ void Pass::initPassFromTarget(Pass *target, const gfx::DepthStencilState &dss, c _priority = target->_priority; _stage = target->_stage; _phase = target->_phase; + _passID = target->_passID; + _phaseID = target->_phaseID; _batchingScheme = target->_batchingScheme; _primitive = target->_primitive; _dynamicStates = target->_dynamicStates; @@ -662,7 +855,12 @@ void Pass::initPassFromTarget(Pass *target, const gfx::DepthStencilState &dss, c _shader = target->_shader; - _pipelineLayout = ProgramLib::getInstance()->getTemplateInfo(_programName)->pipelineLayout; + auto *programLib = render::getProgramLibrary(); + if (programLib) { + _pipelineLayout = programLib->getPipelineLayout(_device, _phaseID, _programName); + } else { + _pipelineLayout = ProgramLib::getInstance()->getTemplateInfo(_programName)->pipelineLayout; + } _hash = target->_hash ^ hashFactor; } @@ -670,7 +868,11 @@ void Pass::updatePassHash() { _hash = Pass::getPassHash(this); } -gfx::DescriptorSetLayout *Pass::getLocalSetLayout() const { +const gfx::DescriptorSetLayout *Pass::getLocalSetLayout() const { + auto *programLib = render::getProgramLibrary(); + if (programLib) { + return &programLib->getLocalDescriptorSetLayout(_device, _phaseID, _programName); + } return ProgramLib::getInstance()->getDescriptorSetLayout(_device, _programName, true); } diff --git a/native/cocos/scene/Pass.h b/native/cocos/scene/Pass.h index 1ca1003995..d80a83ef23 100644 --- a/native/cocos/scene/Pass.h +++ b/native/cocos/scene/Pass.h @@ -263,8 +263,8 @@ public: // infos inline Root *getRoot() const { return _root; } inline gfx::Device *getDevice() const { return _device; } - inline IProgramInfo *getShaderInfo() const { return _shaderInfo; } - gfx::DescriptorSetLayout *getLocalSetLayout() const; + inline const IProgramInfo *getShaderInfo() const { return _shaderInfo; } + const gfx::DescriptorSetLayout *getLocalSetLayout() const; inline const ccstd::string &getProgram() const { return _programName; } inline const Record &getProperties() const { return _properties; } inline const MacroRecord &getDefines() const { return _defines; } @@ -276,16 +276,18 @@ public: inline const ccstd::vector &getBlocks() const { return _blocks; } inline ArrayBuffer *getRootBlock() { return _rootBlock; } inline bool isRootBufferDirty() const { return _rootBufferDirty; } - //NOTE: _setRootBufferDirty must contain a _ prefix to make bindings-generator work correctly. - // In ts engine, Pass has rootBufferDirty getter and without setter, but it contains a protected function named _setRootBufferDirty. - // If we remove _ prefix in C++, bindings-generator doesn't support to bind rootBufferDirty property as getter and ignore to bind setRootBufferDirty as setter at the same time. - // So let's keep the _ prefix temporarily. + // NOTE: _setRootBufferDirty must contain a _ prefix to make bindings-generator work correctly. + // In ts engine, Pass has rootBufferDirty getter and without setter, but it contains a protected function named _setRootBufferDirty. + // If we remove _ prefix in C++, bindings-generator doesn't support to bind rootBufferDirty property as getter and ignore to bind setRootBufferDirty as setter at the same time. + // So let's keep the _ prefix temporarily. inline void _setRootBufferDirty(bool val) { _rootBufferDirty = val; } // NOLINT(readability-identifier-naming) // states inline pipeline::RenderPriority getPriority() const { return _priority; } inline gfx::PrimitiveMode getPrimitive() const { return _primitive; } inline pipeline::RenderPassStage getStage() const { return _stage; } inline uint32_t getPhase() const { return _phase; } + inline uint32_t getPassID() const { return _passID; } + inline uint32_t getPhaseID() const { return _phaseID; } inline const gfx::RasterizerState *getRasterizerState() const { return &_rs; } inline const gfx::DepthStencilState *getDepthStencilState() const { return &_depthStencilState; } inline const gfx::BlendState *getBlendState() const { return &_blendState; } @@ -306,6 +308,19 @@ public: virtual void beginChangeStatesSilently() {} virtual void endChangeStatesSilently() {} +private: + void buildUniformBlocks( + const ccstd::vector &blocks, + const ccstd::vector &blockSizes); + void buildMaterialUniformBlocks( + const ccstd::vector &blocks, + const ccstd::vector &blockSizes); + void buildUniformBlock( + uint32_t binding, int32_t size, + gfx::BufferViewInfo &bufferViewInfo, + ccstd::vector &startOffsets, + size_t &count); + protected: void setState(const gfx::BlendState &bs, const gfx::DepthStencilState &dss, const gfx::RasterizerState &rs, gfx::DescriptorSet *ds); void doInit(const IPassInfoFull &info, bool copyDefines = false); @@ -325,7 +340,7 @@ protected: IntrusivePtr _rootBlock; ccstd::vector _blocks; // Point to position in _rootBlock - IProgramInfo *_shaderInfo; // weakref to template of ProgramLib + const IProgramInfo *_shaderInfo; // weakref to template of ProgramLib MacroRecord _defines; Record _properties; IntrusivePtr _shader; @@ -335,6 +350,8 @@ protected: pipeline::RenderPriority _priority{pipeline::RenderPriority::DEFAULT}; pipeline::RenderPassStage _stage{pipeline::RenderPassStage::DEFAULT}; uint32_t _phase{0}; + uint32_t _passID{0xFFFFFFFF}; + uint32_t _phaseID{0xFFFFFFFF}; ccstd::string _phaseString; gfx::PrimitiveMode _primitive{gfx::PrimitiveMode::TRIANGLE_LIST}; BatchingSchemes _batchingScheme{BatchingSchemes::NONE}; diff --git a/native/cocos/scene/RenderScene.cpp b/native/cocos/scene/RenderScene.cpp index 78b0399c85..098a555ed4 100644 --- a/native/cocos/scene/RenderScene.cpp +++ b/native/cocos/scene/RenderScene.cpp @@ -52,26 +52,13 @@ namespace scene { */ class LodStateCache : public RefCounted { public: - struct ModelInfo { - /** - * @zh model 所属的 LOD 层级 - * @en LOD level of the model。 - */ - int8_t ownerLodLevel{-1}; - const LODGroup *lodGroup{nullptr}; - /** - * @zh model 能被看到的相机列表 - * @en List of cameras that model can be seen. - */ - ccstd::unordered_map visibleCameras; - }; - struct LODInfo { /** * @zh 当前使用哪一级的 LOD, -1 表示没有层级被使用 * @en Which level of LOD is currently in use, -1 means no levels are used */ int8_t usedLevel{-1}; + int8_t lastUsedLevel{-1}; bool transformDirty{true}; }; @@ -96,10 +83,10 @@ public: private: /** - * @zh LOD使用的model集合;包含每个LODGroup的每一级LOD - * @en The collection of models used by LOD; Each LOD of each LODGroup. + * @zh LOD使用的model集合以及每个model当前能被看到的相机列表;包含每个LODGroup的每一级LOD + * @en The set of models used by the LOD and the list of cameras that each models can currently be seen, contains each level of LOD for each LODGroup. */ - ccstd::unordered_map _modelsInLODGroup; + ccstd::unordered_map> _modelsInLODGroup; /** * @zh 指定相机下,LODGroup使用哪一级的LOD @@ -113,6 +100,12 @@ private: */ ccstd::vector _newAddedLodGroupVec; + /** + * @zh 每个LOD上的所有models,包含所有LODGroup中的所有LOD + * @en All mods on each LOD, containing all LODs in all LODGroups. + */ + ccstd::unordered_map>> _levelModels; + RenderScene *_renderScene{nullptr}; }; @@ -397,6 +390,7 @@ void LodStateCache::removeLodGroup(const LODGroup *lodGroup) { for (auto &visibleCamera : _lodStateInCamera) { visibleCamera.second.erase(lodGroup); } + _levelModels.erase(lodGroup); } void LodStateCache::removeModel(const Model *model) { @@ -409,12 +403,13 @@ void LodStateCache::removeModel(const Model *model) { void LodStateCache::updateLodState() { //insert _newAddedLodGroupVec's model into _modelsInLODGroup for (const auto &addedLodGroup : _newAddedLodGroupVec) { + auto &lodModels = _levelModels[addedLodGroup]; for (uint8_t index = 0; index < addedLodGroup->getLodCount(); index++) { + auto &vecModels = lodModels[index]; const auto &lod = addedLodGroup->getLodDataArray()[index]; for (const auto &model : lod->getModels()) { auto &modelInfo = _modelsInLODGroup[model]; - modelInfo.ownerLodLevel = index; - modelInfo.lodGroup = addedLodGroup; + vecModels.push_back(model); } } } @@ -436,19 +431,21 @@ void LodStateCache::updateLodState() { //Update the visible camera list of all models on lodGroup when the visible level changes. if (lodGroup->isLockLevelChanged()) { lodGroup->resetLockChangeFlag(); - for (auto index = 0; index < lodGroup->getLodCount(); index++) { - const auto &lod = lodGroup->getLodDataArray()[index]; - for (const auto &model : lod->getModels()) { - auto &modelInfo = _modelsInLODGroup[model]; - modelInfo.visibleCameras.clear(); + const auto &lodModels = _levelModels[lodGroup]; + for (const auto &level : lodModels) { + const auto &vecModels = lodModels.at(level.first); + for (const auto &model : vecModels) { + _modelsInLODGroup[model].clear(); + } + } + + for (uint8_t visibleIndex : lodLevels) { + const auto &vecModels = lodModels.at(visibleIndex); + for (const auto &model : vecModels) { if (model->getNode() && model->getNode()->isActive()) { - for (uint8_t visibleIndex : lodLevels) { - if (modelInfo.ownerLodLevel == static_cast(visibleIndex)) { - for (auto &visibleCamera : _lodStateInCamera) { - modelInfo.visibleCameras.emplace(visibleCamera.first, true); - } - break; - } + auto &modelInfo = _modelsInLODGroup[model]; + for (const auto &visibleCamera : _lodStateInCamera) { + modelInfo.emplace(visibleCamera.first, true); } } } @@ -471,29 +468,47 @@ void LodStateCache::updateLodState() { int8_t index = lodGroup->getVisibleLODLevel(visibleCamera.first); if (index != lodInfo.usedLevel) { + lodInfo.lastUsedLevel = lodInfo.usedLevel; lodInfo.usedLevel = index; hasUpdated = true; } } } + //The LOD of the last frame is forced to be used, the list of visible cameras of modelInfo needs to be updated. + const auto &lodModels = _levelModels[lodGroup]; if (lodGroup->isLockLevelChanged()) { lodGroup->resetLockChangeFlag(); - hasUpdated = true; - } - //Update the visible camera list of all models on lodGroup + for (const auto &level : lodModels) { + const auto &vecModels = lodModels.at(level.first); + for (const auto &model : vecModels) { + _modelsInLODGroup[model].clear(); + } + } + hasUpdated = true; + } else if (hasUpdated) { + for (auto &visibleCamera : _lodStateInCamera) { + const auto &lodInfo = visibleCamera.second[lodGroup]; + int8_t usedLevel = lodInfo.usedLevel; + if (lodInfo.usedLevel != lodInfo.lastUsedLevel && lodInfo.lastUsedLevel >= 0) { + const auto &vecModels = lodModels.at(static_cast(lodInfo.lastUsedLevel)); + for (const auto &model : vecModels) { + _modelsInLODGroup[model].clear(); + } + } + } + } + //Update the visible camera list of all models on lodGroup. if (hasUpdated) { - for (auto index = 0; index < lodGroup->getLodCount(); index++) { - const auto &lod = lodGroup->getLodDataArray()[index]; - for (const auto &model : lod->getModels()) { - auto &modelInfo = _modelsInLODGroup[model]; - modelInfo.visibleCameras.clear(); - if (model->getNode() && model->getNode()->isActive()) { - for (auto &visibleCamera : _lodStateInCamera) { - if (modelInfo.ownerLodLevel == visibleCamera.second[lodGroup].usedLevel) { - modelInfo.visibleCameras.emplace(visibleCamera.first, true); - } + for (auto &visibleCamera : _lodStateInCamera) { + int8_t usedLevel = visibleCamera.second[lodGroup].usedLevel; + if (usedLevel >= 0) { + const auto &vecModels = lodModels.at(static_cast(usedLevel)); + for (const auto &model : vecModels) { + if (model->getNode() && model->getNode()->isActive()) { + auto &modelInfo = _modelsInLODGroup[model]; + modelInfo.emplace(visibleCamera.first, true); } } } @@ -509,11 +524,12 @@ bool LodStateCache::isLodModelCulled(const Camera *camera, const Model *model) { return false; } - const auto &visibleCamera = itModel->second.visibleCameras; + const auto &visibleCamera = itModel->second; return visibleCamera.count(camera) == 0; } void LodStateCache::clearCache() { + _levelModels.clear(); _modelsInLODGroup.clear(); _lodStateInCamera.clear(); _newAddedLodGroupVec.clear(); diff --git a/native/cocos/xr/ar/ARLib.h b/native/cocos/xr/ar/ARLib.h deleted file mode 100644 index f2fe8ff7e2..0000000000 --- a/native/cocos/xr/ar/ARLib.h +++ /dev/null @@ -1,171 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021-2023 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 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. -****************************************************************************/ - -#pragma once - -#include "ar/IARAPI.h" - -#if CC_PLATFORM == CC_PLATFORM_ANDROID -class _jobject; -#endif - -namespace cc { -namespace ar { - -class ARLib : public IARAPI { -public: - ARLib(); - ~ARLib() override; - void config(int featureMask) override; - uint32_t getSupportMask() override; - void start() override; - void start(void* env, void* context) override; - void resume() override; - void resume(void* env, void* context) override; - void pause() override; - void update() override; - int getAPIState() override; - - Pose getCameraPose() override; - Matrix getCameraViewMatrix() override; - Matrix getCameraProjectionMatrix() override; - TexCoords getCameraTexCoords() override; - - void enableCameraAutoFocus(bool enable) override; - void enableCameraDepth(bool enable) override; - void setDisplayGeometry(uint32_t rotation, uint32_t width, uint32_t height) override; - void setCameraClip(float near, float far) override; - void setCameraTextureName(int id) override; - void* getCameraTextureRef() override; - uint8_t* getCameraDepthBuffer() override; - - void enableLightEstimate(bool enable) override; - LightVal getMainLightDirection() override; - LightVal getMainLightIntensity() override; - - int tryHitAttachAnchor(int planeIndex) override; - Pose getAnchorPose(int index) override; - - bool raycast(float xPx, float yPx, uint32_t trackableTypeMask) override; - Pose getRaycastPose() override; - int getRaycastTrackableId() override; - int getRaycastTrackableType() override; - - int getInfoLength() override; - - // plane detection - void enablePlane(bool enable) override; - void setPlaneDetectionMode(int mode) override; - void setPlaneMaxTrackingNumber(int count) override; - float* getAddedPlanesInfo() override; - float* getUpdatedPlanesInfo() override; - float* getRemovedPlanesInfo() override; - float* getPlanePolygon(int id) override; - - // scene mesh reconstruction - void enableSceneMesh(bool enable) override; - float* getAddedSceneMesh() override; - float* getUpdatedSceneMesh() override; - float* getRemovedSceneMesh() override; - int* requireSceneMesh() override; - float* getSceneMeshVertices(int meshRef) override; - int* getSceneMeshTriangleIndices(int meshRef) override; - void endRequireSceneMesh() override; - - // image recognition & tracking - void enableImageTracking(bool enable) override; - void addImageToLib(const std::string& imageName) override; - void addImageToLibWithSize(const std::string& name, float widthInMeters) override; - void setImageMaxTrackingNumber(int number) override; - float* getAddedImagesInfo() override; - float* getUpdatedImagesInfo() override; - float* getRemovedImagesInfo() override; - - // object recognition & tracking - void enableObjectTracking(bool enable) override; - void addObjectToLib(const std::string& imageName) override; - float* getAddedObjectsInfo() override; - float* getUpdatedObjectsInfo() override; - float* getRemovedObjectsInfo() override; - - // face detection & tracking - void enableFaceTracking(bool enable) override; - float* getAddedFacesInfo() override; - float* getUpdatedFacesInfo() override; - float* getRemovedFacesInfo() override; - float* getFaceBlendShapes(int faceRef) override; - -protected: -#if CC_PLATFORM == CC_PLATFORM_ANDROID - _jobject* _impl{nullptr}; - Pose _cameraPose; - Matrix _viewMatrix; - Matrix _projMatrix; - TexCoords _cameraTexCoords; - uint8_t* _cameraDepthBuffer{nullptr}; - - Pose _hitPose; - Pose _anchorPose; - - int _infoLength = 0; - - float* _addedPlanesInfo{nullptr}; - float* _updatedPlanesInfo{nullptr}; - float* _removedPlanesInfo{nullptr}; - float* _planePolygon{nullptr}; - - float* _sceneMeshVertices{nullptr}; - int* _sceneMeshIndices{nullptr}; - float* _addedSceneMeshInfo{nullptr}; - float* _updatedSceneMeshInfo{nullptr}; - int* _removedSceneMeshRefs{nullptr}; - int* _requiredSceneMeshRefs{nullptr}; - - float* _addedImagesInfo{nullptr}; - float* _updatedImagesInfo{nullptr}; - float* _removedImagesInfo{nullptr}; - - float* _addedObjsInfo{nullptr}; - float* _updatedObjsInfo{nullptr}; - float* _removedObjsInfo{nullptr}; - - float* _addedFacesInfo{nullptr}; - float* _updatedFacesInfo{nullptr}; - float* _removedFacesInfo{nullptr}; - float* _faceBlendShapes{nullptr}; -#elif CC_PLATFORM == CC_PLATFORM_MAC_IOS - void* _impl{nullptr}; - - int _infoLength = 0; - - void* _plane{nullptr}; - void* _sceneMesh{nullptr}; - void* _imageTracking{nullptr}; - void* _objectTracking{nullptr}; - void* _faceTracking{nullptr}; -#endif -}; - -} // namespace ar -} // namespace cc diff --git a/native/cocos/xr/ar/ARModule.cpp b/native/cocos/xr/ar/ARModule.cpp deleted file mode 100644 index 90f1ace3b5..0000000000 --- a/native/cocos/xr/ar/ARModule.cpp +++ /dev/null @@ -1,328 +0,0 @@ -/**************************************************************************** - Copyright (c) 2022-2023 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 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. -****************************************************************************/ - -#include "ar/ARModule.h" -#include -#include -#include "math/Vec3.h" - -#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_MAC_IOS - #include "ar/ARLib.h" -using ARAPIImpl = cc::ar::ARLib; -#elif CC_PLATFORM == CC_PLATFORM_WINDOWS - #include "ar/IARAPI.h" -#endif - -#include "bindings/jswrapper/SeApi.h" - -namespace cc { -namespace ar { - -ARModule::ARModule() { -#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_MAC_IOS - _impl = std::make_unique(); - arModuleInstance.reset(this); - _texInitFlag = true; -#endif -} - -ARModule::~ARModule() { -} - -ARModule* ARModule::createARModule() { - return new ARModule(); -} - -ARModule* ARModule::get() { - return arModuleInstance.get(); -} - -void ARModule::config(int featureMask) { - _impl->config(featureMask); -} - -int ARModule::getSupportMask() { - return _impl->getSupportMask(); -} - -void ARModule::start() { - _impl->start(); -} - -void ARModule::onResume() { - _impl->resume(); -} - -void ARModule::onPause() { - _impl->pause(); -} - -void ARModule::update() { - _impl->update(); -} - -// -1: not started, 0: arkit, 1: arcore, 2: arengine -int ARModule::getAPIState() { - return _impl->getAPIState(); -} - -void ARModule::setCameraId(const std::string& id) { - _cameraId = id; -} - -const std::string& ARModule::getCameraId() const { - return _cameraId; -} - -Pose ARModule::getCameraPose() const { - return _impl->getCameraPose(); -} - -Matrix ARModule::getCameraViewMatrix() const { - return _impl->getCameraViewMatrix(); -} - -Matrix ARModule::getCameraProjectionMatrix() const { - return _impl->getCameraProjectionMatrix(); -} - -TexCoords ARModule::getCameraTexCoords() const { - return _impl->getCameraTexCoords(); -} - -void ARModule::enableCameraAutoFocus(bool enable) const { - _impl->enableCameraAutoFocus(enable); -} - -void ARModule::enableCameraDepth(bool enable) const { - _impl->enableCameraDepth(enable); -} - -void ARModule::setDisplayGeometry(uint32_t rotation, uint32_t width, uint32_t height) const { - _impl->setDisplayGeometry(rotation, width, height); -} - -void ARModule::setCameraClip(float near, float far) const { - _impl->setCameraClip(near, far); -} - -void ARModule::setCameraTextureName(int id) const { - _impl->setCameraTextureName(id); -} - -void* ARModule::getCameraTextureRef() const { - return _impl->getCameraTextureRef(); -} - -uint8_t* ARModule::getCameraDepthBuffer() const { - return _impl->getCameraDepthBuffer(); -} - -bool ARModule::getTexInitFlag() const { - return _texInitFlag; -} -void ARModule::resetTexInitFlag() { - _texInitFlag = false; -} - -void ARModule::enableLightEstimate(bool enable) const { - _impl->enableLightEstimate(enable); -} - -LightVal ARModule::getMainLightDirection() const { - return _impl->getMainLightDirection(); -} - -LightVal ARModule::getMainLightIntensity() const { - return _impl->getMainLightIntensity(); -} - -int ARModule::tryHitAttachAnchor(int trackableId) const { - return _impl->tryHitAttachAnchor(trackableId); -} -Pose ARModule::getAnchorPose(int anchorId) const { - return _impl->getAnchorPose(anchorId); -} - -bool ARModule::tryHitTest(float xPx, float yPx, uint32_t trackableTypeMask) const { - return _impl->raycast(xPx, yPx, trackableTypeMask); -} - -Pose ARModule::getHitResult() const { - return _impl->getRaycastPose(); -} - -int ARModule::getHitId() const { - return _impl->getRaycastTrackableId(); -} - -int ARModule::getHitType() const { - return _impl->getRaycastTrackableType(); -} - -int ARModule::getInfoLength() const { - return _impl->getInfoLength(); -} - -#pragma region plane detection -void ARModule::enablePlane(bool enable) const { - return _impl->enablePlane(enable); -} - -void ARModule::setPlaneDetectionMode(int mode) const { - return _impl->setPlaneDetectionMode(mode); -} - -void ARModule::setPlaneMaxTrackingNumber(int count) const { - return _impl->setPlaneMaxTrackingNumber(count); -} - -float* ARModule::getAddedPlanesInfo() const { - return _impl->getAddedPlanesInfo(); -} - -float* ARModule::getUpdatedPlanesInfo() const { - return _impl->getUpdatedPlanesInfo(); -} - -float* ARModule::getRemovedPlanesInfo() const { - return _impl->getRemovedPlanesInfo(); -} - -float* ARModule::getPlanePolygon(int id) const { - return _impl->getPlanePolygon(id); -} -#pragma endregion // plane detection - -#pragma region scene mesh reconstruction -void ARModule::enableSceneMesh(bool enable) const { - return _impl->enableSceneMesh(enable); -} - -float* ARModule::getAddedSceneMesh() const { - return _impl->getAddedSceneMesh(); -} - -float* ARModule::getUpdatedSceneMesh() const { - return _impl->getUpdatedSceneMesh(); -} - -float* ARModule::getRemovedSceneMesh() const { - return _impl->getRemovedSceneMesh(); -} - -int* ARModule::requireSceneMesh() const { - return _impl->requireSceneMesh(); -} - -float* ARModule::getSceneMeshVertices(int meshRef) const { - return _impl->getSceneMeshVertices(meshRef); -} - -int* ARModule::getSceneMeshTriangleIndices(int meshRef) const { - return _impl->getSceneMeshTriangleIndices(meshRef); -} - -void ARModule::endRequireSceneMesh() const { - return _impl->endRequireSceneMesh(); -} -#pragma endregion // scene mesh reconstruction - -#pragma region image recognition& tracking -void ARModule::enableImageTracking(bool enable) const { - _impl->enableImageTracking(enable); -} - -void ARModule::addImageToLib(const std::string& imageName) const { - _impl->addImageToLib(imageName); -} - -void ARModule::addImageToLibWithSize(const std::string& imageName, float widthInMeters) const { - _impl->addImageToLibWithSize(imageName, widthInMeters); -} - -void ARModule::setImageMaxTrackingNumber(int number) const { - _impl->setImageMaxTrackingNumber(number); -} - -float* ARModule::getAddedImagesInfo() const { - return _impl->getAddedImagesInfo(); -} - -float* ARModule::getUpdatedImagesInfo() const { - return _impl->getUpdatedImagesInfo(); -} - -float* ARModule::getRemovedImagesInfo() const { - return _impl->getRemovedImagesInfo(); -} - -#pragma endregion // image recognition & tracking - -#pragma region object recognition& tracking -void ARModule::enableObjectTracking(bool enable) const { - _impl->enableObjectTracking(enable); -} - -void ARModule::addObjectToLib(const std::string& imageName) const { - _impl->addObjectToLib(imageName); -} - -float* ARModule::getAddedObjectsInfo() const { - return _impl->getAddedObjectsInfo(); -} - -float* ARModule::getUpdatedObjectsInfo() const { - return _impl->getUpdatedObjectsInfo(); -} - -float* ARModule::getRemovedObjectsInfo() const { - return _impl->getRemovedObjectsInfo(); -} -#pragma endregion // object recognition & tracking - -#pragma region face detection& tracking -void ARModule::enableFaceTracking(bool enable) const { - _impl->enableFaceTracking(enable); -} - -float* ARModule::getAddedFacesInfo() const { - return _impl->getAddedFacesInfo(); -} - -float* ARModule::getUpdatedFacesInfo() const { - return _impl->getUpdatedFacesInfo(); -} - -float* ARModule::getRemovedFacesInfo() const { - return _impl->getRemovedFacesInfo(); -} - -float* ARModule::getFaceBlendShapes(int faceRef) const { - return _impl->getFaceBlendShapes(faceRef); -} -#pragma endregion // face detection & tracking - -} // namespace ar -} // namespace cc diff --git a/native/cocos/xr/ar/ARModule.h b/native/cocos/xr/ar/ARModule.h index 464ad1971f..a3192ff549 100644 --- a/native/cocos/xr/ar/ARModule.h +++ b/native/cocos/xr/ar/ARModule.h @@ -24,36 +24,41 @@ #pragma once -#include +#include #include -#include "ar/IARAPI.h" -#include "base/Macros.h" namespace cc { namespace ar { -class CC_DLL ARModule final { +using Pose = std::array; +using Matrix = std::array; +using TexCoords = std::array; +using LightVal = std::array; + +class ARModule { public: static ARModule* createARModule(); static ARModule* get(); - ARModule(); - ~ARModule(); + ~ARModule() = default; - void config(int featureMask); - int getSupportMask(); + void config(uint32_t featureMask); + uint32_t getSupportMask() const; void start(); - void onResume(); - void onPause(); + void start(void *env, void *context); + void stop(); + void resume(); + void resume(void *env, void *context); + void pause(); void update(); int getAPIState(); void setCameraId(const std::string& id); const std::string& getCameraId() const; - Pose getCameraPose() const; - Matrix getCameraViewMatrix() const; - Matrix getCameraProjectionMatrix() const; - TexCoords getCameraTexCoords() const; + Pose getCameraPose(); + Matrix getCameraViewMatrix(); + Matrix getCameraProjectionMatrix(); + TexCoords getCameraTexCoords(); void enableCameraAutoFocus(bool enable) const; void enableCameraDepth(bool enable) const; @@ -61,7 +66,7 @@ public: void setCameraClip(float near, float far) const; void setCameraTextureName(int id) const; void* getCameraTextureRef() const; - uint8_t* getCameraDepthBuffer() const; + uint8_t* getCameraDepthBuffer(); bool getTexInitFlag() const; void resetTexInitFlag(); @@ -69,11 +74,11 @@ public: LightVal getMainLightDirection() const; LightVal getMainLightIntensity() const; - int tryHitAttachAnchor(int trackableId) const; - Pose getAnchorPose(int anchorId) const; + int tryHitAttachAnchor(int id) const; + Pose getAnchorPose(int id); bool tryHitTest(float xPx, float yPx, uint32_t trackableTypeMask) const; - Pose getHitResult() const; + Pose getHitResult(); int getHitId() const; int getHitType() const; @@ -83,52 +88,43 @@ public: // plane detection void enablePlane(bool enable) const; void setPlaneDetectionMode(int mode) const; - void setPlaneMaxTrackingNumber(int count) const; - float* getAddedPlanesInfo() const; - float* getUpdatedPlanesInfo() const; - float* getRemovedPlanesInfo() const; - float* getPlanePolygon(int id) const; + float* getAddedPlanesInfo(); + float* getUpdatedPlanesInfo(); + float* getRemovedPlanesInfo(); + float* getPlanePolygon(int id); // scene mesh reconstruction void enableSceneMesh(bool enable) const; - float* getAddedSceneMesh() const; - float* getUpdatedSceneMesh() const; - float* getRemovedSceneMesh() const; - int* requireSceneMesh() const; - float* getSceneMeshVertices(int meshRef) const; - int* getSceneMeshTriangleIndices(int meshRef) const; + float* getAddedSceneMesh(); + float* getUpdatedSceneMesh(); + float* getRemovedSceneMesh(); + int* requireSceneMesh(); + float* getSceneMeshVertices(int id); + int* getSceneMeshTriangleIndices(int id); void endRequireSceneMesh() const; // image recognition & tracking void enableImageTracking(bool enable) const; - void addImageToLib(const std::string& name) const; void addImageToLibWithSize(const std::string& name, float widthInMeters) const; void setImageMaxTrackingNumber(int number) const; - float* getAddedImagesInfo() const; - float* getUpdatedImagesInfo() const; - float* getRemovedImagesInfo() const; + float* getAddedImagesInfo(); + float* getUpdatedImagesInfo(); + float* getRemovedImagesInfo(); // object recognition & tracking void enableObjectTracking(bool enable) const; void addObjectToLib(const std::string& name) const; - float* getAddedObjectsInfo() const; - float* getUpdatedObjectsInfo() const; - float* getRemovedObjectsInfo() const; + float* getAddedObjectsInfo(); + float* getUpdatedObjectsInfo(); + float* getRemovedObjectsInfo(); // face detection & tracking void enableFaceTracking(bool enable) const; - float* getAddedFacesInfo() const; - float* getUpdatedFacesInfo() const; - float* getRemovedFacesInfo() const; - float* getFaceBlendShapes(int faceRef) const; - -private: - std::unique_ptr _impl; - std::string _cameraId; - bool _texInitFlag{false}; + float* getAddedFacesInfo(); + float* getUpdatedFacesInfo(); + float* getRemovedFacesInfo(); + float* getFaceBlendShapes(int id); }; -static std::unique_ptr arModuleInstance; - } // namespace ar } // namespace cc diff --git a/native/cocos/xr/ar/IARAPI.h b/native/cocos/xr/ar/IARAPI.h deleted file mode 100644 index e5beb1be69..0000000000 --- a/native/cocos/xr/ar/IARAPI.h +++ /dev/null @@ -1,122 +0,0 @@ -/**************************************************************************** - Copyright (c) 2022-2023 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 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. -****************************************************************************/ - -#pragma once - -#include - -namespace cc { -namespace ar { - -using Pose = std::array; -using Matrix = std::array; -using TexCoords = std::array; -using LightVal = std::array; - -class IARAPI { -public: - virtual ~IARAPI() = default; - virtual void config(int featureMask) = 0; - virtual uint32_t getSupportMask() = 0; - virtual void start() = 0; - virtual void start(void* env, void* context) = 0; - virtual void resume() = 0; - virtual void resume(void* env, void* context) = 0; - virtual void pause() = 0; - virtual void update() = 0; - virtual int getAPIState() = 0; - - virtual Pose getCameraPose() = 0; - virtual Matrix getCameraViewMatrix() = 0; - virtual Matrix getCameraProjectionMatrix() = 0; - virtual TexCoords getCameraTexCoords() = 0; - - virtual void enableCameraAutoFocus(bool enable) = 0; - virtual void enableCameraDepth(bool enable) = 0; - virtual void setDisplayGeometry(uint32_t rotation, uint32_t width, uint32_t height) = 0; - virtual void setCameraClip(float near, float far) = 0; - virtual void setCameraTextureName(int id) = 0; - virtual void* getCameraTextureRef() = 0; - virtual uint8_t* getCameraDepthBuffer() = 0; - - virtual void enableLightEstimate(bool enable) = 0; - virtual LightVal getMainLightDirection() = 0; - virtual LightVal getMainLightIntensity() = 0; - - virtual int tryHitAttachAnchor(int id) = 0; - virtual Pose getAnchorPose(int id) = 0; - - virtual bool raycast(float xPx, float yPx, uint32_t trackableTypeMask) = 0; - virtual Pose getRaycastPose() = 0; - virtual int getRaycastTrackableId() = 0; - virtual int getRaycastTrackableType() = 0; - - // for jsb array - virtual int getInfoLength() = 0; - - // plane detection - virtual void enablePlane(bool enable) = 0; - virtual void setPlaneDetectionMode(int mode) = 0; - virtual void setPlaneMaxTrackingNumber(int count) = 0; - virtual float* getAddedPlanesInfo() = 0; - virtual float* getUpdatedPlanesInfo() = 0; - virtual float* getRemovedPlanesInfo() = 0; - virtual float* getPlanePolygon(int id) = 0; - - // scene mesh reconstruction - virtual void enableSceneMesh(bool enable) = 0; - virtual float* getAddedSceneMesh() = 0; - virtual float* getUpdatedSceneMesh() = 0; - virtual float* getRemovedSceneMesh() = 0; - virtual int* requireSceneMesh() = 0; - virtual float* getSceneMeshVertices(int id) = 0; - virtual int* getSceneMeshTriangleIndices(int id) = 0; - virtual void endRequireSceneMesh() = 0; - - // image recognition & tracking - virtual void enableImageTracking(bool enable) = 0; - virtual void addImageToLib(const std::string& name) = 0; - virtual void addImageToLibWithSize(const std::string& name, float widthInMeters) = 0; - virtual void setImageMaxTrackingNumber(int number) = 0; - virtual float* getAddedImagesInfo() = 0; - virtual float* getUpdatedImagesInfo() = 0; - virtual float* getRemovedImagesInfo() = 0; - - // object recognition & tracking - virtual void enableObjectTracking(bool enable) = 0; - virtual void addObjectToLib(const std::string& name) = 0; - virtual float* getAddedObjectsInfo() = 0; - virtual float* getUpdatedObjectsInfo() = 0; - virtual float* getRemovedObjectsInfo() = 0; - - // face detection & tracking - virtual void enableFaceTracking(bool enable) = 0; - virtual float* getAddedFacesInfo() = 0; - virtual float* getUpdatedFacesInfo() = 0; - virtual float* getRemovedFacesInfo() = 0; - virtual float* getFaceBlendShapes(int id) = 0; -}; - -} // namespace ar -} // namespace cc diff --git a/native/external-config.json b/native/external-config.json index 38baf292bc..e1ebf81b17 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3.7.0-7" + "checkout": "v3.7.1-2" } } diff --git a/native/tools/swig-config/ar.i b/native/tools/swig-config/ar.i index 0e632d5052..6f4ba71f2b 100644 --- a/native/tools/swig-config/ar.i +++ b/native/tools/swig-config/ar.i @@ -9,7 +9,6 @@ #pragma once #include "bindings/jswrapper/SeApi.h" #include "bindings/manual/jsb_conversions.h" -#include "xr/ar/IARAPI.h" #include "xr/ar/ARModule.h" %} diff --git a/native/tools/swig-config/assets.i b/native/tools/swig-config/assets.i index abffcf8888..b21252ae46 100644 --- a/native/tools/swig-config/assets.i +++ b/native/tools/swig-config/assets.i @@ -62,6 +62,8 @@ %ignore cc::EffectAsset::_techniques; %ignore cc::EffectAsset::_shaders; %ignore cc::EffectAsset::_combinations; +%ignore cc::IPassInfoFull::passID; +%ignore cc::IPassInfoFull::phaseID; // ----- Rename Section ------ // Brief: Classes, methods or attributes needs to be renamed diff --git a/native/tools/swig-config/pipeline.i b/native/tools/swig-config/pipeline.i index d19faad42d..fca830d950 100644 --- a/native/tools/swig-config/pipeline.i +++ b/native/tools/swig-config/pipeline.i @@ -26,6 +26,7 @@ #include "renderer/pipeline/PipelineSceneData.h" #include "renderer/pipeline/BatchedBuffer.h" #include "renderer/pipeline/GeometryRenderer.h" +#include "renderer/pipeline/DebugView.h" #include "renderer/pipeline/reflection-probe/ReflectionProbeFlow.h" #include "renderer/pipeline/reflection-probe/ReflectionProbeStage.h" %} @@ -167,7 +168,7 @@ using namespace cc; %attribute(cc::pipeline::PipelineSceneData, cc::scene::Skybox*, skybox, getSkybox); %attribute(cc::pipeline::PipelineSceneData, cc::scene::Shadows*, shadows, getShadows); %attribute(cc::pipeline::PipelineSceneData, cc::gi::LightProbes*, lightProbes, getLightProbes); - +%attribute(cc::pipeline::PipelineSceneData, ccstd::vector, validPunctualLights, getValidPunctualLights, setValidPunctualLights); %attribute(cc::pipeline::RenderStage, ccstd::string&, _name, getName, setName); %attribute(cc::pipeline::RenderStage, uint32_t, _priority, getPriority, setPriority); @@ -182,6 +183,10 @@ using namespace cc; %attribute(cc::pipeline::RenderFlow, uint32_t, _tag, getTag, setTag); %attribute(cc::pipeline::RenderFlow, cc::pipeline::RenderStageList, _stages, getStages, setStages); +%attribute(cc::pipeline::DebugView, cc::pipeline::DebugViewSingleType, singleMode, getSingleMode, setSingleMode); +%attribute(cc::pipeline::DebugView, bool, lightingWithAlbedo, isLightingWithAlbedo, setLightingWithAlbedo); +%attribute(cc::pipeline::DebugView, bool, csmLayerColoration, isCsmLayerColoration, setCsmLayerColoration); + #define CC_USE_GEOMETRY_RENDERER 1 // ----- Import Section ------ @@ -221,6 +226,7 @@ using namespace cc; %include "renderer/pipeline/RenderPipeline.h" %include "renderer/pipeline/RenderFlow.h" %include "renderer/pipeline/RenderStage.h" +%include "renderer/pipeline/DebugView.h" %include "renderer/pipeline/forward/ForwardPipeline.h" %include "renderer/pipeline/forward/ForwardFlow.h" diff --git a/native/tools/swig-config/renderer.i b/native/tools/swig-config/renderer.i index cb57e0b6d6..552b5bd730 100644 --- a/native/tools/swig-config/renderer.i +++ b/native/tools/swig-config/renderer.i @@ -98,9 +98,13 @@ using namespace cc::render; %attribute(cc::render::PipelineRuntime, cc::pipeline::GeometryRenderer*, geometryRenderer, getGeometryRenderer); %attribute(cc::render::PipelineRuntime, float, shadingScale, getShadingScale, setShadingScale); %attribute(cc::render::RenderNode, ccstd::string, name, getName, setName); +%attribute(cc::render::RasterPassBuilder, bool, showStatistics, getShowStatistics, setShowStatistics); %attribute(cc::render::SceneVisitor, cc::pipeline::PipelineSceneData*, pipelineSceneData, getPipelineSceneData); %attribute(cc::render::SceneTask, cc::render::TaskType, taskType, getTaskType); -%attribute(cc::render::Pipeline, cc::render::LayoutGraphBuilder*, layoutGraphBuilder, getLayoutGraphBuilder); + +// ----- Release Returned Cpp Object in GC Section ------ +%release_returned_cpp_object_in_gc(cc::render::Pipeline::addRasterPass); +%release_returned_cpp_object_in_gc(cc::render::RasterPassBuilder::addQueue); // ----- Import Section ------ // Brief: Import header files which are depended by 'Include Section' @@ -111,3 +115,4 @@ using namespace cc::render; // ----- Include Section ------ // Brief: Include header files in which classes and methods will be bound %include "renderer/pipeline/custom/RenderInterfaceTypes.h" + diff --git a/native/tools/swig-config/scene.i b/native/tools/swig-config/scene.i index 034f4d6e1c..05f14b1085 100644 --- a/native/tools/swig-config/scene.i +++ b/native/tools/swig-config/scene.i @@ -243,6 +243,7 @@ using namespace cc; %attribute(cc::Root, cc::render::PipelineRuntime *, pipeline, getPipeline); %attribute(cc::Root, cc::render::Pipeline*, customPipeline, getCustomPipeline); %attribute(cc::Root, %arg(ccstd::vector &), cameraList, getCameraList); +%attribute(cc::Root, cc::pipeline::DebugView*, debugView, getDebugView); %attribute(cc::scene::RenderWindow, uint32_t, width, getWidth); %attribute(cc::scene::RenderWindow, uint32_t, height, getHeight); @@ -453,6 +454,7 @@ using namespace cc; %attribute(cc::scene::Model, bool, useLightProbe, getUseLightProbe, setUseLightProbe); %attribute(cc::scene::Model, bool, bakeToReflectionProbe, getBakeToReflectionProbe, setBakeToReflectionProbe); %attribute(cc::scene::Model, uint32_t, reflectionProbeType, getReflectionProbeType, setReflectionProbeType); +%attribute(cc::scene::Model, bool, receiveDirLight, isReceiveDirLight, setReceiveDirLight); %attribute(cc::scene::SubModel, std::shared_ptr>> &, passes, getPasses, setPasses); %attribute(cc::scene::SubModel, ccstd::vector> &, shaders, getShaders, setShaders); diff --git a/package-lock.json b/package-lock.json index 42f32220db..f6c632561c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "cocos-creator", - "version": "3.7.0", + "version": "3.7.2", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 17e4baa692..378a0ab41d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "cocos-creator", "version": "3.8.0", - "description": "Cocos Creator is a cross-platform 2D & 3D game engine written in TypeScript, licensed under MIT.", + "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", "authors": [ diff --git a/platforms/native/engine/jsb-spine-skeleton.js b/platforms/native/engine/jsb-spine-skeleton.js index 087be1d98a..44091be020 100644 --- a/platforms/native/engine/jsb-spine-skeleton.js +++ b/platforms/native/engine/jsb-spine-skeleton.js @@ -428,70 +428,6 @@ const cacheManager = require('./jsb-cache-manager'); this._useAttach = true; nativeSkeleton.setAttachEnabled(true); } - - if (!this.isAnimationCached() && (this.debugBones || this.debugSlots || this.debugMesh) && this._debugRenderer) { - const graphics = this._debugRenderer; - graphics.clear(); - graphics.lineWidth = 5; - - const debugData = this._debugData || nativeSkeleton.getDebugData(); - if (!debugData) return; - let debugIdx = 0; let debugType = 0; let debugLen = 0; - - debugType = debugData[debugIdx++]; - while (debugType !== 0) { - debugLen = debugData[debugIdx++]; - - switch (debugType) { - case 1: // slots - graphics.strokeColor = _slotColor; - for (let i = 0; i < debugLen; i += 8) { - graphics.moveTo(debugData[debugIdx++], debugData[debugIdx++]); - graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]); - graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]); - graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]); - graphics.close(); - graphics.stroke(); - } - break; - case 2: // mesh - graphics.strokeColor = _meshColor; - for (let i = 0; i < debugLen; i += 6) { - graphics.moveTo(debugData[debugIdx++], debugData[debugIdx++]); - graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]); - graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]); - graphics.close(); - graphics.stroke(); - } - break; - case 3: // bones - graphics.strokeColor = _boneColor; - graphics.fillColor = _slotColor; // Root bone color is same as slot color. - for (let i = 0; i < debugLen; i += 4) { - const bx = debugData[debugIdx++]; - const by = debugData[debugIdx++]; - const x = debugData[debugIdx++]; - const y = debugData[debugIdx++]; - - // Bone lengths. - graphics.moveTo(bx, by); - graphics.lineTo(x, y); - graphics.stroke(); - - // Bone origins. - graphics.circle(bx, by, Math.PI * 1.5); - graphics.fill(); - if (i === 0) { - graphics.fillColor = _originColor; - } - } - break; - default: - return; - } - debugType = debugData[debugIdx++]; - } - } }; skeleton.updateWorldTransform = function () { @@ -783,6 +719,70 @@ const cacheManager = require('./jsb-cache-manager'); const nativeSkeleton = this._nativeSkeleton; if (!nativeSkeleton) return; + if (!this.isAnimationCached() && (this.debugBones || this.debugSlots || this.debugMesh) && this._debugRenderer) { + const graphics = this._debugRenderer; + graphics.clear(); + graphics.lineWidth = 5; + + const debugData = this._debugData || nativeSkeleton.getDebugData(); + if (!debugData) return; + let debugIdx = 0; let debugType = 0; let debugLen = 0; + + debugType = debugData[debugIdx++]; + while (debugType !== 0) { + debugLen = debugData[debugIdx++]; + + switch (debugType) { + case 1: // slots + graphics.strokeColor = _slotColor; + for (let i = 0; i < debugLen; i += 8) { + graphics.moveTo(debugData[debugIdx++], debugData[debugIdx++]); + graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]); + graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]); + graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]); + graphics.close(); + graphics.stroke(); + } + break; + case 2: // mesh + graphics.strokeColor = _meshColor; + for (let i = 0; i < debugLen; i += 6) { + graphics.moveTo(debugData[debugIdx++], debugData[debugIdx++]); + graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]); + graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]); + graphics.close(); + graphics.stroke(); + } + break; + case 3: // bones + graphics.strokeColor = _boneColor; + graphics.fillColor = _slotColor; // Root bone color is same as slot color. + for (let i = 0; i < debugLen; i += 4) { + const bx = debugData[debugIdx++]; + const by = debugData[debugIdx++]; + const x = debugData[debugIdx++]; + const y = debugData[debugIdx++]; + + // Bone lengths. + graphics.moveTo(bx, by); + graphics.lineTo(x, y); + graphics.stroke(); + + // Bone origins. + graphics.circle(bx, by, Math.PI * 1.5); + graphics.fill(); + if (i === 0) { + graphics.fillColor = _originColor; + } + } + break; + default: + return; + } + debugType = debugData[debugIdx++]; + } + } + const socketNodes = this.socketNodes; if (socketNodes.size > 0) { const sharedBufferOffset = this._sharedBufferOffset; diff --git a/scripts/fetch-ral.js b/scripts/fetch-ral.js index 19fe458ece..06f2f8f9f0 100644 --- a/scripts/fetch-ral.js +++ b/scripts/fetch-ral.js @@ -161,8 +161,13 @@ async function removeDir (dirPath) { } await cleanOldRal(); await removeDir(repositoryPath); - let exitCode = await runCommand('git clone git@github.com:yangws/runtime-web-adapter.git', __dirname); - if (exitCode !== 0) { + try { + let exitCode = await runCommand('git clone git@github.com:yangws/runtime-web-adapter.git', __dirname); + if (exitCode !== 0) { + await removeDir(repositoryPath); + await runCommand('git clone https://github.com/yangws/runtime-web-adapter', __dirname); + } + } catch (e) { await removeDir(repositoryPath); await runCommand('git clone https://github.com/yangws/runtime-web-adapter', __dirname); } diff --git a/scripts/native-pack-tool/source/base/default.ts b/scripts/native-pack-tool/source/base/default.ts index ff91c8fbb6..99373061a3 100644 --- a/scripts/native-pack-tool/source/base/default.ts +++ b/scripts/native-pack-tool/source/base/default.ts @@ -128,6 +128,13 @@ export abstract class NativePackTool { return this._versionParser; } + /** + * Debug / Release + */ + protected get buildType(): string { + return this.params.debug ? "Debug" : "Release"; + } + /** * Read version number from cocos-version.json */ @@ -429,10 +436,13 @@ export abstract class NativePackTool { await fs.outputFile(file, content); } - protected appendCmakeResDirArgs(args: string[]) { - args.push(`-DRES_DIR="${cchelper.fixPath(this.paths.buildDir)}" -DAPP_NAME="${this.params.projectName}" `); + protected appendCmakeCommonArgs(args: string[]) { + args.push(`-DRES_DIR="${cchelper.fixPath(this.paths.buildDir)}"`); + args.push(`-DAPP_NAME="${this.params.projectName}"`); + args.push(`-DLAUNCH_TYPE="${this.buildType}"`); } + /** * 加密脚本,加密后,会修改 cmake 参数,因而需要再次执行 cmake 配置文件的生成 * @returns diff --git a/scripts/native-pack-tool/source/cocosConfig.ts b/scripts/native-pack-tool/source/cocosConfig.ts index 6777fa5dc3..05df5a91ad 100644 --- a/scripts/native-pack-tool/source/cocosConfig.ts +++ b/scripts/native-pack-tool/source/cocosConfig.ts @@ -5,6 +5,9 @@ export const cocosConfig = { cmake: { windows: { generators: [ + { + G: 'Visual Studio 17 2022', + }, { G: 'Visual Studio 16 2019', }, diff --git a/scripts/native-pack-tool/source/platforms/android.ts b/scripts/native-pack-tool/source/platforms/android.ts index 302adfe9d0..aeafc30222 100644 --- a/scripts/native-pack-tool/source/platforms/android.ts +++ b/scripts/native-pack-tool/source/platforms/android.ts @@ -198,6 +198,7 @@ export class AndroidPackTool extends NativePackTool { content = content.replace(/PROP_MIN_SDK_VERSION=.*/, `PROP_MIN_SDK_VERSION=${Math.min(apiLevel, minimalSDKVersion)}`); content = content.replace(/PROP_APP_NAME=.*/, `PROP_APP_NAME=${this.params.projectName}`); content = content.replace(/PROP_ENABLE_INSTANT_APP=.*/, `PROP_ENABLE_INSTANT_APP=${options.androidInstant ? "true" : "false"}`); + content = content.replace(/PROP_IS_DEBUG=.*/, `PROP_IS_DEBUG=${this.params.debug ? "true" : "false"}`); content = content.replace(/RES_PATH=.*/, `RES_PATH=${cchelper.fixPath(this.paths.buildDir)}`); content = content.replace(/COCOS_ENGINE_PATH=.*/, `COCOS_ENGINE_PATH=${cchelper.fixPath(Paths.nativeRoot)}`); diff --git a/scripts/native-pack-tool/source/platforms/ios.ts b/scripts/native-pack-tool/source/platforms/ios.ts index 517937016e..cac16f3e67 100644 --- a/scripts/native-pack-tool/source/platforms/ios.ts +++ b/scripts/native-pack-tool/source/platforms/ios.ts @@ -93,7 +93,7 @@ export class IOSPackTool extends MacOSPackTool { const ext: string[] = ['-DCMAKE_CXX_COMPILER=clang++', '-DCMAKE_C_COMPILER=clang']; - this.appendCmakeResDirArgs(ext); + this.appendCmakeCommonArgs(ext); const ver = toolHelper.getXcodeMajorVerion() >= 12 ? "12" : "1"; await toolHelper.runCmake(['-S', `"${this.paths.platformTemplateDirInPrj}"`, '-GXcode', `-B"${nativePrjDir}"`, '-T', `buildsystem=${ver}`, diff --git a/scripts/native-pack-tool/source/platforms/mac.ts b/scripts/native-pack-tool/source/platforms/mac.ts index e476926856..ba670498fa 100644 --- a/scripts/native-pack-tool/source/platforms/mac.ts +++ b/scripts/native-pack-tool/source/platforms/mac.ts @@ -33,7 +33,7 @@ export class MacPackTool extends MacOSPackTool { const ver = toolHelper.getXcodeMajorVerion() >= 12 ? "12" : "1"; const cmakeArgs = ['-S', `"${this.paths.platformTemplateDirInPrj}"`, '-GXcode', '-T', `buildsystem=${ver}`, `-B"${nativePrjDir}"`, '-DCMAKE_SYSTEM_NAME=Darwin']; - this.appendCmakeResDirArgs(cmakeArgs); + this.appendCmakeCommonArgs(cmakeArgs); await toolHelper.runCmake(cmakeArgs); diff --git a/scripts/native-pack-tool/source/platforms/windows.ts b/scripts/native-pack-tool/source/platforms/windows.ts index 0748c1587e..2d78401847 100644 --- a/scripts/native-pack-tool/source/platforms/windows.ts +++ b/scripts/native-pack-tool/source/platforms/windows.ts @@ -51,7 +51,7 @@ export class WindowsPackTool extends NativePackTool { } } - this.appendCmakeResDirArgs(generateArgs); + this.appendCmakeCommonArgs(generateArgs); await toolHelper.runCmake([`-S"${cchelper.fixPath(this.paths.platformTemplateDirInPrj)}"`, `-B"${cchelper.fixPath(this.paths.nativePrjDir)}"`].concat(generateArgs)); return true; } diff --git a/templates/android/build/gradle.properties b/templates/android/build/gradle.properties index 6a701a83ce..a0ea1b247c 100644 --- a/templates/android/build/gradle.properties +++ b/templates/android/build/gradle.properties @@ -41,6 +41,9 @@ PROP_ENABLE_INSTANT_APP=true PROP_NDK_PATH= +# Build variant +PROP_IS_DEBUG=true + # Cocos Engine Path COCOS_ENGINE_PATH= diff --git a/templates/android/template/app/build.gradle b/templates/android/template/app/build.gradle index 540d6b684d..5bba17dd16 100644 --- a/templates/android/template/app/build.gradle +++ b/templates/android/template/app/build.gradle @@ -81,7 +81,11 @@ android { arguments "-DHIDE_SYMBOLS=ON" } } - + + if (PROP_IS_DEBUG == "false") { + getIsDefault().set(true) + } + // resValue "string", "app_name", PROP_APP_NAME } diff --git a/templates/cmake/apple.cmake b/templates/cmake/apple.cmake index 29495d6433..0fd71b1f31 100644 --- a/templates/cmake/apple.cmake +++ b/templates/cmake/apple.cmake @@ -1,3 +1,21 @@ + + +macro(cc_apple_set_launch_type target_name) + if("${CMAKE_VERSION}" VERSION_GREATER_EQUAL "3.25.0" AND DEFINED LAUNCH_TYPE) + set_target_properties(${target_name} PROPERTIES + XCODE_GENERATE_SCHEME ON + XCODE_SCHEME_LAUNCH_CONFIGURATION "${LAUNCH_TYPE}" + ) + + if("${LAUNCH_TYPE}" STREQUAL "Release") + set_target_properties(${target_name} PROPERTIES + XCODE_SCHEME_ENABLE_GPU_API_VALIDATION OFF + XCODE_SCHEME_ENABLE_GPU_SHADER_VALIDATION OFF + ) + endif() + endif() +endmacro() + macro(cc_ios_before_target target_name) list(APPEND CC_UI_RESOURCES ${CC_PROJECT_DIR}/LaunchScreenBackground.png @@ -7,22 +25,25 @@ macro(cc_ios_before_target target_name) ) list(APPEND CC_PROJ_SOURCES ${CC_UI_RESOURCES} - ) + ) + if(NOT EXISTS ${CC_PROJECT_DIR}/LaunchScreenBackground.png) - if (USE_PORTRAIT) + if(USE_PORTRAIT) configure_file(${CC_PROJECT_DIR}/LaunchScreenBackgroundPortrait.png ${CC_PROJECT_DIR}/LaunchScreenBackground.png COPYONLY) else() configure_file(${CC_PROJECT_DIR}/LaunchScreenBackgroundLandscape.png ${CC_PROJECT_DIR}/LaunchScreenBackground.png COPYONLY) endif() endif() + if(NOT CUSTOM_COPY_RESOURCE_HOOK) cc_include_resources(${RES_DIR}/data CC_ASSET_FILES) endif() + source_group(TREE ${RES_DIR}/data 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}) - ## values used in Info.plist templates + # # values used in Info.plist templates set(EXECUTABLE_NAME ${target_name}) set(PRODUCT_NAME ${APP_NAME}) @@ -41,7 +62,7 @@ macro(cc_ios_before_target target_name) endmacro() macro(cc_ios_after_target target_name) - set_target_properties(${target_name} PROPERTIES + set_target_properties(${target_name} PROPERTIES MACOSX_BUNDLE 1 MACOSX_BUNDLE_INFO_PLIST "${CC_PROJECT_DIR}/Info.plist" RESOURCE "${CC_UI_RESOURCES}" @@ -58,13 +79,16 @@ macro(cc_ios_after_target target_name) XCODE_ATTRIBUTE_SKIP_INSTALL NO XCODE_ATTRIBUTE_INSTALL_PATH "$(LOCAL_APPS_DIR)" ) - ## exclude arm64 arch and specify x86_64 for iphonesimulator by default, this will apply to both target. + + cc_apple_set_launch_type(${target_name}) + + # # exclude arm64 arch and specify x86_64 for iphonesimulator by default, this will apply to both target. set(CMAKE_XCODE_ATTRIBUTE_EXCLUDED_ARCHS[sdk=iphonesimulator*] "arm64") set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=iphoneos*] "arm64") set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=iphonesimulator*] "x86_64") set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=iphoneos*] "arm64") set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=iphonesimulator*] "x86_64") - + target_link_libraries(${target_name} ${ENGINE_NAME}) target_include_directories(${target_name} PRIVATE @@ -74,9 +98,7 @@ macro(cc_ios_after_target target_name) cc_common_after_target(${target_name}) endmacro() - macro(cc_mac_before_target target_name) - set(CMAKE_OSX_DEPLOYMENT_TARGET ${TARGET_OSX_VERSION}) list(APPEND CC_UI_RESOURCES @@ -87,11 +109,12 @@ macro(cc_mac_before_target target_name) ${CC_PROJECT_DIR}/main.mm ${CC_UI_RESOURCES} ) + if(NOT CUSTOM_COPY_RESOURCE_HOOK) cc_include_resources(${RES_DIR}/data CC_ASSET_FILES) endif() - ## values used in Info.plist templates + # # values used in Info.plist templates set(EXECUTABLE_NAME ${target_name}) set(PRODUCT_NAME ${APP_NAME}) @@ -107,46 +130,46 @@ macro(cc_mac_before_target target_name) cc_common_before_target(${target_name}) endmacro() - macro(cc_mac_after_target target_name) - target_link_libraries(${target_name} ${ENGINE_NAME}) target_include_directories(${target_name} PRIVATE ${CC_PROJECT_DIR}/../common/Classes ) -if(USE_SERVER_MODE) - if(EXISTS ${RES_DIR}/data/jsb-adapter) - set(bin_dir ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}) - add_custom_target(copy_resource ALL - COMMAND ${CMAKE_COMMAND} -E echo "Copying resources to ${bin_dir}" - COMMAND ${CMAKE_COMMAND} -E make_directory ${bin_dir}/Resources - COMMAND ${CMAKE_COMMAND} -E copy_directory "${RES_DIR}/data/" "${bin_dir}/Resources/" - COMMAND ${CMAKE_COMMAND} -E echo "Copying resources done!" - ) - add_dependencies(${target_name} copy_resource) - set_target_properties(copy_resource PROPERTIES FOLDER Utils) - endif() -else() - set_target_properties(${target_name} PROPERTIES - OSX_ARCHITECTURES "x86_64;arm64" - XCODE_ATTRIBUTE_MACOS_DEPLOYMENT_TARGET "${TARGET_OSX_VERSION}" - XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH YES - XCODE_ATTRIBUTE_ASSETCATALOG_COMPILER_APPICON_NAME "AppIcon" - XCODE_ATTRIBUTE_ASSETCATALOG_COMPILER_LAUNCHSTORYBOARD_NAME "LaunchScreen" - MACOSX_BUNDLE 1 - RESOURCE "${CC_UI_RESOURCES}" - MACOSX_BUNDLE_INFO_PLIST "${CC_PROJECT_DIR}/Info.plist" - XCODE_ATTRIBUTE_SKIP_INSTALL NO - XCODE_ATTRIBUTE_INSTALL_PATH "$(LOCAL_APPS_DIR)" - ) - if(ENABLE_SANDBOX) + if(USE_SERVER_MODE) + if(EXISTS ${RES_DIR}/data/jsb-adapter) + set(bin_dir ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}) + add_custom_target(copy_resource ALL + COMMAND ${CMAKE_COMMAND} -E echo "Copying resources to ${bin_dir}" + COMMAND ${CMAKE_COMMAND} -E make_directory ${bin_dir}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory "${RES_DIR}/data/" "${bin_dir}/Resources/" + COMMAND ${CMAKE_COMMAND} -E echo "Copying resources done!" + ) + add_dependencies(${target_name} copy_resource) + set_target_properties(copy_resource PROPERTIES FOLDER Utils) + endif() + else() set_target_properties(${target_name} PROPERTIES - XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS "${CC_PROJECT_DIR}/entitlements.plist" + OSX_ARCHITECTURES "x86_64;arm64" + XCODE_ATTRIBUTE_MACOS_DEPLOYMENT_TARGET "${TARGET_OSX_VERSION}" + XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH YES + XCODE_ATTRIBUTE_ASSETCATALOG_COMPILER_APPICON_NAME "AppIcon" + XCODE_ATTRIBUTE_ASSETCATALOG_COMPILER_LAUNCHSTORYBOARD_NAME "LaunchScreen" + MACOSX_BUNDLE 1 + RESOURCE "${CC_UI_RESOURCES}" + MACOSX_BUNDLE_INFO_PLIST "${CC_PROJECT_DIR}/Info.plist" + XCODE_ATTRIBUTE_SKIP_INSTALL NO + XCODE_ATTRIBUTE_INSTALL_PATH "$(LOCAL_APPS_DIR)" ) + + cc_apple_set_launch_type(${target_name}) + + if(ENABLE_SANDBOX) + set_target_properties(${target_name} PROPERTIES + XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS "${CC_PROJECT_DIR}/entitlements.plist" + ) + endif() endif() -endif() + cc_common_after_target(${target_name}) - endmacro() - diff --git a/templates/launcher/application.ejs b/templates/launcher/application.ejs index 9b688444b2..5ad2fdae89 100644 --- a/templates/launcher/application.ejs +++ b/templates/launcher/application.ejs @@ -3,7 +3,6 @@ let cc; export class Application { constructor () { this.settingsPath = '<%= settingsJsonPath %>'; - this.effectSettingsPath = 'src/effect.bin'; this.showFPS = <%= showFPS %>; } @@ -26,7 +25,6 @@ export class Application { return cc.game.init({ debugMode: <%= debugMode %> ? cc.DebugMode.INFO : cc.DebugMode.ERROR, settingsPath: this.settingsPath, - effectSettingsPath: this.effectSettingsPath, overrideSettings: { // assets: { // preloadBundles: [{ bundle: 'main', version: 'xxx' }], diff --git a/tests/core/ccclass.test.ts b/tests/core/ccclass.test.ts index 1397c31b4c..6fccfa9e91 100644 --- a/tests/core/ccclass.test.ts +++ b/tests/core/ccclass.test.ts @@ -43,7 +43,8 @@ describe('ccclass warnings', () => { warnID.mockClear(); }; - test('Warn on no default value specified', () => { + // TODO + test.skip('Warn on no default value specified', () => { clearWarnID(); { @ccclass class _ { @float p; } } expect(warnID).toHaveBeenCalledTimes(1); diff --git a/tests/core/decorator.test.ts b/tests/core/decorator.test.ts index f0505046fe..53b3ab47b1 100644 --- a/tests/core/decorator.test.ts +++ b/tests/core/decorator.test.ts @@ -11,44 +11,38 @@ import { } from '../../cocos/core/data/decorators'; import { CCClass } from '../../cocos/core/data/class'; import { property } from '../../cocos/core/data/decorators/property'; +import { getClassByName, unregisterClass } from '../../cocos/core/utils/js-typed'; +import { LegacyPropertyDecorator } from '../../cocos/core/data/decorators/utils'; -describe('Decorators signature', () => { +test('Decorators signature', () => { class Foo {} - property(Foo, 'field1', function initializer () { + property(Foo.prototype, 'field1', function initializer () { return 1; }); - property(Foo, 'field2', { + property(Foo.prototype, 'field2', { initializer() { return 2; }, }); - property(Foo, 'property', { value: 1 }); - property(Foo, 'getset', { + property(Foo.prototype, 'property', { value: 1 }); + property(Foo.prototype, 'getset', { get() { return 3; }, set(v) {}, }); - expect(Foo.constructor['__ccclassCache__']).toMatchInlineSnapshot(` - Object { - "proto": Object { - "properties": Object { - "field1": Object { - "default": 1, - }, - "field2": Object { - "default": 2, - }, - "getset": Object { - "get": [Function], - "set": [Function], - }, - "property": Object {}, - }, - }, - } - `); + ccclass('Foo')(Foo); + expect(Foo['__attrs__']).toMatchObject({ + field1$_$default: 1, + field2$_$default: 2, + getset$_$hasGetter: true, + getset$_$hasSetter: true, + getset$_$serializable: false, + }); + expect(Foo['__props__']).toMatchObject(['field1', 'field2', 'property', 'getset']); + + unregisterClass(Foo); }); describe(`Decorators`, () => { @@ -272,3 +266,51 @@ describe(`Decorators`, () => { expect(CCClass.Attr.attr(Tooltip, 'boo').tooltip).toBe('i18n:ENGINE.model.shadow_normal_bias'); }); }); + +describe('Decorated property test', () => { + afterEach(() => { + const cls = getClassByName('A'); + unregisterClass(cls); + }); + + const t = (descriptorOrInitializer?: Parameters[2]) => { + class A { + test: number; + } + property(A.prototype, 'test', descriptorOrInitializer); + ccclass('A')(A); + return CCClass.Attr.attr(A, 'test'); + }; + + test('property without default value', () => { + // Simulate `class A { @property test; }`(in babel case) + expect(t(null)).toMatchObject({}); + }); + + test('property with default value null', () => { + // Simulate `class A { @property test = null; }`(in babel case) + expect(t(() => null)).toMatchObject({ + default: null, + }); + }); + + test('property with property descriptor', () => { + // Simulate `class A { @property test = null; }`(in babel case) + expect(t({ + configurable: true, + enumerable: true, + value: 1, + writable: true, + initializer () { return null; } + })).toMatchObject({ + default: null, + }); + }); + + test('property in TSC compiler', () => { + // Simulate `class A { @property test; }`(in tsc case) + expect(t()).toMatchObject({ + default: undefined, + }); + }); +}); \ No newline at end of file diff --git a/tests/core/math/mat4.test.ts b/tests/core/math/mat4.test.ts new file mode 100644 index 0000000000..5f9c8ba77c --- /dev/null +++ b/tests/core/math/mat4.test.ts @@ -0,0 +1,26 @@ +import { Mat4, Quat, Vec3 } from "../../../cocos/core"; + +test('Conversion between TRS', () => { + const t = new Vec3(1., 2., 3.); + const r = new Quat(4., 5., 6., 7.); + Quat.normalize(r, r); + const s = new Vec3(8., 9., 10.); + + const mat4 = new Mat4(); + expect(Mat4.fromRTS( + mat4, + r, + t, + s, + )).toBe(mat4); + const t2 = new Vec3(); + const r2 = new Quat(); + const s2 = new Vec3(); + Mat4.toRTS(mat4, r2, t2, s2); + expect(Vec3.equals(t2, t)).toBe(true); + expect(Vec3.equals(s2, s)).toBe(true); + expect(Quat.equals(r2, r)).toBe(true); + expect(Vec3.equals(mat4.getTranslation(new Vec3()), t)).toBe(true); + expect(Vec3.equals(mat4.getScale(new Vec3()), s)).toBe(true); + expect(Quat.equals(mat4.getRotation(new Quat()), r)).toBe(true); +}); \ No newline at end of file diff --git a/tests/core/memop/container-manager.test.ts b/tests/core/memop/container-manager.test.ts index f65a6c0a9e..f83cf10d3a 100644 --- a/tests/core/memop/container-manager.test.ts +++ b/tests/core/memop/container-manager.test.ts @@ -1,6 +1,4 @@ -import { ScalableContainer } from '../../../cocos/core/memop/scalable-container'; -import { containerManager } from '../../../cocos/core/memop/container-manager'; - +import { ScalableContainer, scalableContainerManager } from '../../../cocos/core/memop/scalable-container'; class TestContainer extends ScalableContainer { calledTimes = 0; @@ -11,74 +9,74 @@ class TestContainer extends ScalableContainer { test('container', () => { // @ts-expect-error - containerManager._pools.length = 0; + scalableContainerManager._pools.length = 0; const testContainer = new TestContainer(); // @ts-expect-error - expect(containerManager._pools.length).toBe(1); + expect(scalableContainerManager._pools.length).toBe(1); expect(testContainer._poolHandle).toBe(0); - containerManager.addContainer(testContainer); + scalableContainerManager.addContainer(testContainer); // @ts-expect-error - expect(containerManager._pools.length).toBe(1); + expect(scalableContainerManager._pools.length).toBe(1); expect(testContainer._poolHandle).toBe(0); const testContainer1 = new TestContainer(); // @ts-expect-error - expect(containerManager._pools.length).toBe(2); + expect(scalableContainerManager._pools.length).toBe(2); expect(testContainer1._poolHandle).toBe(1); testContainer.destroy(); // @ts-expect-error - expect(containerManager._pools.length).toBe(1); + expect(scalableContainerManager._pools.length).toBe(1); expect(testContainer._poolHandle).toBe(-1); expect(testContainer1._poolHandle).toBe(0); const testContainer2 = new TestContainer(); // @ts-expect-error - expect(containerManager._pools.length).toBe(2); + expect(scalableContainerManager._pools.length).toBe(2); expect(testContainer2._poolHandle).toBe(1); testContainer2.destroy(); // @ts-expect-error - expect(containerManager._pools.length).toBe(1); + expect(scalableContainerManager._pools.length).toBe(1); expect(testContainer2._poolHandle).toBe(-1); expect(testContainer1._poolHandle).toBe(0); testContainer1.destroy(); // @ts-expect-error - expect(containerManager._pools.length).toBe(0); + expect(scalableContainerManager._pools.length).toBe(0); expect(testContainer2._poolHandle).toBe(-1); expect(testContainer1._poolHandle).toBe(-1); expect(testContainer._poolHandle).toBe(-1); - containerManager.removeContainer(testContainer1); + scalableContainerManager.removeContainer(testContainer1); // @ts-expect-error - expect(containerManager._pools.length).toBe(0); + expect(scalableContainerManager._pools.length).toBe(0); }); test('shrink', () => { // @ts-expect-error - containerManager._pools.length = 0; + scalableContainerManager._pools.length = 0; const testContainer = new TestContainer(); expect(testContainer.calledTimes).toBe(0); // default shrink time span is 5 - containerManager.update(6); + scalableContainerManager.update(6); expect(testContainer.calledTimes).toBe(1); const testContainer1 = new TestContainer(); - containerManager.update(3); + scalableContainerManager.update(3); expect(testContainer.calledTimes).toBe(1); expect(testContainer1.calledTimes).toBe(0); - containerManager.update(2); + scalableContainerManager.update(2); expect(testContainer.calledTimes).toBe(2); expect(testContainer1.calledTimes).toBe(1); // set shrink time span - containerManager.shrinkTimeSpan = 0.5; - containerManager.update(0); + scalableContainerManager.shrinkTimeSpan = 0.5; + scalableContainerManager.update(0); expect(testContainer.calledTimes).toBe(3); expect(testContainer1.calledTimes).toBe(2); }); \ No newline at end of file diff --git a/tests/particle/renderer.test.ts b/tests/particle/renderer.test.ts index 20583a3499..089584b3dd 100644 --- a/tests/particle/renderer.test.ts +++ b/tests/particle/renderer.test.ts @@ -1,5 +1,5 @@ import { director, game } from "../../cocos/game"; -import { containerManager } from "../../cocos/core/memop/container-manager"; +import { scalableContainerManager } from "../../cocos/core/memop/scalable-container"; import { Node, Scene } from "../../cocos/scene-graph"; import { ParticleSystem } from "../../exports/particle"; @@ -10,17 +10,15 @@ test('recycle pool release', () => { scene.addChild(node); game.step(); // @ts-expect-error access private property - const beforeLength = containerManager._pools.length; + const beforeLength = scalableContainerManager._pools.length; const comp = node.addComponent(ParticleSystem); game.step(); // @ts-expect-error access private property - const currentLength = containerManager._pools.length; + const currentLength = scalableContainerManager._pools.length; expect(currentLength).toBeGreaterThan(beforeLength); comp.destroy(); game.step(); // @ts-expect-error - expect(containerManager._pools.length).toBeLessThan(currentLength); - - + expect(scalableContainerManager._pools.length).toBeLessThan(currentLength); }); \ No newline at end of file