sorting component add (#12465)

* sorting component add

* menu add

* change sorting layer type to enum

* import fix

* name change

* sorting init

* fix init

* update priority on editor

* add enum index

* sort fix

* api doc add

* remove export to cc

* doc change

* protect

* warn id

Co-authored-by: ChiaNing <sun.clooud.mo@gmail.com>
This commit is contained in:
ChiaNing
2022-09-15 10:15:33 +08:00
committed by GitHub
parent cc01929094
commit 2afd02e711
8 changed files with 356 additions and 2 deletions
+5 -1
View File
@@ -3306,4 +3306,8 @@ The effect('%s') you are looking for does not exist, please confirm the effect n
### 16201
The asset replacing failed, can not found override asset('%s') for '%s'
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
+1 -1
View File
@@ -26,7 +26,7 @@
"animation": { "modules": ["animation"] },
"skeletal-animation": { "modules": ["animation", "skeletal-animation"] },
"2d": {
"modules": [ "2d" ],
"modules": [ "2d", "sorting" ],
"dependentAssets": [
"60f7195c-ec2a-45eb-ba94-8955f60e81d0",
"1c02ae6f-4492-4915-b8f8-7492a3b1e4cd",
+1
View File
@@ -24,6 +24,7 @@
*/
import './component-event-handler.schema';
export { default as System } from './system';
export { default as MissingScript } from './missing-script';
export { EventHandler } from './component-event-handler';
+13
View File
@@ -155,6 +155,19 @@ function updateList<EnumT extends {}> (enumType: EnumT): readonly Enum.Enumerato
return enums;
}
/**
* Reorder the enumerators in the enumeration type by compareFunction.
* @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 = <EnumT extends {}> (enumType: EnumT, compareFn: (a, b) => number) => {
assertIsEnum(enumType);
if (!Array.isArray(enumType.__enums__)) {
return;
}
enumType.__enums__.sort(compareFn);
};
if (DEV) {
// check key order in object literal
const _TestEnum = Enum({
+27
View File
@@ -0,0 +1,27 @@
/*
Copyright (c) 2022 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
export { SortingLayers } from './sorting-layers';
export { Sorting } from './sorting';
+184
View File
@@ -0,0 +1,184 @@
/*
Copyright (c) 2022 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { EDITOR } from 'internal:constants';
import { director } from '../core/director';
import { Game, game } from '../core/game';
import { errorID } from '../core/platform/debug';
import { Settings, settings } from '../core/settings';
import { Enum } from '../core/value-types';
interface SortingItem {
id: number;
name: string;
value: number;
}
const SortingLayer = {
default: 0,
};
game.on(Game.EVENT_POST_SUBSYSTEM_INIT, () => {
SortingLayers.init();
});
/**
* @zh 排序层管理器,用于在 sorting 组件中帮助用户进行对象分组并进行层级排序。
* 在sorting组件中,layer 的排序优先级高于 sortingOrder。
* @en Sorting layers manager, Used in the sorting component to help the user group objects and perform layer sorting.
* In the sorting component, layer has higher sorting priority than sortingOrder.
* */
export class SortingLayers {
private static nameMap = new Map<number, string>();
private static indexMap = new Map<number, number>();
/**
* @en All sortinglayers in an Enum
* @zh 以 Enum 形式存在的所有排序层列表
*/
public static Enum = Enum(SortingLayer);
/**
* @zh 计算排序优先级
* @en Calculate sorting priority
*/
public static getSortingPriority (layer = 0, order = 0): number {
return (((layer + (1 << 15)) << 16) | (order + (1 << 15))) >>> 0;
}
/**
* @zh 获取 Layer 顺序索引
* @en Get Layer index by id
*/
public static getLayerIndex (layer = 0): number {
let index = 0;
if (this.indexMap.has(layer)) {
index = this.indexMap.get(layer)!;
} else {
errorID(2105);
}
return index;
}
/**
* @zh 通过 Layer 名字获取 Layer 顺序索引值
* @en Get Layer index by name
*/
public static getLayerIndexByName (name: string): number {
const id = this.getLayerByName(name);
return this.getLayerIndex(id);
}
/**
* @zh 获取 Layer 名字
* @en Get Layer name by id
*/
public static getLayerName (layer = 0): string {
let name = '';
if (this.nameMap.has(layer)) {
name = this.nameMap.get(layer)!;
} else {
errorID(2105);
}
return name;
}
/**
* @zh 通过 Layer 名字获取 Layer id 值
* @en Get Layer id by name
*/
public static getLayerByName (name: string): number {
const count = this.nameMap.size;
const keyIterator = this.nameMap.keys();
let key = 0;
for (let i = 0; i < count; i++) {
key = keyIterator.next().value;
if (this.nameMap.get(key) === name) return key;
}
errorID(2106);
return 0;
}
/**
* @zh 检查 Layer id 有效性
* @en Check Layer id validity
*/
public static isLayerValid (id: number): boolean {
// check valid
if (this.indexMap.has(id)) {
return true;
} else {
errorID(2105);
return false;
}
}
/**
* @engineInternal
*/
public static init () {
const sortingLayers = settings.querySettings<SortingItem[]>(Settings.Category.ENGINE, 'sortingLayers');
if (!sortingLayers) return;
SortingLayers.resetState();
for (let i = 0; i < sortingLayers.length; i++) {
const layer = sortingLayers[i];
SortingLayers.setLayer(layer.id, layer.name, layer.value);
SortingLayers.Enum[layer.name] = layer.id;
}
Enum.update(SortingLayers.Enum);
Enum.sortList(SortingLayers.Enum, (a, b) => SortingLayers.getLayerIndex(a.value) - SortingLayers.getLayerIndex(b.value));
if (EDITOR) {
const scene = director.getScene();
if (!scene) {
return;
}
scene.walk((node) => {
const sort = node.getComponent('cc.Sorting');
if (sort) {
// @ts-expect-error private method
sort._updateSortingPriority();
}
});
}
}
/**
* @engineInternal
*/
public static setLayer (layer, layerName, layerIndex) {
this.nameMap.set(layer, layerName);
this.indexMap.set(layer, layerIndex);
}
/**
* @engineInternal
*/
private static resetState () {
const oldItem = Object.keys(SortingLayers.Enum);
for (let i = 0; i < oldItem.length; i++) {
delete SortingLayers.Enum[SortingLayers.Enum[oldItem[i]]];
delete SortingLayers.Enum[oldItem[i]];
}
SortingLayers.indexMap.clear();
SortingLayers.nameMap.clear();
}
}
+99
View File
@@ -0,0 +1,99 @@
/*
Copyright (c) 2022 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { ccclass, disallowMultiple, editable, executeInEditMode, menu, range, serializable, type } from 'cc.decorator';
import { clamp } from '../core/math';
import { SortingLayers } from './sorting-layers';
import { Component } from '../core/components/component';
import { ModelRenderer } from '../core/components/model-renderer';
import { warnID } from '../core/platform/debug';
const MAX_INT16 = (1 << 15) - 1;
const MIN_INT16 = -1 << 15;
/**
* @en
* Render sort component. This component must be placed on a node with a [[MeshRenderer]] or [[SpriteRenderer]] component.
*
* @zh
* 渲染排序组件。该组件必须放置在带有 [[MeshRenderer]] 或者 [[SpriteRenderer]] 组件的节点上。
*/
@ccclass('cc.Sorting')
@menu('Sorting/Sorting')
@disallowMultiple
@executeInEditMode
export class Sorting extends Component {
/**
* @zh 组件所属排序层 id,影响组件的渲染排序。
* @en The sorting layer id of the component, which affects the rendering order of the component.
*/
@editable
@type(SortingLayers.Enum)
get sortingLayer () {
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 () {
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 _modelRenderer: ModelRenderer | null = null;
protected __preload () {
this._modelRenderer = this.getComponent('cc.ModelRenderer') as ModelRenderer;
if (!this._modelRenderer) {
warnID(16301, this.node.name);
}
this._updateSortingPriority();
}
protected _updateSortingPriority () {
const sortingLayerValue = SortingLayers.getLayerIndex(this._sortingLayer);
const sortingPriority = SortingLayers.getSortingPriority(sortingLayerValue, this._sortingOrder);
if (this._modelRenderer && this._modelRenderer.isValid) {
this._modelRenderer.priority = sortingPriority;
}
}
}
+26
View File
@@ -0,0 +1,26 @@
/*
Copyright (c) 2022 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
export * from '../cocos/sorting';