diff --git a/EngineErrorMap.md b/EngineErrorMap.md index ff8721296f..8f5891acfb 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -3501,6 +3501,10 @@ The effect('%s') you are looking for does not exist, please confirm the effect n The asset replacing failed, can not found override asset('%s') for '%s' +### 16300 + +node '%s' doesn't have any UIRenderer component, this component will not work. please add UIRenderer component first + ### 16301 node '%s' doesn't have any ModelRenderer component, this component will not work. please add ModelRenderer component first diff --git a/cc.config.json b/cc.config.json index c2ffa9493f..51ff05f712 100644 --- a/cc.config.json +++ b/cc.config.json @@ -82,6 +82,13 @@ "affine-transform": { "modules": ["affine-transform"] }, + "sorting-2d": { + "modules": ["sorting-2d"], + "overrideConstants": { + "USE_SORTING_2D": true + }, + "dependentModules": ["2d"] + }, "particle": { "modules": ["particle"], "dependentAssets": [ @@ -788,6 +795,12 @@ "type": "boolean", "value": false, "internal": true + }, + "USE_SORTING_2D": { + "comment": "An internal constant to indicate whether we're using sorting-2d module.", + "type": "boolean", + "value": false, + "internal": true } }, diff --git a/cocos/2d/framework/ui-renderer.ts b/cocos/2d/framework/ui-renderer.ts index b0c8178520..a367503aa6 100644 --- a/cocos/2d/framework/ui-renderer.ts +++ b/cocos/2d/framework/ui-renderer.ts @@ -272,6 +272,19 @@ export class UIRenderer extends Renderer { */ public _flagChangedVersion = -1; + private _priority = 0; + + get priority (): number { + return this._priority; + } + + set priority (val: number) { + this._priority = val; + if (JSB) { + this._renderEntity.setPriority(val); + } + } + /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ diff --git a/cocos/2d/renderer/batcher-2d.ts b/cocos/2d/renderer/batcher-2d.ts index fbce904946..5e4eed66c4 100644 --- a/cocos/2d/renderer/batcher-2d.ts +++ b/cocos/2d/renderer/batcher-2d.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { DEBUG, JSB } from 'internal:constants'; +import { DEBUG, JSB, USE_SORTING_2D } from 'internal:constants'; import { Camera, Model } from '../../render-scene/scene'; import type { UIStaticBatch } from '../components/ui-static-batch'; import { Material } from '../../asset/assets/material'; @@ -30,7 +30,7 @@ import { RenderRoot2D, UIRenderer } from '../framework'; import { Texture, Device, Attribute, Sampler, DescriptorSetInfo, Buffer, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet, InputAssembler, deviceManager, PrimitiveMode, DepthStencilState } from '../../gfx'; -import { CachedArray, Pool, Mat4, cclegacy, assertIsTrue, assert, approx, EPSILON } from '../../core'; +import { CachedArray, Pool, Mat4, cclegacy, assertIsTrue, assert, approx, EPSILON, RecyclePool } from '../../core'; import { Root } from '../../root'; import { Node } from '../../scene-graph'; import { Stage, StencilManager } from './stencil-manager'; @@ -53,8 +53,33 @@ import { IAssembler } from './base'; import { RenderEntityFillColorType } from './render-entity'; import type { Director } from '../../game/director'; +let sorting2DCount = 0; + +/** + * @engineInternal + */ +export function _setSorting2DCount (v: number): void { + sorting2DCount = v; + if (JSB) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error + n2d.Batcher2d.setSorting2DCount(v); + } +} + const _dsInfo = new DescriptorSetInfo(null!); const m4_1 = new Mat4(); +interface RecordedRendererInfo { + uiRenderer: UIRenderer | null; + finalOpacity: number; // float + opacityDirty: boolean; +} + +const recordedRendererInfoPool = new RecyclePool(() => ({ + uiRenderer: null, + finalOpacity: 0, + opacityDirty: false, +}), 128); /** * @en UI rendering process @@ -81,8 +106,10 @@ export class Batcher2D implements IBatcher { this._currStaticRoot = value; } + /** + * @deprecated since v3.8.7 + */ set currIsStatic (value: boolean) { - this._currIsStatic = value; } public declare device: Device; @@ -107,7 +134,6 @@ export class Batcher2D implements IBatcher { private _currSamplerHash = 0; private _currLayer = 0; private _currDepthStencilStateStage: Stage | null = null; - private _currIsStatic = false; private _currHash = 0; //for middleware @@ -130,17 +156,25 @@ export class Batcher2D implements IBatcher { private _maskClearMtl: Material | null = null; private _maskModelMesh: RenderingSubMesh | null = null; + private _recordedRendererInfoQueue: RecordedRendererInfo[] = []; + constructor (private _root: Root) { this.device = _root.device; this._batches = new CachedArray(64); this._drawBatchPool = new Pool(() => new DrawBatch2D(), 128, (obj) => obj.destroy(this)); } + private getRecordedRendererInfoQueue (): RecordedRendererInfo[] { + return this._recordedRendererInfoQueue; + } + public initialize (): boolean { return true; } public destroy (): void { + this._recordedRendererInfoQueue.length = 0; + for (let i = 0; i < this._batches.length; i++) { if (this._batches.array[i]) { this._batches.array[i].destroy(this); @@ -240,6 +274,7 @@ export class Batcher2D implements IBatcher { if (JSB) { return; } + const screens = this._screens; let offset = 0; for (let i = 0; i < screens.length; ++i) { @@ -254,6 +289,10 @@ export class Batcher2D implements IBatcher { this.walk(screen.node); + if (USE_SORTING_2D && sorting2DCount > 0) { + this._flushRecordedUIRenderers(); + } + this.autoMergeBatches(this._currComponent!); this.resetRenderStates(); @@ -274,6 +313,10 @@ export class Batcher2D implements IBatcher { } } } + + if (USE_SORTING_2D && sorting2DCount > 0) { + recordedRendererInfoPool.reset(); + } } public uploadBuffers (): void { @@ -792,13 +835,81 @@ export class Batcher2D implements IBatcher { this._currMaterial = mat; } + private _handleUIRenderer (render: UIRenderer, finalOpacity: number, opacityDirty: boolean): void { + const renderData = render ? render.renderData : null; + const vertexCount = renderData ? renderData.vertexCount : 0; + + // Render assembler update logic + if (render && render.enabledInHierarchy) { + render.fillBuffers(this);// for rendering + } + + // Update cascaded opacity to vertex buffer + if (opacityDirty && vertexCount > 0) { + // HARD COUPLING + switch (render.getFillColorType()) { + case RenderEntityFillColorType.COLOR: { + updateOpacity(renderData!, finalOpacity); + break; + } + case RenderEntityFillColorType.VERTEX: { + // Use vertex color directly, so do nothing here. + break; + } + default: + break; + } + + const buffer = renderData!.getMeshBuffer(); + if (buffer) { + buffer.setDirty(); + } + } + } + + private _recordUIRenderer (render: UIRenderer, finalOpacity: number, opacityDirty: boolean): RecordedRendererInfo { + if (!USE_SORTING_2D) return null!; + const queue = this.getRecordedRendererInfoQueue(); + const info = recordedRendererInfoPool.add(); + info.uiRenderer = render; + info.finalOpacity = finalOpacity; + info.opacityDirty = opacityDirty; + queue.push(info); + return info; + } + + private _flushRecordedUIRenderers (): void { + if (!USE_SORTING_2D) return; + const queue = this.getRecordedRendererInfoQueue(); + const length = queue.length; + if (length === 0) return; + + queue.sort((a, b) => a.uiRenderer!.priority - b.uiRenderer!.priority); + + for (let i = 0; i < length; i++) { + const info = queue[i]; + const render = info.uiRenderer; + + if (render) { + this._handleUIRenderer(render, info.finalOpacity, info.opacityDirty); + if (render.enabledInHierarchy) { + render.postUpdateAssembler(this); + } + } + info.finalOpacity = 1; + info.opacityDirty = false; + info.uiRenderer = null; + } + queue.length = 0; + } + public walk (node: Node, level = 0): void { if (!node.activeInHierarchy) { return; } const children = node.children; const uiProps = node._uiProps; - const render = uiProps.uiComp as UIRenderer; + const render = uiProps.uiComp as UIRenderer | null; // Save opacity const parentOpacity = this._pOpacity; @@ -808,38 +919,24 @@ export class Batcher2D implements IBatcher { this._pOpacity = opacity *= selfOpacity * uiProps.localOpacity; // TODO Set opacity to ui property's opacity before remove it uiProps.setOpacity(opacity); - if (!approx(opacity, 0, EPSILON)) { - const renderData = render ? render.renderData : null; - const vertexCount = renderData ? renderData.vertexCount : 0; + + const visable = !approx(opacity, 0, EPSILON); + if (visable) { if (uiProps.colorDirty) { - // Cascade color dirty state + // Cascade color dirty state this._opacityDirty++; } + if (render) { + if (USE_SORTING_2D && sorting2DCount > 0) { + if (render.stencilStage === Stage.ENTER_LEVEL || render.stencilStage === Stage.ENTER_LEVEL_INVERTED) { + this._flushRecordedUIRenderers(); - // Render assembler update logic - if (render && render.enabledInHierarchy) { - render.fillBuffers(this);// for rendering - } - - // Update cascaded opacity to vertex buffer - if (this._opacityDirty && vertexCount > 0) { - // HARD COUPLING - switch (render.getFillColorType()) { - case RenderEntityFillColorType.COLOR: { - updateOpacity(renderData!, opacity); - break; - } - case RenderEntityFillColorType.VERTEX: { - // Use vertex color directly, so do nothing here. - break; - } - default: - break; - } - - const buffer = renderData!.getMeshBuffer(); - if (buffer) { - buffer.setDirty(); + this.autoMergeBatches(this._currComponent!); + this.resetRenderStates(); + } + this._recordUIRenderer(render, opacity, !!this._opacityDirty); + } else { + this._handleUIRenderer(render, opacity, !!this._opacityDirty); } } @@ -863,12 +960,19 @@ export class Batcher2D implements IBatcher { // Post render assembler update logic // ATTENTION: Will also reset colorDirty inside postUpdateAssembler if (render && render.enabledInHierarchy) { - render.postUpdateAssembler(this); - if ((render.stencilStage === Stage.ENTER_LEVEL || render.stencilStage === Stage.ENTER_LEVEL_INVERTED) - && (StencilManager.sharedManager!.getMaskStackSize() > 0)) { - this.autoMergeBatches(this._currComponent!); - this.resetRenderStates(); - StencilManager.sharedManager!.exitMask(); + if (!USE_SORTING_2D) { + render.postUpdateAssembler(this); + } + if (visable && (render.stencilStage === Stage.ENTER_LEVEL || render.stencilStage === Stage.ENTER_LEVEL_INVERTED)) { + if (USE_SORTING_2D && sorting2DCount > 0) { + this._flushRecordedUIRenderers(); + } + + if (StencilManager.sharedManager!.getMaskStackSize() > 0) { + this.autoMergeBatches(this._currComponent!); + this.resetRenderStates(); + StencilManager.sharedManager!.exitMask(); + } } } @@ -932,16 +1036,16 @@ export class Batcher2D implements IBatcher { this.resetRenderStates(); this._createClearModel(); this._maskClearModel!.node = this._maskClearModel!.transform = comp.node; - const _stencilManager = StencilManager.sharedManager!; - _stencilManager.pushMask(1);//not need object,only use length - const stage = _stencilManager.clear(comp); //invert + const stencilManager = StencilManager.sharedManager!; + stencilManager.pushMask(1);//not need object,only use length + const stage = stencilManager.clear(comp); //invert let depthStencil: DepthStencilState | null = null; let dssHash = 0; const mat = this._maskClearMtl; if (mat) { - depthStencil = _stencilManager.getStencilStage(stage, mat); - dssHash = _stencilManager.getStencilHash(stage); + depthStencil = stencilManager.getStencilStage(stage, mat); + dssHash = stencilManager.getStencilHash(stage); } const model = this._maskClearModel!; @@ -966,7 +1070,7 @@ export class Batcher2D implements IBatcher { curDrawBatch.descriptorSet = subModel.descriptorSet; this._batches.push(curDrawBatch); } - _stencilManager.enableMask(); + stencilManager.enableMask(); } //sync mesh buffer to naive @@ -1096,7 +1200,6 @@ class DescriptorSetCache { } public getDescriptorSet (batch: DrawBatch2D): DescriptorSet { - const root = cclegacy.director.root; if (batch.useLocalData) { const caches = this._localDescriptorSetCache; for (let i = 0, len = caches.length; i < len; i++) { diff --git a/cocos/2d/renderer/native-2d.ts b/cocos/2d/renderer/native-2d.ts index 40ea755c6e..555fb919b4 100644 --- a/cocos/2d/renderer/native-2d.ts +++ b/cocos/2d/renderer/native-2d.ts @@ -108,6 +108,7 @@ export declare class NativeBatcher2d { syncMeshBuffersToNative(accId: number, buffers: NativeUIMeshBuffer[]); update(); uploadBuffers(); + setSorting2DCount(count: number); reset(); syncRootNodesToNative(nodes: Node[]); releaseDescriptorSetCache(texture: Texture, sampler: Sampler); diff --git a/cocos/2d/renderer/render-entity.ts b/cocos/2d/renderer/render-entity.ts index df233ca2d2..82da5ac980 100644 --- a/cocos/2d/renderer/render-entity.ts +++ b/cocos/2d/renderer/render-entity.ts @@ -40,6 +40,11 @@ export enum RenderEntityType { CROSSED, } +enum RenderEntityUInt32SharedBufferView { + priority, + count, +} + enum RenderEntityUInt8SharedBufferView { colorR, colorG, @@ -79,7 +84,7 @@ export class RenderEntity { protected _useLocal = false; protected _maskMode = MaskMode.NONE; - protected declare _floatSharedBuffer: Float32Array; + protected declare _uint32SharedBuffer: Uint32Array; protected declare _uint8SharedBuffer: Uint8Array; protected declare _boolSharedBuffer: Uint8Array; @@ -99,6 +104,12 @@ export class RenderEntity { // this._renderEntityType = val; // } + setPriority (val: number): void { + if (JSB) { + this._uint32SharedBuffer[RenderEntityUInt32SharedBufferView.priority] = val; + } + } + protected _color: Color = Color.WHITE.clone(); get color (): Color { return this._color; @@ -267,9 +278,10 @@ export class RenderEntity { private initSharedBuffer (): void { if (JSB) { - //this._sharedBuffer = new Float32Array(RenderEntitySharedBufferView.count); const buffer = this._nativeObj.getEntitySharedBufferForJS(); let offset = 0; + this._uint32SharedBuffer = new Uint32Array(buffer, offset, RenderEntityUInt32SharedBufferView.count); + offset += RenderEntityUInt32SharedBufferView.count * 4; this._uint8SharedBuffer = new Uint8Array(buffer, offset, RenderEntityUInt8SharedBufferView.count); offset += RenderEntityUInt8SharedBufferView.count * 1; this._boolSharedBuffer = new Uint8Array(buffer, offset, 1); // Only use 1 bytes for at most 8 booleans diff --git a/cocos/core/value-types/enum.ts b/cocos/core/value-types/enum.ts index dd56193949..d26bd9205b 100644 --- a/cocos/core/value-types/enum.ts +++ b/cocos/core/value-types/enum.ts @@ -172,7 +172,7 @@ function updateList (enumType: EnumT): readonly Enum.Enume * @param enumType @en The enum type defined from [[Enum]] @zh 从[[Enum]]定义的枚举类型。 * @param compareFn @en Function used to determine the order of the elements. @zh 用于确定元素顺序的函数。 */ -Enum.sortList = (enumType: EnumT, compareFn: (a, b) => number): void => { +Enum.sortList = (enumType: EnumT, compareFn: (a: Enum.Enumerator, b: Enum.Enumerator) => number): void => { assertIsEnum(enumType); if (!Array.isArray(enumType.__enums__)) { return; diff --git a/cocos/sorting/sorting-2d.ts b/cocos/sorting/sorting-2d.ts new file mode 100644 index 0000000000..b7fe532569 --- /dev/null +++ b/cocos/sorting/sorting-2d.ts @@ -0,0 +1,115 @@ +/* + Copyright (c) 2025 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 { ccclass, disallowMultiple, editable, executeInEditMode, help, menu, range, serializable, type, requireComponent } from 'cc.decorator'; +import { clamp } from '../core/math'; +import { SortingLayers } from './sorting-layers'; +import { Component } from '../scene-graph/component'; +import { warnID } from '../core/platform/debug'; +import { UIRenderer } from '../2d/framework/ui-renderer'; +import { _setSorting2DCount } from '../2d/renderer/batcher-2d'; + +const MAX_INT16 = (1 << 15) - 1; +const MIN_INT16 = -1 << 15; + +let sorting2DCount = 0; + +/** + * @en + * 2D Render sort component. + * + * @zh + * 2D 渲染排序组件。 + */ +@ccclass('cc.Sorting2D') +@menu('Sorting/Sorting2D') +@help('i18n:cc.Sorting2D') +@disallowMultiple +@executeInEditMode +@requireComponent(UIRenderer) +export class Sorting2D extends Component { + constructor () { + super(); + } + + /** + * @zh 组件所属排序层 id,影响组件的渲染排序。 + * @en The sorting layer id of the component, which affects the rendering order of the component. + */ + @editable + @type(SortingLayers.Enum) + get sortingLayer (): number { + return this._sortingLayer; + } + set sortingLayer (val) { + if (val === this._sortingLayer || !SortingLayers.isLayerValid(val)) return; + this._sortingLayer = val; + this._updateSortingPriority(); + } + + /** + * @zh 组件在当前排序层中的顺序,在默认排序规则中,越小越先渲染。 + * @en Model Renderer's order within a sorting layer. In the default sorting rule, smaller values are rendered first. + */ + @range([MIN_INT16, MAX_INT16, 1]) + get sortingOrder (): number { + return this._sortingOrder; + } + set sortingOrder (val) { + if (val === this._sortingOrder) return; + this._sortingOrder = clamp(val, MIN_INT16, MAX_INT16); + this._updateSortingPriority(); + } + + @serializable + protected _sortingLayer = SortingLayers.Enum.default; // Actually saved id + @serializable + protected _sortingOrder = 0; + + private _uiRenderer: UIRenderer | null = null; + + protected override __preload (): void { + this._uiRenderer = this.getComponent(UIRenderer); + if (!this._uiRenderer) { + warnID(16300, this.node.name); + } + this._updateSortingPriority(); + + ++sorting2DCount; + _setSorting2DCount(sorting2DCount); + } + + protected override onDestroy (): void { + --sorting2DCount; + _setSorting2DCount(sorting2DCount); + } + + protected _updateSortingPriority (): void { + const sortingLayerValue = SortingLayers.getLayerIndex(this._sortingLayer); + const sortingPriority = SortingLayers.getSortingPriority(sortingLayerValue, this._sortingOrder); + if (this._uiRenderer) { + this._uiRenderer.priority = sortingPriority; + } + } +} diff --git a/cocos/sorting/sorting-layers.ts b/cocos/sorting/sorting-layers.ts index 58b1ce23a2..50f9a2ff4a 100644 --- a/cocos/sorting/sorting-layers.ts +++ b/cocos/sorting/sorting-layers.ts @@ -111,7 +111,7 @@ export class SortingLayers { const keyIterator = this.nameMap.keys(); let key = 0; for (let i = 0; i < count; i++) { - key = keyIterator.next().value; + key = keyIterator.next().value as number; if (this.nameMap.get(key) === name) return key; } errorID(2106); diff --git a/editor/engine-features/render-config.json b/editor/engine-features/render-config.json index 2a5c40e2c6..b1cc18050e 100644 --- a/editor/engine-features/render-config.json +++ b/editor/engine-features/render-config.json @@ -71,6 +71,16 @@ "readonly": false, "enginePlugin": true }, + "sorting-2d": { + "default": false, + "label": "i18n:ENGINE.features.sorting_2d.label", + "description": "i18n:ENGINE.features.sorting_2d.description", + "category": "2d", + "dependencies": [ + "2d" + ], + "enginePlugin": true + }, "xr": { "default": false, "label": "i18n:ENGINE.features.xr.label", diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 81b4d170a1..133f5be1f2 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -165,6 +165,7 @@ module.exports = link(mixin({ RenderRoot2D: `${url}/${version}/manual/en/ui-system/components/editor/renderroot2d.html`, ReflectionProbe: `${url}/${version}/manual/en/concepts/scene/light/probe/reflection-art-workflow.html`, Sorting: `${url}/${version}/manual/en/engine/rendering/sorting.html`, + Sorting2D: `${url}/${version}/manual/en/engine/rendering/sorting-2d.html`, }, assets: { javascript: `${url}/${version}/manual/en/concepts/scripting/plugin-scripts.html`, @@ -975,6 +976,10 @@ module.exports = link(mixin({ label: "Basic 2D Features", description: "Components and tools that are widely used in general 2D applications.", }, + sorting_2d: { + label: "2D Rendering Sorting", + description: "Sorting UIRenderers by the configuration in Sorting2D component.", + }, rich_text: { label: "Rich Text", description: "Rich text support.", diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index baafc971a3..83bfe99a7a 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -165,6 +165,7 @@ module.exports = link(mixin({ RenderRoot2D: `${url}/${version}/manual/zh/ui-system/components/editor/renderroot2d.html`, ReflectionProbe: `${url}/${version}/manual/zh/concepts/scene/light/probe/reflection-art-workflow.html`, Sorting: `${url}/${version}/manual/zh/engine/rendering/sorting.html`, + Sorting2D: `${url}/${version}/manual/zh/engine/rendering/sorting-2d.html`, }, assets: { javascript: `${url}/${version}/manual/zh/concepts/scripting/plugin-scripts.html`, @@ -953,6 +954,10 @@ module.exports = link(mixin({ label: "基础 2D 功能", description: "常用于一般 2D 应用的工具与组件。", }, + sorting_2d: { + label: "2D 渲染排序", + description: "根据 Sorting2D 组件中的配置对 UIRenderer 进行排序。", + }, rich_text: { label: "富文本", description: "富文本支持。", diff --git a/exports/sorting-2d.ts b/exports/sorting-2d.ts new file mode 100644 index 0000000000..abcec05068 --- /dev/null +++ b/exports/sorting-2d.ts @@ -0,0 +1,27 @@ +/* + Copyright (c) 2025 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +export { SortingLayers } from '../cocos/sorting/sorting-layers'; +export { Sorting2D } from '../cocos/sorting/sorting-2d'; diff --git a/native/cocos/2d/renderer/Batcher2d.cpp b/native/cocos/2d/renderer/Batcher2d.cpp index 4cc38f67e6..81efeaebf9 100644 --- a/native/cocos/2d/renderer/Batcher2d.cpp +++ b/native/cocos/2d/renderer/Batcher2d.cpp @@ -35,6 +35,9 @@ namespace cc { namespace { +const bool ENABLE_SORTING_2D = true; +int32_t sorting2DCount{0}; + CC_FORCE_INLINE void fillIndexBuffers(RenderDrawInfo* drawInfo) { // NOLINT(readability-convert-member-functions-to-static) uint16_t* ib = drawInfo->getIDataBuffer(); @@ -107,6 +110,8 @@ Batcher2d::Batcher2d(Root* root) _root = root; _device = _root->getDevice(); _stencilManager = StencilManager::getInstance(); + + _recordedRendererInfoQueue.reserve(100); } Batcher2d::~Batcher2d() { // NOLINT @@ -133,6 +138,10 @@ Batcher2d::~Batcher2d() { // NOLINT _maskAttributes.clear(); } +ccstd::vector &Batcher2d::getRecordedRendererInfoQueue() { + return _recordedRendererInfoQueue; +} + void Batcher2d::syncMeshBuffersToNative(uint16_t accId, ccstd::vector&& buffers) { _meshBuffersMap[accId] = std::move(buffers); } @@ -161,6 +170,11 @@ void Batcher2d::fillBuffersAndMergeBatches() { for (auto* rootNode : _rootNodeArr) { // _batches will add by generateBatch walk(rootNode, 1, false); + + if (ENABLE_SORTING_2D && sorting2DCount > 0) { + flushRecordedUIRenderers(); + } + generateBatch(_currEntity, _currDrawInfo); auto* scene = rootNode->getScene()->getRenderScene(); @@ -172,6 +186,41 @@ void Batcher2d::fillBuffersAndMergeBatches() { } } +void Batcher2d::handleUIRenderer(RenderEntity *entity) { // NOLINT(misc-no-recursion) + uint32_t size = entity->getRenderDrawInfosSize(); + for (uint32_t i = 0; i < size; i++) { + auto* drawInfo = entity->getRenderDrawInfoAt(i); + handleDrawInfo(entity, drawInfo, entity->getNode()); + } + entity->setVBColorDirty(false); +} + +int32_t Batcher2d::recordUIRenderer(RenderEntity *entity) { + if (!ENABLE_SORTING_2D) return -1; + auto &queue = getRecordedRendererInfoQueue(); + auto &info = queue.emplace_back(); + info.renderEntity = entity; + return static_cast(queue.size() - 1); +} + +void Batcher2d::flushRecordedUIRenderers() { // NOLINT(misc-no-recursion) + if (!ENABLE_SORTING_2D) return; + auto &queue = getRecordedRendererInfoQueue(); + if (queue.empty()) return; + + std::stable_sort(queue.begin(), queue.end(), [](const auto &a, const auto &b){ + return a.renderEntity->getPriority() < b.renderEntity->getPriority(); + }); + + for (const auto &info : queue) { + auto *entity = info.renderEntity; + if (entity) { + handleUIRenderer(entity); + } + } + queue.clear(); +} + void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { // NOLINT(misc-no-recursion) if (!node->isActiveInHierarchy()) { return; @@ -184,9 +233,11 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { / // Keep the same logic as which in batcher-2d.ts const float finalOpacity = parentOpacity * localOpacity * (entity ? entity->getColorAlpha() : 1.F); node->_setFinalOpacity(finalOpacity); + + const bool visible = math::isNotEqualF(finalOpacity, 0); if (entity) { - if (math::isEqualF(finalOpacity, 0)) { + if (!visible) { breakWalk = true; } else if (entity->isEnabled()) { if (isCurrentColorDirty) { @@ -194,12 +245,17 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { / entity->setVBColorDirty(true); } - uint32_t size = entity->getRenderDrawInfosSize(); - for (uint32_t i = 0; i < size; i++) { - auto* drawInfo = entity->getRenderDrawInfoAt(i); - handleDrawInfo(entity, drawInfo, node); + if (ENABLE_SORTING_2D && sorting2DCount > 0) { + if (entity->getIsMask()) { + flushRecordedUIRenderers(); + + generateBatch(_currEntity, _currDrawInfo); + resetRenderStates(); + } + recordUIRenderer(entity); + } else { + handleUIRenderer(entity); } - entity->setVBColorDirty(false); } if (entity->getRenderEntityType() == RenderEntityType::CROSSED) { @@ -221,8 +277,16 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { / } // post assembler - if (_stencilManager->getMaskStackSize() > 0 && entity && entity->isEnabled()) { - handlePostRender(entity); + if (entity && entity->isEnabled()) { + if (ENABLE_SORTING_2D && sorting2DCount > 0) { + if (visible && entity->getIsMask()) { + flushRecordedUIRenderers(); + } + } + + if (_stencilManager->getMaskStackSize() > 0) { + handlePostRender(entity); + } } } @@ -234,6 +298,7 @@ void Batcher2d::handlePostRender(RenderEntity* entity) { _stencilManager->exitMask(); } } + CC_FORCE_INLINE void Batcher2d::handleComponentDraw(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node) { ccstd::hash_t dataHash = drawInfo->getDataHash(); if (drawInfo->getIsMeshBuffer()) { @@ -700,4 +765,9 @@ void Batcher2d::createClearModel() { _maskClearModel->initSubModel(0, _maskModelMesh, _maskClearMtl); } } + +void Batcher2d::setSorting2DCount(int32_t v) { + sorting2DCount = v; +} + } // namespace cc diff --git a/native/cocos/2d/renderer/Batcher2d.h b/native/cocos/2d/renderer/Batcher2d.h index 72be563bfa..2eb3410205 100644 --- a/native/cocos/2d/renderer/Batcher2d.h +++ b/native/cocos/2d/renderer/Batcher2d.h @@ -40,8 +40,14 @@ class Root; using UIMeshBufferArray = ccstd::vector; using UIMeshBufferMap = ccstd::unordered_map; +struct RecordedRendererInfo { + RenderEntity *renderEntity{nullptr}; +}; + class Batcher2d final { public: + static void setSorting2DCount(int32_t v); + Batcher2d(); explicit Batcher2d(Root* root); ~Batcher2d(); @@ -81,6 +87,11 @@ private: void createClearModel(); gfx::DescriptorSet* getDescriptorSet(gfx::Texture* texture, gfx::Sampler* sampler, const gfx::DescriptorSetLayout* dsLayout); + + ccstd::vector &getRecordedRendererInfoQueue(); + void handleUIRenderer(RenderEntity *entity); + int32_t recordUIRenderer(RenderEntity *entity); + void flushRecordedUIRenderers(); StencilManager* _stencilManager{nullptr}; @@ -92,6 +103,8 @@ private: // manage memory manually ccstd::vector _batches; memop::Pool _drawBatchPool; + + ccstd::vector _recordedRendererInfoQueue; // weak reference gfx::Device* _device{nullptr}; // use getDevice() diff --git a/native/cocos/2d/renderer/RenderEntity.h b/native/cocos/2d/renderer/RenderEntity.h index 0a3e4d751e..f1677eded5 100644 --- a/native/cocos/2d/renderer/RenderEntity.h +++ b/native/cocos/2d/renderer/RenderEntity.h @@ -55,6 +55,7 @@ enum class FillColorType: uint8_t { }; struct EntityAttrLayout { + uint32_t priority{0}; uint8_t colorR{255}; uint8_t colorG{255}; uint8_t colorB{255}; @@ -64,9 +65,10 @@ struct EntityAttrLayout { uint8_t enabledIndex: 1; uint8_t useLocal: 1; uint8_t paddings: 6; + uint8_t paddings2{0}; }; -static_assert(sizeof(EntityAttrLayout) == 7, "Be carefull to add property to EntityAttrLayout which may cause the potential cache miss"); +static_assert(sizeof(EntityAttrLayout) == 12, "Be carefull to add property to EntityAttrLayout which may cause the potential cache miss"); class RenderEntity final : public Node::UserData { public: @@ -140,6 +142,8 @@ public: inline RenderDrawInfo* getRenderDrawInfoAt(uint32_t index) { return _renderEntityType == RenderEntityType::STATIC ? &(_staticDrawInfos[index]) : _dynamicDrawInfos[index]; } + + inline uint32_t getPriority() const { return _entityAttrLayout.priority; } private: CC_DISALLOW_COPY_MOVE_ASSIGN(RenderEntity); @@ -167,7 +171,7 @@ private: }; #if defined(__x86_64__) || defined(__amd64__) || defined(__aarch64__) -static_assert(sizeof(RenderEntity) == 632, "Be carefull to add property to RenderEntity which may cause the potential cache miss"); +static_assert(sizeof(RenderEntity) == 640, "Be carefull to add property to RenderEntity which may cause the potential cache miss"); #endif } // namespace cc