diff --git a/EngineErrorMap.md b/EngineErrorMap.md index b707f1cf3d..c9f1ff2518 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -2467,6 +2467,10 @@ cc.ParticleSystem: not allowing create to be invoked twice with different partic cc.ParticleSystem: shouldn't be initialized repetitively, otherwise there will be potential leak +### 6035 + +cc.ParticleSystem: change material failed, please use proper particle material + ### 6100 diff --git a/cc.config.json b/cc.config.json index 412737ccc1..5deee558bc 100644 --- a/cc.config.json +++ b/cc.config.json @@ -2,7 +2,7 @@ "$schema": "./cc.config.schema.json", "features": { - "base": { "modules": [ "base", "native" ], "dependentAssets": [ + "base": { "modules": [ "base" ], "dependentAssets": [ "ff9be190-20a4-4e48-b68c-76e3c7cff085", "970b0598-bcb0-4714-91fb-2e81440dccd8", "bcd64cc6-2dd9-43f6-abbe-66318d332032", @@ -431,7 +431,7 @@ "SUPPORT_JIT": { "comment": "Support JIT.", "type": "boolean", - "value": "!($MINIGAME || $RUNTIME_BASED)", + "value": "!(($PREVIEW && !$NATIVE) || $MINIGAME || $RUNTIME_BASED)", "ccGlobal": true, "internal": false }, diff --git a/cocos/2d/assembler/sprite/simple.ts b/cocos/2d/assembler/sprite/simple.ts index 8456f4e33d..d81ae70d3a 100644 --- a/cocos/2d/assembler/sprite/simple.ts +++ b/cocos/2d/assembler/sprite/simple.ts @@ -172,23 +172,16 @@ export const simple: IAssembler = { t = ch - appY; } else { const frame = sprite.spriteFrame!; - const originSize = frame.getOriginalSize(); - const rect = frame.getRect(); + const originSize = frame.originalSize; const ow = originSize.width; const oh = originSize.height; - const rw = rect.width; - const rh = rect.height; - const offset = frame.getOffset(); const scaleX = cw / ow; const scaleY = ch / oh; - const trimLeft = offset.x + (ow - rw) / 2; - const trimRight = offset.x - (ow - rw) / 2; - const trimBottom = offset.y + (oh - rh) / 2; - const trimTop = offset.y - (oh - rh) / 2; - l = trimLeft * scaleX - appX; - b = trimBottom * scaleY - appY; - r = cw + trimRight * scaleX - appX; - t = ch + trimTop * scaleY - appY; + const trimmedBorder = frame.trimmedBorder; + l = trimmedBorder.x * scaleX - appX; + b = trimmedBorder.z * scaleY - appY; + r = cw + trimmedBorder.y * scaleX - appX; + t = ch + trimmedBorder.w * scaleY - appY; } dataList[0].x = l; diff --git a/cocos/2d/assets/sprite-frame.ts b/cocos/2d/assets/sprite-frame.ts index f402ba798e..2875dfd046 100644 --- a/cocos/2d/assets/sprite-frame.ts +++ b/cocos/2d/assets/sprite-frame.ts @@ -27,7 +27,7 @@ import { ccclass } from 'cc.decorator'; import { EDITOR, TEST, BUILD } from 'internal:constants'; -import { Color, Mat4, Rect, Size, Vec2, Vec3 } from '../../core/math'; +import { Color, Mat4, Rect, Size, Vec2, Vec3, Vec4 } from '../../core/math'; import { Asset } from '../../core/assets/asset'; import { TextureBase } from '../../core/assets/texture-base'; import { legacyCC } from '../../core/global-exports'; @@ -357,6 +357,7 @@ export class SpriteFrame extends Asset { if (this._texture) { this._calculateUV(); } + this._calcTrimmedBorder(); } /** @@ -376,6 +377,7 @@ export class SpriteFrame extends Asset { if (this._texture) { this._calculateUV(); } + this._calcTrimmedBorder(); } /** @@ -391,6 +393,7 @@ export class SpriteFrame extends Asset { set offset (value) { this._offset.set(value); + this._calcTrimmedBorder(); } /** @@ -534,6 +537,13 @@ export class SpriteFrame extends Asset { return this._mesh; } + /** + * @internal + */ + get trimmedBorder () { + return this._trimmedBorder; + } + /** * @en Vertex list for the mesh type sprite frame * @zh 网格类型精灵帧的所有顶点列表 @@ -557,6 +567,8 @@ export class SpriteFrame extends Asset { // the location of the sprite on rendering texture protected _rect = new Rect(); + protected _trimmedBorder = new Vec4(); + // for trimming protected _offset = new Vec2(); @@ -823,6 +835,7 @@ export class SpriteFrame extends Asset { if (calUV && this.texture) { this._calculateUV(); } + this._calcTrimmedBorder(); } /** @@ -855,6 +868,23 @@ export class SpriteFrame extends Asset { return true; } + private _calcTrimmedBorder () { + const ow = this._originalSize.width; + const oh = this._originalSize.height; + const rw = this._rect.width; + const rh = this._rect.height; + const halfTrimmedWidth = (ow - rw) * 0.5; + const halfTrimmedHeight = (oh - rh) * 0.5; + // left + this._trimmedBorder.x = this._offset.x + halfTrimmedWidth; + // right + this._trimmedBorder.y = this._offset.x - halfTrimmedWidth; + // bottom + this._trimmedBorder.z = this._offset.y + halfTrimmedHeight; + // top + this._trimmedBorder.w = this._offset.y - halfTrimmedHeight; + } + /** * @en Make sure the mesh is available, you should call it before using the mesh * @zh 确保 mesh 可用,你应该在使用 mesh 之前调用它 @@ -1397,7 +1427,6 @@ export class SpriteFrame extends Asset { if (isReset) { this.reset(config); - this.onLoaded(); } this._checkPackable(); @@ -1406,6 +1435,10 @@ export class SpriteFrame extends Asset { } } + public onLoaded () { + this._calcTrimmedBorder(); + } + public initDefault (uuid?: string) { super.initDefault(uuid); const texture = new Texture2D(); diff --git a/cocos/2d/components/graphics.ts b/cocos/2d/components/graphics.ts index 166ffee7e2..9a70697777 100644 --- a/cocos/2d/components/graphics.ts +++ b/cocos/2d/components/graphics.ts @@ -220,6 +220,9 @@ export class Graphics extends UIRenderer { public static LineJoin = LineJoin; public static LineCap = LineCap; public impl: Impl | null = null; + /** + * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. + */ public model: scene.Model | null = null; @serializable protected _lineWidth = 1; @@ -262,12 +265,14 @@ export class Graphics extends UIRenderer { public onLoad () { super.onLoad(); - this.model = director.root!.createModel(scene.Model); - this.model.node = this.model.transform = this.node; - this._flushAssembler(); if (JSB) { this._graphicsNativeProxy.initModel(this.node); + this.model = this._graphicsNativeProxy.getModel(); + } else { + this.model = director.root!.createModel(scene.Model); + this.model.node = this.model.transform = this.node; } + this._flushAssembler(); } // hack for mask @@ -286,17 +291,22 @@ export class Graphics extends UIRenderer { public onDestroy () { this._sceneGetter = null; - if (this.model) { - director.root!.destroyModel(this.model); + if (JSB) { + this.graphicsNativeProxy.destroy(); this.model = null; - } - - const subMeshLength = this._graphicsUseSubMeshes.length; - if (subMeshLength > 0) { - for (let i = 0; i < subMeshLength; ++i) { - this._graphicsUseSubMeshes[i].destroy(); + } else { + if (this.model) { + director.root!.destroyModel(this.model); + this.model = null; + } + + const subMeshLength = this._graphicsUseSubMeshes.length; + if (subMeshLength > 0) { + for (let i = 0; i < subMeshLength; ++i) { + this._graphicsUseSubMeshes[i].destroy(); + } + this._graphicsUseSubMeshes.length = 0; } - this._graphicsUseSubMeshes.length = 0; } if (this.impl) { @@ -560,14 +570,13 @@ export class Graphics extends UIRenderer { this.impl.clear(); this._isDrawing = false; - if (this.model) { + if (JSB) { + this._graphicsNativeProxy.clear();// need native + } else if (this.model) { for (let i = 0; i < this.model.subModels.length; i++) { const subModel = this.model.subModels[i]; subModel.inputAssembler.indexCount = 0; } - if (JSB) { - this._graphicsNativeProxy.clear();// need native - } } this.markForUpdateRenderData(); @@ -726,7 +735,11 @@ export class Graphics extends UIRenderer { return false; } - return !!this.model && this._isDrawing; + if (JSB) { + return this._isDrawing; + } else { + return !!this.model && this._isDrawing; + } } public updateRenderer () { @@ -738,12 +751,7 @@ export class Graphics extends UIRenderer { for (let i = 0; i < renderDataList.length; i++) { renderDataList[i].setRenderDrawInfoAttributes(); } - const len = this.model!.subModels.length; - if (renderDataList.length > len) { - for (let i = len; i < renderDataList.length; i++) { - this._graphicsNativeProxy.activeSubModel(i); - } - } + this._graphicsNativeProxy.activeSubModels(); } this._graphicsNativeProxy.uploadData(); this._isNeedUploadData = false; diff --git a/cocos/2d/components/label.ts b/cocos/2d/components/label.ts index d6c3071a98..3dc4a31e70 100644 --- a/cocos/2d/components/label.ts +++ b/cocos/2d/components/label.ts @@ -25,7 +25,7 @@ */ import { ccclass, help, executionOrder, menu, tooltip, displayOrder, visible, multiline, type, serializable, editable } from 'cc.decorator'; -import { BYTEDANCE, EDITOR } from 'internal:constants'; +import { BYTEDANCE, EDITOR, JSB } from 'internal:constants'; import { minigame } from 'pal/minigame'; import { BitmapFont, Font, SpriteFrame } from '../assets'; import { ImageAsset, Texture2D } from '../../core/assets'; @@ -38,7 +38,9 @@ import { TextureBase } from '../../core/assets/texture-base'; import { PixelFormat } from '../../core/assets/asset-enum'; import { legacyCC } from '../../core/global-exports'; import { BlendFactor } from '../../core/gfx'; +import { Color } from '../../core'; +const tempColor = Color.WHITE.clone(); /** * @en Enum for horizontal text alignment. * @@ -747,6 +749,17 @@ export class Label extends UIRenderer { this.markForUpdateRenderData(); } + public setEntityColor (color: Color) { + if (JSB) { + if (this._font instanceof BitmapFont || this.cacheMode === CacheMode.CHAR) { + this._renderEntity.color = color; + } else { + tempColor.set(255, 255, 255, color.a); + this._renderEntity.color = tempColor; + } + } + } + protected _canRender () { if (!super._canRender() || !this._string) { return false; diff --git a/cocos/2d/components/mask.ts b/cocos/2d/components/mask.ts index d31ce3ad4d..37d8bc8be9 100644 --- a/cocos/2d/components/mask.ts +++ b/cocos/2d/components/mask.ts @@ -364,7 +364,9 @@ export class Mask extends UIRenderer { super.onEnable(); this._updateGraphics(); this._enableGraphics(); + this._changeRenderType(); this.node.on(NodeEventType.SIZE_CHANGED, this._sizeChange, this); + this.node.on(NodeEventType.ANCHOR_CHANGED, this._anchorChange, this); this.node.on(NodeEventType.SIBLING_ORDER_CHANGED, this._siblingChange, this); this.node.on(NodeEventType.LAYER_CHANGED, this._layerChange, this); this._sizeChange(); @@ -387,6 +389,7 @@ export class Mask extends UIRenderer { super.onDisable(); this._disableGraphics(); this.node.off(NodeEventType.SIZE_CHANGED, this._sizeChange, this); + this.node.off(NodeEventType.ANCHOR_CHANGED, this._anchorChange, this); this.node.off(NodeEventType.SIBLING_ORDER_CHANGED, this._siblingChange, this); this.node.off(NodeEventType.LAYER_CHANGED, this._layerChange, this); } @@ -513,6 +516,12 @@ export class Mask extends UIRenderer { } } + private _anchorChange () { + if (this._sprite) { + this._maskNode!._uiProps.uiTransformComp!.setAnchorPoint(this.node._uiProps.uiTransformComp!.anchorPoint); + } + } + private _siblingChange () { if (this._maskNode && this._maskNode.getSiblingIndex() !== 0) { this._maskNode.setSiblingIndex(0); @@ -534,6 +543,7 @@ export class Mask extends UIRenderer { sprite._postAssembler = Mask.ChildPostAssembler!.getAssembler(this); sprite.sizeMode = 0; this._sizeChange(); + this._anchorChange(); } this._sprite.spriteFrame = this._spriteFrame; this._updateMaterial(); @@ -562,7 +572,7 @@ export class Mask extends UIRenderer { // @ts-expect-error hack for graphics protected attributes graphics._postAssembler = Mask.ChildPostAssembler!.getAssembler(this); } - + this.node.insertChild(this._maskNode!, 0); this._updateMaterial(); } diff --git a/cocos/2d/components/sprite.ts b/cocos/2d/components/sprite.ts index 50924edf6e..bf884dea04 100644 --- a/cocos/2d/components/sprite.ts +++ b/cocos/2d/components/sprite.ts @@ -625,8 +625,6 @@ export class Sprite extends UIRenderer { this.node._uiProps.uiTransformComp!.setContentSize(rect.width, rect.height); } } - - this._activateMaterial(); } } @@ -681,7 +679,6 @@ export class Sprite extends UIRenderer { if (oldFrame && this._type === SpriteType.SLICED) { oldFrame.off(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this); } - this._updateUVs(); let textureChanged = false; if (spriteFrame) { diff --git a/cocos/2d/components/ui-mesh-renderer.ts b/cocos/2d/components/ui-mesh-renderer.ts index 3bb3df2990..e8b02feb58 100644 --- a/cocos/2d/components/ui-mesh-renderer.ts +++ b/cocos/2d/components/ui-mesh-renderer.ts @@ -88,7 +88,7 @@ export class UIMeshRenderer extends Component { onDisable () { uiRendererManager.removeRenderer(this); - if (this.renderEntity) this.renderEntity.enabled = false; + this.renderEntity.enabled = this._canRender(); } public onLoad () { @@ -153,6 +153,7 @@ export class UIMeshRenderer extends Component { // Native updateAssembler public updateRenderer () { if (JSB) { + this.renderEntity.enabled = this._canRender(); if (this._modelComponent) { const models = this._modelComponent._collectModels(); // @ts-expect-error: UIMeshRenderer do not attachToScene @@ -240,6 +241,10 @@ export class UIMeshRenderer extends Component { public setTextureDirty () { } + protected _canRender () { + return (this.enabled && this._modelComponent !== null); + } + get renderEntity () { if (DEBUG) { assert(this._renderEntity, 'this._renderEntity should not be invalid'); diff --git a/cocos/2d/framework/ui-component.ts b/cocos/2d/framework/ui-component.ts index ebfb335255..70c23a3c4e 100644 --- a/cocos/2d/framework/ui-component.ts +++ b/cocos/2d/framework/ui-component.ts @@ -31,9 +31,9 @@ import { Node } from '../../core/scene-graph'; import { Stage } from '../renderer/stencil-manager'; /** - * @en Legacy 2D base class for rendering component, please use [[Renderable2D]] instead. + * @en Legacy 2D base class for rendering component, please use [[UIRenderer]] instead. * This component will setup NodeUIProperties.uiComp in its owner [[Node]] - * @zh 旧的 2D 渲染组件基类,请使用 [[Renderable2D]] 替代。 + * @zh 旧的 2D 渲染组件基类,请使用 [[UIRenderer]] 替代。 * 这个组件会设置 [[Node]] 上的 NodeUIProperties.uiComp。 * @deprecated since v3.4.1 */ diff --git a/cocos/2d/framework/ui-renderer.ts b/cocos/2d/framework/ui-renderer.ts index 54da6921c5..71e03c56c2 100644 --- a/cocos/2d/framework/ui-renderer.ts +++ b/cocos/2d/framework/ui-renderer.ts @@ -165,7 +165,7 @@ export class UIRenderer extends Renderer { */ @type(Material) @displayOrder(0) - @tooltip('i18n:renderable2D.customMaterial') + @tooltip('i18n:UIRenderer.customMaterial') @displayName('CustomMaterial') @disallowAnimation get customMaterial () { @@ -182,7 +182,7 @@ export class UIRenderer extends Renderer { * @zh 渲染颜色,一般情况下会和贴图颜色相乘。 */ @displayOrder(1) - @tooltip('i18n:renderable2D.color') + @tooltip('i18n:UIRenderer.color') get color (): Readonly { return this._color; } @@ -206,13 +206,6 @@ export class UIRenderer extends Renderer { return this._renderData; } - /** - * @internal - */ - get blendHash () { - return this._blendHash; - } - /** * @internal */ @@ -220,14 +213,6 @@ export class UIRenderer extends Renderer { return this._useVertexOpacity; } - // Render data can be submitted even if it is not on the node tree - /** - * @internal - */ - set delegateSrc (value: Node) { - this._delegateSrc = value; - } - /** * @en The component stencil stage (please do not any modification directly on this object) * @zh 组件模板缓冲状态 (注意:请不要直接修改它的值) @@ -264,13 +249,9 @@ export class UIRenderer extends Renderer { protected _renderEntity: RenderEntity; - // 特殊渲染节点,给一些不在节点树上的组件做依赖渲染(例如 mask 组件内置两个 graphics 来渲染) - // Special delegate node for the renderer component, it allows standalone component to be rendered as if it's attached to the delegate node - // It's used by graphics stencil component in Mask - protected _delegateSrc: Node | null = null; protected _instanceMaterialType = -1; - protected _blendState: BlendState = new BlendState(); - protected _blendHash = 0; + protected _srcBlendFactorCache = BlendFactor.SRC_ALPHA; + protected _dstBlendFactorCache = BlendFactor.ONE_MINUS_SRC_ALPHA; /** * @internal */ @@ -348,18 +329,6 @@ export class UIRenderer extends Renderer { if (instance) { instance.destroy(); } } } - if (this._blendState) { - this._blendState.destroy(); - } - } - - /** - * @en Update the hash for the blend states. - * @zh 更新混合模式的哈希值标记 - */ - public updateBlendHash () { - const dst = this._blendState.targets[0].blendDst << 4; - this._blendHash = dst | this._blendState.targets[0].blendSrc; } /** @@ -397,6 +366,7 @@ export class UIRenderer extends Renderer { if (!this.renderData) { return; } + this.renderData.removeRenderDrawInfo(this); RenderData.remove(this.renderData); this._renderData = null; } @@ -440,8 +410,7 @@ export class UIRenderer extends Renderer { assert(this.isValid, 'this component should not be invalid!'); } return this.getMaterial(0) !== null - && this.enabled - && (this._delegateSrc ? this._delegateSrc.activeInHierarchy : this.enabledInHierarchy) + && this._enabled && this._color.a > 0; } @@ -450,7 +419,6 @@ export class UIRenderer extends Renderer { protected updateMaterial () { if (this._customMaterial) { this.setMaterial(this._customMaterial, 0); - this._blendHash = -1; // a flag to check merge return; } const mat = this._updateBuiltinMaterial(); @@ -477,7 +445,6 @@ export class UIRenderer extends Renderer { const render = node._uiProps.uiComp as UIRenderer; if (render && render.color) { // exclude UIMeshRenderer which has not color render._renderEntity.colorDirty = dirty; - render._renderEntity.color = render.color;// necessity to be considering } for (let i = 0; i < node.children.length; i++) { UIRenderer.setEntityColorDirtyRecursively(node.children[i], dirty); @@ -513,25 +480,22 @@ export class UIRenderer extends Renderer { */ public _updateBlendFunc () { // todo: Not only Pass[0].target[0] - let target = this._blendState.targets[0]; - if (!target) { - target = new BlendTarget(); - this._blendState.setTarget(0, target); - } - if (target.blendDst !== this._dstBlendFactor || target.blendSrc !== this._srcBlendFactor) { + let target = this.getRenderMaterial(0)!.passes[0].blendState.targets[0]; + this._dstBlendFactorCache = target.blendDst; + this._srcBlendFactorCache = target.blendSrc; + if (this._dstBlendFactorCache !== this._dstBlendFactor || this._srcBlendFactorCache !== this._srcBlendFactor) { + target = this.getMaterialInstance(0)!.passes[0].blendState.targets[0]; target.blend = true; target.blendDstAlpha = BlendFactor.ONE_MINUS_SRC_ALPHA; target.blendDst = this._dstBlendFactor; target.blendSrc = this._srcBlendFactor; - if (this.renderData) { - this.renderData.passDirty = true; - } + const targetPass = this.getMaterialInstance(0)!.passes[0]; + targetPass.blendState.setTarget(0, target); + // @ts-expect-error hack for UI use pass object + targetPass._updatePassHash(); + this._dstBlendFactorCache = this._dstBlendFactor; + this._srcBlendFactorCache = this._srcBlendFactor; } - this.updateBlendHash(); - } - - public getBlendState () { - return this._blendState; } // pos, rot, scale changed diff --git a/cocos/2d/renderer/batcher-2d.ts b/cocos/2d/renderer/batcher-2d.ts index aff394be8d..74be9392a4 100644 --- a/cocos/2d/renderer/batcher-2d.ts +++ b/cocos/2d/renderer/batcher-2d.ts @@ -151,7 +151,7 @@ export class Batcher2D implements IBatcher { StencilManager.sharedManager!.destroy(); } - private syncRootNodesToNative() { + private syncRootNodesToNative () { if (JSB) { const rootNodes: Node[] = []; for (const screen of this._screens) { @@ -388,7 +388,6 @@ export class Batcher2D implements IBatcher { this._currComponent = comp; this._currTransform = transform; this._currMaterial = comp.getRenderMaterial(0)!; - // this._currBlendTargetHash = comp.blendHash; this._currDepthStencilStateStage = depthStencilStateStage; this._currLayer = comp.node.layer; if (frame) { @@ -425,13 +424,9 @@ export class Batcher2D implements IBatcher { this.autoMergeBatches(this._currComponent!); this.resetRenderStates(); } - let blendState; let depthStencil; let dssHash = 0; - let bsHash = 0; if (renderComp) { - blendState = renderComp.blendHash === -1 ? null : renderComp.getBlendState(); - bsHash = renderComp.blendHash; renderComp.stencilStage = StencilManager.sharedManager!.stage; if (renderComp.customMaterial !== null) { depthStencil = StencilManager.sharedManager!.getStencilStage(renderComp.stencilStage, mat); @@ -451,7 +446,7 @@ export class Batcher2D implements IBatcher { curDrawBatch.textureHash = tex.getHash(); curDrawBatch.samplerHash = curDrawBatch.sampler.hash; } - curDrawBatch.fillPasses(mat || null, depthStencil, dssHash, blendState, bsHash, null, this); + curDrawBatch.fillPasses(mat || null, depthStencil, dssHash, null); this._batches.push(curDrawBatch); } @@ -501,7 +496,7 @@ export class Batcher2D implements IBatcher { curDrawBatch.sampler = null; curDrawBatch.useLocalData = null; if (!depthStencil) { depthStencil = null; } - curDrawBatch.fillPasses(mat, depthStencil, dssHash, null, 0, subModel.patches, this); + curDrawBatch.fillPasses(mat, depthStencil, dssHash, subModel.patches); curDrawBatch.inputAssembler = subModel.inputAssembler; curDrawBatch.model!.visFlags = curDrawBatch.visFlags; curDrawBatch.descriptorSet = subModel.descriptorSet; @@ -584,13 +579,9 @@ export class Batcher2D implements IBatcher { return; } - let blendState; let depthStencil; let dssHash = 0; - let bsHash = 0; if (renderComp) { - blendState = renderComp.blendHash === -1 ? null : renderComp.getBlendState(); - bsHash = renderComp.blendHash; if (renderComp.customMaterial !== null) { depthStencil = StencilManager.sharedManager!.getStencilStage(renderComp.stencilStage, mat); } else { @@ -607,7 +598,7 @@ export class Batcher2D implements IBatcher { curDrawBatch.useLocalData = this._currTransform; curDrawBatch.textureHash = this._currTextureHash; curDrawBatch.samplerHash = this._currSamplerHash; - curDrawBatch.fillPasses(mat, depthStencil, dssHash, blendState, bsHash, null, this); + curDrawBatch.fillPasses(mat, depthStencil, dssHash, null); this._batches.push(curDrawBatch); } diff --git a/cocos/2d/renderer/deprecated.ts b/cocos/2d/renderer/deprecated.ts index 0978708739..fb79fba44a 100644 --- a/cocos/2d/renderer/deprecated.ts +++ b/cocos/2d/renderer/deprecated.ts @@ -35,7 +35,14 @@ export { VertexFormat as UIVertexFormat }; export { Batcher2D as UI }; -export { DrawBatch2D as UIDrawBatch }; +export { UIDrawBatch }; + +/** + * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. + * @internal + */ +class UIDrawBatch extends DrawBatch2D { +} markAsWarning(MeshBuffer.prototype, 'MeshBuffer', [ diff --git a/cocos/2d/renderer/draw-batch.ts b/cocos/2d/renderer/draw-batch.ts index 47f852b318..a552e84865 100644 --- a/cocos/2d/renderer/draw-batch.ts +++ b/cocos/2d/renderer/draw-batch.ts @@ -107,12 +107,12 @@ export class DrawBatch2D { } // object version - public fillPasses (mat: Material | null, dss, dssHash, bs, bsHash, patches, batcher: IBatcher) { + public fillPasses (mat: Material | null, dss, dssHash, patches) { if (mat) { const passes = mat.passes; if (!passes) { return; } - let hashFactor = 0; + const hashFactor = 0; let dirty = false; this._shaders.length = passes.length; @@ -127,14 +127,10 @@ export class DrawBatch2D { mtlPass.update(); // Hack: Cause pass.hash can not check all pass value - if (!dss) { dss = mtlPass.depthStencilState; dssHash = 0; } - if (!bs) { bs = mtlPass.blendState; bsHash = 0; } - if (bsHash === -1) { bsHash = 0; } - hashFactor = (dssHash << 16) | bsHash; // @ts-expect-error hack for UI use pass object - passInUse._initPassFromTarget(mtlPass, dss, bs, hashFactor); + passInUse._initPassFromTarget(mtlPass, dss, dssHash); this._shaders[i] = passInUse.getShaderVariant(patches)!; diff --git a/cocos/2d/renderer/mesh-buffer.ts b/cocos/2d/renderer/mesh-buffer.ts index f250a55eac..46e7c607dc 100644 --- a/cocos/2d/renderer/mesh-buffer.ts +++ b/cocos/2d/renderer/mesh-buffer.ts @@ -128,6 +128,17 @@ export class MeshBuffer { } } + protected _useLinkedData = false; + get useLinkedData () { + return this._useLinkedData; + } + set useLinkedData (val:boolean) { + if (JSB && this._useLinkedData !== val) { + this._nativeObj.useLinkData = val; + } + this._useLinkedData = val; + } + private _vertexFormatBytes = 0; private _initVDataCount = 0; private _initIDataCount = 0; diff --git a/cocos/2d/renderer/native-2d.ts b/cocos/2d/renderer/native-2d.ts index dab487fb54..ebf46cc569 100644 --- a/cocos/2d/renderer/native-2d.ts +++ b/cocos/2d/renderer/native-2d.ts @@ -46,6 +46,7 @@ export declare class NativeRenderEntity { setDynamicRenderDrawInfo(drawInfo: NativeRenderDrawInfo, index: number); removeDynamicRenderDrawInfo(); clearDynamicRenderDrawInfos(); + clearStaticRenderDrawInfos(); get node(): Node | null; set node(node: Node | null); @@ -65,6 +66,8 @@ export declare class NativeUIMeshBuffer { set vData(val: Float32Array); get iData(): Uint16Array; set iData(val: Uint16Array); + get useLinkData(): boolean; + set useLinkData(val: boolean); syncSharedBufferToNative(data: TypedArray); @@ -87,10 +90,11 @@ export declare class NativeBatcher2d { export declare class NativeUIModelProxy { initModel(node); - activeSubModel(index: number); + activeSubModels(); uploadData(); destroy(); clear(); + getModel(): Model; updateModels(model); attachDrawInfo(); attachNode(node); diff --git a/cocos/2d/renderer/render-data.ts b/cocos/2d/renderer/render-data.ts index 5afd0617ac..efca37057a 100644 --- a/cocos/2d/renderer/render-data.ts +++ b/cocos/2d/renderer/render-data.ts @@ -23,7 +23,7 @@ THE SOFTWARE. */ -import { JSB } from 'internal:constants'; +import { DEBUG, JSB } from 'internal:constants'; import { director } from '../../core/director'; import { Material } from '../../core/assets/material'; import { TextureBase } from '../../core/assets/texture-base'; @@ -40,6 +40,7 @@ import { RenderDrawInfo, RenderDrawInfoType } from './render-draw-info'; import { StencilManager } from './stencil-manager'; import { Batcher2D } from './batcher-2d'; import { RenderEntity, RenderEntityType } from './render-entity'; +import { assert } from '../../core'; /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. @@ -188,6 +189,8 @@ export class BaseRenderData { const renderEntity: RenderEntity = comp.renderEntity; if (renderEntity.renderEntityType === RenderEntityType.DYNAMIC) { renderEntity.removeDynamicRenderDrawInfo(); + } else if (renderEntity.renderEntityType === RenderEntityType.STATIC) { + renderEntity.clearStaticRenderDrawInfos(); } } } @@ -293,14 +296,6 @@ export class RenderData extends BaseRenderData { this._textureHash = val; } - protected _blendHash = -1; - get blendHash () { - return this._blendHash; - } - set blendHash (val: number) { - this._blendHash = val; - } - public indices: Uint16Array | null = null; public set frame (val: SpriteFrame | TextureBase | null) { @@ -332,6 +327,7 @@ export class RenderData extends BaseRenderData { private _height = 0; private _frame: SpriteFrame | TextureBase | null = null; protected _accessor: StaticVBAccessor = null!; + get accessor () { return this._accessor; } public vertexRow = 1; public vertexCol = 1; @@ -382,16 +378,16 @@ export class RenderData extends BaseRenderData { this._renderDrawInfo.setSampler(this.frame ? this.frame.getGFXSampler() : null); } } - + /** + * @internal + */ public fillDrawInfoAttributes (drawInfo: RenderDrawInfo) { if (JSB) { if (!drawInfo) { return; } - - drawInfo.setAccId(this._accessor.id); drawInfo.setDrawInfoType(this._drawInfoType); - drawInfo.setBufferId(this.chunk.bufferId); + drawInfo.setAccAndBuffer(this._accessor.id, this.chunk.bufferId); drawInfo.setVertexOffset(this.chunk.vertexOffset); drawInfo.setIndexOffset(this.chunk.meshBuffer.indexOffset); drawInfo.setVB(this.chunk.vb); @@ -448,7 +444,6 @@ export class RenderData extends BaseRenderData { public updatePass (comp: UIRenderer) { this.material = comp.getRenderMaterial(0)!; - this.blendHash = comp.blendHash; this.passDirty = false; this.hashDirty = true; } @@ -462,7 +457,7 @@ export class RenderData extends BaseRenderData { public updateHash () { const bid = this.chunk ? this.chunk.bufferId : -1; - const hashString = `${bid}${this.layer} ${this.blendHash} ${this.textureHash}`; + const hashString = `${bid}${this.layer} ${this.textureHash}`; this.dataHash = murmurhash2_32_gc(hashString, 666); this.hashDirty = false; } @@ -470,7 +465,6 @@ export class RenderData extends BaseRenderData { public updateRenderData (comp: UIRenderer, frame: SpriteFrame | TextureBase) { if (this.passDirty) { this.material = comp.getRenderMaterial(0)!; - this.blendHash = comp.blendHash; this.passDirty = false; this.hashDirty = true; @@ -508,24 +502,11 @@ export class RenderData extends BaseRenderData { // Hack Do not update pre frame if (JSB && this.multiOwner === false) { - // for sync vData and iData address to native - //this.setRenderDrawInfoAttributes(); - // sync shared buffer to native - this.copyRenderDataToSharedBuffer(); - } - } - - copyRenderDataToSharedBuffer () { - if (JSB) { - const entity = this._renderDrawInfo; - const sharedBuffer = entity.render2dBuffer; - - if (sharedBuffer.length < this.floatStride * this._data.length) { - console.error('Vertex count doesn\'t match.'); - return; + if (DEBUG) { + assert(this._renderDrawInfo.render2dBuffer.length === this._floatStride * this._data.length, 'Vertex count doesn\'t match.'); } - - entity.fillRender2dBuffer(this._data); + // sync shared buffer to native + this._renderDrawInfo.fillRender2dBuffer(this._data); } } @@ -559,7 +540,6 @@ export class RenderData extends BaseRenderData { this.hashDirty = true; this.layer = 0; - this.blendHash = -1; this.frame = null; this.textureHash = 0; this.dataHash = 0; diff --git a/cocos/2d/renderer/render-draw-info.ts b/cocos/2d/renderer/render-draw-info.ts index 9bf2b185d2..8e30ba1569 100644 --- a/cocos/2d/renderer/render-draw-info.ts +++ b/cocos/2d/renderer/render-draw-info.ts @@ -106,10 +106,12 @@ export class RenderDrawInfo { } public setAccId (accId) { - this._accId = accId; if (JSB) { - this._uint16SharedBuffer[AttrUInt16ArrayView.AccessorID] = accId; + if (this._accId !== accId) { + this._uint16SharedBuffer[AttrUInt16ArrayView.AccessorID] = accId; + } } + this._accId = accId; } public setBufferId (bufferId) { @@ -122,6 +124,18 @@ export class RenderDrawInfo { this._bufferId = bufferId; } + public setAccAndBuffer (accId, bufferId) { + if (JSB) { + if (this._accId !== accId || this._bufferId !== bufferId) { + this._uint16SharedBuffer[AttrUInt16ArrayView.AccessorID] = accId; + this._uint16SharedBuffer[AttrUInt16ArrayView.BufferID] = bufferId; + this._nativeObj.changeMeshBuffer(); + } + } + this._bufferId = bufferId; + this._accId = accId; + } + public setVertexOffset (vertexOffset) { this._vertexOffset = vertexOffset; if (JSB) { @@ -266,27 +280,12 @@ export class RenderDrawInfo { const fillLength = Math.min(this._vbCount, vertexDataArr.length); let bufferOffset = 0; for (let i = 0; i < fillLength; i++) { - this.updateVertexBuffer(bufferOffset, vertexDataArr[i]); + const temp = vertexDataArr[i]; + this._render2dBuffer[bufferOffset] = temp.x; + this._render2dBuffer[bufferOffset + 1] = temp.y; + this._render2dBuffer[bufferOffset + 2] = temp.z; bufferOffset += this._stride; } } } - - public updateVertexBuffer (bufferOffset: number, vertexData: IRenderData) { - if (JSB) { - if (bufferOffset >= this.render2dBuffer.length) { - return; - } - const temp: IRenderData = vertexData; - this._render2dBuffer[bufferOffset++] = temp.x; - this._render2dBuffer[bufferOffset++] = temp.y; - this._render2dBuffer[bufferOffset++] = temp.z; - this._render2dBuffer[bufferOffset++] = temp.u; - this._render2dBuffer[bufferOffset++] = temp.v; - this._render2dBuffer[bufferOffset++] = temp.color.r; - this._render2dBuffer[bufferOffset++] = temp.color.g; - this._render2dBuffer[bufferOffset++] = temp.color.b; - this._render2dBuffer[bufferOffset++] = temp.color.a; - } - } } diff --git a/cocos/2d/renderer/render-entity.ts b/cocos/2d/renderer/render-entity.ts index 2cfc5c0feb..e303b4eb7a 100644 --- a/cocos/2d/renderer/render-entity.ts +++ b/cocos/2d/renderer/render-entity.ts @@ -152,6 +152,12 @@ export class RenderEntity { } } + public clearStaticRenderDrawInfos () { + if (JSB) { + this._nativeObj.clearStaticRenderDrawInfos(); + } + } + public setDynamicRenderDrawInfo (renderDrawInfo: RenderDrawInfo | null, index: number) { if (JSB) { if (renderDrawInfo) { diff --git a/cocos/core/animation/animation-clip.ts b/cocos/core/animation/animation-clip.ts index c98ce97c20..e9b4f13b3a 100644 --- a/cocos/core/animation/animation-clip.ts +++ b/cocos/core/animation/animation-clip.ts @@ -311,6 +311,14 @@ export class AnimationClip extends Asset { this._tracks.length = 0; } + /** + * Returns if this clip has any event. + * @internal Do not use this in your code. + */ + public containsAnyEvent () { + return this._events.length !== 0; + } + /** * Creates an event evaluator for this animation. * @param targetNode Target node used to fire events. @@ -325,6 +333,14 @@ export class AnimationClip extends Asset { ); } + /** + * Returns if this clip has any embedded player. + * @internal Do not use this in your code. + */ + public containsAnyEmbeddedPlayer () { + return this._embeddedPlayers.length !== 0; + } + /** * Creates an embedded player evaluator for this animation. * @param targetNode Target node. @@ -940,6 +956,17 @@ class EmbeddedPlayerEvaluation { ); } + public destroy () { + const { + _embeddedPlayerEvaluationInfos: embeddedPlayerEvaluationInfos, + } = this; + const nEmbeddedPlayers = embeddedPlayerEvaluationInfos.length; + for (let iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) { + embeddedPlayerEvaluationInfos[iEmbeddedPlayer]?.instantiatedPlayer.destroy(); + } + this._embeddedPlayerEvaluationInfos.length = 0; + } + /** * Evaluates the embedded players. * @param time The time([0, clipDuration]). diff --git a/cocos/core/animation/animation-state.ts b/cocos/core/animation/animation-state.ts index 6e883dee0a..433e41871d 100644 --- a/cocos/core/animation/animation-state.ts +++ b/cocos/core/animation/animation-state.ts @@ -222,7 +222,7 @@ export class AnimationState extends Playable { set speed (value) { this._speed = value; - this._clipEmbeddedPlayerEval.notifyHostSpeedChanged(value); + this._clipEmbeddedPlayerEval?.notifyHostSpeedChanged(value); } /** @@ -305,7 +305,7 @@ export class AnimationState extends Playable { private _weight = 1.0; private _clipEval: ReturnType | undefined; private _clipEventEval: ReturnType | undefined; - private declare _clipEmbeddedPlayerEval: ReturnType; + private _clipEmbeddedPlayerEval: ReturnType | undefined; /** * @internal For internal usage. Really hack... */ @@ -343,6 +343,13 @@ export class AnimationState extends Playable { // TODO: destroy? this._clipEval = undefined; } + if (this._clipEventEval) { + this._clipEventEval = undefined; + } + if (this._clipEmbeddedPlayerEval) { + this._clipEmbeddedPlayerEval.destroy(); + this._clipEmbeddedPlayerEval = undefined; + } this._targetNode = root; const clip = this._clip; @@ -374,11 +381,15 @@ export class AnimationState extends Playable { } if (!(EDITOR && !legacyCC.GAME_VIEW)) { - this._clipEventEval = clip.createEventEvaluator(this._targetNode); + if (clip.containsAnyEvent()) { + this._clipEventEval = clip.createEventEvaluator(this._targetNode); + } } - this._clipEmbeddedPlayerEval = clip.createEmbeddedPlayerEvaluator(this._targetNode); - this._clipEmbeddedPlayerEval.notifyHostSpeedChanged(this._speed); + if (clip.containsAnyEmbeddedPlayer()) { + this._clipEmbeddedPlayerEval = clip.createEmbeddedPlayerEvaluator(this._targetNode); + this._clipEmbeddedPlayerEval.notifyHostSpeedChanged(this._speed); + } } public destroy () { @@ -484,7 +495,7 @@ export class AnimationState extends Playable { // var playPerfectFirstFrame = (this.time === 0); if (this._currentFramePlayed) { - this.time += (delta * this.speed); + this.time += (delta * this._speed); } else { this._currentFramePlayed = true; } @@ -507,7 +518,7 @@ export class AnimationState extends Playable { this._delayTime = this._delay; this._onReplayOrResume(); this.emit(EventType.PLAY, this); - this._clipEmbeddedPlayerEval.notifyHostPlay(this.current); + this._clipEmbeddedPlayerEval?.notifyHostPlay(this.current); } protected onStop () { @@ -515,19 +526,19 @@ export class AnimationState extends Playable { this._onPauseOrStop(); } this.emit(EventType.STOP, this); - this._clipEmbeddedPlayerEval.notifyHostStop(); + this._clipEmbeddedPlayerEval?.notifyHostStop(); } protected onResume () { this._onReplayOrResume(); this.emit(EventType.RESUME, this); - this._clipEmbeddedPlayerEval.notifyHostPlay(this.current); + this._clipEmbeddedPlayerEval?.notifyHostPlay(this.current); } protected onPause () { this._onPauseOrStop(); this.emit(EventType.PAUSE, this); - this._clipEmbeddedPlayerEval.notifyHostPause(this.current); + this._clipEmbeddedPlayerEval?.notifyHostPause(this.current); } /** @@ -592,12 +603,14 @@ export class AnimationState extends Playable { } this._sampleCurves(playbackStart + time); - const wrapInfo = this.getWrappedInfo(this.time, this._wrappedInfo); - if (!EDITOR || legacyCC.GAME_VIEW) { - this._sampleEvents(wrapInfo); - } + if (this._clipEventEval || this._clipEmbeddedPlayerEval) { + const wrapInfo = this.getWrappedInfo(this.time, this._wrappedInfo); + if (!EDITOR || legacyCC.GAME_VIEW) { + this._sampleEvents(wrapInfo); + } - this._sampleEmbeddedPlayers(wrapInfo); + this._sampleEmbeddedPlayers(wrapInfo); + } if (this._allowLastFrame) { if (Number.isNaN(this._lastIterations)) { @@ -636,9 +649,13 @@ export class AnimationState extends Playable { private getWrappedInfo (time: number, info?: WrappedInfo) { info = info || new WrappedInfo(); - const playbackStart = this._getPlaybackStart(); - const playbackEnd = this._getPlaybackEnd(); - const playbackDuration = playbackEnd - playbackStart; + const { + _playbackRange: { + min: playbackStart, + }, + _playbackDuration: playbackDuration, + } = this; + const repeatCount = this.repeatCount; if (playbackDuration === 0.0) { @@ -703,10 +720,6 @@ export class AnimationState extends Playable { return this._playbackRange.min; } - private _getPlaybackEnd () { - return this._playbackRange.max; - } - private _sampleEvents (wrapInfo: WrappedInfo) { this._clipEventEval?.sample( wrapInfo.ratio, @@ -716,7 +729,7 @@ export class AnimationState extends Playable { } private _sampleEmbeddedPlayers (wrapInfo: WrappedInfo) { - this._clipEmbeddedPlayerEval.evaluate( + this._clipEmbeddedPlayerEval?.evaluate( wrapInfo.time, Math.trunc(wrapInfo.iterations), ); diff --git a/cocos/core/animation/marionette/animation-graph.ts b/cocos/core/animation/marionette/animation-graph.ts index 13a95401bc..f7e4be9011 100644 --- a/cocos/core/animation/marionette/animation-graph.ts +++ b/cocos/core/animation/marionette/animation-graph.ts @@ -94,12 +94,21 @@ class AnimationTransition extends Transition { /** * @en The start time of (final) destination motion state when this transition starts. - * Its unit is the duration of destination motion state. - * @zh 此过渡开始时,(最终)目标动作状态的起始时间。其单位是目标动作状态的周期。 + * Its unit is seconds if `relativeDestinationStart` is `false`, + * Otherwise, its unit is the duration of destination motion state. + * @zh 此过渡开始时,(最终)目标动作状态的起始时间。 + * 如果 `relativeDestinationStart`为 `false`,其单位是秒,否则其单位是目标动作状态的周期。 */ @serializable public destinationStart = 0.0; + /** + * @en Determines the unit of destination start time. See `destinationStart`. + * @zh 决定了目标起始时间的单位。见 `destinationStart`。 + */ + @serializable + public relativeDestinationStart = false; + get exitCondition () { return this._exitCondition; } @@ -158,11 +167,20 @@ export class EmptyStateTransition extends Transition { /** * @en The start time of (final) destination motion state when this transition starts. - * Its unit is the duration of destination motion state. - * @zh 此过渡开始时,(最终)目标动作状态的起始时间。其单位是目标动作状态的周期。 + * Its unit is seconds if `relativeDestinationStart` is `false`, + * Otherwise, its unit is the duration of destination motion state. + * @zh 此过渡开始时,(最终)目标动作状态的起始时间。 + * 如果 `relativeDestinationStart`为 `false`,其单位是秒,否则其单位是目标动作状态的周期。 */ @serializable public destinationStart = 0.0; + + /** + * @en Determines the unit of destination start time. See `destinationStart`. + * @zh 决定了目标起始时间的单位。见 `destinationStart`。 + */ + @serializable + public relativeDestinationStart = false; } @ccclass('cc.animation.StateMachine') diff --git a/cocos/core/animation/marionette/graph-eval.ts b/cocos/core/animation/marionette/graph-eval.ts index b3e8047587..c79b50962d 100644 --- a/cocos/core/animation/marionette/graph-eval.ts +++ b/cocos/core/animation/marionette/graph-eval.ts @@ -499,6 +499,7 @@ class LayerEval { duration: 0.0, normalizedDuration: false, destinationStart: 0.0, + relativeDestinationStart: false, exitCondition: 0.0, exitConditionEnabled: false, interruption: TransitionInterruptionSource.NONE, @@ -510,10 +511,12 @@ class LayerEval { transitionEval.exitConditionEnabled = outgoing.exitConditionEnabled; transitionEval.exitCondition = outgoing.exitCondition; transitionEval.destinationStart = outgoing.destinationStart; + transitionEval.relativeDestinationStart = outgoing.relativeDestinationStart; transitionEval.interruption = outgoing.interruptionSource; } else if (outgoing instanceof EmptyStateTransition) { transitionEval.duration = outgoing.duration; transitionEval.destinationStart = outgoing.destinationStart; + transitionEval.relativeDestinationStart = outgoing.relativeDestinationStart; } transitionEval.conditions.forEach((conditionEval, iCondition) => { @@ -961,8 +964,14 @@ class LayerEval { if (targetNode.kind === NodeKind.animation) { const { destinationStart, + relativeDestinationStart, } = currentTransitionPath[0]; - targetNode.resetToPort(destinationStart); + const destinationStartRatio = relativeDestinationStart + ? destinationStart + : targetNode.duration === 0 + ? 0.0 + : destinationStart / targetNode.duration; + targetNode.resetToPort(destinationStartRatio); } this._callEnterMethods(targetNode); } @@ -1759,6 +1768,7 @@ interface TransitionEval { exitConditionEnabled: boolean; exitCondition: number; destinationStart: number; + relativeDestinationStart: boolean; /** * Bound triggers, once this transition satisfied. All triggers would be reset. */ diff --git a/cocos/core/asset-manager/asset-manager.ts b/cocos/core/asset-manager/asset-manager.ts index e7ad816ea4..6509f34013 100644 --- a/cocos/core/asset-manager/asset-manager.ts +++ b/cocos/core/asset-manager/asset-manager.ts @@ -288,6 +288,7 @@ export class AssetManager { private _parsed = parsed; private _parsePipeline = BUILD ? null : new Pipeline('parse existing json', [this.loadPipe]); + private _projectBundles: string[] = []; /** * @en @@ -345,6 +346,7 @@ export class AssetManager { } this.generalImportBase = importBase; this.generalNativeBase = nativeBase; + this._projectBundles = settings.querySettings(Settings.Category.ASSETS, 'projectBundles') || []; } /** diff --git a/cocos/core/asset-manager/factory.ts b/cocos/core/asset-manager/factory.ts index 7748dc3383..8c44138726 100644 --- a/cocos/core/asset-manager/factory.ts +++ b/cocos/core/asset-manager/factory.ts @@ -23,6 +23,7 @@ THE SOFTWARE. */ +import { EDITOR } from 'internal:constants'; import { ImageAsset } from '../assets/image-asset'; import JsonAsset from '../assets/json-asset'; import TextAsset from '../assets/text-asset'; @@ -87,9 +88,14 @@ function createBundle (id: string, data: IConfigOption, options: IDownloadParseO data.base = data.base || `${id}/`; bundle.init(data); } - import(`virtual:///prerequisite-imports/${bundle.name}`).then(() => { + //HACK: Can not import scripts in GameView due to the difference of Scripting System between the GameView and Preview + if (!EDITOR) { + import(`virtual:///prerequisite-imports/${bundle.name}`).then(() => { + onComplete(null, bundle); + }).catch(onComplete); + } else { onComplete(null, bundle); - }).catch(onComplete); + } } export class Factory { diff --git a/cocos/core/assets/asset.jsb.ts b/cocos/core/assets/asset.jsb.ts index 5c34eda92b..3f15de796b 100644 --- a/cocos/core/assets/asset.jsb.ts +++ b/cocos/core/assets/asset.jsb.ts @@ -115,6 +115,10 @@ assetProto.decRef = function (autoRelease = true): Asset { return this; }; +assetProto.toString = function () { + return this.nativeUrl; +}; + assetProto.createNode = null!; // @ts-ignore diff --git a/cocos/core/components/camera-component.ts b/cocos/core/components/camera-component.ts index 63a2822ae7..3e1faa6599 100644 --- a/cocos/core/components/camera-component.ts +++ b/cocos/core/components/camera-component.ts @@ -569,7 +569,6 @@ export class Camera extends Component { * this.convertToUINode(target.worldPosition, uiNode.parent, out); * uiNode.position = out; * ``` - * @deprecated since v3.6, please use UITransform.convertToNodeSpaceAR instead */ public convertToUINode (wpos: Vec3 | Readonly, uiNode: Node, out?: Vec3) { if (!out) { diff --git a/cocos/core/components/model-renderer.ts b/cocos/core/components/model-renderer.ts index 9baeaf4567..c8e7056318 100644 --- a/cocos/core/components/model-renderer.ts +++ b/cocos/core/components/model-renderer.ts @@ -59,6 +59,7 @@ export class ModelRenderer extends Renderer { set priority (val) { if (val === this._priority) return; + this._priority = val; this._updatePriority(); } diff --git a/cocos/core/data/class.ts b/cocos/core/data/class.ts index c5a9c32306..2c07599477 100644 --- a/cocos/core/data/class.ts +++ b/cocos/core/data/class.ts @@ -40,6 +40,8 @@ import { PropertyStash, PropertyStashInternalFlag } from './class-stash'; const DELIMETER = attributeUtils.DELIMETER; const CCCLASS_TAG = '__ctors__'; // Still use this historical name to avoid unsynchronized version issue +export const ENUM_TAG = 'Enum'; +export const BITMASK_TAG = 'BitMask'; function pushUnique (array, item) { if (array.indexOf(item) < 0) { @@ -444,10 +446,10 @@ function parseAttributes (constructor: Function, attributes: PropertyStash, clas // } else if (typeof type === 'object') { if (Enum.isEnum(type)) { - (attrs || initAttrs())[`${propertyNamePrefix}type`] = 'Enum'; + (attrs || initAttrs())[`${propertyNamePrefix}type`] = ENUM_TAG; attrs![`${propertyNamePrefix}enumList`] = Enum.getList(type); } else if (BitMask.isBitMask(type)) { - (attrs || initAttrs())[`${propertyNamePrefix}type`] = 'BitMask'; + (attrs || initAttrs())[`${propertyNamePrefix}type`] = BITMASK_TAG; attrs![`${propertyNamePrefix}bitmaskList`] = BitMask.getList(type); } else if (DEV) { errorID(3645, className, propertyName, type); diff --git a/cocos/core/data/deserialize-dynamic.ts b/cocos/core/data/deserialize-dynamic.ts index ab54008dee..7eb9f98d5f 100644 --- a/cocos/core/data/deserialize-dynamic.ts +++ b/cocos/core/data/deserialize-dynamic.ts @@ -28,7 +28,7 @@ import { EDITOR, TEST, DEV, DEBUG, JSB, PREVIEW, SUPPORT_JIT } from 'internal:co import { legacyCC } from '../global-exports'; import * as js from '../utils/js'; import * as misc from '../utils/misc'; -import { CCClass } from './class'; +import { CCClass, ENUM_TAG, BITMASK_TAG } from './class'; import * as Attr from './utils/attribute'; import MissingScript from '../components/missing-script'; import { Details } from './deserialize'; @@ -145,11 +145,11 @@ function compileDeserializeJIT (self: _Deserializer, klass: CCClassConstructor(Settings.Category.ASSETS, 'preloadBundles'); if (!preloadBundles) return Promise.resolve([]); return Promise.all(preloadBundles.map(({ bundle, version }) => new Promise((resolve, reject) => { diff --git a/cocos/core/pipeline/debug-view.ts b/cocos/core/pipeline/debug-view.ts index 7a84e920f6..ba24e9f532 100644 --- a/cocos/core/pipeline/debug-view.ts +++ b/cocos/core/pipeline/debug-view.ts @@ -210,6 +210,15 @@ export class DebugView { return this._getType() !== RenderingDebugViewType.NONE; } + /** + * @en Disable all debug view modes, reset to standard rendering mode. + * @zh 关闭所有的渲染调试模式,恢复到正常渲染。 + */ + public reset () { + this._activate(); + this._updatePipeline(); + } + /** * @internal */ diff --git a/cocos/core/pipeline/pipeline-serialization.ts b/cocos/core/pipeline/pipeline-serialization.ts index ee87e3fb13..2900a49277 100644 --- a/cocos/core/pipeline/pipeline-serialization.ts +++ b/cocos/core/pipeline/pipeline-serialization.ts @@ -35,6 +35,7 @@ ccenum(TextureUsageBit); ccenum(StoreOp); ccenum(LoadOp); ccenum(AccessFlagBit); +ccenum(Format); /** * @en The tag of the render flow, including SCENE, POSTPROCESS and UI. diff --git a/cocos/core/pipeline/pipeline-ubo.ts b/cocos/core/pipeline/pipeline-ubo.ts index 1a84ab35cb..dcfb7d9f85 100644 --- a/cocos/core/pipeline/pipeline-ubo.ts +++ b/cocos/core/pipeline/pipeline-ubo.ts @@ -194,8 +194,8 @@ export class PipelineUBO { return 1.0 / (shadowMapSize * 0.5); case PCFType.SOFT_2X: return 2.0 / (shadowMapSize * 0.5); - case PCFType.SOFT_4X: - return 3.0 / (shadowMapSize * 0.5); + // case PCFType.SOFT_4X: + // return 3.0 / (shadowMapSize * 0.5); default: } return 0.0; diff --git a/cocos/core/renderer/core/pass.ts b/cocos/core/renderer/core/pass.ts index 267fd023f4..b5e21c8f3e 100644 --- a/cocos/core/renderer/core/pass.ts +++ b/cocos/core/renderer/core/pass.ts @@ -628,14 +628,14 @@ export class Pass { } // Only for UI - private _initPassFromTarget (target: Pass, dss: DepthStencilState, bs: BlendState, hashFactor: number) { + private _initPassFromTarget (target: Pass, dss: DepthStencilState, hashFactor: number) { this._priority = target.priority; this._stage = target.stage; this._phase = target.phase; this._batchingScheme = target.batchingScheme; this._primitive = target.primitive; this._dynamicStates = target.dynamicStates; - this._bs = bs; + this._bs = target.blendState; this._dss = dss; this._descriptorSet = target.descriptorSet; this._rs = target.rasterizerState; @@ -656,6 +656,11 @@ export class Pass { this._hash = target._hash ^ hashFactor; } + // Only for UI + private _updatePassHash () { + this._hash = Pass.getPassHash(this); + } + // infos get root (): Root { return this._root; } get device (): Device { return this._device; } diff --git a/cocos/core/renderer/core/render-scene.ts b/cocos/core/renderer/core/render-scene.ts index 7d576c2179..f640c3245c 100644 --- a/cocos/core/renderer/core/render-scene.ts +++ b/cocos/core/renderer/core/render-scene.ts @@ -409,6 +409,8 @@ export class RenderScene { * @en Add a draw batch of 2d objects, all draw batches attached to the render scene will be submitted for rendering. * @zh 增加一个 2D 渲染批次,渲染场景上挂载的所有 2D 渲染批次都会被提交渲染。 * @param batch The draw batch. + * @internal + * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. */ public addBatch (batch: DrawBatch2D) { this._batches.push(batch); @@ -418,6 +420,8 @@ export class RenderScene { * @en Remove a draw batch of 2d objects, draw batch removed will no longer be submitted for rendering. * @zh 删除一个 2D 渲染批次,移除的 2D 渲染批次将不再被提交渲染。 * @param batch The draw batch. + * @internal + * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. */ public removeBatch (batch: DrawBatch2D) { for (let i = 0; i < this._batches.length; ++i) { @@ -431,6 +435,8 @@ export class RenderScene { /** * @en Remove all 2d draw batches. * @zh 删除所有 2D 渲染批次。 + * @internal + * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. */ public removeBatches () { this._batches.length = 0; diff --git a/cocos/core/renderer/scene/shadows.ts b/cocos/core/renderer/scene/shadows.ts index 7673f65793..dce5ae3697 100644 --- a/cocos/core/renderer/scene/shadows.ts +++ b/cocos/core/renderer/scene/shadows.ts @@ -121,12 +121,12 @@ export const PCFType = Enum({ */ SOFT_2X: 2, - /** - * @zh x16 次采样 - * @en x16 times - * @readonly - */ - SOFT_4X: 3, + // /** + // * @zh x16 次采样 + // * @en x16 times + // * @readonly + // */ + // SOFT_4X: 3, }); /** diff --git a/cocos/core/renderer/scene/skybox.ts b/cocos/core/renderer/scene/skybox.ts index 4b23715426..82a59cdd6e 100644 --- a/cocos/core/renderer/scene/skybox.ts +++ b/cocos/core/renderer/scene/skybox.ts @@ -368,31 +368,23 @@ export class Skybox { } if (this.enabled) { + const envmap = this.envmap ? this.envmap : this._default; if (this._editableMaterial) { - if (this.reflectionMap) { - this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE, USE_REFLECTION_CUBEMAP: true }); - this._editableMaterial.setProperty('environmentMap', this.envmap); - } else { - this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE, USE_REFLECTION_CUBEMAP: false }); - } + this._editableMaterial.setProperty('environmentMap', envmap); + this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); } else if (skybox_material) { - if (this.reflectionMap) { - skybox_material.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE, USE_REFLECTION_CUBEMAP: true }); - skybox_material.setProperty('environmentMap', this.envmap); + skybox_material.setProperty('environmentMap', envmap); + skybox_material.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); + } + if (this._model) { + if (this._editableMaterial) { + this._model.setSubModelMaterial(0, this._editableMaterial); } else { - skybox_material.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE, USE_REFLECTION_CUBEMAP: false }); + this._model.setSubModelMaterial(0, skybox_material!); } + this._updateSubModes(); } } - - if (this._model) { - if (this._editableMaterial) { - this._model.setSubModelMaterial(0, this._editableMaterial); - } else { - this._model.setSubModelMaterial(0, skybox_material!); - } - this._updateSubModes(); - } } protected _updateGlobalBinding () { diff --git a/cocos/core/root.jsb.ts b/cocos/core/root.jsb.ts index 9e1b3c32d5..9c16d122ac 100644 --- a/cocos/core/root.jsb.ts +++ b/cocos/core/root.jsb.ts @@ -209,3 +209,15 @@ rootProto.setRenderPipeline = function (pipeline) { this._createBatcher2D(); return ppl; } + +rootProto.addBatch = function (batch) { + console.error('The Draw Batch class is implemented differently in the native platform and does not support this interface.'); +} + +rootProto.removeBatch = function (batch) { + console.error('The Draw Batch class is implemented differently in the native platform and does not support this interface.'); +} + +rootProto.removeBatches = function () { + console.error('The Draw Batch class is implemented differently in the native platform and does not support this interface.'); +} \ No newline at end of file diff --git a/cocos/core/scene-graph/base-node.ts b/cocos/core/scene-graph/base-node.ts index c831d7c419..ff25d7332e 100644 --- a/cocos/core/scene-graph/base-node.ts +++ b/cocos/core/scene-graph/base-node.ts @@ -1289,12 +1289,6 @@ export class BaseNode extends CCObject implements ISchedulable { // PrefabUtils.unlinkPrefab(cloned); } } - if (EDITOR && legacyCC.GAME_VIEW) { - const syncing = newPrefabInfo && cloned === newPrefabInfo.root && newPrefabInfo.sync; - if (!syncing) { - cloned._name += ' (Clone)'; - } - } // reset and init cloned._parent = null; diff --git a/cocos/core/scene-graph/node.jsb.ts b/cocos/core/scene-graph/node.jsb.ts index f49bcdb8f6..2422b35d8a 100644 --- a/cocos/core/scene-graph/node.jsb.ts +++ b/cocos/core/scene-graph/node.jsb.ts @@ -35,6 +35,7 @@ import { _tempFloatArray, fillMat4WithTempFloatArray } from './utils.jsb'; import { getClassByName, isChildClassOf } from '../utils/js-typed'; import { syncNodeValues } from "../utils/jsb-utils"; import { property } from '../data/class-decorator'; +import * as js from '../utils/js'; import './base-node'; const reserveContentsForAllSyncablePrefabTag = Symbol('ReserveContentsForAllSyncablePrefab'); @@ -47,6 +48,10 @@ export type Node = jsb.Node; legacyCC.Node = Node; const NodeCls: any = Node; + + +NodeCls.reserveContentsForAllSyncablePrefabTag = reserveContentsForAllSyncablePrefabTag; + /** * @en Event types emitted by Node * @zh 节点可能发出的事件类型 @@ -91,6 +96,24 @@ function getConstructor (typeOrClassName) { return typeOrClassName; } +/** + * @en + * Properties configuration function. + * All properties in attrs will be set to the node, + * when the setter of the node is available, + * the property will be set via setter function. + * @zh 属性配置函数。在 attrs 的所有属性将被设置为节点属性。 + * @param attrs - Properties to be set to node + * @example + * ``` + * var attrs = { name: 'New Name', active: false }; + * node.attr(attrs); + * ``` + */ +nodeProto.attr = function(attrs: unknown) { + js.mixin(this, attrs); +} + nodeProto.getComponent = function (typeOrClassName) { const constructor = getConstructor(typeOrClassName); if (constructor) { diff --git a/cocos/core/scene-graph/scene-globals.jsb.ts b/cocos/core/scene-graph/scene-globals.jsb.ts index d512665a21..ccb956e29e 100644 --- a/cocos/core/scene-graph/scene-globals.jsb.ts +++ b/cocos/core/scene-graph/scene-globals.jsb.ts @@ -153,6 +153,7 @@ legacyCC.SkyboxInfo = SkyboxInfo; // @ts-ignore export const FogInfo = jsb.FogInfo; legacyCC.FogInfo = FogInfo; +FogInfo.FogType = FogType; // @ts-ignore export const ShadowsInfo = jsb.ShadowsInfo; diff --git a/cocos/dragon-bones/ArmatureDisplay.ts b/cocos/dragon-bones/ArmatureDisplay.ts index d7db2aceb4..87c1beba14 100644 --- a/cocos/dragon-bones/ArmatureDisplay.ts +++ b/cocos/dragon-bones/ArmatureDisplay.ts @@ -958,10 +958,6 @@ export class ArmatureDisplay extends UIRenderer { return Array.from(this._cachedSockets.keys()).sort(); } - public setBlendHash () { - if (this._blendHash !== -1) this._blendHash = -1; - } - /** * @en Query socket path with slot or bone name. * @zh 查询 Socket 路径 @@ -1347,6 +1343,13 @@ export class ArmatureDisplay extends UIRenderer { renderEntity.setUseLocal(true); return renderEntity; } + + public markForUpdateRenderData (enable = true) { + super.markForUpdateRenderData(enable); + if (this._debugDraw) { + this._debugDraw.markForUpdateRenderData(enable); + } + } } legacyCC.internal.ArmatureDisplay = ArmatureDisplay; diff --git a/cocos/dragon-bones/assembler/simple.ts b/cocos/dragon-bones/assembler/simple.ts index 867c4b76e9..5f6978a3a6 100644 --- a/cocos/dragon-bones/assembler/simple.ts +++ b/cocos/dragon-bones/assembler/simple.ts @@ -114,7 +114,6 @@ function _getSlotMaterial (tex: TextureBase | null, blendMode: BlendMode) { dst = BlendFactor.ONE_MINUS_SRC_ALPHA; break; } - _comp!.setBlendHash(); return _comp!.getMaterialForBlend(src, dst); } diff --git a/cocos/native-binding/impl.ts b/cocos/native-binding/impl.ts index b2ac5a301c..1b95baf61d 100644 --- a/cocos/native-binding/impl.ts +++ b/cocos/native-binding/impl.ts @@ -133,4 +133,11 @@ export const native = { fileUtils: globalJsb.fileUtils, DebugRenderer: globalJsb.DebugRenderer, copyTextToClipboard: globalJsb.copyTextToClipboard?.bind(globalJsb), + garbageCollect: globalJsb.garbageCollect, + reflection: globalJsb.reflection, + bridge: globalJsb.bridge, + jsbBridgeWrapper: globalJsb.jsbBridgeWrapper, + AssetsManager: globalJsb.AssetsManager, + EventAssetsManager: globalJsb.EventAssetsManager, + Manifest: globalJsb.Manifest, }; diff --git a/cocos/native-binding/index.ts b/cocos/native-binding/index.ts index 5a19c2764e..1daf159025 100644 --- a/cocos/native-binding/index.ts +++ b/cocos/native-binding/index.ts @@ -40,7 +40,326 @@ export declare namespace native { * @en Copy text to clipboard @zh 拷贝字符串到剪切板 * @param text */ - export function copyTextToClipboard(text:string): void; + export function copyTextToClipboard(text: string): void; + + /** + * @en Trigger garbage collection of ScriptEngine @zh 触发 ScriptEngine 的 GC + */ + export function garbageCollect(): void; + + export class EventAssetsManager { + // methods list + getEventCode(): number; + getCURLECode(): number; + getCURLMCode(): number; + getMessage(): string; + getAssetId(): string; + getAssetsManagerEx(): AssetsManager; + isResuming(): boolean; + getPercent(): number; + getPercentByFile(): number; + getDownloadedBytes(): number; + getTotalBytes(): number; + getDownloadedFiles(): number; + getTotalFiles(): number; + constructor(eventName: string, manager: AssetsManager, code: number, assetId: string, message: string, curleCode: number, curlmCode: number); + } + + export namespace EventAssetsManager { + export const ERROR_NO_LOCAL_MANIFEST:number; + export const ERROR_DOWNLOAD_MANIFEST:number; + export const ERROR_PARSE_MANIFEST :number; + export const NEW_VERSION_FOUND :number; + export const ALREADY_UP_TO_DATE :number; + export const UPDATE_PROGRESSION :number; + export const ASSET_UPDATED :number; + export const ERROR_UPDATING :number; + export const UPDATE_FINISHED :number; + export const UPDATE_FAILED :number; + export const ERROR_DECOMPRESS :number; + } + + export interface ManifestAsset { + md5: string; + path: string; + compressed: boolean; + size: number; + downloadState: number; + } + + export class Manifest { + /** + * @en Check whether the version informations have been fully loaded + * @zh 检查是否已加载版本信息 + */ + isVersionLoaded(): boolean; + /** + * @en Check whether the manifest have been fully loaded + * @zh 检查是否已加载 manifest + */ + isLoaded(): boolean; + /** + * @en Gets remote package url. + * @zh 获取远程包的 URL + */ + getPackageUrl(): string; + /** + * @en Gets remote manifest file url. + * @zh 获取远程 manifest 文件的 URL + */ + getManifestFileUrl(): string; + /** + * @en Gets remote version file url. + * @zh 获取远程版本文件的 URL + */ + getVersionFileUrl(): string; + /** + * @en Gets manifest version. + * @zh 获取远程 manifest 文件的版本 + */ + getVersion(): string; + /** + * @en Get the search paths list related to the Manifest. + * @zh 返回 Manifest 相关的搜索路径 + */ + getSearchPaths(): string[]; + /** + * @en Get the manifest root path, normally it should also be the local storage path. + * @zh 获取 manifest 的根路径, 一般为本地存储目录. + */ + getManifestRoot(): string; + + constructor(content: string, manifestRoot: string); + constructor(manifestUrl: string); + /** + * @en Parse the manifest file information into this manifest + * @zh 解析 manifest 文件 + * @param manifestUrl @en Url of the local manifest @zh 文件路径 + */ + parseFile(manifestUrl: string): void; + /** + * @en Parse the manifest from json string into this manifest + * @zh 解析 manifest 的 JSON 文件 + * @param content @en Json string content @zh JSON 文本 + * @param manifestRoot @en The root path of the manifest file (It should be local path, + * so that we can find assets path relative to the root path) @zh manifest 根路径 + */ + parseJSONString(content: string, manifestRoot: string): void; + /** + * @en Get whether the manifest is being updating + * @en 是否在更新 + * @return @en Updating or not @zh 是否在更新 + */ + isUpdating(): boolean; + /** + * @en Set whether the manifest is being updating + * @zh 设置更新状态 + * @param updating @en Updating or not @zh 是否更新 + */ + setUpdating(updating: boolean): void; + } // endof class Manifest + + export namespace Manifest { + export enum DownloadState { + UNSTARTED, + DOWNLOADING, + SUCCESSED, + UNMARKED, + } + } + + export class AssetsManager { + // static methods list + /** + * @en Create function for creating a new AssetsManagerEx + * + * warning The cached manifest in your storage path have higher priority and will be searched first, + * only if it doesn't exist, AssetsManagerEx will use the given manifestUrl. + * + * @zh 创建 AssetManager + * + * @param manifestUrl @en The url for the local manifest file @zh manifest 文件路径 + * @param storagePath @en The storage path for downloaded assets @zh 存储路径 + */ + static create(manifestUrl: string, storagePath: string): AssetsManager; + // methods list + constructor(manifestUrl: string, storagePath: string, handle: (arg1: string, arg2: string) => number); + constructor(manifestUrl: string, storagePath: string); + /** + * @en Check out if there is a new version of manifest. + * You may use this method before updating, then let user determine whether + * he wants to update resources. + * @zh 检查更新 + */ + checkUpdate(): void; // void + /** + * @en Prepare the update process, this will cleanup download process flags, + * fill up download units with temporary manifest or remote manifest + * @zh 准备更新 + */ + prepareUpdate(): void; // void + /** + * @en Update with the current local manifest. + * @zh 执行更新 + */ + update(): void; // void + /** + * @en Reupdate all failed assets under the current AssetsManagerEx context + * @zh 重新下载之前失败的资源 + */ + downloadFailedAssets(): void; // void + /** + * @en Gets the current update state. + * @zh 返回当前的状态码 + */ + getState(): number; // cc::extension::AssetsManagerEx::State + /** + * @en Gets storage path. + * @zh 获取存储路径 + */ + getStoragePath(): string; // std::string + /** + * @en Function for retrieving the local manifest object + * @zh 获取本地 manifest 路径 + */ + getLocalManifest(): Manifest; // cc::extension::Manifest* + /** + * @en Load a local manifest from url. + * + * You can only manually load local manifest when the update state is UNCHECKED, it will fail once the update process is began. + * + * This API will do the following things: + * + * 1. Reset storage path + * + * 2. Set local storage + * + * 3. Search for cached manifest and compare with the local manifest + * + * 4. Init temporary manifest and remote manifest + * + * If successfully load the given local manifest and inited other manifests, it will return true, otherwise it will return false + * @zh 加载本地的 manifest + * @param manifestUrl @en The local manifest url @zh manifest 路径 + */ + loadLocalManifest(manifestUrl: string): boolean; + /** + * @en Load a custom local manifest object, the local manifest must be loaded already. + * + * You can only manually load local manifest when the update state is UNCHECKED, it will fail once the update process is began. + * + * This API will do the following things: + * + * 1. Reset storage path + * + * 2. Set local storage + * + * 3. Search for cached manifest and compare with the local manifest + * + * 4. Init temporary manifest and remote manifest + * + * If successfully load the given local manifest and inited other manifests, it will return true, otherwise it will return false + * @zh 加载本地的 manifest + * + * @param localManifest @en The local manifest object to be set @zh manifest 对象 + * + * @param storagePath @en The local storage path @zh 存储路径 + */ + loadLocalManifest(localManifest: Manifest, storagePath: string): boolean; + /** + * @en Function for retrieving the remote manifest object + * @zh 获取远程的 manifest 对象 + */ + getRemoteManifest(): Manifest; + /** + * @en Load a custom remote manifest object, the manifest must be loaded already. + * + * You can only manually load remote manifest when the update state is UNCHECKED and local manifest is already inited, + * it will fail once the update process is began. + * @zh 加载自定义i的远程 manifest 对象 + * @param remoteManifest @en The remote manifest object to be set @zh manifest 对象 + */ + loadRemoteManifest(remoteManifest: Manifest): boolean; + /** + * @en Gets whether the current download is resuming previous unfinished job, + * this will only be available after READY_TO_UPDATE state, + * under unknown states it will return false by default. + * @zh 是否在恢复状态 + */ + isResuming(): boolean; + /** + * @en Gets the total byte size to be downloaded of the update, this will only be available + * after READY_TO_UPDATE state, under unknown states it will return 0 by default. + * @zh 需要下载或者更新的总字节数 + */ + getTotalBytes(): number; + /** + * @en Gets the current downloaded byte size of the update, this will only be available + * after READY_TO_UPDATE state, under unknown states it will return 0 by default. + * @zh 已下载的字节数 + */ + getDownloadedBytes(): number; + /** + * @en Gets the total files count to be downloaded of the update, this will only be available + * after READY_TO_UPDATE state, under unknown states it will return 0 by default. + * @zh 需要下载的总的文件数目 + */ + getTotalFiles(): number; + /** + * @en Gets the current downloaded files count of the update, this will only be available + * after READY_TO_UPDATE state, under unknown states it will return 0 by default. + * @zh 已下载的文件数目 + */ + getDownloadedFiles(): number; + /** + * @en Function for retrieving the max concurrent task count + * @zh 下载的最大并发数 + */ + getMaxConcurrentTask(): number; + /** + * @en Function for setting the max concurrent task count + * @zh 设置下载的最大并发数目 + */ + setMaxConcurrentTask(max: number): void; + /** + * @en Set the handle function for comparing manifests versions + * @zh 设置版本比对函数 + * + * @param handle @en The compare function @zh 比较函数 + */ + setVersionCompareHandle(handle: (arg1: string, arg2: string) => number): void; + /** + * @en Set the verification function for checking whether downloaded asset is correct, e.g. using md5 verification + * @zh 设置内容校验函数 + * @param callback @en The verify callback function @zh 校验函数 + */ + setVerifyCallback(callback: (arg1: string, arg: ManifestAsset) => boolean): void; + /** + * @en Set the event callback for receiving update process events + * @zh 设置更新事件处理回调 + * @param callback @en The event callback function @zh 事件处理回调 + */ + setEventCallback(callback: (arg: EventAssetsManager) => void): void; + } + + export namespace AssetsManager { + export enum State { + UNINITED, + UNCHECKED, + PREDOWNLOAD_VERSION, + DOWNLOADING_VERSION, + VERSION_LOADED, + PREDOWNLOAD_MANIFEST, + DOWNLOADING_MANIFEST, + MANIFEST_LOADED, + NEED_UPDATE, + READY_TO_UPDATE, + UPDATING, + UNZIPPING, + UP_TO_DATE, + FAIL_TO_UPDATE, + } + } /** * @en DownloaderHints @zh 下载任务的配置接口 @@ -84,7 +403,7 @@ export declare namespace native { * let downloader = new native.Downloader(hints); // create a Downloader object with DownloaderHints * ``` */ - constructor (hints: DownloaderHints); + constructor(hints: DownloaderHints); /** * @en create a download task. The maximum size for a single download file is 4GB. @@ -98,7 +417,7 @@ export declare namespace native { * let task = downloader.createDownloadTask('https://example.com/exampleFile.zip', native.fileUtils.getWritablePath()); * ``` */ - createDownloadTask (requestURL:string, storagePath:string, identifier?:string): DownloaderTask; + createDownloadTask(requestURL: string, storagePath: string, identifier?: string): DownloaderTask; /** * @en setter for the callback function after download success @@ -161,7 +480,7 @@ export declare namespace native { * let task = downloader.createDownloadFileTask('https://example.com/exampleFile.zip', native.fileUtils.getWritablePath()); * ``` */ - createDownloadFileTask (requestURL:string, storagePath:string, identifier?:string): DownloaderTask; + createDownloadFileTask(requestURL: string, storagePath: string, identifier?: string): DownloaderTask; /** * @deprecated since v3.6.0, please use setter `onSuccess` to instead. @@ -176,7 +495,7 @@ export declare namespace native { * }); * ``` */ - setOnFileTaskSuccess (onSucceed: (task: DownloaderTask) => void): void; + setOnFileTaskSuccess(onSucceed: (task: DownloaderTask) => void): void; /** * @deprecated since v3.6.0, please use setter `onProgress` to instead. @@ -192,7 +511,7 @@ export declare namespace native { * }); * ``` */ - setOnTaskProgress (onProgress: (task: DownloaderTask, bytesReceived: number, + setOnTaskProgress(onProgress: (task: DownloaderTask, bytesReceived: number, totalBytesReceived: number, totalBytesExpected: number) => void): void; /** * @deprecated since v3.6.0, please use setter `onError` to instead. @@ -207,14 +526,14 @@ export declare namespace native { * }); * ``` */ - setOnTaskError (onError: (task: DownloaderTask, errorCode: number, errorCodeInternal: number, errorStr: string) => void): void; + setOnTaskError(onError: (task: DownloaderTask, errorCode: number, errorCodeInternal: number, errorStr: string) => void): void; } /** * @en ZipUtils Helper class to handle unzip related operations. * @zh ZipUtils 对解压操作的辅助类。 */ - export namespace zipUtils{ + export namespace zipUtils { /** * @en * Inflates either zlib or gzip deflated memory. The inflated memory is expected to be freed by the caller. @@ -230,7 +549,7 @@ export declare namespace native { * * @return @en The deflated buffer. @zh 解压后的数据缓存区 */ - export function inflateMemory(input:string | ArrayBuffer | TypedArray, outLengthHint?: number): ArrayBuffer | null; + export function inflateMemory(input: string | ArrayBuffer | TypedArray, outLengthHint?: number): ArrayBuffer | null; /** * @en Inflates a GZip file into memory. @@ -240,7 +559,7 @@ export declare namespace native { * * @return @en The deflated buffer. @zh 解压后的数据缓存区 */ - export function inflateGZipFile(path:string): ArrayBuffer | null; + export function inflateGZipFile(path: string): ArrayBuffer | null; /** * @en Test a file is a GZip format file or not. @@ -250,7 +569,7 @@ export declare namespace native { * * @return @en True is a GZip format file. false is not. @zh true GZip 格式文件,否则不是。 */ - export function isGZipFile(path:string): boolean; + export function isGZipFile(path: string): boolean; /** * @en Test the buffer is GZip format or not. @@ -260,7 +579,7 @@ export declare namespace native { * * @return @en True is GZip format. false is not. @zh 返回true表示是 GZip 格式,否则不是。 */ - export function isGZipBuffer(buffer:string | ArrayBuffer | TypedArray): boolean; + export function isGZipBuffer(buffer: string | ArrayBuffer | TypedArray): boolean; /** * @en Inflates a CCZ file into memory. @@ -269,7 +588,7 @@ export declare namespace native { * @param path @en The CCZ file path. @zh CCZ 文件的路径 * @return @en The deflated buffer. @zh 解压后的数据缓存区 */ - export function inflateCCZFile(path:string): ArrayBuffer | null; + export function inflateCCZFile(path: string): ArrayBuffer | null; /** * @en Inflates a buffer with CCZ format into memory. @@ -279,7 +598,7 @@ export declare namespace native { * * @return @en The deflated buffer. @zh 解压后的数据缓存区 */ - export function inflateCCZBuffer(buffer:string | ArrayBuffer | TypedArray): ArrayBuffer | null; + export function inflateCCZBuffer(buffer: string | ArrayBuffer | TypedArray): ArrayBuffer | null; /** * @en Test a file is a CCZ format file or not. @@ -287,7 +606,7 @@ export declare namespace native { * * @return @en True is a CCZ format file. false is not. @zh 返回true表示是 CCZ 格式,否则不是。 */ - export function isCCZFile(path:string): boolean; + export function isCCZFile(path: string): boolean; /** * @en Test the buffer is CCZ format or not. @@ -297,7 +616,7 @@ export declare namespace native { * * @return @en True is CCZ format. false is not. @zh 返回true表示是 CCZ 格式,否则不是。 */ - export function isCCZBuffer(buffer:string | ArrayBuffer | TypedArray): boolean; + export function isCCZBuffer(buffer: string | ArrayBuffer | TypedArray): boolean; /** * @en @@ -342,7 +661,7 @@ export declare namespace native { * @param index @en Part of the key [0..3]. @zh 密钥[0..3]的部分。 * @param value @en Value of the key part. @zh 密钥部分的值。 */ - export function setPvrEncryptionKeyPart(index:number, value:number): void; + export function setPvrEncryptionKeyPart(index: number, value: number): void; /** * @en @@ -374,7 +693,7 @@ export declare namespace native { * @param keyPart3 @en The key value part 3. @zh 密钥部分 3 的值。 * @param keyPart4 @en The key value part 4. @zh 密钥部分 4 的值。 */ - export function setPvrEncryptionKey(keyPart1:number, keyPart2:number, keyPart3:number, keyPart4:number): void; + export function setPvrEncryptionKey(keyPart1: number, keyPart2: number, keyPart3: number, keyPart4: number): void; } /** @@ -393,7 +712,7 @@ export declare namespace native { * @param path The path that needs to be checked. * @return True if it's an absolute path, false if not. */ - export function isAbsolutePath (path:string):boolean; + export function isAbsolutePath(path: string): boolean; /** * @en * Returns the fullpath for a given filename. @@ -443,7 +762,7 @@ export declare namespace native { * 通过文件名获取绝对路径 * @since v2.1 */ - export function fullPathForFilename (filename:string):string; + export function fullPathForFilename(filename: string): string; /** * * @en @@ -453,7 +772,7 @@ export declare namespace native { * 读取文件里的字符串 * */ - export function getStringFromFile (filename:string):string; + export function getStringFromFile(filename: string): string; /** * @en * Removes a file. @@ -464,7 +783,7 @@ export declare namespace native { * @param filepath The full path of the file, it must be an absolute path. * @return True if the file have been removed successfully, false if not. */ - export function removeFile (filepath:string):boolean; + export function removeFile(filepath: string): boolean; /** * @en * Checks whether the path is a directory. @@ -475,7 +794,7 @@ export declare namespace native { * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return True if the directory exists, false if not. */ - export function isDirectoryExist (dirPath:string):boolean; + export function isDirectoryExist(dirPath: string): boolean; /** * @en * Normalize: remove . and .. @@ -485,7 +804,7 @@ export declare namespace native { * * @param filepath */ - export function normalizePath (filepath:string):string; + export function normalizePath(filepath: string): string; /** * @en * Gets the array of search paths. @@ -494,7 +813,7 @@ export declare namespace native { * 获取默认资源根路径 * */ - export function getDefaultResourceRootPath ():string; + export function getDefaultResourceRootPath(): string; /** * @en @@ -505,7 +824,7 @@ export declare namespace native { * 将文件的内容转换为 ValueVector * 这个方法是内部使用的 */ - export function getValueVectorFromFile (filepath:string):Array; + export function getValueVectorFromFile(filepath: string): Array; /** * @en * Gets the array of search paths. @@ -520,7 +839,7 @@ export declare namespace native { * @see fullPathForFilename (const char*). * @lua NA */ - export function getSearchPaths ():Array; + export function getSearchPaths(): Array; /** * @en * Get the directory where the file is located by the file path. @@ -529,7 +848,7 @@ export declare namespace native { * 通过文件路径获取文件所在目录 * @param filepath */ - export function getFileDir (filepath:string):string; + export function getFileDir(filepath: string): string; /** * @en * write a ValueMap into a plist file. @@ -540,7 +859,7 @@ export declare namespace native { * @param dict the ValueMap want to save (key,value) * @return bool */ - export function writeToFile (valueMap:any):boolean; + export function writeToFile(valueMap: any): boolean; /** * @en * Gets the original search path array set by 'setSearchPaths' or 'addSearchPath'. @@ -550,7 +869,7 @@ export declare namespace native { * * @return The array of the original search paths */ - export function getOriginalSearchPaths ():Array; + export function getOriginalSearchPaths(): Array; /** * @en * List all files in a directory @@ -561,7 +880,7 @@ export declare namespace native { * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return File paths in a string vector */ - export function listFiles (filepath:string):Array; + export function listFiles(filepath: string): Array; /** * @en * Converts the contents of a file to a ValueMap. @@ -573,7 +892,7 @@ export declare namespace native { * @return ValueMap of the file contents. * @note This method is used internally. */ - export function getValueMapFromFile (filepath:string):any; + export function getValueMapFromFile(filepath: string): any; /** * @en * Retrieve the file size. @@ -584,7 +903,7 @@ export declare namespace native { * @param filepath The path of the file, it could be a relative or absolute path. * @return The file size. */ - export function getFileSize (filepath:string):number; + export function getFileSize(filepath: string): number; /** * @en @@ -596,7 +915,7 @@ export declare namespace native { * 这个方法是内部使用的 * */ - export function getValueMapFromData (filedata:string, filesize:number):any; + export function getValueMapFromData(filedata: string, filesize: number): any; /** * * @en @@ -608,7 +927,7 @@ export declare namespace native { * @param dirPath The full path of the directory, it must be an absolute path. * @return True if the directory have been removed successfully, false if not. */ - export function removeDirectory (dirPath:string):boolean; + export function removeDirectory(dirPath: string): boolean; /** * @en * Sets the array of search paths. @@ -632,7 +951,7 @@ export declare namespace native { * In js:var setSearchPaths(var jsval); * @lua NA */ - export function setSearchPaths (searchPath:Array):void; + export function setSearchPaths(searchPath: Array): void; /** * @en * write a string into a file. @@ -644,7 +963,7 @@ export declare namespace native { * @param fullPath The full path to the file you want to save a string * @return bool True if write success */ - export function writeStringToFile (dataStr:string, fullPath:string):boolean; + export function writeStringToFile(dataStr: string, fullPath: string): boolean; /** * @en @@ -655,7 +974,7 @@ export declare namespace native { * * @since v2.1 */ - export function addSearchPath (path:string, front:boolean):void; + export function addSearchPath(path: string, front: boolean): void; /** * * @en @@ -668,7 +987,7 @@ export declare namespace native { *@param fullPath The full path to the file you want to save a string *@return bool */ - export function writeValueVectorToFile (vecData:Array, fullPath:string):boolean; + export function writeValueVectorToFile(vecData: Array, fullPath: string): boolean; /** * @en * Checks whether a file exists. @@ -680,7 +999,7 @@ export declare namespace native { * @param filename The path of the file, it could be a relative or absolute path. * @return True if the file exists, false if not. */ - export function isFileExist (filename:string):boolean; + export function isFileExist(filename: string): boolean; /** * * @en @@ -689,7 +1008,7 @@ export declare namespace native { * @zh * 清除路径缓存 */ - export function purgeCachedEntries ():void; + export function purgeCachedEntries(): void; /** * @en * Gets full path from a file name and the path of the relative file. @@ -704,7 +1023,7 @@ export declare namespace native { * Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. ) * */ - export function fullPathFromRelativeFile (filename:string, relativeFile:string):string; + export function fullPathFromRelativeFile(filename: string, relativeFile: string): string; /** * @en * Windows fopen can't support UTF-8 filename @@ -716,7 +1035,7 @@ export declare namespace native { * @param filenameUtf8 std::string name file for conversion from utf-8 * @return std::string ansi filename in current locale */ - export function getSuitableFOpen (filenameUtf8:string):string; + export function getSuitableFOpen(filenameUtf8: string): string; /** * * @en @@ -728,7 +1047,7 @@ export declare namespace native { * @param fullPath The full path to the file you want to save a string * @return bool */ - export function writeValueMapToFile (dict:any, fullPath:string):string; + export function writeValueMapToFile(dict: any, fullPath: string): string; /** * @en * Gets filename extension is a suffix (separated from the base filename by a dot) in lower case. @@ -740,7 +1059,7 @@ export declare namespace native { * @param filePath The path of the file, it could be a relative or absolute path. * @return suffix for filename in lower case or empty if a dot not found. */ - export function getFileExtension (filePath:string):string; + export function getFileExtension(filePath: string): string; /** * @en * Sets writable path. @@ -750,7 +1069,7 @@ export declare namespace native { * * @param writablePath The path of the directory. */ - export function setWritablePath (writablePath:string):void; + export function setWritablePath(writablePath: string): void; /** * @en * Set default resource root path. @@ -760,7 +1079,7 @@ export declare namespace native { * * @param dirPath The path of the directory. */ - export function setDefaultResourceRootPath (dirPath:string):void; + export function setDefaultResourceRootPath(dirPath: string): void; /** * @en @@ -772,7 +1091,7 @@ export declare namespace native { * @param dirPath The path of the directory, it must be an absolute path. * @return True if the directory have been created successfully, false if not. */ - export function createDirectory (dirPath:string):string; + export function createDirectory(dirPath: string): string; /** * @en * List all files recursively in a directory. @@ -783,12 +1102,12 @@ export declare namespace native { * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return File paths in a string vector */ - export function listFilesRecursively (dirPath:string, files:Array):void; + export function listFilesRecursively(dirPath: string, files: Array): void; /** * Gets the writable path. * @return The path that can be write/read a file in */ - export function getWritablePath():string; + export function getWritablePath(): string; /** * @en @@ -801,7 +1120,7 @@ export declare namespace native { * @param newFullPath The new fullpath of the file. Includes path and name. * @return True if the file have been renamed successfully, false if not. */ - export function renameFile(oldFullpath: string, newFullPath: string):boolean; + export function renameFile(oldFullpath: string, newFullPath: string): boolean; /** * @en @@ -813,7 +1132,7 @@ export declare namespace native { * @param fullpath The current fullpath of the file. Includes path and name. * @return A data object. */ - export function getDataFromFile(fullpath: string):ArrayBuffer; + export function getDataFromFile(fullpath: string): ArrayBuffer; /** * @en @@ -826,7 +1145,7 @@ export declare namespace native { * @param fullpath The full path to the file you want to save a string * @return bool */ - export function writeDataToFile(buffer: ArrayBuffer, fullpath: string):boolean; + export function writeDataToFile(buffer: ArrayBuffer, fullpath: string): boolean; } /** @@ -868,7 +1187,7 @@ export declare namespace native { * @param screenPos @en the output screen position @zh 输出的屏幕位置 * @param info @en the output text information @zh 输出的文本属性 */ - addText(text:string, screenPos: Vec2, info?: DebugTextInfo): void; + addText(text: string, screenPos: Vec2, info?: DebugTextInfo): void; } export namespace reflection { @@ -882,7 +1201,7 @@ export declare namespace native { * @param methodSignature : @en the method signature of the Objective-C/Java class @zh Objective-C/Java 方法签名 * @param parameters : @en the parameters of the Objective-C/Java class to translate @zh 传递至该 Objective-C/Java 方法的参数 */ - export function callStaticMethod (methodName: string, methodSignature: string, ...parameters:any): any; + export function callStaticMethod(className: string, methodName: string, methodSignature: string, ...parameters: any): any; } /** @@ -937,7 +1256,7 @@ export declare namespace native { * @param arg0 : @en the first parameter @zh 第一个参数 * @param arg1 : @en the second parameter @zh 第二个参数 */ - export function onNative(arg0: string, arg1?: string|null): void; + export function onNative(arg0: string, arg1?: string | null): void; } /** * @en diff --git a/cocos/particle/renderer/particle-system-renderer-data.ts b/cocos/particle/renderer/particle-system-renderer-data.ts index 7c25be4fad..12108f38a1 100644 --- a/cocos/particle/renderer/particle-system-renderer-data.ts +++ b/cocos/particle/renderer/particle-system-renderer-data.ts @@ -32,7 +32,7 @@ import ParticleSystemRendererGPU from './particle-system-renderer-gpu'; import { director } from '../../core/director'; import { Device, Feature, Format, FormatFeatureBit } from '../../core/gfx'; import { legacyCC } from '../../core/global-exports'; -import { errorID } from '../../core'; +import { errorID, warnID } from '../../core'; function isSupportGPUParticle () { const device: Device = director.root!.device; @@ -170,6 +170,7 @@ export default class ParticleSystemRenderer { } else { const effectName = val.effectName; if (effectName.indexOf('particle') === -1 || effectName.indexOf('particle-gpu') !== -1) { + warnID(6035); return; } } @@ -198,6 +199,7 @@ export default class ParticleSystemRenderer { } else { const effectName = val.effectName; if (effectName.indexOf('particle-gpu') === -1) { + warnID(6035); return; } } diff --git a/cocos/physics/bullet/bullet-contact-data.ts b/cocos/physics/bullet/bullet-contact-data.ts index b371def21f..8e4602e117 100644 --- a/cocos/physics/bullet/bullet-contact-data.ts +++ b/cocos/physics/bullet/bullet-contact-data.ts @@ -33,12 +33,15 @@ import { bullet2CocosQuat, bullet2CocosVec3 } from './bullet-utils'; export class BulletContactData implements IContactEquation { get isBodyA (): boolean { const sb = (this.event.selfCollider.shape as BulletShape).sharedBody.body; - return sb === bt.PersistentManifold_getBody0(this.impl); + return sb === bt.PersistentManifold_getBody0(this.event.impl); } - impl: Bullet.ptr = 0; + impl: Bullet.ptr = 0; //btManifoldPoint + event: ICollisionEvent; - constructor (public event: ICollisionEvent) { } + constructor (event: ICollisionEvent) { + this.event = event; + } getLocalPointOnA (out: IVec3Like): void { if (this.impl) bullet2CocosVec3(out, bt.ManifoldPoint_get_m_localPointA(this.impl)); @@ -59,7 +62,7 @@ export class BulletContactData implements IContactEquation { getLocalNormalOnA (out: IVec3Like): void { if (this.impl) { const bt_rot = BulletCache.instance.BT_QUAT_0; - const body = bt.PersistentManifold_getBody0(this.impl); + const body = bt.PersistentManifold_getBody0(this.event.impl); const trans = bt.CollisionObject_getWorldTransform(body); bt.Transform_getRotation(trans, bt_rot); const inv_rot = CC_QUAT_0; @@ -74,7 +77,7 @@ export class BulletContactData implements IContactEquation { getLocalNormalOnB (out: IVec3Like): void { if (this.impl) { const bt_rot = BulletCache.instance.BT_QUAT_0; - const body = bt.PersistentManifold_getBody1(this.impl); + const body = bt.PersistentManifold_getBody1(this.event.impl); const trans = bt.CollisionObject_getWorldTransform(body); bt.Transform_getRotation(trans, bt_rot); const inv_rot = CC_QUAT_0; diff --git a/cocos/physics/bullet/bullet-world.ts b/cocos/physics/bullet/bullet-world.ts index fc7faff2d2..7466543c2b 100644 --- a/cocos/physics/bullet/bullet-world.ts +++ b/cocos/physics/bullet/bullet-world.ts @@ -276,7 +276,7 @@ export class BulletWorld implements IPhysicsWorld { TriggerEventObject.type = 'onTriggerEnter'; this.triggerArrayMat.set(shape0.id, shape1.id, true); } - TriggerEventObject.impl = data.impl; + TriggerEventObject.impl = data.impl; //btPersistentManifold TriggerEventObject.selfCollider = collider0; TriggerEventObject.otherCollider = collider1; collider0.emit(TriggerEventObject.type, TriggerEventObject); @@ -303,16 +303,18 @@ export class BulletWorld implements IPhysicsWorld { } for (let i = 0; i < data.contacts.length; i++) { - const cq = data.contacts[i]; + const cq = data.contacts[i]; //btManifoldPoint if (contactsPool.length > 0) { - const c = contactsPool.pop(); c!.impl = cq; + const c = contactsPool.pop(); + c!.impl = cq; //btManifoldPoint CollisionEventObject.contacts.push(c!); } else { - const c = new BulletContactData(CollisionEventObject); c.impl = cq; + const c = new BulletContactData(CollisionEventObject); + c.impl = cq; //btManifoldPoint CollisionEventObject.contacts.push(c); } } - CollisionEventObject.impl = data.impl; + CollisionEventObject.impl = data.impl; //btPersistentManifold CollisionEventObject.selfCollider = collider0; CollisionEventObject.otherCollider = collider1; collider0.emit(CollisionEventObject.type, CollisionEventObject); @@ -383,10 +385,10 @@ export class BulletWorld implements IPhysicsWorld { gatherConatactData () { const numManifolds = bt.Dispatcher_getNumManifolds(this._dispatcher); for (let i = 0; i < numManifolds; i++) { - const manifold = bt.Dispatcher_getManifoldByIndexInternal(this._dispatcher, i); + const manifold = bt.Dispatcher_getManifoldByIndexInternal(this._dispatcher, i);//btPersistentManifold const numContacts = bt.PersistentManifold_getNumContacts(manifold); for (let j = 0; j < numContacts; j++) { - const manifoldPoint = bt.PersistentManifold_getContactPoint(manifold, j); + const manifoldPoint = bt.PersistentManifold_getContactPoint(manifold, j);//btManifoldPoint const s0 = bt.ManifoldPoint_getShape0(manifoldPoint); const s1 = bt.ManifoldPoint_getShape1(manifoldPoint); const shape0: BulletShape = BulletCache.getWrapper(s0, BulletShape.TYPE); @@ -400,7 +402,7 @@ export class BulletWorld implements IPhysicsWorld { item = this.contactsDic.set(shape0.id, shape1.id, { shape0, shape1, contacts: [], impl: manifold }); } - item.contacts.push(manifoldPoint); + item.contacts.push(manifoldPoint);//btManifoldPoint } } } diff --git a/cocos/spine/lib/spine-core.js b/cocos/spine/lib/spine-core.js index a1a88d96ac..b2137750c1 100644 --- a/cocos/spine/lib/spine-core.js +++ b/cocos/spine/lib/spine-core.js @@ -7735,7 +7735,7 @@ var spine; return _this; } BoundingBoxAttachment.prototype.copy = function () { - var copy = new BoundingBoxAttachment(name); + var copy = new BoundingBoxAttachment(this.name); this.copyTo(copy); copy.color.setFromColor(this.color); return copy; @@ -7754,7 +7754,7 @@ var spine; return _this; } ClippingAttachment.prototype.copy = function () { - var copy = new ClippingAttachment(name); + var copy = new ClippingAttachment(this.name); this.copyTo(copy); copy.endSlot = this.endSlot; copy.color.setFromColor(this.color); @@ -7898,7 +7898,7 @@ var spine; return _this; } PathAttachment.prototype.copy = function () { - var copy = new PathAttachment(name); + var copy = new PathAttachment(this.name); this.copyTo(copy); copy.lengths = new Array(this.lengths.length); spine.Utils.arrayCopy(this.lengths, 0, copy.lengths, 0, this.lengths.length); @@ -7932,7 +7932,7 @@ var spine; return Math.atan2(y, x) * spine.MathUtils.radDeg; }; PointAttachment.prototype.copy = function () { - var copy = new PointAttachment(name); + var copy = new PointAttachment(this.name); copy.x = this.x; copy.y = this.y; copy.rotation = this.rotation; @@ -8040,7 +8040,7 @@ var spine; worldVertices[offset + 1] = offsetX * c + offsetY * d + y; }; RegionAttachment.prototype.copy = function () { - var copy = new RegionAttachment(name); + var copy = new RegionAttachment(this.name); copy.region = this.region; copy.rendererObject = this.rendererObject; copy.path = this.path; diff --git a/cocos/spine/skeleton.ts b/cocos/spine/skeleton.ts index 55fee777f0..edd0e034f9 100644 --- a/cocos/spine/skeleton.ts +++ b/cocos/spine/skeleton.ts @@ -1388,18 +1388,6 @@ export class Skeleton extends UIRenderer { this.markForUpdateRenderData(); } - protected updateMaterial () { - if (this._customMaterial) { - this.setMaterial(this._customMaterial, 0); - this._blendHash = -1; // a flag to check merge - return; - } - const mat = this._updateBuiltinMaterial(); - this.setMaterial(mat, 0); - this._updateBlendFunc(); - this._blendHash = -1; - } - public querySockets () { if (!this._skeleton) { return []; @@ -1743,6 +1731,13 @@ export class Skeleton extends UIRenderer { renderEntity.setUseLocal(true); return renderEntity; } + + public markForUpdateRenderData (enable = true) { + super.markForUpdateRenderData(enable); + if (this._debugRenderer) { + this._debugRenderer.markForUpdateRenderData(enable); + } + } } legacyCC.internal.SpineSkeleton = Skeleton; diff --git a/cocos/tiledmap/tiled-object-group.ts b/cocos/tiledmap/tiled-object-group.ts index c4400cf52f..821560607c 100644 --- a/cocos/tiledmap/tiled-object-group.ts +++ b/cocos/tiledmap/tiled-object-group.ts @@ -342,11 +342,16 @@ export class TiledObjectGroup extends Component { sprite.sizeMode = Sprite.SizeMode.CUSTOM; - // @ts-expect-error remove when component remove blend function - sprite._srcBlendFactor = this._premultiplyAlpha ? BlendFactor.ONE : BlendFactor.SRC_ALPHA; - // @ts-expect-error remove when component remove blend function - sprite._dstBlendFactor = BlendFactor.ONE_MINUS_SRC_ALPHA; - sprite._updateBlendFunc(); + // HACK: we should support _premultiplyAlpha when group had material + const srcBlendFactor = this._premultiplyAlpha ? BlendFactor.ONE : BlendFactor.SRC_ALPHA; + // @ts-expect-error remove when ui-render remove blend + if (sprite._srcBlendFactor !== srcBlendFactor) { + // @ts-expect-error remove when ui-render remove blend + sprite._srcBlendFactor = srcBlendFactor; + if (sprite.material) { + sprite._updateBlendFunc(); + } + } let spf = grid.spriteFrame; if (!spf) { diff --git a/cocos/ui/widget.ts b/cocos/ui/widget.ts index 8731a549f4..769aca8b5c 100644 --- a/cocos/ui/widget.ts +++ b/cocos/ui/widget.ts @@ -951,7 +951,7 @@ export class Widget extends Component { } protected _setDirtyByMode () { - if (this.alignMode === AlignMode.ALWAYS || EDITOR) { + if (this.alignMode === AlignMode.ALWAYS || (EDITOR && !legacyCC.GAME_VIEW)) { this._recursiveDirty(); } } diff --git a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk index 137f3e6742..735b9ffe71 100644 --- a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk +++ b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk @@ -196,9 +196,11 @@ float CCGetLinearDepth(vec3 worldPos) { pos = ApplyShadowDepthBias_Perspective(shadowPos, shadowBias.x); #endif - if (pcf > 2.9) { - return CCGetSpotLightShadowFactorSoft5X(pos, worldPos); - } else if (pcf > 1.9) { + /*todo: use CC_SHADOWMAP_PCF_TYPE for better performance + if (pcf > 2.9) { + return CCGetSpotLightShadowFactorSoft5X(pos, worldPos); + } else */ + if (pcf > 1.9) { return CCGetSpotLightShadowFactorSoft3X(pos, worldPos); }else if (pcf > 0.9) { return CCGetSpotLightShadowFactorSoft(pos, worldPos); @@ -214,9 +216,11 @@ float CCGetLinearDepth(vec3 worldPos) { pos = ApplyShadowDepthBias_Orthographic(pos, shadowBias.x, cc_shadowProjDepthInfo.x, cc_shadowProjDepthInfo.y); float pcf = cc_shadowWHPBInfo.z; - if (pcf > 2.9) { - realtimeShadow = CCGetDirLightShadowFactorSoft5X(pos); - } else if (pcf > 1.9) { + /*todo: use CC_SHADOWMAP_PCF_TYPE for better performance + if (pcf > 2.9) { + realtimeShadow = CCGetDirLightShadowFactorSoft5X(pos); + } else */ + if (pcf > 1.9) { realtimeShadow = CCGetDirLightShadowFactorSoft3X(pos); }else if (pcf > 0.9) { realtimeShadow = CCGetDirLightShadowFactorSoft(pos); @@ -262,9 +266,11 @@ float CCGetLinearDepth(vec3 worldPos) { pos = ApplyShadowDepthBias_Orthographic(pos, shadowBias.x, shadowProjDepthInfo.x, shadowProjDepthInfo.y); float pcf = cc_shadowWHPBInfo.z; + /*todo: use CC_SHADOWMAP_PCF_TYPE for better performance if (pcf > 2.9) { realtimeShadow = CCGetDirLightShadowFactorSoft5X(pos); - } else if (pcf > 1.9) { + } else */ + if (pcf > 1.9) { realtimeShadow = CCGetDirLightShadowFactorSoft3X(pos); } else if (pcf > 0.9) { realtimeShadow = CCGetDirLightShadowFactorSoft(pos); diff --git a/editor/assets/chunks/common/data/unpack.chunk b/editor/assets/chunks/common/data/unpack.chunk index d901ca542c..0af8a618fa 100644 --- a/editor/assets/chunks/common/data/unpack.chunk +++ b/editor/assets/chunks/common/data/unpack.chunk @@ -1,5 +1,19 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. +vec4 packRGBE (vec3 rgb) { + highp float maxComp = max(max(rgb.r, rgb.g), rgb.b); + highp float e = 128.0; + if (maxComp > 0.0001) { + e = log(maxComp) / log(1.1); + e = ceil(e); + e = clamp(e + 128.0, 0.0, 255.0); + } + highp float sc = 1.0 / pow(1.1, e - 128.0); + vec3 encode = clamp(rgb * sc, vec3(0.0), vec3(1.0)) * 255.0; + vec3 encode_rounded = floor(encode) + step(encode - floor(encode), vec3(0.5)); //equals to round(encode) + return vec4(encode_rounded, e) / 255.0; +} + vec3 unpackRGBE (vec4 rgbe) { return rgbe.rgb * pow(1.1, rgbe.a * 255.0 - 128.0); } diff --git a/editor/assets/chunks/common/math/number.chunk b/editor/assets/chunks/common/math/number.chunk index be14d95854..bf59eb75e2 100644 --- a/editor/assets/chunks/common/math/number.chunk +++ b/editor/assets/chunks/common/math/number.chunk @@ -7,17 +7,24 @@ bool isinf(float x) { } #endif +bool isnans(vec2 val) { + return isnan(val.x) || isnan(val.y); +} bool isnans(vec3 val) { - return isnan(val.x) && isnan(val.y) && isnan(val.z); + return isnan(val.x) || isnan(val.y) || isnan(val.z); } bool isnans(vec4 val) { - return isnan(val.x) && isnan(val.y) && isnan(val.z) && isnan(val.w); + return isnan(val.x) || isnan(val.y) || isnan(val.z) || isnan(val.w); } -bool isinfs(vec4 val) { - return isinf(val.x) && isinf(val.y) && isinf(val.z) && isinf(val.w); + +bool isinfs(vec2 val) { + return isinf(val.x) || isinf(val.y); } bool isinfs(vec3 val) { - return isinf(val.x) && isinf(val.y) && isinf(val.z); + return isinf(val.x) || isinf(val.y) || isinf(val.z); +} +bool isinfs(vec4 val) { + return isinf(val.x) || isinf(val.y) || isinf(val.z) || isinf(val.w); } diff --git a/editor/assets/chunks/legacy/shading-standard-base.chunk b/editor/assets/chunks/legacy/shading-standard-base.chunk index 138f64223e..c0d72b302f 100644 --- a/editor/assets/chunks/legacy/shading-standard-base.chunk +++ b/editor/assets/chunks/legacy/shading-standard-base.chunk @@ -99,17 +99,28 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { vec3 N = normalize(s.normal); vec3 V = normalize(cc_cameraPos.xyz - position); + vec3 L = normalize(-cc_mainLitDir.xyz); + float NL = max(dot(N, L), 0.0); + + float shadow = 1.0; + #if CC_RECEIVE_SHADOW + if (NL > 0.0 && cc_mainLitDir.w > 0.0) { + if (cc_shadowLPNNInfo.w > 0.0) { + shadow = CCCSMFactorBase(position, N, s.shadowBias); + } else { + shadow = CCShadowFactorBase(shadowPos, N, s.shadowBias); + } + } + #endif #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD - vec3 finalColor = diffuse * s.lightmap.rgb; + vec3 finalColor = diffuse * s.lightmap.rgb * shadow; #else float NV = max(abs(dot(N, V)), 0.0); specular = BRDFApprox(specular, s.roughness, NV); - vec3 L = normalize(-cc_mainLitDir.xyz); vec3 H = normalize(L + V); float NH = max(dot(N, H), 0.0); - float NL = max(dot(N, L), 0.0); vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w; vec3 diffuseContrib = diffuse / PI; @@ -117,17 +128,6 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N); vec3 dirlightContrib = (diffuseContrib + specularContrib); - float shadow = 1.0; - #if CC_RECEIVE_SHADOW - if (NL > 0.0 && cc_mainLitDir.w > 0.0) { - if (cc_shadowLPNNInfo.w > 0.0) { - shadow = CCCSMFactorBase(position, N, s.shadowBias); - } else { - shadow = CCShadowFactorBase(shadowPos, N, s.shadowBias); - } - } - #endif - dirlightContrib *= shadow; finalColor *= dirlightContrib; #endif 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 2124986c01..52d1c761bf 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk @@ -62,24 +62,8 @@ CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData, surfaceData, -cc_mainLitDir.xyz); - // CCSurfacesLightingCalculateBaked: - lightingResult.lightmapColor = vec3(0.0); - #if CC_SURFACES_USE_LIGHT_MAP && !USE_BATCHING && !CC_FORWARD_ADD - vec4 lightmap = GetLightMapColor(cc_lightingMap, FSInput_lightMapUV.xy, FSInput_lightMapUV.z); - lightingResult.lightmapColor = lightmap.rgb; - // lightingResult.shadow/ao *= lightmap.a; - - // static dir light - lightingResult.directDiffuse = lightingResult.directSpecular = vec3(0.0); - lightingResult.shadow = lightingResult.ao = 1.0; - // dynamic & stationary dir light - #else - CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); - - CCSurfacesLightingCalculateDirect(lightingResult.directDiffuse, lightingResult.directSpecular, lightingData, cc_mainLitColor); - - // CCSurfacesLightingCalculateShadow: - lightingResult.shadow = 1.0; + // CCSurfacesLightingCalculateShadow: + lightingResult.shadow = 1.0; #if CC_RECEIVE_SHADOW if (cc_mainLitDir.w > 0.0) { if (CCSurfacesLightingEnableShadow(lightingData.NoL)) { @@ -92,7 +76,22 @@ } } #endif - #endif + + // CCSurfacesLightingCalculateBaked: + lightingResult.lightmapColor = vec3(0.0); + #if CC_SURFACES_USE_LIGHT_MAP && !USE_BATCHING && !CC_FORWARD_ADD + vec4 lightmap = GetLightMapColor(cc_lightingMap, FSInput_lightMapUV.xy, FSInput_lightMapUV.z); + lightingResult.lightmapColor = lightmap.rgb; + // lightingResult.shadow/ao *= lightmap.a; + + // static dir light + lightingResult.directDiffuse = lightingResult.directSpecular = vec3(0.0); + // dynamic & stationary dir light + #else + CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); + + CCSurfacesLightingCalculateDirect(lightingResult.directDiffuse, lightingResult.directSpecular, lightingData, cc_mainLitColor); + #endif // apply SSR, local probe & global probe CCSurfacesLightingCalculateEnvironment(lightingResult, lightingData); diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap.meta new file mode 100644 index 0000000000..b93be62103 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "04da2a4a-6935-4292-bb30-80ade09b721b", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap/fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap/fs.chunk new file mode 100644 index 0000000000..750c21b903 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap/fs.chunk @@ -0,0 +1,46 @@ +layout(location = 0) out vec4 fragColorX; + +void main() { +#if CC_DISABLE_STRUCTURE_IN_FRAGMENT_SHADER + float NoL = dot(-cc_mainLitDir.xyz, FSInput_worldNormal.xyz); //trigger ubo binding + vec4 color = SurfacesFragmentModifyBaseColorAndTransparency(); +#else + // Surface + SurfacesMaterialData surfaceData; + CCSurfacesFragmentGetMaterialData(surfaceData); + + // Shadow parameters + vec2 shadowBias = vec2(0.0); + #if CC_RECEIVE_SHADOW + shadowBias = FSInput_shadowBias; + #endif + + + // Fog factor + #if !CC_FORWARD_ADD + float fogFactor = 1.0; + #if CC_USE_FOG != CC_FOG_NONE + #if !CC_USE_ACCURATE_FOG + fogFactor = FSInput_fogFactor; + #else + CC_TRANSFER_FOG_BASE(vec4(FSInput_worldPos, 1.0), fogFactor); + #endif + #endif + #endif + + + // Lighting + LightingResult lightingResult; + CCSurfacesLighting(lightingResult, surfaceData, shadowBias); + + // Shading + vec4 color = CCSurfacesShading(surfaceData, lightingResult); + + #if !CC_FORWARD_ADD + CC_APPLY_FOG_BASE(color, fogFactor); + #endif +#endif + + // Color output (RGBE) + fragColorX = packRGBE(color.rgb); +} diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap/fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap/fs.chunk.meta new file mode 100644 index 0000000000..4661c2d092 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap/fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.6", + "importer": "effect-header", + "imported": true, + "uuid": "ea587cc9-8792-4693-a555-0c5787ce7d89", + "files": [], + "subMetas": {}, + "userData": {} +} 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 f3f97bb6b9..49a262517a 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 @@ -108,11 +108,15 @@ void main() { CC_APPLY_FOG_BASE(color, fogFactor); #endif - // CSM Debug #if CC_USE_DEBUG_VIEW && CC_SURFACES_ENABLE_DEBUG_VIEW + // CSM Debug if (IS_DEBUG_VIEW_MISC_ENABLE_CSM_LAYER_COLORATION) { color.rgb *= colDebugCSMLayer.rgb; } + // Invalid input data visualization + #if CC_SURFACES_USE_TANGENT_SPACE + color = CCSurfacesDebugDisplayInvalidInputData(color, FSInput_worldTangent); + #endif #endif #endif @@ -127,9 +131,7 @@ void main() { if (IS_DEBUG_VIEW_COMPOSITE_ENABLE_GAMMA_CORRECTION) #endif color.rgb = LinearToSRGB(color.rgb); + - - CCSurfacesDebugDisplayInvalidNumber(color); - - fragColorX = color; + fragColorX = CCSurfacesDebugDisplayInvalidNumber(color); } diff --git a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk index 6454bd2fbe..02dbdb5113 100644 --- a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk +++ b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk @@ -1,10 +1,18 @@ // make divid-by-zero, non-rational pixel more obvious -void CCSurfacesDebugDisplayInvalidNumber(inout vec4 color) +vec4 CCSurfacesDebugDisplayInvalidNumber(vec4 color) { float index = mod(cc_time.x * 10.0, 2.0); vec4 error = index < 1.0 ? vec4(1.0, 0.0, 0.2, 1.0) : vec4(0.0, 1.0, 0.2, 1.0); - color = (isnans(color.rgb) || isinfs(color.rgb)) ? error : color; + return (isnans(color.rgb) || isinfs(color.rgb)) ? error : color; +} + +vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) +{ + float index = mod(cc_time.x * 10.0, 2.0); + vec4 error = index < 1.0 ? vec4(1.0, 0.0, 0.2, 1.0) : vec4(0.0, 1.0, 0.2, 1.0); + + return (isnans(data) || isinfs(data)) ? error : color; } diff --git a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk index ab4ec5037e..899ea2987a 100644 --- a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk @@ -113,13 +113,14 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li color.xyz += lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting; color.xyz += lightingResult.directSpecular * lightingResult.specularColorWithLighting; #else - color.xyz += lightingResult.lightmapColor * lightingResult.diffuseColorWithLighting - + (lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting + color.xyz += + ( lightingResult.lightmapColor * lightingResult.diffuseColorWithLighting + + lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.directSpecular * lightingResult.specularColorWithLighting) * lightingResult.shadow; - color.xyz += ( - lightingResult.environmentDiffuse * lightingResult.diffuseColorWithLighting + color.xyz += + ( lightingResult.environmentDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.environmentSpecular * lightingResult.specularColorWithLighting) * lightingResult.ao; diff --git a/editor/assets/default_fonts/builtin-bitmap/OpenSans-BoldItalic_0.png.meta b/editor/assets/default_fonts/builtin-bitmap/OpenSans-BoldItalic_0.png.meta index 0e61f377dd..3e4a4764b8 100644 --- a/editor/assets/default_fonts/builtin-bitmap/OpenSans-BoldItalic_0.png.meta +++ b/editor/assets/default_fonts/builtin-bitmap/OpenSans-BoldItalic_0.png.meta @@ -111,7 +111,11 @@ 64, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "ver": "1.0.11", "imported": true, diff --git a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Bold_0.png.meta b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Bold_0.png.meta index 490914e3a3..bed30957c3 100644 --- a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Bold_0.png.meta +++ b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Bold_0.png.meta @@ -111,7 +111,11 @@ 64, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "ver": "1.0.11", "imported": true, diff --git a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Italic_0.png.meta b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Italic_0.png.meta index 25d6e50dcf..beae837a7a 100644 --- a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Italic_0.png.meta +++ b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Italic_0.png.meta @@ -111,7 +111,11 @@ 64, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "ver": "1.0.11", "imported": true, diff --git a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Regular_0.png.meta b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Regular_0.png.meta index 618ffc86aa..c7f2bc2a58 100644 --- a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Regular_0.png.meta +++ b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Regular_0.png.meta @@ -111,7 +111,11 @@ 64, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "ver": "1.0.11", "imported": true, diff --git a/editor/assets/default_renderpipeline/deferred-lighting.mtl.meta b/editor/assets/default_renderpipeline/deferred-lighting.mtl.meta index 61aed8a277..b680c511f8 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.12", + "ver": "1.0.13", "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 b23a18d3a4..4102039e4d 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.12", + "ver": "1.0.13", "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 f17c9e0ce1..cdb05e0fef 100644 --- a/editor/assets/default_renderpipeline/tonemap.mtl.meta +++ b/editor/assets/default_renderpipeline/tonemap.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.12", + "ver": "1.0.13", "importer": "material", "imported": true, "uuid": "9d9704d8-08b4-4917-ba47-9d778bc77ac6", diff --git a/editor/assets/default_ui/atom.png.meta b/editor/assets/default_ui/atom.png.meta index 00f5422c2a..5c97537beb 100644 --- a/editor/assets/default_ui/atom.png.meta +++ b/editor/assets/default_ui/atom.png.meta @@ -111,7 +111,11 @@ 15.5, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "ver": "1.0.11", "imported": true, diff --git a/editor/assets/default_ui/default_btn_disabled.png.meta b/editor/assets/default_ui/default_btn_disabled.png.meta index 129deb57d8..fcf5c3d60e 100644 --- a/editor/assets/default_ui/default_btn_disabled.png.meta +++ b/editor/assets/default_ui/default_btn_disabled.png.meta @@ -123,7 +123,11 @@ 20, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_btn_disabled", "id": "f9941", diff --git a/editor/assets/default_ui/default_btn_normal.png.meta b/editor/assets/default_ui/default_btn_normal.png.meta index 83e0f37685..599e2d36b2 100644 --- a/editor/assets/default_ui/default_btn_normal.png.meta +++ b/editor/assets/default_ui/default_btn_normal.png.meta @@ -123,7 +123,11 @@ 20, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_btn_normal", "id": "f9941", diff --git a/editor/assets/default_ui/default_btn_pressed.png.meta b/editor/assets/default_ui/default_btn_pressed.png.meta index 8e74d199ca..2c839b3fa7 100644 --- a/editor/assets/default_ui/default_btn_pressed.png.meta +++ b/editor/assets/default_ui/default_btn_pressed.png.meta @@ -123,7 +123,11 @@ 20, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_btn_pressed", "id": "f9941", diff --git a/editor/assets/default_ui/default_editbox_bg.png.meta b/editor/assets/default_ui/default_editbox_bg.png.meta index 934855ed58..fe7c4a1164 100644 --- a/editor/assets/default_ui/default_editbox_bg.png.meta +++ b/editor/assets/default_ui/default_editbox_bg.png.meta @@ -123,7 +123,11 @@ 20, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_editbox_bg", "id": "f9941", diff --git a/editor/assets/default_ui/default_panel.png.meta b/editor/assets/default_ui/default_panel.png.meta index 0ee011206a..5b14a29f14 100644 --- a/editor/assets/default_ui/default_panel.png.meta +++ b/editor/assets/default_ui/default_panel.png.meta @@ -123,7 +123,11 @@ 10, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_panel", "id": "f9941", diff --git a/editor/assets/default_ui/default_progressbar.png.meta b/editor/assets/default_ui/default_progressbar.png.meta index 908a212144..8b66679429 100644 --- a/editor/assets/default_ui/default_progressbar.png.meta +++ b/editor/assets/default_ui/default_progressbar.png.meta @@ -123,7 +123,11 @@ 7.5, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_progressbar", "id": "f9941", diff --git a/editor/assets/default_ui/default_progressbar_bg.png.meta b/editor/assets/default_ui/default_progressbar_bg.png.meta index a48c4ed82e..18bda7027f 100644 --- a/editor/assets/default_ui/default_progressbar_bg.png.meta +++ b/editor/assets/default_ui/default_progressbar_bg.png.meta @@ -123,7 +123,11 @@ 7.5, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_progressbar_bg", "id": "f9941", diff --git a/editor/assets/default_ui/default_radio_button_off.png.meta b/editor/assets/default_ui/default_radio_button_off.png.meta index 895d35ea00..05ec0d79c5 100644 --- a/editor/assets/default_ui/default_radio_button_off.png.meta +++ b/editor/assets/default_ui/default_radio_button_off.png.meta @@ -123,7 +123,11 @@ 13, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_radio_button_off", "id": "f9941", diff --git a/editor/assets/default_ui/default_radio_button_on.png.meta b/editor/assets/default_ui/default_radio_button_on.png.meta index d5d81a6619..e384514b35 100644 --- a/editor/assets/default_ui/default_radio_button_on.png.meta +++ b/editor/assets/default_ui/default_radio_button_on.png.meta @@ -123,7 +123,11 @@ 15, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_radio_button_on", "id": "f9941", diff --git a/editor/assets/default_ui/default_scrollbar.png.meta b/editor/assets/default_ui/default_scrollbar.png.meta index 8a4913269d..b6d2022335 100644 --- a/editor/assets/default_ui/default_scrollbar.png.meta +++ b/editor/assets/default_ui/default_scrollbar.png.meta @@ -123,7 +123,11 @@ 7.5, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_scrollbar", "id": "f9941", diff --git a/editor/assets/default_ui/default_scrollbar_bg.png.meta b/editor/assets/default_ui/default_scrollbar_bg.png.meta index b76517c577..1072568b45 100644 --- a/editor/assets/default_ui/default_scrollbar_bg.png.meta +++ b/editor/assets/default_ui/default_scrollbar_bg.png.meta @@ -123,7 +123,11 @@ 7.5, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_scrollbar_bg", "id": "f9941", diff --git a/editor/assets/default_ui/default_scrollbar_vertical.png.meta b/editor/assets/default_ui/default_scrollbar_vertical.png.meta index 8581ec0295..1c9f0ae3d6 100644 --- a/editor/assets/default_ui/default_scrollbar_vertical.png.meta +++ b/editor/assets/default_ui/default_scrollbar_vertical.png.meta @@ -123,7 +123,11 @@ 15, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_scrollbar_vertical", "id": "f9941", diff --git a/editor/assets/default_ui/default_scrollbar_vertical_bg.png.meta b/editor/assets/default_ui/default_scrollbar_vertical_bg.png.meta index d0ea273735..376456f7d1 100644 --- a/editor/assets/default_ui/default_scrollbar_vertical_bg.png.meta +++ b/editor/assets/default_ui/default_scrollbar_vertical_bg.png.meta @@ -123,7 +123,11 @@ 15, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_scrollbar_vertical_bg", "id": "f9941", diff --git a/editor/assets/default_ui/default_sprite.png.meta b/editor/assets/default_ui/default_sprite.png.meta index 46846d159f..2557d0a65e 100644 --- a/editor/assets/default_ui/default_sprite.png.meta +++ b/editor/assets/default_ui/default_sprite.png.meta @@ -123,7 +123,11 @@ 18, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_sprite", "id": "f9941", diff --git a/editor/assets/default_ui/default_sprite_splash.png.meta b/editor/assets/default_ui/default_sprite_splash.png.meta index 6ce37c02fe..bf413bbca0 100644 --- a/editor/assets/default_ui/default_sprite_splash.png.meta +++ b/editor/assets/default_ui/default_sprite_splash.png.meta @@ -123,7 +123,11 @@ 1, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_sprite_splash", "id": "f9941", diff --git a/editor/assets/default_ui/default_toggle_checkmark.png.meta b/editor/assets/default_ui/default_toggle_checkmark.png.meta index 4882c07993..26adfb7e12 100644 --- a/editor/assets/default_ui/default_toggle_checkmark.png.meta +++ b/editor/assets/default_ui/default_toggle_checkmark.png.meta @@ -123,7 +123,11 @@ 9, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_toggle_checkmark", "id": "f9941", diff --git a/editor/assets/default_ui/default_toggle_normal.png.meta b/editor/assets/default_ui/default_toggle_normal.png.meta index 65b426ad8a..0b8b872f05 100644 --- a/editor/assets/default_ui/default_toggle_normal.png.meta +++ b/editor/assets/default_ui/default_toggle_normal.png.meta @@ -123,7 +123,11 @@ 14, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_toggle_normal", "id": "f9941", diff --git a/editor/assets/default_ui/default_toggle_pressed.png.meta b/editor/assets/default_ui/default_toggle_pressed.png.meta index a32f1d1d8a..9efd242834 100644 --- a/editor/assets/default_ui/default_toggle_pressed.png.meta +++ b/editor/assets/default_ui/default_toggle_pressed.png.meta @@ -123,7 +123,11 @@ 14, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "displayName": "default_toggle_pressed", "id": "f9941", diff --git a/editor/assets/effects/builtin-billboard.effect.meta b/editor/assets/effects/builtin-billboard.effect.meta index b99edfc9ce..e20264a1b4 100644 --- a/editor/assets/effects/builtin-billboard.effect.meta +++ b/editor/assets/effects/builtin-billboard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "711ebe11-f673-4cd9-9a83-63c60ba54c5b", diff --git a/editor/assets/effects/builtin-camera-texture.effect.meta b/editor/assets/effects/builtin-camera-texture.effect.meta index 963bb6e224..9fa7a4b82b 100644 --- a/editor/assets/effects/builtin-camera-texture.effect.meta +++ b/editor/assets/effects/builtin-camera-texture.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "bf4078d6-d2d7-4073-83bb-cd6f1802e880", diff --git a/editor/assets/effects/builtin-clear-stencil.effect.meta b/editor/assets/effects/builtin-clear-stencil.effect.meta index 7d8f0c60b4..7e84dd0a25 100644 --- a/editor/assets/effects/builtin-clear-stencil.effect.meta +++ b/editor/assets/effects/builtin-clear-stencil.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "810e96e4-e456-4468-9b59-f4e8f39732c0", diff --git a/editor/assets/effects/builtin-debug-renderer.effect.meta b/editor/assets/effects/builtin-debug-renderer.effect.meta index 5716841b4d..c3b4e76c92 100644 --- a/editor/assets/effects/builtin-debug-renderer.effect.meta +++ b/editor/assets/effects/builtin-debug-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "ff9be190-20a4-4e48-b68c-76e3c7cff085", diff --git a/editor/assets/effects/builtin-geometry-renderer.effect.meta b/editor/assets/effects/builtin-geometry-renderer.effect.meta index 003d482453..85f549aa9d 100644 --- a/editor/assets/effects/builtin-geometry-renderer.effect.meta +++ b/editor/assets/effects/builtin-geometry-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "4bb480dd-8384-4bc9-987f-de67cc53052a", diff --git a/editor/assets/effects/builtin-graphics.effect.meta b/editor/assets/effects/builtin-graphics.effect.meta index 4359b7a619..606abf3434 100644 --- a/editor/assets/effects/builtin-graphics.effect.meta +++ b/editor/assets/effects/builtin-graphics.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "1c02ae6f-4492-4915-b8f8-7492a3b1e4cd", diff --git a/editor/assets/effects/builtin-occlusion-query.effect.meta b/editor/assets/effects/builtin-occlusion-query.effect.meta index 9df4581862..b72166aaa6 100644 --- a/editor/assets/effects/builtin-occlusion-query.effect.meta +++ b/editor/assets/effects/builtin-occlusion-query.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "d9937e59-61fe-4ec6-92ab-7ac5a19c89b0", diff --git a/editor/assets/effects/builtin-particle-gpu.effect.meta b/editor/assets/effects/builtin-particle-gpu.effect.meta index a2520b7436..2a00666780 100644 --- a/editor/assets/effects/builtin-particle-gpu.effect.meta +++ b/editor/assets/effects/builtin-particle-gpu.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "971bdb23-3ff6-43eb-b422-1c30165a3663", diff --git a/editor/assets/effects/builtin-particle-trail.effect.meta b/editor/assets/effects/builtin-particle-trail.effect.meta index 2229e8dadf..2fc3662360 100644 --- a/editor/assets/effects/builtin-particle-trail.effect.meta +++ b/editor/assets/effects/builtin-particle-trail.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "17debcc3-0a6b-4b8a-b00b-dc58b885581e", diff --git a/editor/assets/effects/builtin-particle.effect.meta b/editor/assets/effects/builtin-particle.effect.meta index c03b1229ae..199127c767 100644 --- a/editor/assets/effects/builtin-particle.effect.meta +++ b/editor/assets/effects/builtin-particle.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "d1346436-ac96-4271-b863-1f4fdead95b0", diff --git a/editor/assets/effects/builtin-reflection-deferred.effect.meta b/editor/assets/effects/builtin-reflection-deferred.effect.meta index ca823d592a..8c5fecb1b5 100644 --- a/editor/assets/effects/builtin-reflection-deferred.effect.meta +++ b/editor/assets/effects/builtin-reflection-deferred.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "99498f84-efe6-43a6-a9a7-e6e93eb845c1", diff --git a/editor/assets/effects/builtin-spine.effect.meta b/editor/assets/effects/builtin-spine.effect.meta index 0fe556b993..9554bc18ba 100644 --- a/editor/assets/effects/builtin-spine.effect.meta +++ b/editor/assets/effects/builtin-spine.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "c27215d8-6835-4b68-bfbb-bdeac6100c04", diff --git a/editor/assets/effects/builtin-sprite-renderer.effect.meta b/editor/assets/effects/builtin-sprite-renderer.effect.meta index 02784a96f0..4feaac9132 100644 --- a/editor/assets/effects/builtin-sprite-renderer.effect.meta +++ b/editor/assets/effects/builtin-sprite-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "6ef1defe-7997-477a-9b35-c18859ff8066", diff --git a/editor/assets/effects/builtin-sprite.effect.meta b/editor/assets/effects/builtin-sprite.effect.meta index 2d830603b1..493b73d9b7 100644 --- a/editor/assets/effects/builtin-sprite.effect.meta +++ b/editor/assets/effects/builtin-sprite.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "60f7195c-ec2a-45eb-ba94-8955f60e81d0", diff --git a/editor/assets/effects/builtin-standard.effect.meta b/editor/assets/effects/builtin-standard.effect.meta index 04f0c87578..5ef7581ebd 100644 --- a/editor/assets/effects/builtin-standard.effect.meta +++ b/editor/assets/effects/builtin-standard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "1baf0fc9-befa-459c-8bdd-af1a450a0319", diff --git a/editor/assets/effects/builtin-terrain.effect.meta b/editor/assets/effects/builtin-terrain.effect.meta index 410178cb44..f4b88c274b 100644 --- a/editor/assets/effects/builtin-terrain.effect.meta +++ b/editor/assets/effects/builtin-terrain.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "1d08ef62-a503-4ce2-8b9a-46c90873f7d3", diff --git a/editor/assets/effects/builtin-toon.effect.meta b/editor/assets/effects/builtin-toon.effect.meta index 137aaed477..a7cbaf60ad 100644 --- a/editor/assets/effects/builtin-toon.effect.meta +++ b/editor/assets/effects/builtin-toon.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "a7612b54-35e3-4238-a1a9-4a7b54635839", diff --git a/editor/assets/effects/builtin-unlit.effect.meta b/editor/assets/effects/builtin-unlit.effect.meta index a66c3e0920..b5fe8b2ef9 100644 --- a/editor/assets/effects/builtin-unlit.effect.meta +++ b/editor/assets/effects/builtin-unlit.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "a3cd009f-0ab0-420d-9278-b9fdab939bbc", diff --git a/editor/assets/effects/builtin-wireframe.effect.meta b/editor/assets/effects/builtin-wireframe.effect.meta index 8bc31eefbc..73586b5297 100644 --- a/editor/assets/effects/builtin-wireframe.effect.meta +++ b/editor/assets/effects/builtin-wireframe.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "81127eb0-7556-453c-b147-670782dd5e53", diff --git a/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta b/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta index eaa8359626..ce0d8acab3 100644 --- a/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta +++ b/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "2ec11458-f855-4978-b14d-f3ed5cf697fa", diff --git a/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta b/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta index 36c2df10a9..65cdc0ec62 100644 --- a/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta +++ b/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "f648964e-8d32-41fc-9ac9-7a1e714dd17b", diff --git a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta index 05e963698b..f29d286864 100644 --- a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta +++ b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "994bae8e-8bfc-4bc4-a32d-ad924f9917d0", diff --git a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta index 36d84ac32b..110a000176 100644 --- a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta +++ b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "5b7d6814-90a6-4d9f-b7fd-410dca9de957", diff --git a/editor/assets/effects/editor/gizmo.effect.meta b/editor/assets/effects/editor/gizmo.effect.meta index da110fe4b9..0afaef47ed 100644 --- a/editor/assets/effects/editor/gizmo.effect.meta +++ b/editor/assets/effects/editor/gizmo.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "9d6c6bde-2fe2-44ee-883b-909608948b04", diff --git a/editor/assets/effects/editor/grid-2d.effect.meta b/editor/assets/effects/editor/grid-2d.effect.meta index 435d55ae85..8490f31350 100644 --- a/editor/assets/effects/editor/grid-2d.effect.meta +++ b/editor/assets/effects/editor/grid-2d.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "cb2c332a-fa5e-4235-a129-f011634bb7ad", diff --git a/editor/assets/effects/editor/grid-stroke.effect.meta b/editor/assets/effects/editor/grid-stroke.effect.meta index a1571f491e..2d786d73a1 100644 --- a/editor/assets/effects/editor/grid-stroke.effect.meta +++ b/editor/assets/effects/editor/grid-stroke.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "4736e978-c8fa-449f-9cf6-fe0158ded9d7", diff --git a/editor/assets/effects/editor/grid.effect.meta b/editor/assets/effects/editor/grid.effect.meta index ce5401dd4c..a2b07395c1 100644 --- a/editor/assets/effects/editor/grid.effect.meta +++ b/editor/assets/effects/editor/grid.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "ba35f02e-a81c-464c-bfc5-c788328da667", diff --git a/editor/assets/effects/editor/light.effect.meta b/editor/assets/effects/editor/light.effect.meta index 9a8c7639de..75bd610c46 100644 --- a/editor/assets/effects/editor/light.effect.meta +++ b/editor/assets/effects/editor/light.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "e4e4cb19-8dd2-450d-ad20-1a818263b8d3", diff --git a/editor/assets/effects/editor/terrain-circle-brush.effect.meta b/editor/assets/effects/editor/terrain-circle-brush.effect.meta index a777d57d97..c3dac65d38 100644 --- a/editor/assets/effects/editor/terrain-circle-brush.effect.meta +++ b/editor/assets/effects/editor/terrain-circle-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "a3e72674-c38f-4336-a285-1826b1799cd7", diff --git a/editor/assets/effects/editor/terrain-image-brush.effect.meta b/editor/assets/effects/editor/terrain-image-brush.effect.meta index 5e5f19b091..c99fcfbba0 100644 --- a/editor/assets/effects/editor/terrain-image-brush.effect.meta +++ b/editor/assets/effects/editor/terrain-image-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "7a115de7-2d94-4620-8b89-766d7f8cbff9", diff --git a/editor/assets/effects/editor/terrain-select-brush.effect.meta b/editor/assets/effects/editor/terrain-select-brush.effect.meta index 3509cb6b08..f07ce0350f 100644 --- a/editor/assets/effects/editor/terrain-select-brush.effect.meta +++ b/editor/assets/effects/editor/terrain-select-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "9b4d3fa5-89bf-4715-b69a-dbbd1efaf6a5", diff --git a/editor/assets/effects/pipeline/bloom.effect.meta b/editor/assets/effects/pipeline/bloom.effect.meta index 31ef120dd6..0dd3ccc25b 100644 --- a/editor/assets/effects/pipeline/bloom.effect.meta +++ b/editor/assets/effects/pipeline/bloom.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "28d6d6b8-3f66-4a73-9795-17a0852ba2d4", diff --git a/editor/assets/effects/pipeline/deferred-lighting.effect.meta b/editor/assets/effects/pipeline/deferred-lighting.effect.meta index d473a6e17d..b16f8f6e0a 100644 --- a/editor/assets/effects/pipeline/deferred-lighting.effect.meta +++ b/editor/assets/effects/pipeline/deferred-lighting.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "5d45aa00-e064-4938-b314-4265f0c2258c", diff --git a/editor/assets/effects/pipeline/planar-shadow.effect.meta b/editor/assets/effects/pipeline/planar-shadow.effect.meta index b41c449ee9..13c12b217c 100644 --- a/editor/assets/effects/pipeline/planar-shadow.effect.meta +++ b/editor/assets/effects/pipeline/planar-shadow.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "9361fd90-ba52-4f84-aa93-6e878fd576ca", diff --git a/editor/assets/effects/pipeline/post-process.effect.meta b/editor/assets/effects/pipeline/post-process.effect.meta index 00fc08ae12..3146f233da 100644 --- a/editor/assets/effects/pipeline/post-process.effect.meta +++ b/editor/assets/effects/pipeline/post-process.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "ec8106fe-05bf-4e94-943c-e0d3b7bb5e45", diff --git a/editor/assets/effects/pipeline/skybox.effect b/editor/assets/effects/pipeline/skybox.effect index 239893f61c..446e599179 100644 --- a/editor/assets/effects/pipeline/skybox.effect +++ b/editor/assets/effects/pipeline/skybox.effect @@ -59,21 +59,12 @@ CCProgram sky-fs %{ in mediump vec4 viewDir; - vec3 getEnvironment(samplerCube cubeMap) - { - #if USE_RGBE_CUBEMAP - vec3 c = unpackRGBE(fragTextureLod(cubeMap, viewDir.xyz, 0.0)); - #else - vec3 c = SRGBToLinear(fragTextureLod(cubeMap, viewDir.xyz, 0.0).rgb); - #endif - return c; - } uniform samplerCube environmentMap; vec4 frag () { - #if USE_REFLECTION_CUBEMAP - vec3 c = getEnvironment(environmentMap); + #if USE_RGBE_CUBEMAP + vec3 c = unpackRGBE(fragTextureLod(environmentMap, viewDir.xyz, 0.0)); #else - vec3 c = getEnvironment(cc_environment); + vec3 c = SRGBToLinear(fragTextureLod(environmentMap, viewDir.xyz, 0.0).rgb); #endif return CCFragOutput(vec4(c * cc_ambientSky.w, 1.0)); } diff --git a/editor/assets/effects/pipeline/skybox.effect.meta b/editor/assets/effects/pipeline/skybox.effect.meta index bcfe4cc866..77302e9090 100644 --- a/editor/assets/effects/pipeline/skybox.effect.meta +++ b/editor/assets/effects/pipeline/skybox.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "511d2633-09a7-4bdd-ac42-f778032124b3", diff --git a/editor/assets/effects/pipeline/smaa.effect.meta b/editor/assets/effects/pipeline/smaa.effect.meta index 76f2381c99..c14844616e 100644 --- a/editor/assets/effects/pipeline/smaa.effect.meta +++ b/editor/assets/effects/pipeline/smaa.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "6624c63c-0e3d-4d5f-bd15-a7805b71c521", diff --git a/editor/assets/effects/pipeline/tonemap.effect.meta b/editor/assets/effects/pipeline/tonemap.effect.meta index 04ff4a614a..026e08f574 100644 --- a/editor/assets/effects/pipeline/tonemap.effect.meta +++ b/editor/assets/effects/pipeline/tonemap.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "31b152ff-f689-4082-a292-3eb5a0b33014", diff --git a/editor/assets/effects/surfaces/sky.effect b/editor/assets/effects/surfaces/sky.effect index aad126744a..ee0192e58d 100644 --- a/editor/assets/effects/surfaces/sky.effect +++ b/editor/assets/effects/surfaces/sky.effect @@ -29,28 +29,16 @@ CCProgram surface-vertex %{ CCProgram surface-fragment %{ uniform samplerCube environmentMap; - - vec3 getEnvironment(samplerCube cubeMap) - { - vec3 c = vec3(1.0); - vec3 normal = normalize(FSInput_worldNormal); - #if USE_RGBE_CUBEMAP - c *= unpackRGBE(fragTextureLod(cubeMap, normal.xyz, 0.0)); - #else - c *= SRGBToLinear(fragTextureLod(cubeMap, normal.xyz, 0.0).rgb); - #endif - return c; - } - #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY vec4 SurfacesFragmentModifyBaseColorAndTransparency() { vec3 c = vec3(1.0); #if CC_USE_IBL - #if USE_REFLECTION_CUBEMAP - c = getEnvironment(environmentMap); + vec3 normal = normalize(FSInput_worldNormal); + #if USE_RGBE_CUBEMAP + c *= unpackRGBE(fragTextureLod(environmentMap, normal.xyz, 0.0)); #else - c = getEnvironment(cc_environment); + c *= SRGBToLinear(fragTextureLod(environmentMap, normal.xyz, 0.0).rgb); #endif #endif return vec4(c * cc_ambientSky.w, 1.0); diff --git a/editor/assets/effects/surfaces/sky.effect.meta b/editor/assets/effects/surfaces/sky.effect.meta index 0178ca6f69..eb8789005a 100644 --- a/editor/assets/effects/surfaces/sky.effect.meta +++ b/editor/assets/effects/surfaces/sky.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "6308c013-7d49-4160-9516-562dd205b480", diff --git a/editor/assets/effects/surfaces/standard.effect b/editor/assets/effects/surfaces/standard.effect index 3aa5030fe6..0823cd36c3 100644 --- a/editor/assets/effects/surfaces/standard.effect +++ b/editor/assets/effects/surfaces/standard.effect @@ -26,7 +26,7 @@ CCEffect %{ metallicRoughnessMap: { value: grey } occlusionMap: { value: white } emissiveMap: { value: grey } - anisotropyRotationMap: { value: black, editor : { parent: IS_ANISOTROPY } } + anisotropyMap: { value: black, editor : { parent: IS_ANISOTROPY } } - &forward-add vert: standard-vs frag: standard-fs @@ -170,8 +170,8 @@ CCProgram surface-fragment %{ uniform sampler2D emissiveMap; #pragma define-meta EMISSIVE_UV options([v_uv, v_uv1]) #endif - #if IS_ANISOTROPY && USE_ANISOTROPY_ROTATION_MAP - uniform sampler2D anisotropyRotationMap; + #if IS_ANISOTROPY && USE_ANISOTROPY_MAP + uniform sampler2D anisotropyMap; #endif #pragma define OCCLUSION_CHANNEL r @@ -241,8 +241,10 @@ CCProgram surface-fragment %{ { float anisotropyRotation = anisotropyParam.y; float anisotropyShape = anisotropyParam.x; - #if IS_ANISOTROPY && USE_ANISOTROPY_ROTATION_MAP - anisotropyRotation = fract(anisotropyRotation + texture(anisotropyRotationMap, DEFAULT_UV).x); + #if IS_ANISOTROPY && USE_ANISOTROPY_MAP + vec4 tex = texture(anisotropyMap, DEFAULT_UV); + anisotropyRotation = fract(anisotropyRotation + tex.x); + anisotropyShape = tex.y; #endif return vec4(anisotropyRotation, anisotropyShape, 0.0, 0.0); } diff --git a/editor/assets/effects/surfaces/standard.effect.meta b/editor/assets/effects/surfaces/standard.effect.meta index d79f6cf3a5..6af96b1627 100644 --- a/editor/assets/effects/surfaces/standard.effect.meta +++ b/editor/assets/effects/surfaces/standard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "c8f66d17-351a-48da-a12c-0212d28575c4", diff --git a/editor/assets/effects/surfaces/toon.effect.meta b/editor/assets/effects/surfaces/toon.effect.meta index a40ba7fcb4..18b6d782a7 100644 --- a/editor/assets/effects/surfaces/toon.effect.meta +++ b/editor/assets/effects/surfaces/toon.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "9b20a514-6cc3-49de-b216-b6b863046249", diff --git a/editor/assets/effects/util/batched-unlit.effect.meta b/editor/assets/effects/util/batched-unlit.effect.meta index 5f0fe9590c..74f7b84313 100644 --- a/editor/assets/effects/util/batched-unlit.effect.meta +++ b/editor/assets/effects/util/batched-unlit.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "f1556893-88b6-4c65-8c16-a5256ef3ad25", diff --git a/editor/assets/effects/util/profiler.effect.meta b/editor/assets/effects/util/profiler.effect.meta index a0bd1c8fd4..50bd98cf46 100644 --- a/editor/assets/effects/util/profiler.effect.meta +++ b/editor/assets/effects/util/profiler.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "871c3b6c-7379-419d-bda3-794b239ab90d", diff --git a/editor/assets/effects/util/sequence-anim.effect.meta b/editor/assets/effects/util/sequence-anim.effect.meta index 2c4ed14748..bdbc5ce866 100644 --- a/editor/assets/effects/util/sequence-anim.effect.meta +++ b/editor/assets/effects/util/sequence-anim.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "27cc5a0b-ec0b-4a67-98cf-b42d4fa971de", diff --git a/editor/assets/effects/util/splash-screen.effect.meta b/editor/assets/effects/util/splash-screen.effect.meta index 02692371d7..a1007e16dd 100644 --- a/editor/assets/effects/util/splash-screen.effect.meta +++ b/editor/assets/effects/util/splash-screen.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.8", + "ver": "1.5.9", "importer": "effect", "imported": true, "uuid": "970b0598-bcb0-4714-91fb-2e81440dccd8", diff --git a/editor/assets/gizmo/scene-gizmo.mtl.meta b/editor/assets/gizmo/scene-gizmo.mtl.meta index ded8f08375..1cd949f6c7 100644 --- a/editor/assets/gizmo/scene-gizmo.mtl.meta +++ b/editor/assets/gizmo/scene-gizmo.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.12", + "ver": "1.0.13", "importer": "material", "imported": true, "uuid": "6d3bfb1f-604a-4fb3-9fd8-789862cc55e7", diff --git a/editor/assets/gizmo/x.png.meta b/editor/assets/gizmo/x.png.meta index 931b8339d1..f7d69d7edb 100644 --- a/editor/assets/gizmo/x.png.meta +++ b/editor/assets/gizmo/x.png.meta @@ -111,7 +111,11 @@ 24.5, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "ver": "1.0.11", "imported": true, diff --git a/editor/assets/gizmo/y.png.meta b/editor/assets/gizmo/y.png.meta index 8f359328aa..f4ce95fa46 100644 --- a/editor/assets/gizmo/y.png.meta +++ b/editor/assets/gizmo/y.png.meta @@ -111,7 +111,11 @@ 24.5, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "ver": "1.0.11", "imported": true, diff --git a/editor/assets/gizmo/z.png.meta b/editor/assets/gizmo/z.png.meta index 47cc5a3c70..b11ad7b240 100644 --- a/editor/assets/gizmo/z.png.meta +++ b/editor/assets/gizmo/z.png.meta @@ -111,7 +111,11 @@ 24.5, 0 ] - } + }, + "pixelsToUnit": 100, + "pivotX": 0.5, + "pivotY": 0.5, + "meshType": 0 }, "ver": "1.0.11", "imported": true, diff --git a/editor/assets/primitives.fbx.meta b/editor/assets/primitives.fbx.meta index f979262dd8..d4bb5bcfb7 100644 --- a/editor/assets/primitives.fbx.meta +++ b/editor/assets/primitives.fbx.meta @@ -1,5 +1,5 @@ { - "ver": "2.2.0", + "ver": "2.3.0", "importer": "fbx", "imported": true, "uuid": "1263d74c-8167-4928-91a6-4e2672411f47", diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 85d9a5c15c..085c31d493 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -347,7 +347,7 @@ module.exports = { trailMaterial: 'Trail material of particle', useGPU: 'Enable GPU particle', }, - renderable2D: { + UIRenderer: { srcBlendFactor: 'Source blend factor', dstBlendFactor: 'Destination blend factor', customMaterial: 'User specified material', @@ -674,8 +674,8 @@ module.exports = { textureAnimationModule: 'Texture animation module', trailModule: 'Trail module (only support on CPU)', renderer: 'Particle render module', - renderCulling: 'Whether to enable the particle culling feature. \nIf enabled, a particle emitter bounding box will be generated, and the particle emitter will be culled if the bounding box is not in the visible range of the camera. Please refer to the cullingMode option below for the behavior settings after particle culling.', - cullingMode: 'Sets the behavior of the particle emitter after it has been culled. \nThe available options include Pause, Pause and Catchup, and Always Simulate.\nWhen the Pause is selected, the particle will pause the simulation if the particle emitter bounding box is not in the camera\'s visible range. If it resumes visibility, the particle will continue simulating at the time of last pause.\nWhen the Pause and Catchup is selected, if the particle emitter bounding box is not in the camera\'s visible range, the particle will pause the simulation. If visible again, the particle will start simulating at the current time.\nWhen the Always Simulate is selected, the particle will keep simulating regardless of whether the particle emitter bounding box is in the camera\'s visible range, but will not render when it is not in the camera\'s visible range.', + renderCulling: 'Whether to enable the particle culling feature. \nIf enabled, a particle emitter bounding box will be generated, \nand the particle emitter will be culled if the bounding box is not in the visible range of the camera. \nPlease refer to the cullingMode option below for the behavior settings after particle culling.', + cullingMode: 'Sets the behavior of the particle emitter after it has been culled. \nThe available options include Pause, Pause and Catchup, and Always Simulate.\nWhen the Pause is selected, the particle will pause the simulation if the particle emitter bounding box is not in the camera\'s visible range. \nIf it resumes visibility, the particle will continue simulating at the time of last pause.\nWhen the Pause and Catchup is selected, if the particle emitter bounding box is not in the camera\'s visible range, the particle will pause the simulation. If visible again, the particle will start simulating at the current time.\nWhen the Always Simulate is selected, the particle will keep simulating regardless of whether the particle emitter bounding box is in the camera\'s visible range, but will not render when it is not in the camera\'s visible range.', alignSpace: 'Particle alignment space, the available options include View Space. \nWorld Space and Local Space.\nWhen the View Space is selected, the rotation direction of the particle mesh will follow the camera\'s view direction.\nWhen the World Space is selected, the direction of the particle mesh will use the world space rotation direction of the node where the particle emitter is located.\nWhen the Local Space is selected, the particle mesh will use the local space rotation direction of the node where the particle emitter is located.', aabbHalfX: 'Half width of the emitter bounding box', aabbHalfY: 'Half height of the emitter bounding box', diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index f4855446b4..441849cc2f 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -341,7 +341,7 @@ module.exports = { trailMaterial: '拖尾使用的材质', useGPU: '是否启用GPU粒子', }, - renderable2D: { + UIRenderer: { srcBlendFactor: '原始混合因子', dstBlendFactor: '目标混合因子', customMaterial: '用户指定的材质', @@ -658,8 +658,8 @@ module.exports = { textureAnimationModule: '贴图动画模块', trailModule: '粒子轨迹模块(只支持 CPU 粒子)', renderer: '粒子渲染模块', - renderCulling: '是否开启粒子剔除功能。开启该项将会生成一个粒子发射器包围盒,若包围盒不在摄像机的可见范围内,该粒子发射器便会被剔除。粒子发射器被剔除后的行为请参考下面的 cullingMode。', - cullingMode: '粒子发射器被剔除之后的行为,可设置的选项包括 pause、pause and catchup、always simulate。\n选择 pause 时,若粒子发射器包围盒不在摄像机的可见范围内,粒子暂停模拟。若恢复可见,则粒子会接着上次暂停的时间继续模拟;\n选择 pause and catchup 时,若粒子发射器包围盒不在摄像机的可见范围内,粒子暂停模拟。若恢复可见,则粒子会以当前的时间开始模拟;\n选择 always simulate 时,无论粒子发射器包围盒是否在摄像机的可见范围内,粒子都会一直模拟,只是不在摄像机的可见范围内时不进行渲染。', + renderCulling: '是否开启粒子剔除功能。\n开启该项将会生成一个粒子发射器包围盒,若包围盒不在摄像机的可见范围内,该粒子发射器便会被剔除。\n粒子发射器被剔除后的行为请参考下面的 Culling Mode。', + cullingMode: '粒子发射器被剔除之后的行为,可设置的选项包括 Pause, Pause and Catchup, Always Simulate。\n选择 Pause 时,若粒子发射器包围盒不在摄像机的可见范围内,粒子暂停模拟。若恢复可见,则粒子会接着上次暂停的时间继续模拟;\n选择 Pause and Catchup 时,若粒子发射器包围盒不在摄像机的可见范围内,粒子暂停模拟。若恢复可见,则粒子会以当前的时间开始模拟;\n选择 Always Simulate 时,无论粒子发射器包围盒是否在摄像机的可见范围内,粒子都会一直模拟,只是不在摄像机的可见范围内时不进行渲染。', alignSpace: '粒子对齐方向空间,可设置的选项包括:视角空间、世界空间和局部空间。\n选择视角空间时,粒子网格的旋转方向将会跟随摄像机的视角方向;\n选择世界空间时,粒子网格的方向将会使用发射器节点的世界空间旋转方向;\n选择局部空间时,粒子网格使用发射器节点的局部空间旋转方向。', aabbHalfX: '设置发射器包围盒半宽', aabbHalfY: '设置发射器包围盒半高', @@ -670,20 +670,20 @@ module.exports = { type: '遮罩类型', spriteFrame: '遮罩所需要的贴图', inverted: '反向遮罩(不支持 Canvas 模式)', - alphaThreshold: 'Alpha阈值,只有当模板的像素的 alpha 大于 alpha Threshold 时,才会绘制内容(不支持 Canvas 模式)', + alphaThreshold: 'Alpha 阈值,只有当模板的像素的 Alpha 大于 Alpha Threshold 时,才会绘制内容(不支持 Canvas 模式)', segements: '椭圆遮罩的曲线细分数', }, physics: { rigidbody: { - enabledContactListener: '是否启用接触接听器。当 collider 产生碰撞时,只有开启了接触接听器才会调用相应的回调函数', + enabledContactListener: '是否启用接触接听器。当 Collider 产生碰撞时,只有开启了接触接听器才会调用相应的回调函数', bullet: '这个刚体是否是一个快速移动的刚体,并且需要禁止穿过其他快速移动的刚体', type: '刚体类型:\nStatic(静态), \nKinematic(不受外力), \nDynamic(动态)和 Animated(通过设置线性速度和角速度驱动)', - allowSleep: '如果此刚体永远都不应该进入睡眠,那么设置这个属性为 false。需要注意这将使 CPU 占用率提高', + allowSleep: '如果此刚体永远都不应该进入睡眠,那么设置这个属性为 False。需要注意这将使 CPU 占用率提高', gravityScale: '缩放应用在此刚体上的重力值', linearDamping: - 'Linear damping 用于衰减刚体的线性速度。衰减系数可以大于 1,但是当衰减系数比较大的时候,衰减的效果会变得比较敏感。', + 'Linear Damping 用于衰减刚体的线性速度。衰减系数可以大于 1,但是当衰减系数比较大的时候,衰减的效果会变得比较敏感。', angularDamping: - 'Angular damping 用于衰减刚体的角速度。衰减系数可以大于 1,但是当衰减系数比较大的时候,衰减的效果会变得比较敏感。', + 'Angular Damping 用于衰减刚体的角速度。衰减系数可以大于 1,但是当衰减系数比较大的时候,衰减的效果会变得比较敏感。', linearVelocity: '刚体在世界坐标下的线性速度', angularVelocity: '刚体的角速度', fixedRotation: '是否禁止此刚体进行旋转', diff --git a/editor/inspector/assets/fbx/model.js b/editor/inspector/assets/fbx/model.js index bb82838971..44def8d59d 100644 --- a/editor/inspector/assets/fbx/model.js +++ b/editor/inspector/assets/fbx/model.js @@ -214,7 +214,7 @@ const Elements = { update() { const panel = this; - panel.$.disableMeshSplitCheckbox.value = panel.getDefault(panel.meta.userData.disableMeshSplit, false); + panel.$.disableMeshSplitCheckbox.value = panel.getDefault(panel.meta.userData.disableMeshSplit, true); panel.updateInvalid(panel.$.disableMeshSplitCheckbox, 'disableMeshSplit'); panel.updateReadonly(panel.$.disableMeshSplitCheckbox); @@ -363,7 +363,7 @@ const Elements = { }, }; -exports.update = function(assetList, metaList) { +exports.update = function (assetList, metaList) { this.assetList = assetList; this.metaList = metaList; this.asset = assetList[0]; @@ -377,7 +377,7 @@ exports.update = function(assetList, metaList) { } }; -exports.ready = function() { +exports.ready = function () { for (const prop in Elements) { const element = Elements[prop]; if (element.ready) { @@ -386,7 +386,7 @@ exports.ready = function() { } }; -exports.close = function() { +exports.close = function () { for (const prop in Elements) { const element = Elements[prop]; if (element.close) { diff --git a/editor/inspector/assets/material.js b/editor/inspector/assets/material.js index d371abe55c..d33c21cf88 100644 --- a/editor/inspector/assets/material.js +++ b/editor/inspector/assets/material.js @@ -466,6 +466,11 @@ exports.update = async function(assetList, metaList) { this.asset = assetList[0]; this.meta = metaList[0]; + // 增加容错 + if (!this.$this.isConnected) { + return; + } + if (assetList.length !== 1) { this.$.invalid.setAttribute('active', ''); return; @@ -492,7 +497,7 @@ exports.update = async function(assetList, metaList) { /** * Method of initializing the panel */ -exports.ready = async function() { +exports.ready = function() { this.canUpdatePreview = false; // Used to determine whether the material has been modified in isDirty() this.dirtyData = { diff --git a/editor/inspector/assets/particle.js b/editor/inspector/assets/particle.js index 05d4f87e62..a7e01a02ae 100644 --- a/editor/inspector/assets/particle.js +++ b/editor/inspector/assets/particle.js @@ -8,7 +8,7 @@ exports.template = ` tooltip="i18n:ENGINE.assets.particle.spriteFrameTip" value="i18n:ENGINE.assets.particle.spriteFrame" > - ui-checkbox'); + if (oldCheckbox) { + oldCheckbox.removeEventListener('change', oldCheckbox.changeEvent); + oldCheckbox.changeEvent = undefined; + } + const header = document.createElement('ui-prop'); header.setAttribute('slot', 'header'); header.setAttribute('type', 'dump'); @@ -370,10 +377,11 @@ const uiElements = { header.className = 'header'; header.dump = this.getObjectByKey(this.dump.value, key); const checkbox = document.createElement('ui-checkbox'); - checkbox.addEventListener('change', (event) => { + checkbox.changeEvent = (event) => { this.getObjectByKey(this.dump.value, key).value.enable.value = event.target.value; header.dispatch('change-dump'); - }); + }; + checkbox.addEventListener('change', checkbox.changeEvent); checkbox.setAttribute('value', this.getObjectByKey(this.dump.value, key).value.enable.value); const label = document.createElement('ui-label'); label.setAttribute('value', this.getName(this.getObjectByKey(this.dump.value, key))); @@ -669,7 +677,7 @@ exports.$ = { noisePreview: '#noisePreview', }; -exports.ready = function () { +exports.ready = function() { for (const key in uiElements) { const element = uiElements[key]; if (typeof element.ready === 'function') { @@ -677,7 +685,7 @@ exports.ready = function () { } } }; -exports.update = function (dump) { +exports.update = function(dump) { this.dump = dump; for (const key in uiElements) { const element = uiElements[key]; diff --git a/editor/inspector/contributions/asset.css b/editor/inspector/contributions/asset.css index daa0b936f6..51f52e0cfa 100644 --- a/editor/inspector/contributions/asset.css +++ b/editor/inspector/contributions/asset.css @@ -63,15 +63,15 @@ cursor: pointer; } -:host > .container > .header > ui-button { +:host > .container > .header > .tiny { display: none; - padding: 0 6px; - height: 22px; - margin-left: 6px; - margin-right: 6px; + padding: 0 4px; + height: 20px; + line-height: 20px; + margin-left: 8px; } -:host > .container > .header[dirty] > ui-button { +:host > .container > .header[dirty] > .tiny { display: inline-block; } diff --git a/editor/inspector/contributions/asset.js b/editor/inspector/contributions/asset.js index f9feae2fac..64dd3f6b91 100644 --- a/editor/inspector/contributions/asset.js +++ b/editor/inspector/contributions/asset.js @@ -23,7 +23,9 @@ exports.template = ` - + + +
diff --git a/editor/inspector/contributions/node.css b/editor/inspector/contributions/node.css index 6a5e052b2e..a308940dcd 100644 --- a/editor/inspector/contributions/node.css +++ b/editor/inspector/contributions/node.css @@ -8,8 +8,10 @@ flex: 1; display: flex; flex-direction: column; - overflow: scroll; + overflow-y: scroll; + overflow-x: auto; padding-left: 6px; + padding-right: 2px; } .container[hoving] { @@ -151,6 +153,7 @@ .component .component-header > .link { padding: 0 5px; transition: color 0.15s; + color: var(--color-default-contrast-emphasis); } .component .component-header > .menu:hover { diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index 450169d09c..0e64b45132 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -167,6 +167,19 @@ exports.listeners = { return; } + /** + * Hack:stop preview + * For the reason: preview-set-property and cancel-preview-set-property is command machining. + * Changes between component properties are not controlled to be strictly reversible. + * So stop preview some properties. + */ + const stopPreviewOnTheseTooltips = [ + 'i18n:animation.default_clip', + ]; + if (stopPreviewOnTheseTooltips.includes(dump.tooltip)) { + return; + } + const { method, value: assetUuid } = event.detail; if (method === 'confirm') { clearTimeout(panel.previewTimeId); @@ -182,6 +195,8 @@ exports.listeners = { value = dump.values[i]; } + + // 预览新的值 value.uuid = assetUuid; @@ -669,9 +684,12 @@ const Elements = { const panel = this; if (!panel.dump || !panel.dump.isScene) { - panel.toggleShowAddComponentBtn(true); + if (!panel.isAnimationMode()) { + panel.toggleShowAddComponentBtn(true); + } return; } + // 场景模式要隐藏按钮 panel.toggleShowAddComponentBtn(false); panel.$this.setAttribute('sub-type', 'scene'); @@ -1230,7 +1248,7 @@ const Elements = { panel.$.sectionAsset.prepend(materialPanel); } - materialPanel.addEventListener('focus', () => { + materialPanel.focusEventInNode = () => { const children = Array.from(materialPanel.parentElement.children); children.forEach((child) => { if (child === materialPanel) { @@ -1239,14 +1257,16 @@ const Elements = { child.removeAttribute('focused'); } }); - }); - materialPanel.addEventListener('blur', () => { + }; + materialPanel.blurEventInNode = () => { if (panel.blurSleep) { return; } materialPanel.removeAttribute('focused'); - }); + }; + materialPanel.addEventListener('focus', materialPanel.focusEventInNode); + materialPanel.addEventListener('blur', materialPanel.blurEventInNode); } materialPanels.push(materialPanel); materialPrevPanel = materialPanel; @@ -1256,6 +1276,10 @@ const Elements = { for (const oldChild of oldChildren) { if (oldChild && materialPanels.indexOf(oldChild) === -1) { await oldChild.panel.beforeClose.call(oldChild.panelObject); + oldChild.removeEventListener('focus', oldChild.focusEventInNode); + oldChild.removeEventListener('blur', oldChild.blurEventInNode); + oldChild.focusEventInNode = undefined; + oldChild.blurEventInNode = undefined; oldChild.remove(); } } @@ -1271,6 +1295,10 @@ const Elements = { if (next === false) { return false; } else { + materialPanel.removeEventListener('focus', materialPanel.focusEventInNode); + materialPanel.removeEventListener('blur', materialPanel.blurEventInNode); + materialPanel.focusEventInNode = undefined; + materialPanel.blurEventInNode = undefined; materialPanel.remove(); } } @@ -1420,9 +1448,11 @@ exports.methods = { label: Editor.I18n.t('ENGINE.menu.copy_component'), enabled: !isMultiple, async click() { + const info = JSON.parse(JSON.stringify(dump)); + delete info.value.__prefab; Editor.Clipboard.write('_dump_component_', { cid: dump.cid, - dump: JSON.parse(JSON.stringify(dump)), + dump: info, }); }, }, @@ -1679,9 +1709,11 @@ exports.methods = { toggleShowAddComponentBtn(show) { this.$.componentAdd.style.display = show ? 'inline-block' : 'none'; }, + isAnimationMode() { + return Editor.EditMode.getMode() === 'animation'; + }, handlerSceneChangeMode() { - const mode = Editor.EditMode.getMode(); - this.toggleShowAddComponentBtn(mode !== 'animation'); // 动画编辑模式下,要隐藏按钮 + this.toggleShowAddComponentBtn(!this.isAnimationMode()); // 动画编辑模式下,要隐藏按钮 }, }; diff --git a/editor/src/marionette/preview.ts b/editor/src/marionette/preview.ts index 31a16b939e..69eda729fa 100644 --- a/editor/src/marionette/preview.ts +++ b/editor/src/marionette/preview.ts @@ -229,6 +229,11 @@ export class TransitionPreviewer extends AnimationGraphPartialPreviewer { this._timelineStatsDirty = true; } + public setRelativeDestinationStart(value: boolean) { + this._relativeDestinationStart = value; + this._timelineStatsDirty = true; + } + public calculateExitTimesFromTimelineLength(value: number) { assertIsNonNullable(this._source); return value / this._source.duration; @@ -257,6 +262,7 @@ export class TransitionPreviewer extends AnimationGraphPartialPreviewer { _transitionDuration: transitionDuration, _relativeDuration: relativeDuration, _destinationStart: destinationStart, + _relativeDestinationStart: relativeDestinationStart, } = this; if (!source || !target) { @@ -274,12 +280,14 @@ export class TransitionPreviewer extends AnimationGraphPartialPreviewer { ? sourceDuration * transitionDuration : transitionDuration; + const destinationStartAbsolute = relativeDestinationStart ? destinationStart * targetDuration : destinationStart; + if (time < exitTimeAbsolute) { source.sample(time / sourceDuration, 1.0); } else { const transitionTime = time - exitTimeAbsolute; if (transitionTime > transitionDurationAbsolute) { - target.sample(destinationStart + transitionTime / targetDuration, 1.0); + target.sample((destinationStartAbsolute + transitionTime) / targetDuration, 1.0); } else { const transitionRatio = transitionTime / transitionDurationAbsolute; const sourceWeight = 1.0 - transitionRatio; @@ -298,6 +306,7 @@ export class TransitionPreviewer extends AnimationGraphPartialPreviewer { private _exitConditionEnabled: boolean = false; private _exitCondition: number = 0.0; private _destinationStart = 0.0; + private _relativeDestinationStart = false; private _source: MotionEval | null = null; private _target: MotionEval | null = null; private _timelineStatsDirty = true; @@ -324,6 +333,7 @@ export class TransitionPreviewer extends AnimationGraphPartialPreviewer { _transitionDuration: transitionDuration, _relativeDuration: relativeDuration, _destinationStart: destinationStart, + _relativeDestinationStart: relativeDestinationStart, } = this; assertIsNonNullable(source); @@ -340,7 +350,7 @@ export class TransitionPreviewer extends AnimationGraphPartialPreviewer { const sourceMotionRepeatCount = sourceMotionLiveTime / sourceMotionDuration; const targetMotionDuration = target.duration; - const destinationStartAbsolute = targetMotionDuration * destinationStart; + const destinationStartAbsolute = relativeDestinationStart ? targetMotionDuration * destinationStart : destinationStart; const targetMotionStart = exitTimeAbsolute - destinationStartAbsolute; const targetMotionLiveTime = Math.max(transitionDurationAbsolute, targetMotionDuration); const targetMotionRepeatCount = targetMotionLiveTime / targetMotionDuration; diff --git a/exports/base.ts b/exports/base.ts index 87bd6bed43..28bebf84ce 100644 --- a/exports/base.ts +++ b/exports/base.ts @@ -44,6 +44,8 @@ export { legacyCC as cclegacy }; export * from '../cocos/input/types'; export * from '../cocos/input'; +export * from '../cocos/native-binding/index'; + type Constructor_ = Constructor; export type { Constructor_ as Constructor }; diff --git a/exports/native.ts b/exports/native.ts deleted file mode 100644 index 8c04f3f7f8..0000000000 --- a/exports/native.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '../cocos/native-binding/index'; diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 3a0c0290c2..4c4816e307 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -120,6 +120,11 @@ if(USE_JOB_SYSTEM_TASKFLOW AND USE_JOB_SYSTEM_TBB) set(USE_JOB_SYSTEM_TBB OFF) endif() +if(OHOS AND USE_JOB_SYSTEM_TBB) + message(WARNING "JobSystem tbb is not supported by HarmonyOS") + set(USE_JOB_SYSTEM_TBB OFF) +endif() + if(USE_JOB_SYSTEM_TASKFLOW) set(CMAKE_CXX_STANDARD 17) if(IOS AND "${TARGET_IOS_VERSION}" VERSION_LESS "12.0") @@ -496,8 +501,6 @@ endif() cocos_source_files( cocos/platform/interfaces/OSInterface.cpp cocos/platform/interfaces/OSInterface.h - cocos/platform/interfaces/OSInterfaceManager.cpp - cocos/platform/interfaces/OSInterfaceManager.h ) ############ platform : Interface definition diff --git a/native/cmake/predefine.cmake b/native/cmake/predefine.cmake index 6b9d421d0c..30446637ec 100644 --- a/native/cmake/predefine.cmake +++ b/native/cmake/predefine.cmake @@ -113,7 +113,12 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) if("$ENV{COCOS_ENGINE_DEV}" EQUAL "1") - set(WERROR_FLAGS "-Werror -Werror=return-type -Wno-deprecated-declarations") # -Wshorten-64-to-32 -Werror=return-type + set(WERROR_FLAGS "-Werror -Werror=return-type") # -Wshorten-64-to-32 -Werror=return-type + + if(APPLE) + set(WERROR_FLAGS "${WERROR_FLAGS} -Wno-deprecated-declarations") + endif() + if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") set(WERROR_FLAGS "/WX") endif() diff --git a/native/cocos/2d/renderer/Batcher2d.cpp b/native/cocos/2d/renderer/Batcher2d.cpp index b548df9913..1fd1c1d3a4 100644 --- a/native/cocos/2d/renderer/Batcher2d.cpp +++ b/native/cocos/2d/renderer/Batcher2d.cpp @@ -27,6 +27,7 @@ #include "application/ApplicationManager.h" #include "base/TypeDef.h" #include "core/Root.h" +#include "editor-support/MiddlewareManager.h" #include "renderer/pipeline/Define.h" #include "scene/Pass.h" @@ -98,6 +99,8 @@ void Batcher2d::walk(Node* node, float parentOpacity) { // NOLINT(misc-no-recurs float localOpacity = entity->getLocalOpacity(); float localColorAlpha = entity->getColorAlpha(); entity->setOpacity(parentOpacity * localOpacity * localColorAlpha); + entity->setColorDirty(false); + entity->setVBColorDirty(true); } if (entity->isEnabled()) { uint32_t size = entity->getRenderDrawInfosSize(); @@ -105,9 +108,11 @@ void Batcher2d::walk(Node* node, float parentOpacity) { // NOLINT(misc-no-recurs auto* drawInfo = entity->getRenderDrawInfoAt(i); handleDrawInfo(entity, drawInfo, node); } + entity->setVBColorDirty(false); + } + if (entity->getRenderEntityType() == RenderEntityType::CROSSED) { + breakWalk = true; } - if (entity->getRenderEntityType() == RenderEntityType::CROSSED) breakWalk = true; - entity->setColorDirty(false); } if (!breakWalk) { @@ -138,163 +143,184 @@ void Batcher2d::handlePostRender(RenderEntity* entity) { _stencilManager->enableMask(); } } +CC_FORCE_INLINE void Batcher2d::handleComponentDraw(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node) { + ccstd::hash_t dataHash = drawInfo->getDataHash(); + if (drawInfo->getIsMeshBuffer()) { + dataHash = 0; + } + + entity->setEnumStencilStage(_stencilManager->getStencilStage()); + auto tempStage = static_cast(entity->getStencilStage()); + + if (_currHash != dataHash || dataHash == 0 || _currMaterial != drawInfo->getMaterial() || _currStencilStage != tempStage) { + // Generate a batch if not batching + generateBatch(_currEntity, _currDrawInfo); + + bool isSubMask = entity->getIsSubMask(); + if (isSubMask) { + // Mask subComp + _stencilManager->enterLevel(entity); + } + if (!drawInfo->getIsMeshBuffer()) { + UIMeshBuffer* buffer = drawInfo->getMeshBuffer(); + if (_currMeshBuffer != buffer) { + _currMeshBuffer = buffer; + _indexStart = _currMeshBuffer->getIndexOffset(); + } + } + + _currHash = dataHash; + _currMaterial = drawInfo->getMaterial(); + _currStencilStage = tempStage; + _currLayer = entity->getNode()->getLayer(); + _currEntity = entity; + _currDrawInfo = drawInfo; + + _currTexture = drawInfo->getTexture(); + _currSampler = drawInfo->getSampler(); + if (_currSampler == nullptr) { + _currSamplerHash = 0; + } else { + _currSamplerHash = _currSampler->getHash(); + } + } + + if (!drawInfo->getIsMeshBuffer()) { + if (node->getChangedFlags() || drawInfo->getVertDirty()) { + fillVertexBuffers(entity, drawInfo); + drawInfo->setVertDirty(false); + } + if (entity->getVBColorDirty()) { + fillColors(entity, drawInfo); + } + + fillIndexBuffers(drawInfo); + } +} + +CC_FORCE_INLINE void Batcher2d::handleModelDraw(RenderEntity* entity, RenderDrawInfo* drawInfo) { + generateBatch(_currEntity, _currDrawInfo); + resetRenderStates(); + + // stencil stage + gfx::DepthStencilState* depthStencil = nullptr; + ccstd::hash_t dssHash = 0; + Material* renderMat = drawInfo->getMaterial(); + + bool isMask = entity->getIsMask(); + bool isSubMask = entity->getIsSubMask(); + if (isMask) { + //Mask node + _stencilManager->pushMask(); + _stencilManager->clear(entity); + + } else if (isSubMask) { + //Mask Comp + _stencilManager->enterLevel(entity); + } + _currStencilStage = _stencilManager->getStencilStage(); + + StencilStage entityStage = entity->getEnumStencilStage(); + if (entityStage == StencilStage::ENABLED || entityStage == StencilStage::DISABLED) { + entity->setEnumStencilStage(_stencilManager->getStencilStage()); + } + depthStencil = _stencilManager->getDepthStencilState(entityStage, renderMat); + dssHash = _stencilManager->getStencilHash(entityStage); + + // Model + auto* model = drawInfo->getModel(); + if (model == nullptr) return; + auto stamp = CC_CURRENT_ENGINE()->getTotalFrames(); + model->updateTransform(stamp); + model->updateUBOs(stamp); + + const auto& subModelList = model->getSubModels(); + for (const auto& submodel : subModelList) { + auto* curdrawBatch = _drawBatchPool.alloc(); + curdrawBatch->setVisFlags(entity->getNode()->getLayer()); + curdrawBatch->setModel(model); + curdrawBatch->setInputAssembler(submodel->getInputAssembler()); + curdrawBatch->setDescriptorSet(submodel->getDescriptorSet()); + + curdrawBatch->fillPass(renderMat, depthStencil, dssHash, &(submodel->getPatches())); + _batches.push_back(curdrawBatch); + } +} + +CC_FORCE_INLINE void Batcher2d::handleIADraw(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node) { + generateBatch(_currEntity, _currDrawInfo); + uint32_t dataHash = drawInfo->getDataHash(); + entity->setEnumStencilStage(_stencilManager->getStencilStage()); + auto tempStage = static_cast(entity->getStencilStage()); + _currHash = dataHash; + _currMaterial = drawInfo->getMaterial(); + _currStencilStage = tempStage; + _currLayer = entity->getNode()->getLayer(); + + // make sure next generateBatch return. + _currEntity = nullptr; + _currDrawInfo = nullptr; + _currMeshBuffer = nullptr; + + // if(frame) + _currTexture = drawInfo->getTexture(); + _currSampler = drawInfo->getSampler(); + _currSamplerHash = _currSampler->getHash(); + setIndexRange(drawInfo); + + UIMeshBuffer* currMeshBuffer = drawInfo->getMeshBuffer(); + currMeshBuffer->setDirty(true); + gfx::InputAssembler* ia = currMeshBuffer->requireFreeIA(getDevice()); + ia->setFirstIndex(drawInfo->getIndexOffset()); + ia->setIndexCount(drawInfo->getIbCount()); + + // stencilstage + gfx::DepthStencilState* depthStencil = nullptr; + ccstd::hash_t dssHash = 0; + StencilStage entityStage = entity->getEnumStencilStage(); + depthStencil = _stencilManager->getDepthStencilState(entityStage, drawInfo->getMaterial()); + dssHash = _stencilManager->getStencilHash(entityStage); + + auto* curdrawBatch = _drawBatchPool.alloc(); + curdrawBatch->setVisFlags(_currLayer); + curdrawBatch->setInputAssembler(ia); + curdrawBatch->fillPass(_currMaterial, depthStencil, dssHash); + const auto& pass = curdrawBatch->getPasses().at(0); + if (entity->getUseLocal()) { + drawInfo->updateLocalDescriptorSet(node, pass->getLocalSetLayout()); + curdrawBatch->setDescriptorSet(drawInfo->getLocalDes()); + } else { + curdrawBatch->setDescriptorSet(getDescriptorSet(_currTexture, _currSampler, pass->getLocalSetLayout())); + } + _batches.push_back(curdrawBatch); +} + +CC_FORCE_INLINE void Batcher2d::handleSubNode(RenderEntity* entity, RenderDrawInfo* drawInfo) { // NOLINT + if (drawInfo->getSubNode()) { + walk(drawInfo->getSubNode(), entity->getOpacity()); + } +} 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(); - if (drawInfoType == RenderDrawInfoType::COMP) { - ccstd::hash_t dataHash = drawInfo->getDataHash(); - if (drawInfo->getIsMeshBuffer()) { - dataHash = 0; - } - - entity->setEnumStencilStage(_stencilManager->getStencilStage()); - auto tempStage = static_cast(entity->getStencilStage()); - - if (_currHash != dataHash || dataHash == 0 || _currMaterial != drawInfo->getMaterial() || _currStencilStage != tempStage) { - // Generate a batch if not batching - generateBatch(_currEntity, _currDrawInfo); - - bool isSubMask = entity->getIsSubMask(); - if (isSubMask) { - // Mask subComp - _stencilManager->enterLevel(entity); - } - if (!drawInfo->getIsMeshBuffer()) { - UIMeshBuffer* buffer = drawInfo->getMeshBuffer(); - if (_currMeshBuffer != buffer) { - _currMeshBuffer = buffer; - _indexStart = _currMeshBuffer->getIndexOffset(); - } - } - - _currHash = dataHash; - _currMaterial = drawInfo->getMaterial(); - _currStencilStage = tempStage; - _currLayer = entity->getNode()->getLayer(); - _currEntity = entity; - _currDrawInfo = drawInfo; - - _currTexture = drawInfo->getTexture(); - _currSampler = drawInfo->getSampler(); - if (_currSampler == nullptr) { - _currSamplerHash = 0; - } else { - _currSamplerHash = _currSampler->getHash(); - } - } - - if (!drawInfo->getIsMeshBuffer()) { - if (node->getChangedFlags() || drawInfo->getVertDirty()) { - fillVertexBuffers(entity, drawInfo); - drawInfo->setVertDirty(false); - } - if (entity->getColorDirty()) { - fillColors(entity, drawInfo); - } - - fillIndexBuffers(drawInfo); - } - - } else if (drawInfoType == RenderDrawInfoType::MODEL) { - generateBatch(_currEntity, _currDrawInfo); - resetRenderStates(); - - // stencil stage - gfx::DepthStencilState* depthStencil = nullptr; - ccstd::hash_t dssHash = 0; - Material* renderMat = drawInfo->getMaterial(); - - bool isMask = entity->getIsMask(); - bool isSubMask = entity->getIsSubMask(); - if (isMask) { - //Mask node - _stencilManager->pushMask(); - _stencilManager->clear(entity); - - } else if (isSubMask) { - //Mask Comp - _stencilManager->enterLevel(entity); - } - _currStencilStage = _stencilManager->getStencilStage(); - - StencilStage entityStage = entity->getEnumStencilStage(); - if (entityStage == StencilStage::ENABLED || entityStage == StencilStage::DISABLED) { - entity->setEnumStencilStage(_stencilManager->getStencilStage()); - } - depthStencil = _stencilManager->getDepthStencilState(entityStage, renderMat); - dssHash = _stencilManager->getStencilHash(entityStage); - - // Model - auto* model = drawInfo->getModel(); - if (model == nullptr) return; - auto stamp = CC_CURRENT_ENGINE()->getTotalFrames(); - model->updateTransform(stamp); - model->updateUBOs(stamp); - - const auto& subModelList = model->getSubModels(); - for (const auto& submodel : subModelList) { - auto* curdrawBatch = _drawBatchPool.alloc(); - curdrawBatch->setVisFlags(entity->getNode()->getLayer()); - curdrawBatch->setModel(model); - curdrawBatch->setInputAssembler(submodel->getInputAssembler()); - curdrawBatch->setDescriptorSet(submodel->getDescriptorSet()); - - curdrawBatch->fillPass(renderMat, depthStencil, dssHash, &(submodel->getPatches())); - _batches.push_back(curdrawBatch); - } - } else if (drawInfoType == RenderDrawInfoType::IA) { - generateBatch(_currEntity, _currDrawInfo); - uint32_t dataHash = drawInfo->getDataHash(); - entity->setEnumStencilStage(_stencilManager->getStencilStage()); - auto tempStage = static_cast(entity->getStencilStage()); - _currHash = dataHash; - _currMaterial = drawInfo->getMaterial(); - _currStencilStage = tempStage; - _currLayer = entity->getNode()->getLayer(); - - // make sure next generateBatch return. - _currEntity = nullptr; - _currDrawInfo = nullptr; - _currMeshBuffer = nullptr; - - // if(frame) - _currTexture = drawInfo->getTexture(); - _currSampler = drawInfo->getSampler(); - _currSamplerHash = _currSampler->getHash(); - setIndexRange(drawInfo); - - UIMeshBuffer* currMeshBuffer = drawInfo->getMeshBuffer(); - currMeshBuffer->setDirty(true); - gfx::InputAssembler* ia = currMeshBuffer->requireFreeIA(getDevice()); - ia->setFirstIndex(drawInfo->getIndexOffset()); - ia->setIndexCount(drawInfo->getIbCount()); - - // stencilstage - gfx::DepthStencilState* depthStencil = nullptr; - ccstd::hash_t dssHash = 0; - StencilStage entityStage = entity->getEnumStencilStage(); - depthStencil = _stencilManager->getDepthStencilState(entityStage, drawInfo->getMaterial()); - dssHash = _stencilManager->getStencilHash(entityStage); - - auto* curdrawBatch = _drawBatchPool.alloc(); - curdrawBatch->setVisFlags(_currLayer); - curdrawBatch->setInputAssembler(ia); - curdrawBatch->fillPass(_currMaterial, depthStencil, dssHash); - const auto& pass = curdrawBatch->getPasses().at(0); - if (entity->getUseLocal()) { - drawInfo->updateLocalDescriptorSet(node, pass->getLocalSetLayout()); - curdrawBatch->setDescriptorSet(drawInfo->getLocalDes()); - } else { - curdrawBatch->setDescriptorSet(getDescriptorSet(_currTexture, _currSampler, pass->getLocalSetLayout())); - } - _batches.push_back(curdrawBatch); - } else { - if (drawInfo->getSubNode()) { - walk(drawInfo->getSubNode(), entity->getOpacity()); - } + switch (drawInfoType) { + case RenderDrawInfoType::COMP: + handleComponentDraw(entity, drawInfo, node); + break; + case RenderDrawInfoType::MODEL: + handleModelDraw(entity, drawInfo); + break; + case RenderDrawInfoType::IA: + handleIADraw(entity, drawInfo, node); + break; + case RenderDrawInfoType::SUB_NODE: + handleSubNode(entity, drawInfo); + break; + default: + break; } } @@ -302,7 +328,6 @@ void Batcher2d::generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo) { if (drawInfo == nullptr || _currMaterial == nullptr) { return; } - gfx::InputAssembler* ia = nullptr; if (drawInfo->getIsMeshBuffer()) { // Todo MeshBuffer RenderData @@ -427,13 +452,34 @@ void Batcher2d::uploadBuffers() { meshRenderData->uploadBuffers(); } + size_t i = 0; + size_t ii = 0; for (auto& map : _meshBuffersMap) { for (auto& buffer : map.second) { +#if CC_USE_MIDDLEWARE + // set vData and iData With Middleware buffer. + if (buffer->getUseLinkData()) { + int nativeFormat = 9; + size_t index = i; + if (buffer->getAttributes().size() == 3) { + i++; + } else { + nativeFormat = 13; + index = ii; + ii++; + } + auto* middleWare = middleware::MiddlewareManager::getInstance(); + auto* middleBuffer = middleWare->getMeshBuffer(nativeFormat); + auto* srcIBuf = middleBuffer->getIBFromBufferArray(index); + auto* srcVBuf = middleBuffer->getVBFromBufferArray(index); + buffer->setVData(reinterpret_cast(srcVBuf)); + buffer->setIData(reinterpret_cast(srcIBuf)); + } +#endif buffer->uploadBuffers(); buffer->reset(); } } - updateDescriptorSet(); } diff --git a/native/cocos/2d/renderer/Batcher2d.h b/native/cocos/2d/renderer/Batcher2d.h index 16c4b06321..abe346f0cd 100644 --- a/native/cocos/2d/renderer/Batcher2d.h +++ b/native/cocos/2d/renderer/Batcher2d.h @@ -67,6 +67,10 @@ public: void walk(Node* node, float parentOpacity); void handlePostRender(RenderEntity* entity); void handleDrawInfo(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node); + void handleComponentDraw(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node); + void handleModelDraw(RenderEntity* entity, RenderDrawInfo* drawInfo); + void handleIADraw(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node); + void handleSubNode(RenderEntity* entity, RenderDrawInfo* drawInfo); void generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo); void resetRenderStates(); diff --git a/native/cocos/2d/renderer/RenderDrawInfo.h b/native/cocos/2d/renderer/RenderDrawInfo.h index 0b74d8b8d3..ae9b120bdf 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.h +++ b/native/cocos/2d/renderer/RenderDrawInfo.h @@ -49,7 +49,7 @@ enum class RenderDrawInfoType : uint8_t { COMP, MODEL, IA, - SUB_NODE + SUB_NODE, }; struct LocalDSBF { @@ -218,6 +218,32 @@ public: inline gfx::DescriptorSet* getLocalDes() { return _localDSBF->ds; } void updateLocalDescriptorSet(Node* transform, gfx::DescriptorSetLayout* dsLayout); + inline void resetDrawInfo() { + destroy(); + + _drawInfoAttrs._bufferId = 0; + _drawInfoAttrs._accId = 0; + _drawInfoAttrs._vertexOffset = 0; + _drawInfoAttrs._indexOffset = 0; + _drawInfoAttrs._vbCount = 0; + _drawInfoAttrs._ibCount = 0; + _drawInfoAttrs._stride = 0; + _drawInfoAttrs._dataHash = 0; + _drawInfoAttrs._vertDirty = false; + _drawInfoAttrs._isMeshBuffer = false; + + _vbBuffer = nullptr; + _ibBuffer = nullptr; + _vDataBuffer = nullptr; + _iDataBuffer = nullptr; + _material = nullptr; + _texture = nullptr; + _sampler = nullptr; + _subNode = nullptr; + _model = nullptr; + _sharedBuffer = nullptr; + } + private: CC_DISALLOW_COPY_MOVE_ASSIGN(RenderDrawInfo); void destroy(); diff --git a/native/cocos/2d/renderer/RenderEntity.cpp b/native/cocos/2d/renderer/RenderEntity.cpp index 9652f09e55..aaaf6d0059 100644 --- a/native/cocos/2d/renderer/RenderEntity.cpp +++ b/native/cocos/2d/renderer/RenderEntity.cpp @@ -66,6 +66,16 @@ void RenderEntity::clearDynamicRenderDrawInfos() { _dynamicDrawInfos.clear(); } +void RenderEntity::clearStaticRenderDrawInfos() { + CC_ASSERT(_renderEntityType == RenderEntityType::STATIC); + + for (uint32_t i = 0; i < _staticDrawInfoSize; i++) { + RenderDrawInfo& drawInfo = _staticDrawInfos[i]; + drawInfo.resetDrawInfo(); + } + _staticDrawInfoSize = 0; +} + void RenderEntity::setNode(Node* node) { if (_node) { _node->setUserData(nullptr); diff --git a/native/cocos/2d/renderer/RenderEntity.h b/native/cocos/2d/renderer/RenderEntity.h index f9d1963765..c597aebfdc 100644 --- a/native/cocos/2d/renderer/RenderEntity.h +++ b/native/cocos/2d/renderer/RenderEntity.h @@ -73,6 +73,7 @@ public: void setDynamicRenderDrawInfo(RenderDrawInfo* drawInfo, uint32_t index); void removeDynamicRenderDrawInfo(); void clearDynamicRenderDrawInfos(); + void clearStaticRenderDrawInfos(); inline bool getIsMask() const { return static_cast(_entityAttrLayout.maskMode) == MaskMode::MASK || static_cast(_entityAttrLayout.maskMode) == MaskMode::MASK_INVERTED; @@ -116,6 +117,8 @@ public: inline se::Object* getEntitySharedBufferForJS() const { return _entitySharedBufferActor.getSharedArrayBufferObject(); } inline bool getColorDirty() const { return _entityAttrLayout.colorDirtyBit != 0; } inline void setColorDirty(bool dirty) { _entityAttrLayout.colorDirtyBit = dirty ? 1 : 0; } + inline bool getVBColorDirty() const { return _vbColorDirty; } + inline void setVBColorDirty(bool vbColorDirty) { _vbColorDirty = vbColorDirty; } inline Color getColor() const { return Color(_entityAttrLayout.colorR, _entityAttrLayout.colorG, _entityAttrLayout.colorB, _entityAttrLayout.colorA); } inline float getColorAlpha() const { return static_cast(_entityAttrLayout.colorA) / 255.F; } inline float getLocalOpacity() const { return _entityAttrLayout.localOpacity; } @@ -145,5 +148,6 @@ private: StencilStage _stencilStage{StencilStage::DISABLED}; RenderEntityType _renderEntityType{RenderEntityType::STATIC}; uint8_t _staticDrawInfoSize{0}; + bool _vbColorDirty{true}; }; } // namespace cc diff --git a/native/cocos/2d/renderer/StencilManager.cpp b/native/cocos/2d/renderer/StencilManager.cpp index edb2fa6009..1a5912abe7 100644 --- a/native/cocos/2d/renderer/StencilManager.cpp +++ b/native/cocos/2d/renderer/StencilManager.cpp @@ -65,7 +65,7 @@ gfx::DepthStencilState* StencilManager::getDepthStencilState(StencilStage stage, gfx::ComparisonFunc depthFunc = gfx::ComparisonFunc::LESS; auto* cacheMap = &_cacheStateMap; - if (mat && mat->getPasses()->at(0)) { + if (mat && !mat->getPasses()->empty()) { IntrusivePtr& pass = mat->getPasses()->at(0); const gfx::DepthStencilState* dss = pass->getDepthStencilState(); uint32_t depthTestValue = 0; diff --git a/native/cocos/2d/renderer/UIMeshBuffer.cpp b/native/cocos/2d/renderer/UIMeshBuffer.cpp index c3d92ae4c4..c539933ac8 100644 --- a/native/cocos/2d/renderer/UIMeshBuffer.cpp +++ b/native/cocos/2d/renderer/UIMeshBuffer.cpp @@ -180,4 +180,5 @@ void UIMeshBuffer::setDirty(bool dirty) const { void UIMeshBuffer::setFloatsPerVertex(uint32_t floatsPerVertex) { _meshBufferLayout->floatsPerVertex = floatsPerVertex; } + } // namespace cc diff --git a/native/cocos/2d/renderer/UIMeshBuffer.h b/native/cocos/2d/renderer/UIMeshBuffer.h index 80ed34c835..fde15af0fc 100644 --- a/native/cocos/2d/renderer/UIMeshBuffer.h +++ b/native/cocos/2d/renderer/UIMeshBuffer.h @@ -52,9 +52,7 @@ public: void destroy(); void setDirty(); void uploadBuffers(); - void syncSharedBufferToNative(uint32_t* buffer); - void resetIA(); void recycleIA(gfx::InputAssembler* ia); void parseLayout(); @@ -72,6 +70,11 @@ public: void setDirty(bool dirty) const; inline uint32_t getFloatsPerVertex() const { return _meshBufferLayout->floatsPerVertex; } void setFloatsPerVertex(uint32_t floatsPerVertex); + inline bool getUseLinkData() const { return _useLinkData; } + inline void setUseLinkData(bool val) { _useLinkData = val; } + inline const ccstd::vector& getAttributes() const { + return _attributes; + } protected: CC_DISALLOW_COPY_MOVE_ASSIGN(UIMeshBuffer); @@ -96,5 +99,6 @@ private: gfx::InputAssemblerInfo _iaInfo; uint32_t _nextFreeIAHandle{0}; bool _needDeleteVData{false}; + bool _useLinkData{false}; }; } // namespace cc diff --git a/native/cocos/2d/renderer/UIModelProxy.cpp b/native/cocos/2d/renderer/UIModelProxy.cpp index 1a4b9cddac..8c77bdabc7 100644 --- a/native/cocos/2d/renderer/UIModelProxy.cpp +++ b/native/cocos/2d/renderer/UIModelProxy.cpp @@ -43,35 +43,41 @@ void UIModelProxy::initModel(Node* node) { _node = node; } -void UIModelProxy::activeSubModel(uint8_t val) { +void UIModelProxy::activeSubModels() { if (_model == nullptr) return; - if (_model->getSubModels().size() <= val) { - auto* entity = static_cast(_node->getUserData()); - RenderDrawInfo* drawInfo = entity->getDynamicRenderDrawInfo(val); - if (drawInfo == nullptr) { - return; + auto* entity = static_cast(_node->getUserData()); + auto drawInfoSize = entity->getDynamicRenderDrawInfos().size(); + auto subModelSize = _model->getSubModels().size(); + if (drawInfoSize > subModelSize) { + for (size_t i = subModelSize; i < drawInfoSize; i++) { + if (_model->getSubModels().size() <= i) { + RenderDrawInfo* drawInfo = entity->getDynamicRenderDrawInfo(static_cast(i)); + if (drawInfo == nullptr) { + return; + } + + auto* vertexBuffer = _device->createBuffer({ + gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, + gfx::MemoryUsageBit::DEVICE, + 65535 * _stride, + _stride, + }); + auto* indexBuffer = _device->createBuffer({ + gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST, + gfx::MemoryUsageBit::DEVICE, + 65535 * sizeof(uint16_t) * 2, + sizeof(uint16_t), + }); + gfx::BufferList vbReference; + vbReference.emplace_back(vertexBuffer); + + auto* renderMesh = ccnew RenderingSubMesh(vbReference, _attributes, _primitiveMode, indexBuffer); + renderMesh->setSubMeshIdx(0); + + _model->initSubModel(static_cast(i), renderMesh, drawInfo->getMaterial()); + _graphicsUseSubMeshes.emplace_back(renderMesh); + } } - - auto* vertexBuffer = _device->createBuffer({ - gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, - gfx::MemoryUsageBit::DEVICE, - 65535 * _stride, - _stride, - }); - auto* indexBuffer = _device->createBuffer({ - gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST, - gfx::MemoryUsageBit::DEVICE, - 65535 * sizeof(uint16_t) * 2, - sizeof(uint16_t), - }); - gfx::BufferList vbReference; - vbReference.emplace_back(vertexBuffer); - - auto* renderMesh = ccnew RenderingSubMesh(vbReference, _attributes, _primitiveMode, indexBuffer); - renderMesh->setSubMeshIdx(0); - - _model->initSubModel(val, renderMesh, drawInfo->getMaterial()); - _graphicsUseSubMeshes.emplace_back(renderMesh); } } @@ -113,6 +119,12 @@ void UIModelProxy::destroy() { Root::getInstance()->destroyModel(_model); _model = nullptr; } + + for (auto& subMesh : _graphicsUseSubMeshes) { + subMesh->destroy(); + subMesh = nullptr; + } + _graphicsUseSubMeshes.clear(); } void UIModelProxy::clear() { diff --git a/native/cocos/2d/renderer/UIModelProxy.h b/native/cocos/2d/renderer/UIModelProxy.h index 0a0d04480d..d2f872f5e0 100644 --- a/native/cocos/2d/renderer/UIModelProxy.h +++ b/native/cocos/2d/renderer/UIModelProxy.h @@ -35,10 +35,11 @@ public: ~UIModelProxy(); void initModel(Node* node); - void activeSubModel(uint8_t val); + void activeSubModels(); void uploadData(); void destroy(); void clear(); + inline scene::Model* getModel() const { return _model; } // For UIModel void updateModels(scene::Model* models); void attachDrawInfo(); @@ -50,9 +51,9 @@ protected: private: Node* _node{nullptr}; ccstd::vector _models{}; - ccstd::vector _graphicsUseSubMeshes{}; + ccstd::vector> _graphicsUseSubMeshes{}; // For UIModel - scene::Model* _model{nullptr}; + IntrusivePtr _model; gfx::Device* _device{nullptr}; uint32_t _stride{32}; diff --git a/native/cocos/application/ApplicationManager.h b/native/cocos/application/ApplicationManager.h index 26b475c5f3..5d1099782d 100644 --- a/native/cocos/application/ApplicationManager.h +++ b/native/cocos/application/ApplicationManager.h @@ -73,7 +73,6 @@ private: #define CC_CURRENT_APPLICATION_SAFE() CC_APPLICATION_MANAGER()->getCurrentAppSafe() #define CC_CURRENT_ENGINE() CC_CURRENT_APPLICATION_SAFE()->getEngine() #define CC_GET_PLATFORM_INTERFACE(intf) CC_CURRENT_ENGINE()->getInterface() - /** * @brief Called at the user-defined main entry */ diff --git a/native/cocos/application/CocosApplication.cpp b/native/cocos/application/CocosApplication.cpp index 53dea7afbf..9808bed6c7 100644 --- a/native/cocos/application/CocosApplication.cpp +++ b/native/cocos/application/CocosApplication.cpp @@ -45,15 +45,27 @@ CocosApplication::CocosApplication() { } CocosApplication::~CocosApplication() { - _engine->off(BaseEngine::ON_RESUME); - _engine->off(BaseEngine::ON_PAUSE); - _engine->off(BaseEngine::ON_CLOSE); + unregisterAllEngineEvents(); +} + +void CocosApplication::unregisterAllEngineEvents() { + if (_engine != nullptr) { + _engine->offAll(BaseEngine::ON_START); + _engine->offAll(BaseEngine::ON_RESUME); + _engine->offAll(BaseEngine::ON_PAUSE); + _engine->offAll(BaseEngine::ON_CLOSE); + } } int CocosApplication::init() { if (_engine->init()) { return -1; } + unregisterAllEngineEvents(); + + _engine->on(BaseEngine::ON_START, [this]() { + this->onStart(); + }); _engine->on(BaseEngine::ON_RESUME, [this]() { this->onResume(); @@ -112,6 +124,10 @@ BaseEngine::Ptr CocosApplication::getEngine() const { return _engine; } +void CocosApplication::onStart() { + // TODO(cc): Handling engine start events +} + void CocosApplication::onPause() { // TODO(cc): Handling pause events } diff --git a/native/cocos/application/CocosApplication.h b/native/cocos/application/CocosApplication.h index df961ab6b0..fd1305fc32 100644 --- a/native/cocos/application/CocosApplication.h +++ b/native/cocos/application/CocosApplication.h @@ -66,6 +66,10 @@ public: */ BaseEngine::Ptr getEngine() const override; + /** + * @brief Processing engine start events. + */ + virtual void onStart(); /** * @brief Processing pause events.. */ @@ -123,6 +127,8 @@ public: virtual void setXXTeaKey(const ccstd::string &key); private: + void unregisterAllEngineEvents(); + ISystemWindow *_systemWindow{nullptr}; BaseEngine::Ptr _engine{nullptr}; }; diff --git a/native/cocos/bindings/auto/jsb_2d_auto.cpp b/native/cocos/bindings/auto/jsb_2d_auto.cpp index 5c85514f9a..896bced7ab 100644 --- a/native/cocos/bindings/auto/jsb_2d_auto.cpp +++ b/native/cocos/bindings/auto/jsb_2d_auto.cpp @@ -65,6 +65,26 @@ static bool js_2d_UIMeshBuffer_getIData(se::State& s) // NOLINT(readability-iden } SE_BIND_FUNC_AS_PROP_GET(js_2d_UIMeshBuffer_getIData) +static bool js_2d_UIMeshBuffer_getUseLinkData(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + bool result = cobj->getUseLinkData(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC_AS_PROP_GET(js_2d_UIMeshBuffer_getUseLinkData) + static bool js_2d_UIMeshBuffer_getVData(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -147,6 +167,26 @@ static bool js_2d_UIMeshBuffer_setIData(se::State& s) // NOLINT(readability-iden } SE_BIND_FUNC_AS_PROP_SET(js_2d_UIMeshBuffer_setIData) +static bool js_2d_UIMeshBuffer_setUseLinkData(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setUseLinkData(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC_AS_PROP_SET(js_2d_UIMeshBuffer_setUseLinkData) + static bool js_2d_UIMeshBuffer_setVData(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -228,6 +268,7 @@ bool js_register_2d_UIMeshBuffer(se::Object* obj) // NOLINT(readability-identifi #endif cls->defineProperty("vData", _SE(js_2d_UIMeshBuffer_getVData_asGetter), _SE(js_2d_UIMeshBuffer_setVData_asSetter)); cls->defineProperty("iData", _SE(js_2d_UIMeshBuffer_getIData_asGetter), _SE(js_2d_UIMeshBuffer_setIData_asSetter)); + cls->defineProperty("useLinkData", _SE(js_2d_UIMeshBuffer_getUseLinkData_asGetter), _SE(js_2d_UIMeshBuffer_setUseLinkData_asSetter)); cls->defineFunction("destroy", _SE(js_2d_UIMeshBuffer_destroy)); cls->defineFunction("initialize", _SE(js_2d_UIMeshBuffer_initialize)); cls->defineFunction("reset", _SE(js_2d_UIMeshBuffer_reset)); @@ -1322,6 +1363,22 @@ static bool js_2d_RenderEntity_clearDynamicRenderDrawInfos(se::State& s) // NOLI } SE_BIND_FUNC(js_2d_RenderEntity_clearDynamicRenderDrawInfos) +static bool js_2d_RenderEntity_clearStaticRenderDrawInfos(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cobj->clearStaticRenderDrawInfos(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_2d_RenderEntity_clearStaticRenderDrawInfos) + static bool js_2d_RenderEntity_getEntitySharedBufferForJS(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -1799,6 +1856,7 @@ bool js_register_2d_RenderEntity(se::Object* obj) // NOLINT(readability-identifi cls->defineProperty("stencilStage", _SE(js_2d_RenderEntity_getStencilStage_asGetter), _SE(js_2d_RenderEntity_setStencilStage_asSetter)); cls->defineFunction("addDynamicRenderDrawInfo", _SE(js_2d_RenderEntity_addDynamicRenderDrawInfo)); cls->defineFunction("clearDynamicRenderDrawInfos", _SE(js_2d_RenderEntity_clearDynamicRenderDrawInfos)); + cls->defineFunction("clearStaticRenderDrawInfos", _SE(js_2d_RenderEntity_clearStaticRenderDrawInfos)); cls->defineFunction("getEntitySharedBufferForJS", _SE(js_2d_RenderEntity_getEntitySharedBufferForJS)); cls->defineFunction("getIsMask", _SE(js_2d_RenderEntity_getIsMask)); cls->defineFunction("getIsMaskInverted", _SE(js_2d_RenderEntity_getIsMaskInverted)); @@ -2066,25 +2124,21 @@ bool js_register_2d_Batcher2d(se::Object* obj) // NOLINT(readability-identifier- se::Object* __jsb_cc_UIModelProxy_proto = nullptr; // NOLINT se::Class* __jsb_cc_UIModelProxy_class = nullptr; // NOLINT -static bool js_2d_UIModelProxy_activeSubModel(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_2d_UIModelProxy_activeSubModels(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); if (nullptr == cobj) return true; const auto& args = s.args(); size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - cobj->activeSubModel(arg0.value()); + if (argc == 0) { + cobj->activeSubModels(); return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } -SE_BIND_FUNC(js_2d_UIModelProxy_activeSubModel) +SE_BIND_FUNC(js_2d_UIModelProxy_activeSubModels) static bool js_2d_UIModelProxy_attachDrawInfo(se::State& s) // NOLINT(readability-identifier-naming) { @@ -2154,6 +2208,26 @@ static bool js_2d_UIModelProxy_destroy(se::State& s) // NOLINT(readability-ident } SE_BIND_FUNC(js_2d_UIModelProxy_destroy) +static bool js_2d_UIModelProxy_getModel(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + cc::scene::Model* result = cobj->getModel(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_2d_UIModelProxy_getModel) + static bool js_2d_UIModelProxy_initModel(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -2233,11 +2307,12 @@ bool js_register_2d_UIModelProxy(se::Object* obj) // NOLINT(readability-identifi #if CC_DEBUG cls->defineStaticProperty("isJSBClass", _SE(js_2d_getter_return_true), nullptr); #endif - cls->defineFunction("activeSubModel", _SE(js_2d_UIModelProxy_activeSubModel)); + cls->defineFunction("activeSubModels", _SE(js_2d_UIModelProxy_activeSubModels)); cls->defineFunction("attachDrawInfo", _SE(js_2d_UIModelProxy_attachDrawInfo)); cls->defineFunction("attachNode", _SE(js_2d_UIModelProxy_attachNode)); cls->defineFunction("clear", _SE(js_2d_UIModelProxy_clear)); cls->defineFunction("destroy", _SE(js_2d_UIModelProxy_destroy)); + cls->defineFunction("getModel", _SE(js_2d_UIModelProxy_getModel)); cls->defineFunction("initModel", _SE(js_2d_UIModelProxy_initModel)); cls->defineFunction("updateModels", _SE(js_2d_UIModelProxy_updateModels)); cls->defineFunction("uploadData", _SE(js_2d_UIModelProxy_uploadData)); diff --git a/native/cocos/bindings/auto/jsb_2d_auto.h b/native/cocos/bindings/auto/jsb_2d_auto.h index 2067c02f05..d5f8f08fbd 100644 --- a/native/cocos/bindings/auto/jsb_2d_auto.h +++ b/native/cocos/bindings/auto/jsb_2d_auto.h @@ -55,6 +55,7 @@ bool js_register_cc_RenderEntity(se::Object *obj); // NOLINT SE_DECLARE_FUNC(js_2d_RenderEntity_addDynamicRenderDrawInfo); SE_DECLARE_FUNC(js_2d_RenderEntity_clearDynamicRenderDrawInfos); +SE_DECLARE_FUNC(js_2d_RenderEntity_clearStaticRenderDrawInfos); SE_DECLARE_FUNC(js_2d_RenderEntity_getEntitySharedBufferForJS); SE_DECLARE_FUNC(js_2d_RenderEntity_getIsMask); SE_DECLARE_FUNC(js_2d_RenderEntity_getIsMaskInverted); @@ -94,11 +95,12 @@ extern se::Class *__jsb_cc_UIModelProxy_class; // NOLINT bool js_register_cc_UIModelProxy(se::Object *obj); // NOLINT -SE_DECLARE_FUNC(js_2d_UIModelProxy_activeSubModel); +SE_DECLARE_FUNC(js_2d_UIModelProxy_activeSubModels); SE_DECLARE_FUNC(js_2d_UIModelProxy_attachDrawInfo); SE_DECLARE_FUNC(js_2d_UIModelProxy_attachNode); SE_DECLARE_FUNC(js_2d_UIModelProxy_clear); SE_DECLARE_FUNC(js_2d_UIModelProxy_destroy); +SE_DECLARE_FUNC(js_2d_UIModelProxy_getModel); SE_DECLARE_FUNC(js_2d_UIModelProxy_initModel); SE_DECLARE_FUNC(js_2d_UIModelProxy_updateModels); SE_DECLARE_FUNC(js_2d_UIModelProxy_uploadData); diff --git a/native/cocos/bindings/auto/jsb_assets_auto.cpp b/native/cocos/bindings/auto/jsb_assets_auto.cpp index 791c0fe33a..8c649c1353 100644 --- a/native/cocos/bindings/auto/jsb_assets_auto.cpp +++ b/native/cocos/bindings/auto/jsb_assets_auto.cpp @@ -10657,7 +10657,7 @@ bool js_register_assets_Material(se::Object* obj) // NOLINT(readability-identifi cls->defineFunction("setPropertyVec3Array", _SE(js_assets_Material_setPropertyVec3Array)); cls->defineFunction("setPropertyVec4", _SE(js_assets_Material_setPropertyVec4)); cls->defineFunction("setPropertyVec4Array", _SE(js_assets_Material_setPropertyVec4Array)); - cls->defineStaticFunction("getHashForMaterial", _SE(js_assets_Material_getHashForMaterial_static)); + cls->defineStaticFunction("getHash", _SE(js_assets_Material_getHashForMaterial_static)); cls->defineFinalizeFunction(_SE(js_cc_Material_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -20260,7 +20260,7 @@ bool js_register_assets_Skeleton(se::Object* obj) // NOLINT(readability-identifi #endif cls->defineProperty({"_joints", "joints"}, _SE(js_assets_Skeleton_getJoints_asGetter), _SE(js_assets_Skeleton_setJoints_asSetter)); cls->defineProperty({"_hash", "hash"}, _SE(js_assets_Skeleton_getHash_asGetter), _SE(js_assets_Skeleton_setHash_asSetter)); - cls->defineProperty({"_invBindposes", "invBindposes"}, _SE(js_assets_Skeleton_getInverseBindposes_asGetter), nullptr); + cls->defineProperty({"_invBindposes", "inverseBindposes"}, _SE(js_assets_Skeleton_getInverseBindposes_asGetter), nullptr); cls->defineFunction("_getBindposes", _SE(js_assets_Skeleton_getBindposes)); cls->defineFunction("getHash", _SE(js_assets_Skeleton_getHash)); cls->defineFunction("getInverseBindposes", _SE(js_assets_Skeleton_getInverseBindposes)); diff --git a/native/cocos/bindings/auto/jsb_geometry_auto.cpp b/native/cocos/bindings/auto/jsb_geometry_auto.cpp index 56d95754ae..5d0e66a0d1 100644 --- a/native/cocos/bindings/auto/jsb_geometry_auto.cpp +++ b/native/cocos/bindings/auto/jsb_geometry_auto.cpp @@ -416,6 +416,26 @@ bool js_register_geometry_Capsule(se::Object* obj) // NOLINT(readability-identif se::Object* __jsb_cc_geometry_Plane_proto = nullptr; // NOLINT se::Class* __jsb_cc_geometry_Plane_class = nullptr; // NOLINT +static bool js_geometry_Plane_clone(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + cc::geometry::Plane result = cobj->clone(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_geometry_Plane_clone) + static bool js_geometry_Plane_define(se::State& s) // NOLINT(readability-identifier-naming) { CC_UNUSED bool ok = true; @@ -563,6 +583,86 @@ static bool js_geometry_Plane_getZ(se::State& s) // NOLINT(readability-identifie } SE_BIND_FUNC(js_geometry_Plane_getZ) +static bool js_geometry_Plane_setW(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setW(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_geometry_Plane_setW) + +static bool js_geometry_Plane_setX(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setX(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_geometry_Plane_setX) + +static bool js_geometry_Plane_setY(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setY(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_geometry_Plane_setY) + +static bool js_geometry_Plane_setZ(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setZ(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_geometry_Plane_setZ) + static bool js_geometry_Plane_transform(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -583,6 +683,48 @@ static bool js_geometry_Plane_transform(se::State& s) // NOLINT(readability-iden } SE_BIND_FUNC(js_geometry_Plane_transform) +static bool js_geometry_Plane_clone_static(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cc::geometry::Plane* result = cc::geometry::Plane::clone(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_geometry_Plane_clone_static) + +static bool js_geometry_Plane_copy_static(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 2) { + HolderType arg0 = {}; + HolderType arg1 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + ok &= sevalue_to_native(args[1], &arg1, nullptr); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cc::geometry::Plane* result = cc::geometry::Plane::copy(arg0.value(), arg1.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); + return false; +} +SE_BIND_FUNC(js_geometry_Plane_copy_static) + static bool js_geometry_Plane_create_static(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -609,6 +751,106 @@ static bool js_geometry_Plane_create_static(se::State& s) // NOLINT(readability- } SE_BIND_FUNC(js_geometry_Plane_create_static) +static bool js_geometry_Plane_fromNormalAndPoint_static(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 3) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + ok &= sevalue_to_native(args[1], &arg1, nullptr); + ok &= sevalue_to_native(args[2], &arg2, nullptr); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cc::geometry::Plane* result = cc::geometry::Plane::fromNormalAndPoint(arg0.value(), arg1.value(), arg2.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3); + return false; +} +SE_BIND_FUNC(js_geometry_Plane_fromNormalAndPoint_static) + +static bool js_geometry_Plane_fromPoints_static(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 4) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + HolderType arg3 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + ok &= sevalue_to_native(args[1], &arg1, nullptr); + ok &= sevalue_to_native(args[2], &arg2, nullptr); + ok &= sevalue_to_native(args[3], &arg3, nullptr); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cc::geometry::Plane* result = cc::geometry::Plane::fromPoints(arg0.value(), arg1.value(), arg2.value(), arg3.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 4); + return false; +} +SE_BIND_FUNC(js_geometry_Plane_fromPoints_static) + +static bool js_geometry_Plane_normalize_static(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 2) { + HolderType arg0 = {}; + HolderType arg1 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + ok &= sevalue_to_native(args[1], &arg1, nullptr); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cc::geometry::Plane* result = cc::geometry::Plane::normalize(arg0.value(), arg1.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); + return false; +} +SE_BIND_FUNC(js_geometry_Plane_normalize_static) + +static bool js_geometry_Plane_set_static(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 5) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + HolderType arg3 = {}; + HolderType arg4 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + ok &= sevalue_to_native(args[1], &arg1, nullptr); + ok &= sevalue_to_native(args[2], &arg2, nullptr); + ok &= sevalue_to_native(args[3], &arg3, nullptr); + ok &= sevalue_to_native(args[4], &arg4, nullptr); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cc::geometry::Plane* result = cc::geometry::Plane::set(arg0.value(), arg1.value(), arg2.value(), arg3.value(), arg4.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 5); + return false; +} +SE_BIND_FUNC(js_geometry_Plane_set_static) + static bool js_geometry_Plane_get_n(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -718,14 +960,25 @@ bool js_register_geometry_Plane(se::Object* obj) // NOLINT(readability-identifie #endif cls->defineProperty("n", _SE(js_geometry_Plane_get_n), _SE(js_geometry_Plane_set_n)); cls->defineProperty("d", _SE(js_geometry_Plane_get_d), _SE(js_geometry_Plane_set_d)); + cls->defineFunction("clone", _SE(js_geometry_Plane_clone)); cls->defineFunction("define", _SE(js_geometry_Plane_define)); cls->defineFunction("distance", _SE(js_geometry_Plane_distance)); cls->defineFunction("getW", _SE(js_geometry_Plane_getW)); cls->defineFunction("getX", _SE(js_geometry_Plane_getX)); cls->defineFunction("getY", _SE(js_geometry_Plane_getY)); cls->defineFunction("getZ", _SE(js_geometry_Plane_getZ)); + cls->defineFunction("setW", _SE(js_geometry_Plane_setW)); + cls->defineFunction("setX", _SE(js_geometry_Plane_setX)); + cls->defineFunction("setY", _SE(js_geometry_Plane_setY)); + cls->defineFunction("setZ", _SE(js_geometry_Plane_setZ)); cls->defineFunction("transform", _SE(js_geometry_Plane_transform)); + cls->defineStaticFunction("clone", _SE(js_geometry_Plane_clone_static)); + cls->defineStaticFunction("copy", _SE(js_geometry_Plane_copy_static)); cls->defineStaticFunction("create", _SE(js_geometry_Plane_create_static)); + cls->defineStaticFunction("fromNormalAndPoint", _SE(js_geometry_Plane_fromNormalAndPoint_static)); + cls->defineStaticFunction("fromPoints", _SE(js_geometry_Plane_fromPoints_static)); + cls->defineStaticFunction("normalize", _SE(js_geometry_Plane_normalize_static)); + cls->defineStaticFunction("set", _SE(js_geometry_Plane_set_static)); cls->defineFinalizeFunction(_SE(js_cc_geometry_Plane_finalize)); cls->install(); JSBClassType::registerClass(cls); diff --git a/native/cocos/bindings/auto/jsb_geometry_auto.h b/native/cocos/bindings/auto/jsb_geometry_auto.h index bd96e6bb20..980cce0585 100644 --- a/native/cocos/bindings/auto/jsb_geometry_auto.h +++ b/native/cocos/bindings/auto/jsb_geometry_auto.h @@ -50,14 +50,25 @@ extern se::Class *__jsb_cc_geometry_Plane_class; // NOLINT bool js_register_cc_geometry_Plane(se::Object *obj); // NOLINT +SE_DECLARE_FUNC(js_geometry_Plane_clone); SE_DECLARE_FUNC(js_geometry_Plane_define); SE_DECLARE_FUNC(js_geometry_Plane_distance); SE_DECLARE_FUNC(js_geometry_Plane_getW); SE_DECLARE_FUNC(js_geometry_Plane_getX); SE_DECLARE_FUNC(js_geometry_Plane_getY); SE_DECLARE_FUNC(js_geometry_Plane_getZ); +SE_DECLARE_FUNC(js_geometry_Plane_setW); +SE_DECLARE_FUNC(js_geometry_Plane_setX); +SE_DECLARE_FUNC(js_geometry_Plane_setY); +SE_DECLARE_FUNC(js_geometry_Plane_setZ); SE_DECLARE_FUNC(js_geometry_Plane_transform); +SE_DECLARE_FUNC(js_geometry_Plane_clone); +SE_DECLARE_FUNC(js_geometry_Plane_copy); SE_DECLARE_FUNC(js_geometry_Plane_create); +SE_DECLARE_FUNC(js_geometry_Plane_fromNormalAndPoint); +SE_DECLARE_FUNC(js_geometry_Plane_fromPoints); +SE_DECLARE_FUNC(js_geometry_Plane_normalize); +SE_DECLARE_FUNC(js_geometry_Plane_set); SE_DECLARE_FUNC(js_geometry_Plane_Plane); extern se::Object *__jsb_cc_geometry_Frustum_proto; // NOLINT diff --git a/native/cocos/bindings/auto/jsb_scene_auto.cpp b/native/cocos/bindings/auto/jsb_scene_auto.cpp index c4bc974cec..7896a5c0b5 100644 --- a/native/cocos/bindings/auto/jsb_scene_auto.cpp +++ b/native/cocos/bindings/auto/jsb_scene_auto.cpp @@ -325,6 +325,26 @@ static bool js_scene_Node_getParent(se::State& s) // NOLINT(readability-identifi } SE_BIND_FUNC(js_scene_Node_getParent) +static bool js_scene_Node_getPathInHierarchy(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + std::string result = cobj->getPathInHierarchy(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_scene_Node_getPathInHierarchy) + static bool js_scene_Node_getScene(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -539,103 +559,6 @@ static bool js_scene_Node_lookAt(se::State& s) // NOLINT(readability-identifier- } SE_BIND_FUNC(js_scene_Node_lookAt) -static bool js_scene_Node_off(se::State& s) // NOLINT(readability-identifier-naming) -{ - CC_UNUSED bool ok = true; - auto* cobj = SE_THIS_OBJECT(s); - // SE_PRECONDITION2( cobj, false, "Invalid Native Object"); - if (nullptr == cobj) return true; - const auto& args = s.args(); - size_t argc = args.size(); - do { - if (argc == 2) { - HolderType arg0 = {}; - HolderType arg1 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - if (!ok) { ok = true; break; } - cobj->off(arg0.value(), arg1.value()); - return true; - } - } while(false); - - do { - if (argc == 3) { - HolderType arg0 = {}; - HolderType arg1 = {}; - HolderType arg2 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); - cobj->off(arg0.value(), arg1.value(), arg2.value()); - return true; - } - } while(false); - - do { - if (argc == 1) { - HolderType arg0 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - cobj->off(arg0.value()); - return true; - } - } while(false); - - do { - if (argc == 2) { - HolderType arg0 = {}; - HolderType arg1 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - cobj->off(arg0.value(), arg1.value()); - return true; - } - } while(false); - - do { - if (argc == 2) { - HolderType arg0 = {}; - HolderType arg1 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - if (!ok) { ok = true; break; } - cobj->off(arg0.value(), arg1.value()); - return true; - } - } while(false); - - do { - if (argc == 3) { - HolderType arg0 = {}; - HolderType arg1 = {}; - HolderType arg2 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); - cobj->off(arg0.value(), arg1.value(), arg2.value()); - return true; - } - } while(false); - - SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); - return false; -} -SE_BIND_FUNC(js_scene_Node_off) - static bool js_scene_Node_onPostActivated(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -1821,6 +1744,7 @@ bool js_register_scene_Node(se::Object* obj) // NOLINT(readability-identifier-na cls->defineFunction("getDirtyFlag", _SE(js_scene_Node_getDirtyFlag)); cls->defineFunction("getLayer", _SE(js_scene_Node_getLayer)); cls->defineFunction("getParent", _SE(js_scene_Node_getParent)); + cls->defineFunction("getPathInHierarchy", _SE(js_scene_Node_getPathInHierarchy)); cls->defineFunction("getScene", _SE(js_scene_Node_getScene)); cls->defineFunction("getSiblingIndex", _SE(js_scene_Node_getSiblingIndex)); cls->defineFunction("insertChild", _SE(js_scene_Node_insertChild)); @@ -1829,7 +1753,6 @@ bool js_register_scene_Node(se::Object* obj) // NOLINT(readability-identifier-na cls->defineFunction("isChildOf", _SE(js_scene_Node_isChildOf)); cls->defineFunction("isStatic", _SE(js_scene_Node_isStatic)); cls->defineFunction("lookAt", _SE(js_scene_Node_lookAt)); - cls->defineFunction("off", _SE(js_scene_Node_off)); cls->defineFunction("onPostActivated", _SE(js_scene_Node_onPostActivated)); cls->defineFunction("_onPreDestroy", _SE(js_scene_Node_onPreDestroy)); cls->defineFunction("_onPreDestroyBase", _SE(js_scene_Node_onPreDestroyBase)); @@ -15503,6 +15426,22 @@ static bool js_scene_Pass_update(se::State& s) // NOLINT(readability-identifier- } SE_BIND_FUNC(js_scene_Pass_update) +static bool js_scene_Pass_updatePassHash(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cobj->updatePassHash(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_scene_Pass_updatePassHash) + static bool js_scene_Pass_fillPipelineInfo_static(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -15712,6 +15651,7 @@ bool js_register_scene_Pass(se::Object* obj) // NOLINT(readability-identifier-na cls->defineFunction("setUniformArray", _SE(js_scene_Pass_setUniformArray)); cls->defineFunction("tryCompile", _SE(js_scene_Pass_tryCompile)); cls->defineFunction("update", _SE(js_scene_Pass_update)); + cls->defineFunction("_updatePassHash", _SE(js_scene_Pass_updatePassHash)); cls->defineStaticFunction("fillPipelineInfo", _SE(js_scene_Pass_fillPipelineInfo_static)); cls->defineStaticFunction("getBindingFromHandle", _SE(js_scene_Pass_getBindingFromHandle_static)); cls->defineStaticFunction("getCountFromHandle", _SE(js_scene_Pass_getCountFromHandle_static)); diff --git a/native/cocos/bindings/auto/jsb_scene_auto.h b/native/cocos/bindings/auto/jsb_scene_auto.h index 4acef8293d..e57f4ce78c 100644 --- a/native/cocos/bindings/auto/jsb_scene_auto.h +++ b/native/cocos/bindings/auto/jsb_scene_auto.h @@ -101,6 +101,7 @@ SE_DECLARE_FUNC(js_scene_Node_getChildByUuid); SE_DECLARE_FUNC(js_scene_Node_getDirtyFlag); SE_DECLARE_FUNC(js_scene_Node_getLayer); SE_DECLARE_FUNC(js_scene_Node_getParent); +SE_DECLARE_FUNC(js_scene_Node_getPathInHierarchy); SE_DECLARE_FUNC(js_scene_Node_getScene); SE_DECLARE_FUNC(js_scene_Node_getSiblingIndex); SE_DECLARE_FUNC(js_scene_Node_insertChild); @@ -109,7 +110,6 @@ SE_DECLARE_FUNC(js_scene_Node_isActive); SE_DECLARE_FUNC(js_scene_Node_isChildOf); SE_DECLARE_FUNC(js_scene_Node_isStatic); SE_DECLARE_FUNC(js_scene_Node_lookAt); -SE_DECLARE_FUNC(js_scene_Node_off); SE_DECLARE_FUNC(js_scene_Node_onPostActivated); SE_DECLARE_FUNC(js_scene_Node_onPreDestroy); SE_DECLARE_FUNC(js_scene_Node_onPreDestroyBase); @@ -513,6 +513,7 @@ SE_DECLARE_FUNC(js_scene_Pass_setUniform); SE_DECLARE_FUNC(js_scene_Pass_setUniformArray); SE_DECLARE_FUNC(js_scene_Pass_tryCompile); SE_DECLARE_FUNC(js_scene_Pass_update); +SE_DECLARE_FUNC(js_scene_Pass_updatePassHash); SE_DECLARE_FUNC(js_scene_Pass_fillPipelineInfo); SE_DECLARE_FUNC(js_scene_Pass_getBindingFromHandle); SE_DECLARE_FUNC(js_scene_Pass_getCountFromHandle); diff --git a/native/cocos/bindings/jswrapper/v8/Class.cpp b/native/cocos/bindings/jswrapper/v8/Class.cpp index 2bb2a7867d..f2f8c77434 100644 --- a/native/cocos/bindings/jswrapper/v8/Class.cpp +++ b/native/cocos/bindings/jswrapper/v8/Class.cpp @@ -119,7 +119,7 @@ bool Class::init(const ccstd::string &clsName, Object *parent, Object *parentPro } _ctorTemplate.Get(__isolate)->SetClassName(jsNameVal.ToLocalChecked()); - _ctorTemplate.Get(__isolate)->InstanceTemplate()->SetInternalFieldCount(2); + _ctorTemplate.Get(__isolate)->InstanceTemplate()->SetInternalFieldCount(1); return true; } diff --git a/native/cocos/bindings/jswrapper/v8/Class.h b/native/cocos/bindings/jswrapper/v8/Class.h index 50ff1c10db..395329ea10 100644 --- a/native/cocos/bindings/jswrapper/v8/Class.h +++ b/native/cocos/bindings/jswrapper/v8/Class.h @@ -151,6 +151,7 @@ private: friend class ScriptEngine; friend class Object; + friend class JSBPersistentHandleVisitor; }; } // namespace se diff --git a/native/cocos/bindings/jswrapper/v8/Object.cpp b/native/cocos/bindings/jswrapper/v8/Object.cpp index 7c89467805..a88b185eec 100644 --- a/native/cocos/bindings/jswrapper/v8/Object.cpp +++ b/native/cocos/bindings/jswrapper/v8/Object.cpp @@ -51,6 +51,57 @@ uint32_t nativeObjectId = 0; #endif } // namespace +class JSBPersistentHandleVisitor : public v8::PersistentHandleVisitor { +public: + JSBPersistentHandleVisitor() = default; + + void VisitPersistentHandle(v8::Persistent *value, uint16_t classId) override { + if (value == nullptr || classId != ObjectWrap::MAGIC_CLASS_ID_JSB) { + return; + } + + auto &persistObj = v8::Persistent::Cast(*value); + const int fieldCount = v8::Object::InternalFieldCount(persistObj); + if (fieldCount != 1) { + return; + } + + void *ptr = v8::Object::GetAlignedPointerFromInternalField(persistObj, 0); + if (ptr == nullptr) { + return; + } + + auto *obj = reinterpret_cast(ptr); + auto *nativeObj = obj->getPrivateData(); + if (nativeObj == nullptr) { + // Not a JSB binding object + return; + } + + // Remove mapping + auto iter = se::NativePtrToObjectMap::find(nativeObj); + if (iter != se::NativePtrToObjectMap::end()) { + se::NativePtrToObjectMap::erase(iter); + } + + // Invoke finalize callback + if (obj->_finalizeCb != nullptr) { + obj->_finalizeCb(obj); + } else { + if (obj->_getClass() != nullptr) { + if (obj->_getClass()->_finalizeFunc != nullptr) { + obj->_getClass()->_finalizeFunc(obj); + } + } + } + + if (obj->getRefCount() != 1) { + CC_LOG_WARNING("se::Object (%p) reference count (%u) is not 1", obj, obj->getRefCount()); + } + obj->decRef(); + } +}; + Object::Object() { //NOLINT #if JSB_TRACK_OBJECT_CREATION _objectCreationStackFrame = se::ScriptEngine::getInstance()->getCurrentStackTrace(); @@ -75,8 +126,8 @@ void Object::nativeObjectFinalizeHook(Object *seObj) { return; } - if (seObj->_clearMappingInFinalizer && seObj->_privateObject != nullptr) { - void *nativeObj = seObj->_privateObject->getRaw(); + if (seObj->_clearMappingInFinalizer && seObj->_privateData != nullptr) { + void *nativeObj = seObj->_privateData; auto iter = NativePtrToObjectMap::find(nativeObj); if (iter != NativePtrToObjectMap::end()) { NativePtrToObjectMap::erase(iter); @@ -90,6 +141,7 @@ void Object::nativeObjectFinalizeHook(Object *seObj) { seObj->_getClass()->_finalizeFunc(seObj); } } + seObj->decRef(); } @@ -103,45 +155,16 @@ void Object::setup() { } void Object::cleanup() { - void *nativeObj = nullptr; - Object *obj = nullptr; - Class *cls = nullptr; - - auto iter = NativePtrToObjectMap::begin(); - while (iter != NativePtrToObjectMap::end()) { - nativeObj = iter->first; - obj = iter->second; - - if (obj->_finalizeCb != nullptr) { - obj->_finalizeCb(obj); - } else { - if (obj->_getClass() != nullptr) { - if (obj->_getClass()->_finalizeFunc != nullptr) { - obj->_getClass()->_finalizeFunc(obj); - } - } - } - - obj->decRef(); - iter = NativePtrToObjectMap::erase(iter); - } - + JSBPersistentHandleVisitor jsbVisitor; + __isolate->VisitHandlesWithClassIds(&jsbVisitor); SE_ASSERT(NativePtrToObjectMap::size() == 0, "NativePtrToObjectMap should be empty!"); if (__objectMap) { - ccstd::vector toReleaseObjects; for (const auto &e : *__objectMap) { - obj = e.first; - cls = obj->_getClass(); + auto *obj = e.first; obj->_obj.persistent().Reset(); + // NOTE: Set _rootCount to 0 to avoid invoking _obj.unref in Object's destructor which may cause crash. obj->_rootCount = 0; - - if (cls != nullptr && cls->_name == "__PrivateData") { - toReleaseObjects.push_back(obj); - } - } - for (auto *e : toReleaseObjects) { - e->decRef(); } } @@ -578,7 +601,7 @@ void Object::setPrivateObject(PrivateObjectBase *data) { if (data != nullptr) { _privateData = data->getRaw(); - NativePtrToObjectMap::emplace(data->getRaw(), this); + NativePtrToObjectMap::emplace(_privateData, this); } else { _privateData = nullptr; } @@ -591,11 +614,12 @@ PrivateObjectBase *Object::getPrivateObject() const { void Object::clearPrivateData(bool clearMapping) { if (_privateObject != nullptr) { if (clearMapping) { - NativePtrToObjectMap::erase(_privateObject->getRaw()); + NativePtrToObjectMap::erase(_privateData); } internal::clearPrivate(__isolate, _obj); delete _privateObject; _privateObject = nullptr; + _privateData = nullptr; } } diff --git a/native/cocos/bindings/jswrapper/v8/Object.h b/native/cocos/bindings/jswrapper/v8/Object.h index defeb47d90..2b7074117e 100644 --- a/native/cocos/bindings/jswrapper/v8/Object.h +++ b/native/cocos/bindings/jswrapper/v8/Object.h @@ -466,7 +466,9 @@ private: #if JSB_TRACK_OBJECT_CREATION ccstd::string _objectCreationStackFrame; #endif + friend class ScriptEngine; + friend class JSBPersistentHandleVisitor; }; // NOLINTNEXTLINE extern std::unique_ptr> __objectMap; // Currently, the value `void*` is always nullptr diff --git a/native/cocos/bindings/jswrapper/v8/ObjectWrap.cpp b/native/cocos/bindings/jswrapper/v8/ObjectWrap.cpp index 8bba496f30..39f41c6676 100644 --- a/native/cocos/bindings/jswrapper/v8/ObjectWrap.cpp +++ b/native/cocos/bindings/jswrapper/v8/ObjectWrap.cpp @@ -85,6 +85,11 @@ void ObjectWrap::wrap(void *nativeObj, uint32_t fieldIndex) { CC_ASSERT(handle()->InternalFieldCount() > 0); CC_ASSERT(fieldIndex >= 0 && fieldIndex < 1); handle()->SetAlignedPointerInInternalField(static_cast(fieldIndex), nativeObj); + if (nativeObj) { + persistent().SetWrapperClassId(MAGIC_CLASS_ID_JSB); + } else { + persistent().SetWrapperClassId(0); + } } v8::Local ObjectWrap::handle() { diff --git a/native/cocos/bindings/jswrapper/v8/ObjectWrap.h b/native/cocos/bindings/jswrapper/v8/ObjectWrap.h index ce19a12373..c621bfff90 100644 --- a/native/cocos/bindings/jswrapper/v8/ObjectWrap.h +++ b/native/cocos/bindings/jswrapper/v8/ObjectWrap.h @@ -57,6 +57,8 @@ namespace se { class ObjectWrap { public: + static constexpr uint16_t MAGIC_CLASS_ID_JSB = 0x1234; + ObjectWrap(); ~ObjectWrap(); diff --git a/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp b/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp index 494de05183..d235faf34c 100644 --- a/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp +++ b/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp @@ -585,8 +585,12 @@ bool ScriptEngine::init(v8::Isolate *isolate) { _context.Reset(_isolate, context); _context.Get(isolate)->Enter(); } else { + static v8::ArrayBuffer::Allocator *arrayBufferAllocator{nullptr}; + if (arrayBufferAllocator == nullptr) { + arrayBufferAllocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); + } v8::Isolate::CreateParams createParams; - createParams.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); + createParams.array_buffer_allocator = arrayBufferAllocator; _isolate = v8::Isolate::New(createParams); v8::HandleScope hs(_isolate); _context.Reset(_isolate, v8::Context::New(_isolate)); @@ -659,6 +663,11 @@ void ScriptEngine::cleanup() { for (const auto &hook : _afterCleanupHookArray) { hook(); } + + // Cleanup all hooks + _beforeInitHookArray.clear(); + _afterInitHookArray.clear(); + _beforeCleanupHookArray.clear(); _afterCleanupHookArray.clear(); _isInCleanup = false; diff --git a/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp b/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp index cdb2031fb1..fe3bba3148 100644 --- a/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp +++ b/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp @@ -575,7 +575,7 @@ static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { //NOLINT(reada jargs[i].l = nullptr; } else { ccstd::string str; - sevalue_to_native(args[index], &str); + seval_to_std_string(args[index], &str); jargs[i].l = call.getEnv()->NewStringUTF(str.c_str()); toReleaseObjects.push_back(jargs[i].l); } diff --git a/native/cocos/bindings/manual/jsb_assets_manual.cpp b/native/cocos/bindings/manual/jsb_assets_manual.cpp index ed94996817..4994d066f4 100644 --- a/native/cocos/bindings/manual/jsb_assets_manual.cpp +++ b/native/cocos/bindings/manual/jsb_assets_manual.cpp @@ -47,8 +47,11 @@ static bool js_assets_ImageAsset_setData(se::State &s) // NOLINT(readability-ide if (args[0].isObject()) { if (args[0].toObject()->isTypedArray()) { args[0].toObject()->getTypedArrayData(&data, nullptr); + } else if (args[0].toObject()->isArrayBuffer()) { + args[0].toObject()->getArrayBufferData(&data, nullptr); } else { auto *dataHolder = static_cast(args[0].toObject()->getPrivateData()); + CC_ASSERT(dataHolder != nullptr); data = dataHolder->getData(); } } else { diff --git a/native/cocos/bindings/manual/jsb_cocos_manual.cpp b/native/cocos/bindings/manual/jsb_cocos_manual.cpp index 8effce1bfa..4560ee9d7c 100644 --- a/native/cocos/bindings/manual/jsb_cocos_manual.cpp +++ b/native/cocos/bindings/manual/jsb_cocos_manual.cpp @@ -375,7 +375,7 @@ static bool js_CanvasRenderingContext2D_setCanvasBufferUpdatedCallback(se::State CC_UNUSED bool ok = true; se::ValueArray args; args.resize(1); - ok &= Data_to_seval(larg0, &args[0]); + ok &= Data_to_TypedArray(larg0, &args[0]); se::Value rval; se::Object *funcObj = jsFunc.toObject(); bool succeed = funcObj->call(args, thisObj, &rval); @@ -663,6 +663,11 @@ static bool js_se_setExceptionCallback(se::State &s) { // NOLINT(readability-ide jsArgs[2] = se::Value(stack); objFunc->call(jsArgs, nullptr); }); + + se::ScriptEngine::getInstance()->addBeforeCleanupHook([objFunc] { + objFunc->decRef(); + }); + return true; } SE_BIND_FUNC(js_se_setExceptionCallback) // NOLINT(readability-identifier-naming) diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index 8e68e3abe6..47357671d9 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -33,6 +33,7 @@ #include "base/Ptr.h" #include "base/RefCounted.h" #include "base/std/any.h" +#include "base/std/container/map.h" #include "base/std/container/vector.h" #include "base/std/optional.h" #include "base/std/variant.h" @@ -673,6 +674,9 @@ bool sevalue_to_native(const se::Value &from, ccstd::optional *to, se::Object /// ccstd::unordered_map template bool sevalue_to_native(const se::Value &from, ccstd::unordered_map *to, se::Object *ctx); //NOLINT(readability-identifier-naming) +/// ccstd::map +template +bool sevalue_to_native(const se::Value &from, ccstd::map *to, se::Object *ctx); //NOLINT(readability-identifier-naming) // std::tuple template bool sevalue_to_native(const se::Value &from, std::tuple *to, se::Object *ctx); // NOLINT(readability-identifier-naming) @@ -974,7 +978,6 @@ inline bool sevalue_to_native(const se::Value &from, HolderType CC_ASSERT(false); // default construtor not provided } return sevalue_to_native(from, holder->ptr, ctx); - } else if CC_CONSTEXPR (is_jsb_object_v) { void *ptr = from.toObject()->getPrivateData(); if (ptr) { @@ -982,7 +985,6 @@ inline bool sevalue_to_native(const se::Value &from, HolderType return true; } return sevalue_to_native(from, &(holder->data), ctx); - } else { return sevalue_to_native(from, &(holder->data), ctx); } @@ -1156,6 +1158,23 @@ bool sevalue_to_native(const se::Value &from, ccstd::unordered_map +bool sevalue_to_native(const se::Value &from, ccstd::map *to, se::Object *ctx) { //NOLINT + se::Object *jsmap = from.toObject(); + ccstd::vector allKeys; + jsmap->getAllKeys(&allKeys); + bool ret = true; + se::Value property; + for (auto &it : allKeys) { + if (jsmap->getProperty(it.c_str(), &property)) { + auto &output = (*to)[it]; + ret &= sevalue_to_native(property, &output, jsmap); + } + } + return true; +} + ///////////////// ccstd::optional template bool sevalue_to_native(const se::Value &from, ccstd::optional *to, se::Object *ctx) { //NOLINT @@ -1286,6 +1305,9 @@ inline bool nativevalue_to_se(const ccstd::vector &from, se::Value &to, se::O template inline bool nativevalue_to_se(const ccstd::unordered_map &from, se::Value &to, se::Object *ctx); // NOLINT +template +inline bool nativevalue_to_se(const ccstd::map &from, se::Value &to, se::Object *ctx); // NOLINT + template inline bool nativevalue_to_se(const cc::TypedArrayTemp &typedArray, se::Value &to, se::Object *ctx); // NOLINT @@ -1357,6 +1379,18 @@ inline bool nativevalue_to_se(const ccstd::unordered_map &from, se::Value to.setObject(ret); return true; } +template +inline bool nativevalue_to_se(const ccstd::map &from, se::Value &to, se::Object *ctx) { // NOLINT + se::HandleObject ret{se::Object::createPlainObject()}; + se::Value value; + bool ok = true; + for (auto &it : from) { + ok &= nativevalue_to_se(it.second, value, ctx); + cc_tmp_set_property(ret, it.first, value); + } + to.setObject(ret); + return true; +} template inline bool nativevalue_to_se(const ccstd::array &from, se::Value &to, se::Object *ctx) { // NOLINT(readability-identifier-naming) @@ -1580,3 +1614,6 @@ bool nativevalue_to_se(const std::reference_wrapper ref, se::Value &to, se::O #if __clang__ && defined(HAS_PUSH_DIAGNOSTI) #pragma clang diagnostic pop #endif + +// Remove this in near future. +#include "jsb_conversions_deprecated.h" diff --git a/native/cocos/bindings/manual/jsb_conversions_deprecated.h b/native/cocos/bindings/manual/jsb_conversions_deprecated.h new file mode 100644 index 0000000000..7c4d5cb69f --- /dev/null +++ b/native/cocos/bindings/manual/jsb_conversions_deprecated.h @@ -0,0 +1,105 @@ +/**************************************************************************** + 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. +****************************************************************************/ + +// deprecated conversion functions + +// native value -> se value +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool int8_to_seval(int8_t v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool uint8_to_seval(uint8_t v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool int32_to_seval(int32_t v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool uint32_to_seval(uint32_t v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool int16_to_seval(uint16_t v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool uint16_to_seval(uint16_t v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool boolean_to_seval(bool v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool float_to_seval(float v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool double_to_seval(double v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool long_to_seval(long v, se::Value *ret) { // NOLINT(readability-identifier-naming, google-runtime-int) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool ulong_to_seval(unsigned long v, se::Value *ret) { // NOLINT(readability-identifier-naming, google-runtime-int) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool longlong_to_seval(long long v, se::Value *ret) { // NOLINT(readability-identifier-naming, google-runtime-int) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool uintptr_t_to_seval(uintptr_t v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool size_to_seval(size_t v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool std_string_to_seval(const std::string &v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} + +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool std_vector_string_to_seval(const std::vector &v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool std_vector_int_to_seval(const std::vector &v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool std_vector_uint16_to_seval(const std::vector &v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool std_vector_float_to_seval(const std::vector &v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} +CC_DEPRECATED(3.6, "use nativevalue_to_se instead") +inline bool std_map_string_string_to_seval(const std::map &v, se::Value *ret) { // NOLINT(readability-identifier-naming) + return nativevalue_to_se(v, *ret, nullptr); +} diff --git a/native/cocos/bindings/manual/jsb_conversions_spec.cpp b/native/cocos/bindings/manual/jsb_conversions_spec.cpp index 77cede41c9..5657efc43b 100644 --- a/native/cocos/bindings/manual/jsb_conversions_spec.cpp +++ b/native/cocos/bindings/manual/jsb_conversions_spec.cpp @@ -20,6 +20,7 @@ ****************************************************************************/ #include +#include "base/Value.h" #include "cocos/base/DeferredReleasePool.h" #include "cocos/base/RefMap.h" #include "cocos/base/RefVector.h" @@ -101,33 +102,6 @@ static bool isNumberString(const ccstd::string &str) { return true; } -namespace { - -template -bool std_vector_T_to_seval(const ccstd::vector &v, se::Value *ret) { // NOLINT(readability-identifier-naming) - CC_ASSERT(ret != nullptr); - se::HandleObject obj(se::Object::createArrayObject(v.size())); - bool ok = true; - - uint32_t i = 0; - for (const auto &value : v) { - if (!obj->setArrayElement(i, se::Value(value))) { - ok = false; - ret->setUndefined(); - break; - } - ++i; - } - - if (ok) { - ret->setObject(obj); - } - - return ok; -} - -} // namespace - namespace { enum class DataType { INT, @@ -144,63 +118,18 @@ enum class MathType { RECT, COLOR, }; -bool uintptr_t_to_seval(uintptr_t v, se::Value *ret) { // NOLINT(readability-identifier-naming) - ret->setDouble(v); - return true; -} - -bool size_to_seval(size_t v, se::Value *ret) { // NOLINT(readability-identifier-naming) - ret->setSize(v); - return true; -} +} // namespace bool Vec2_to_seval(const cc::Vec2 &v, se::Value *ret) { // NOLINT(readability-identifier-naming) - CC_ASSERT(ret != nullptr); - se::HandleObject obj(se::Object::createPlainObject()); - obj->setProperty("x", se::Value(v.x)); - obj->setProperty("y", se::Value(v.y)); - obj->setProperty("type", se::Value(static_cast(MathType::VEC2))); - ret->setObject(obj); - - return true; + return ret ? nativevalue_to_se(v, *ret, nullptr) : false; } bool Vec3_to_seval(const cc::Vec3 &v, se::Value *ret) { // NOLINT(readability-identifier-naming) - CC_ASSERT(ret != nullptr); - se::HandleObject obj(se::Object::createPlainObject()); - obj->setProperty("x", se::Value(v.x)); - obj->setProperty("y", se::Value(v.y)); - obj->setProperty("z", se::Value(v.z)); - obj->setProperty("type", se::Value(static_cast(MathType::VEC3))); - ret->setObject(obj); - - return true; + return ret ? nativevalue_to_se(v, *ret, nullptr) : false; } bool Vec4_to_seval(const cc::Vec4 &v, se::Value *ret) { // NOLINT(readability-identifier-naming) - CC_ASSERT(ret != nullptr); - se::HandleObject obj(se::Object::createPlainObject()); - obj->setProperty("x", se::Value(v.x)); - obj->setProperty("y", se::Value(v.y)); - obj->setProperty("z", se::Value(v.z)); - obj->setProperty("w", se::Value(v.w)); - obj->setProperty("type", se::Value(static_cast(MathType::VEC4))); - ret->setObject(obj); - - return true; -} - -bool Quaternion_to_seval(const cc::Quaternion &v, se::Value *ret) { // NOLINT(readability-identifier-naming) - CC_ASSERT(ret != nullptr); - se::HandleObject obj(se::Object::createPlainObject()); - obj->setProperty("x", se::Value(v.x)); - obj->setProperty("y", se::Value(v.y)); - obj->setProperty("z", se::Value(v.z)); - obj->setProperty("w", se::Value(v.w)); - obj->setProperty("type", se::Value(static_cast(MathType::QUATERNION))); - ret->setObject(obj); - - return true; + return ret ? nativevalue_to_se(v, *ret, nullptr) : false; } bool Mat4_to_seval(const cc::Mat4 &v, se::Value *ret) { // NOLINT(readability-identifier-naming) @@ -217,128 +146,46 @@ bool Mat4_to_seval(const cc::Mat4 &v, se::Value *ret) { // NOLINT(readability-id } bool Size_to_seval(const cc::Size &v, se::Value *ret) { // NOLINT(readability-identifier-naming) - CC_ASSERT(ret != nullptr); - se::HandleObject obj(se::Object::createPlainObject()); - obj->setProperty("width", se::Value(v.width)); - obj->setProperty("height", se::Value(v.height)); - obj->setProperty("type", se::Value(static_cast(MathType::SIZE))); - ret->setObject(obj); - return true; + return ret ? nativevalue_to_se(v, *ret, nullptr) : false; } bool Rect_to_seval(const cc::Rect &v, se::Value *ret) { // NOLINT(readability-identifier-naming) - CC_ASSERT(ret != nullptr); - se::HandleObject obj(se::Object::createPlainObject()); - obj->setProperty("x", se::Value(v.x)); - obj->setProperty("y", se::Value(v.y)); - obj->setProperty("width", se::Value(v.width)); - obj->setProperty("height", se::Value(v.height)); - obj->setProperty("type", se::Value(static_cast(MathType::RECT))); - ret->setObject(obj); - return true; + return ret ? nativevalue_to_se(v, *ret, nullptr) : false; } - -void toVec2(void *data, DataType type, se::Value *ret) { - auto *intptr = static_cast(data); - auto *floatptr = static_cast(data); - cc::Vec2 vec2; - if (DataType::INT == type) { - vec2.x = static_cast(intptr[0]); - vec2.y = static_cast(intptr[1]); - } else { - vec2.x = *floatptr; - vec2.y = *(floatptr + 1); - } - - Vec2_to_seval(vec2, ret); -} - -void toVec3(void *data, DataType type, se::Value *ret) { - auto *intptr = static_cast(data); - auto *floatptr = static_cast(data); - cc::Vec3 vec3; - if (DataType::INT == type) { - vec3.x = static_cast(intptr[0]); - vec3.y = static_cast(intptr[1]); - vec3.z = static_cast(intptr[2]); - } else { - vec3.x = floatptr[0]; - vec3.y = floatptr[1]; - vec3.z = floatptr[2]; - } - - Vec3_to_seval(vec3, ret); -} - -void toVec4(void *data, DataType type, se::Value *ret) { - auto *intptr = static_cast(data); - auto *floatptr = static_cast(data); - cc::Vec4 vec4; - if (DataType::INT == type) { - vec4.x = static_cast(intptr[0]); - vec4.y = static_cast(intptr[1]); - vec4.z = static_cast(intptr[2]); - vec4.w = static_cast(intptr[3]); - } else { - vec4.x = *floatptr; - vec4.y = *(floatptr + 1); - vec4.z = *(floatptr + 2); - vec4.w = *(floatptr + 3); - } - - Vec4_to_seval(vec4, ret); -} - -void toMat(const float *data, int num, se::Value *ret) { - se::HandleObject obj(se::Object::createPlainObject()); - - char propName[4] = {0}; - for (int i = 0; i < num; ++i) { - if (i < 10) { - snprintf(propName, 3, "m0%d", i); - } - - else { - snprintf(propName, 3, "m%d", i); - } - - obj->setProperty(propName, se::Value(*(data + i))); - } - ret->setObject(obj); -} -} // namespace - //////////////////////////////////////////////////////////////////////////// /////////////////sevalue to native////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // NOLINTNEXTLINE(readability-identifier-naming) bool seval_to_ccvalue(const se::Value &v, cc::Value *ret) { // NOLINT - CC_ASSERT(ret != nullptr); + return sevalue_to_native(v, ret, nullptr); +} +bool sevalue_to_native(const se::Value &from, cc::Value *to, se::Object * /*ctx*/) { // NOLINT + CC_ASSERT(to != nullptr); bool ok = true; - if (v.isObject()) { - se::Object *jsobj = v.toObject(); + if (from.isObject()) { + se::Object *jsobj = from.toObject(); if (!jsobj->isArray()) { // It's a normal js object. cc::ValueMap dictVal; - ok = seval_to_ccvaluemap(v, &dictVal); - SE_PRECONDITION3(ok, false, *ret = cc::Value::VALUE_NULL); - *ret = cc::Value(dictVal); + ok = sevalue_to_native(from, &dictVal, nullptr); + SE_PRECONDITION3(ok, false, *to = cc::Value::VALUE_NULL); + *to = cc::Value(dictVal); } else { // It's a js array object. cc::ValueVector arrVal; - ok = seval_to_ccvaluevector(v, &arrVal); - SE_PRECONDITION3(ok, false, *ret = cc::Value::VALUE_NULL); - *ret = cc::Value(arrVal); + ok = sevalue_to_native(from, &arrVal, nullptr); + SE_PRECONDITION3(ok, false, *to = cc::Value::VALUE_NULL); + *to = cc::Value(arrVal); } - } else if (v.isString()) { - *ret = v.toString(); - } else if (v.isNumber()) { - *ret = v.toDouble(); - } else if (v.isBoolean()) { - *ret = v.toBoolean(); - } else if (v.isNullOrUndefined()) { - *ret = cc::Value::VALUE_NULL; + } else if (from.isString()) { + *to = from.toString(); + } else if (from.isNumber()) { + *to = from.toDouble(); + } else if (from.isBoolean()) { + *to = from.toBoolean(); + } else if (from.isNullOrUndefined()) { + *to = cc::Value::VALUE_NULL; } else { SE_PRECONDITION2(false, false, "type not supported!"); } @@ -348,30 +195,34 @@ bool seval_to_ccvalue(const se::Value &v, cc::Value *ret) { // NOLINT // NOLINTNEXTLINE(readability-identifier-naming) bool seval_to_ccvaluemap(const se::Value &v, cc::ValueMap *ret) { // NOLINT - CC_ASSERT(ret != nullptr); + return sevalue_to_native(v, ret, nullptr); +} - if (v.isNullOrUndefined()) { - ret->clear(); +bool sevalue_to_native(const se::Value &from, cc::ValueMap *to, se::Object * /*ctx*/) { // NOLINT + CC_ASSERT(to != nullptr); + + if (from.isNullOrUndefined()) { + to->clear(); return true; } - SE_PRECONDITION3(v.isObject(), false, ret->clear()); - SE_PRECONDITION3(!v.isNullOrUndefined(), false, ret->clear()); + SE_PRECONDITION3(from.isObject(), false, to->clear()); + SE_PRECONDITION3(!from.isNullOrUndefined(), false, to->clear()); - se::Object *obj = v.toObject(); + se::Object *obj = from.toObject(); - cc::ValueMap &dict = *ret; + cc::ValueMap &dict = *to; ccstd::vector allKeys; - SE_PRECONDITION3(obj->getAllKeys(&allKeys), false, ret->clear()); + SE_PRECONDITION3(obj->getAllKeys(&allKeys), false, to->clear()); bool ok = false; se::Value value; cc::Value ccvalue; for (const auto &key : allKeys) { - SE_PRECONDITION3(obj->getProperty(key.c_str(), &value), false, ret->clear()); - ok = seval_to_ccvalue(value, &ccvalue); - SE_PRECONDITION3(ok, false, ret->clear()); + SE_PRECONDITION3(obj->getProperty(key.c_str(), &value), false, to->clear()); + ok = sevalue_to_native(value, &ccvalue, nullptr); + SE_PRECONDITION3(ok, false, to->clear()); dict.emplace(key, ccvalue); } @@ -459,6 +310,9 @@ bool sevals_variadic_to_ccvaluevector(const se::ValueArray &args, cc::ValueVecto // NOLINTNEXTLINE(readability-identifier-naming) bool seval_to_Data(const se::Value &v, cc::Data *ret) { + return sevalue_to_native(v, ret, nullptr); +} +bool sevalue_to_native(const se::Value &v, cc::Data *ret, se::Object * /*ctx*/) { // NOLINT CC_ASSERT(ret != nullptr); SE_PRECONDITION2(v.isObject() && (v.toObject()->isTypedArray() || v.toObject()->isArrayBuffer()), false, "Convert parameter to Data failed!"); uint8_t *ptr = nullptr; @@ -475,7 +329,6 @@ bool seval_to_Data(const se::Value &v, cc::Data *ret) { } else { ret->clear(); } - return ok; } @@ -504,7 +357,7 @@ bool seval_to_DownloaderHints(const se::Value &v, cc::network::DownloaderHints * } // NOLINTNEXTLINE(readability-identifier-naming) -bool sevalue_to_native(const se::Value &from, cc::Vec4 *to, se::Object * /*unused*/) { +bool sevalue_to_native(const se::Value &from, cc::Vec4 *to, se::Object * /*ctx*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Vec4 failed!"); se::Object *obj = from.toObject(); se::Value tmp; @@ -516,7 +369,7 @@ bool sevalue_to_native(const se::Value &from, cc::Vec4 *to, se::Object * /*unuse } // NOLINTNEXTLINE(readability-identifier-naming) -bool sevalue_to_native(const se::Value &from, cc::gfx::Rect *to, se::Object * /*unused*/) { +bool sevalue_to_native(const se::Value &from, cc::gfx::Rect *to, se::Object * /*ctx*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Rect failed!"); se::Object *obj = from.toObject(); se::Value tmp; @@ -529,7 +382,7 @@ bool sevalue_to_native(const se::Value &from, cc::gfx::Rect *to, se::Object * /* } // NOLINTNEXTLINE(readability-identifier-naming) -bool sevalue_to_native(const se::Value &from, cc::Rect *to, se::Object * /*unused*/) { +bool sevalue_to_native(const se::Value &from, cc::Rect *to, se::Object * /*ctx*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Rect failed!"); se::Object *obj = from.toObject(); se::Value tmp; @@ -542,7 +395,7 @@ bool sevalue_to_native(const se::Value &from, cc::Rect *to, se::Object * /*unuse } // NOLINTNEXTLINE(readability-identifier-naming) -bool sevalue_to_native(const se::Value &from, cc::Mat3 *to, se::Object * /*unused*/) { +bool sevalue_to_native(const se::Value &from, cc::Mat3 *to, se::Object * /*ctx*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Matrix3 failed!"); se::Object *obj = from.toObject(); @@ -1094,6 +947,8 @@ bool sevalue_to_native(const se::Value &from, cc::ArrayBuffer *to, se::Object * to->setJSArrayBuffer(from.toObject()); return true; } + +// NOLINTNEXTLINE(readability-identifier-naming) bool sevalue_to_native(const se::Value &from, cc::ArrayBuffer **to, se::Object * /*ctx*/) { CC_ASSERT(from.isObject()); auto *obj = from.toObject(); @@ -1316,74 +1171,12 @@ bool seval_to_Map_string_key(const se::Value &v, cc::RefMapsetNull(); - break; - case cc::Value::Type::UNSIGNED: - ret->setUint32(v.asUnsignedInt()); - break; - case cc::Value::Type::BOOLEAN: - ret->setBoolean(v.asBool()); - break; - case cc::Value::Type::FLOAT: - case cc::Value::Type::DOUBLE: - ret->setDouble(v.asDouble()); - break; - case cc::Value::Type::INTEGER: - ret->setInt32(v.asInt()); - break; - case cc::Value::Type::STRING: - ret->setString(v.asString()); - break; - case cc::Value::Type::VECTOR: - ok = ccvaluevector_to_seval(v.asValueVector(), ret); - break; - case cc::Value::Type::MAP: - ok = ccvaluemap_to_seval(v.asValueMap(), ret); - break; - case cc::Value::Type::INT_KEY_MAP: - ok = ccvaluemapintkey_to_seval(v.asIntKeyMap(), ret); - break; - default: - SE_LOGE("Could not the way to convert cc::Value::Type (%d) type!", (int)v.getType()); - ok = false; - break; - } - - return ok; + return ret ? nativevalue_to_se(v, *ret, nullptr) : false; } // NOLINTNEXTLINE(readability-identifier-naming) bool ccvaluemap_to_seval(const cc::ValueMap &v, se::Value *ret) { // NOLINT - CC_ASSERT(ret != nullptr); - - se::HandleObject obj(se::Object::createPlainObject()); - bool ok = true; - for (const auto &e : v) { - const ccstd::string &key = e.first; - const cc::Value &value = e.second; - - if (key.empty()) { - continue; - } - - se::Value tmp; - if (!ccvalue_to_seval(value, &tmp)) { - ok = false; - ret->setUndefined(); - break; - } - - obj->setProperty(key.c_str(), tmp); - } - if (ok) { - ret->setObject(obj); - } - - return ok; + return ret ? nativevalue_to_se(v, *ret, nullptr) : false; } // NOLINTNEXTLINE(readability-identifier-naming) @@ -1445,20 +1238,17 @@ bool ccvaluevector_to_seval(const cc::ValueVector &v, se::Value *ret) { // NOLIN // NOLINTNEXTLINE(readability-identifier-naming) bool ManifestAsset_to_seval(const cc::extension::ManifestAsset &v, se::Value *ret) { - CC_ASSERT(ret != nullptr); - se::HandleObject obj(se::Object::createPlainObject()); - obj->setProperty("md5", se::Value(v.md5)); - obj->setProperty("path", se::Value(v.path)); - obj->setProperty("compressed", se::Value(v.compressed)); - obj->setProperty("size", se::Value(v.size)); - obj->setProperty("downloadState", se::Value(v.downloadState)); - ret->setObject(obj); - - return true; + return ret ? nativevalue_to_se(v, *ret, nullptr) : false; } // NOLINTNEXTLINE(readability-identifier-naming) bool Data_to_seval(const cc::Data &v, se::Value *ret) { + // NOTICE: should remove this function, kept for backward compatibility + return Data_to_TypedArray(v, ret); +} + +bool Data_to_TypedArray(const cc::Data &v, se::Value *ret) { // NOLINT(readability-identifier-naming) + // NOTICE: should remove this function, kept for backward compatibility CC_ASSERT(ret != nullptr); if (v.isNull()) { ret->setNull(); @@ -1471,16 +1261,18 @@ bool Data_to_seval(const cc::Data &v, se::Value *ret) { // NOLINTNEXTLINE(readability-identifier-naming) bool DownloadTask_to_seval(const cc::network::DownloadTask &v, se::Value *ret) { - CC_ASSERT(ret != nullptr); + return ret ? nativevalue_to_se(v, *ret, nullptr) : false; +} +bool nativevalue_to_se(const cc::network::DownloadTask &from, se::Value &to, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) se::HandleObject obj(se::Object::createPlainObject()); - obj->setProperty("identifier", se::Value(v.identifier)); - obj->setProperty("requestURL", se::Value(v.requestURL)); - obj->setProperty("storagePath", se::Value(v.storagePath)); - ret->setObject(obj); - + obj->setProperty("identifier", se::Value(from.identifier)); + obj->setProperty("requestURL", se::Value(from.requestURL)); + obj->setProperty("storagePath", se::Value(from.storagePath)); + to.setObject(obj); return true; } + #if CC_USE_SPINE // NOLINTNEXTLINE(readability-identifier-naming) bool nativevalue_to_se(const spine::String &obj, se::Value &val, se::Object * /*unused*/) { @@ -1514,54 +1306,156 @@ bool nativevalue_to_se(const spine::Vector &v, se::Value &ret, se // NOLINTNEXTLINE(readability-identifier-naming) bool nativevalue_to_se(const cc::Data &from, se::Value &to, se::Object * /*unused*/) { - se::Object *buffer = se::Object::createArrayBufferObject(from.getBytes(), from.getSize()); + se::HandleObject buffer{se::Object::createArrayBufferObject(from.getBytes(), from.getSize())}; to.setObject(buffer); return true; } -// NOLINTNEXTLINE(readability-identifier-naming) +// NOLINTNEXTLINE bool nativevalue_to_se(const cc::Value &from, se::Value &to, se::Object * /*unused*/) { - return ccvalue_to_seval(from, &to); + bool ok = true; + switch (from.getType()) { + case cc::Value::Type::NONE: + to.setNull(); + break; + case cc::Value::Type::UNSIGNED: + to.setUint32(from.asUnsignedInt()); + break; + case cc::Value::Type::BOOLEAN: + to.setBoolean(from.asBool()); + break; + case cc::Value::Type::FLOAT: + case cc::Value::Type::DOUBLE: + to.setDouble(from.asDouble()); + break; + case cc::Value::Type::INTEGER: + to.setInt32(from.asInt()); + break; + case cc::Value::Type::STRING: + to.setString(from.asString()); + break; + case cc::Value::Type::VECTOR: + ok = nativevalue_to_se(from.asValueVector(), to, nullptr); + break; + case cc::Value::Type::MAP: + ok = nativevalue_to_se(from.asValueMap(), to, nullptr); + break; + case cc::Value::Type::INT_KEY_MAP: + ok = nativevalue_to_se(from.asIntKeyMap(), to, nullptr); + break; + default: + SE_LOGE("Could not the way to convert cc::Value::Type (%d) type!", (int)from.getType()); + ok = false; + break; + } + return ok; } -// NOLINTNEXTLINE(readability-identifier-naming) +// NOLINTNEXTLINE bool nativevalue_to_se(const ccstd::unordered_map &from, se::Value &to, se::Object * /*unused*/) { - return ccvaluemap_to_seval(from, &to); + se::HandleObject obj(se::Object::createPlainObject()); + bool ok = true; + for (const auto &e : from) { + const ccstd::string &key = e.first; + const cc::Value &value = e.second; + + if (key.empty()) { + continue; + } + + se::Value tmp; + if (!nativevalue_to_se(value, tmp, nullptr)) { + ok = false; + to.setUndefined(); + break; + } + + obj->setProperty(key.c_str(), tmp); + } + if (ok) { + to.setObject(obj); + } + + return ok; } // NOLINTNEXTLINE(readability-identifier-naming) bool nativevalue_to_se(const cc::Vec4 &from, se::Value &to, se::Object * /*unused*/) { - return Vec4_to_seval(from, &to); + se::HandleObject obj(se::Object::createPlainObject()); + obj->setProperty("x", se::Value(from.x)); + obj->setProperty("y", se::Value(from.y)); + obj->setProperty("z", se::Value(from.z)); + obj->setProperty("w", se::Value(from.w)); + obj->setProperty("type", se::Value(static_cast(MathType::VEC4))); + to.setObject(obj); + return true; } // NOLINTNEXTLINE(readability-identifier-naming) bool nativevalue_to_se(const cc::Vec2 &from, se::Value &to, se::Object * /*unused*/) { - return Vec2_to_seval(from, &to); + se::HandleObject obj(se::Object::createPlainObject()); + obj->setProperty("x", se::Value(from.x)); + obj->setProperty("y", se::Value(from.y)); + obj->setProperty("type", se::Value(static_cast(MathType::VEC2))); + to.setObject(obj); + return true; } // NOLINTNEXTLINE(readability-identifier-naming) bool nativevalue_to_se(const cc::Vec3 &from, se::Value &to, se::Object * /*unused*/) { - return Vec3_to_seval(from, &to); + se::HandleObject obj(se::Object::createPlainObject()); + obj->setProperty("x", se::Value(from.x)); + obj->setProperty("y", se::Value(from.y)); + obj->setProperty("z", se::Value(from.z)); + obj->setProperty("type", se::Value(static_cast(MathType::VEC3))); + to.setObject(obj); + return true; } // NOLINTNEXTLINE(readability-identifier-naming) bool nativevalue_to_se(const cc::Size &from, se::Value &to, se::Object * /*unused*/) { - return Size_to_seval(from, &to); + se::HandleObject obj(se::Object::createPlainObject()); + obj->setProperty("width", se::Value(from.width)); + obj->setProperty("height", se::Value(from.height)); + obj->setProperty("type", se::Value(static_cast(MathType::SIZE))); + to.setObject(obj); + return true; } // NOLINTNEXTLINE(readability-identifier-naming) bool nativevalue_to_se(const cc::extension::ManifestAsset &from, se::Value &to, se::Object * /*unused*/) { - return ManifestAsset_to_seval(from, &to); + se::HandleObject obj(se::Object::createPlainObject()); + obj->setProperty("md5", se::Value(from.md5)); + obj->setProperty("path", se::Value(from.path)); + obj->setProperty("compressed", se::Value(from.compressed)); + obj->setProperty("size", se::Value(from.size)); + obj->setProperty("downloadState", se::Value(from.downloadState)); + to.setObject(obj); + return true; } // NOLINTNEXTLINE(readability-identifier-naming) bool nativevalue_to_se(const cc::Quaternion &from, se::Value &to, se::Object * /*ctx*/) { - return Quaternion_to_seval(from, &to); + se::HandleObject obj(se::Object::createPlainObject()); + obj->setProperty("x", se::Value(from.x)); + obj->setProperty("y", se::Value(from.y)); + obj->setProperty("z", se::Value(from.z)); + obj->setProperty("w", se::Value(from.w)); + obj->setProperty("type", se::Value(static_cast(MathType::QUATERNION))); + to.setObject(obj); + return true; } // NOLINTNEXTLINE(readability-identifier-naming) bool nativevalue_to_se(const cc::Rect &from, se::Value &to, se::Object * /*unused*/) { - return Rect_to_seval(from, &to); + se::HandleObject obj(se::Object::createPlainObject()); + obj->setProperty("x", se::Value(from.x)); + obj->setProperty("y", se::Value(from.y)); + obj->setProperty("width", se::Value(from.width)); + obj->setProperty("height", se::Value(from.height)); + obj->setProperty("type", se::Value(static_cast(MathType::RECT))); + to.setObject(obj); + return true; } // NOLINTNEXTLINE(readability-identifier-naming) diff --git a/native/cocos/bindings/manual/jsb_conversions_spec.h b/native/cocos/bindings/manual/jsb_conversions_spec.h index 480c3e1bad..4d3dc54db4 100644 --- a/native/cocos/bindings/manual/jsb_conversions_spec.h +++ b/native/cocos/bindings/manual/jsb_conversions_spec.h @@ -141,13 +141,20 @@ class Map; //////////////////////////////////////////////////////////////////////////// // se value -> native value -bool seval_to_ccvalue(const se::Value &v, cc::Value *ret); // NOLINT(readability-identifier-naming) -bool seval_to_ccvaluemap(const se::Value &v, cc::ValueMap *ret); // NOLINT(readability-identifier-naming) -bool seval_to_ccvaluemapintkey(const se::Value &v, cc::ValueMapIntKey *ret); // NOLINT(readability-identifier-naming) -bool seval_to_ccvaluevector(const se::Value &v, cc::ValueVector *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use sevalue_to_native instead") +bool seval_to_ccvalue(const se::Value &v, cc::Value *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use sevalue_to_native instead") +bool seval_to_ccvaluemap(const se::Value &v, cc::ValueMap *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use sevalue_to_native instead") +bool seval_to_ccvaluemapintkey(const se::Value &v, cc::ValueMapIntKey *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use sevalue_to_native instead") +bool seval_to_ccvaluevector(const se::Value &v, cc::ValueVector *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use sevalue_to_native instead") bool sevals_variadic_to_ccvaluevector(const se::ValueArray &args, cc::ValueVector *ret); // NOLINT(readability-identifier-naming) -bool seval_to_Data(const se::Value &v, cc::Data *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use sevalue_to_native instead") +bool seval_to_Data(const se::Value &v, cc::Data *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use sevalue_to_native instead") bool seval_to_DownloaderHints(const se::Value &v, cc::network::DownloaderHints *ret); // NOLINT(readability-identifier-naming) bool sevalue_to_native(const se::Value &from, cc::MacroValue *to, se::Object *ctx); // NOLINT(readability-identifier-naming) @@ -172,6 +179,12 @@ inline bool sevalue_to_native(const se::Value &from, ccstd::string *to, se::Obje return true; } +inline bool seval_to_std_string(const se::Value &from, ccstd::string *ret) { // NOLINT(readability-identifier-naming) + assert(ret); + *ret = from.toStringForce(); + return true; +} + inline bool sevalue_to_native(const se::Value &from, std::string_view *to, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) if (from.isString()) { *to = from.toString(); @@ -251,13 +264,9 @@ inline bool sevalue_to_native(const se::Value &from, double *to, se::Object * /* // return false; //} -inline bool sevalue_to_native(const se::Value &from, cc::Data *to, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) - return seval_to_Data(from, to); -} +bool sevalue_to_native(const se::Value &from, cc::Data *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) -inline bool sevalue_to_native(const se::Value &from, cc::Value *to, se::Object * /*unused*/) { // NOLINT(readability-identifier-naming) - return seval_to_ccvalue(from, to); -} +bool sevalue_to_native(const se::Value &from, cc::Value *to, se::Object * /*unused*/); // NOLINT(readability-identifier-naming) inline bool sevalue_to_native(const se::Value &from, se::Value *to, se::Object * /*unused*/) { // NOLINT(readability-identifier-naming) *to = from; @@ -340,9 +349,7 @@ inline bool sevalue_to_native(const se::Value &from, ccstd::string **to, se::Obj return true; } -inline bool sevalue_to_native(const se::Value &from, cc::ValueMap *to, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) - return seval_to_ccvaluemap(from, to); -} +bool sevalue_to_native(const se::Value &from, cc::ValueMap *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) bool sevalue_to_native(const se::Value &from, ccstd::vector *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) @@ -377,17 +384,42 @@ bool sevalue_to_native(const se::Value &from, cc::geometry::Spline *to, se::Obje //////////////////////////////////////////////////////////////////////////// // native value -> se value -bool ccvalue_to_seval(const cc::Value &v, se::Value *ret); // NOLINT(readability-identifier-naming) -bool ccvaluemap_to_seval(const cc::ValueMap &v, se::Value *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use native_to_se instead") +bool ccvalue_to_seval(const cc::Value &v, se::Value *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use native_to_se instead") +bool ccvaluemap_to_seval(const cc::ValueMap &v, se::Value *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use native_to_se instead") bool ccvaluemapintkey_to_seval(const cc::ValueMapIntKey &v, se::Value *ret); // NOLINT(readability-identifier-naming) -bool ccvaluevector_to_seval(const cc::ValueVector &v, se::Value *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use native_to_se instead") +bool ccvaluevector_to_seval(const cc::ValueVector &v, se::Value *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use native_to_se instead") bool ManifestAsset_to_seval(const cc::extension::ManifestAsset &v, se::Value *ret); // NOLINT(readability-identifier-naming) -bool Data_to_seval(const cc::Data &v, se::Value *ret); // NOLINT(readability-identifier-naming) -bool DownloadTask_to_seval(const cc::network::DownloadTask &v, se::Value *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use native_to_se instead") +bool Data_to_seval(const cc::Data &v, se::Value *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use native_to_se instead") +bool DownloadTask_to_seval(const cc::network::DownloadTask &v, se::Value *ret); // NOLINT(readability-identifier-naming) + +CC_DEPRECATED(3.6, "use native_to_se instead") +bool Vec2_to_seval(const cc::Vec2 &v, se::Value *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use native_to_se instead") +bool Vec3_to_seval(const cc::Vec3 &v, se::Value *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use native_to_se instead") +bool Vec4_to_seval(const cc::Vec4 &v, se::Value *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use native_to_se instead") +bool Mat4_to_seval(const cc::Mat4 &v, se::Value *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use native_to_se instead") +bool Size_to_seval(const cc::Size &v, se::Value *ret); // NOLINT(readability-identifier-naming) +CC_DEPRECATED(3.6, "use native_to_se instead") +bool Rect_to_seval(const cc::Rect &v, se::Value *ret); // NOLINT(readability-identifier-naming) //bool nativevalue_to_se(const cc::TypedArray &typedArray, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) // NOLINT +/** + * WARN: call nativevalue_to_se instead and it converts cc::Data to ArrayBuffer + */ +bool Data_to_TypedArray(const cc::Data &v, se::Value *ret); // NOLINT(readability-identifier-naming) + bool nativevalue_to_se(const cc::ArrayBuffer &arrayBuffer, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) // NOLINT inline bool nativevalue_to_se(cc::ArrayBuffer *arrayBuffer, se::Value &to, se::Object *ctx) { // NOLINT(readability-identifier-naming) // NOLINT if (arrayBuffer == nullptr) { @@ -526,9 +558,7 @@ bool nativevalue_to_se(const cc::Rect &from, se::Value &to, se::Object *ctx); // bool nativevalue_to_se(const cc::gfx::Rect &from, se::Value &to, se::Object *ctx); // NOLINT(readability-identifier-naming) -inline bool nativevalue_to_se(const cc::network::DownloadTask &from, se::Value &to, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) - return DownloadTask_to_seval(from, &to); -} +bool nativevalue_to_se(const cc::network::DownloadTask &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) inline bool nativevalue_to_se(const ccstd::monostate & /*from*/, se::Value &to, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) to.setUndefined(); diff --git a/native/cocos/bindings/manual/jsb_gfx_manual.cpp b/native/cocos/bindings/manual/jsb_gfx_manual.cpp index da5b91728f..c5dce7f2db 100644 --- a/native/cocos/bindings/manual/jsb_gfx_manual.cpp +++ b/native/cocos/bindings/manual/jsb_gfx_manual.cpp @@ -152,7 +152,7 @@ bool js_gfx_Device_copyTexImagesToTexture(se::State &s) { // NOLINT(readability- cc::gfx::BufferDataList arg0; cc::gfx::Texture *arg1 = nullptr; cc::gfx::BufferTextureCopyList arg2; - CC_UNUSED size_t dataLength = 0; + if (args[0].isObject()) { se::Object *dataObj = args[0].toObject(); SE_PRECONDITION2(dataObj->isArray(), false, "Buffers must be an array!"); @@ -164,15 +164,18 @@ bool js_gfx_Device_copyTexImagesToTexture(se::State &s) { // NOLINT(readability- for (uint32_t i = 0; i < length; ++i) { if (dataObj->getArrayElement(i, &value)) { if (value.isObject()) { + CC_UNUSED size_t dataLength = 0; + uint8_t *buffer{nullptr}; if (value.toObject()->isTypedArray()) { - uint8_t *address = nullptr; - value.toObject()->getTypedArrayData(&address, &dataLength); - arg0[i] = address; + value.toObject()->getTypedArrayData(&buffer, &dataLength); + } else if (value.toObject()->isArrayBuffer()) { + value.toObject()->getArrayBufferData(&buffer, &dataLength); } else { auto *dataHolder = static_cast(value.toObject()->getPrivateData()); - uint8_t *data = dataHolder->getData(); - arg0[i] = data; + CC_ASSERT(dataHolder != nullptr); + buffer = dataHolder->getData(); } + arg0[i] = buffer; } else { CC_ASSERT(false); } diff --git a/native/cocos/bindings/manual/jsb_network_manual.cpp b/native/cocos/bindings/manual/jsb_network_manual.cpp index 7b1300724f..57bfa397a3 100644 --- a/native/cocos/bindings/manual/jsb_network_manual.cpp +++ b/native/cocos/bindings/manual/jsb_network_manual.cpp @@ -47,7 +47,7 @@ static bool js_network_Downloader_createDownloadFileTask(se::State &s) { // NOLI "js_network_Downloader_createDownloadFileTask : Error processing arguments"); std::shared_ptr result = cobj->createDownloadTask( arg0, arg1); - ok &= DownloadTask_to_seval(*result, &s.rval()); + ok &= nativevalue_to_se(*result, s.rval()); //ROOT downloader object s.thisObject()->root(); @@ -66,7 +66,7 @@ static bool js_network_Downloader_createDownloadFileTask(se::State &s) { // NOLI "js_network_Downloader_createDownloadFileTask : Error processing arguments"); std::shared_ptr result = cobj->createDownloadTask( arg0, arg1, arg2); - ok &= DownloadTask_to_seval(*result, &s.rval()); + ok &= nativevalue_to_se(*result, s.rval()); //ROOT downloader object s.thisObject()->root(); @@ -96,7 +96,7 @@ static bool js_network_Downloader_createDownloadTask(se::State &s) { // NOLINT(r "js_network_Downloader_createDownloadTask : Error processing arguments"); std::shared_ptr result = cobj->createDownloadTask( arg0, arg1); - ok &= DownloadTask_to_seval(*result, &s.rval()); + ok &= nativevalue_to_se(*result, s.rval()); //ROOT downloader object s.thisObject()->root(); @@ -115,7 +115,7 @@ static bool js_network_Downloader_createDownloadTask(se::State &s) { // NOLINT(r "js_network_Downloader_createDownloadTask : Error processing arguments"); std::shared_ptr result = cobj->createDownloadTask( arg0, arg1, arg2); - ok &= DownloadTask_to_seval(*result, &s.rval()); + ok &= nativevalue_to_se(*result, s.rval()); //ROOT downloader object s.thisObject()->root(); @@ -151,7 +151,7 @@ static bool js_network_Downloader_setOnFileTaskSuccess(se::State &s) { // NOLINT CC_UNUSED bool ok = true; se::ValueArray args; args.resize(1); - ok &= DownloadTask_to_seval(larg0, &args[0]); + ok &= nativevalue_to_se(larg0, args[0]); se::Value rval; se::Object *funcObj = jsFunc.toObject(); bool succeed = funcObj->call(args, thisObj, &rval); @@ -197,7 +197,7 @@ static bool js_network_Downloader_setOnSuccess(se::State &s) { // NOLINT(readabi CC_UNUSED bool ok = true; se::ValueArray args; args.resize(1); - ok &= DownloadTask_to_seval(larg0, &args[0]); + ok &= nativevalue_to_se(larg0, args[0]); se::Value rval; se::Object *funcObj = jsFunc.toObject(); bool succeed = funcObj->call(args, thisObj, &rval); @@ -244,7 +244,7 @@ static bool js_network_Downloader_setOnTaskError(se::State &s) { // NOLINT(reada CC_UNUSED bool ok = true; se::ValueArray args; args.resize(4); - ok &= DownloadTask_to_seval(larg0, &args[0]); + ok &= nativevalue_to_se(larg0, args[0]); ok &= nativevalue_to_se(larg1, args[1]); ok &= nativevalue_to_se(larg2, args[2]); ok &= nativevalue_to_se(larg3, args[3]); @@ -293,7 +293,7 @@ static bool js_network_Downloader_setOnError(se::State &s) { // NOLINT(readabili CC_UNUSED bool ok = true; se::ValueArray args; args.resize(4); - ok &= DownloadTask_to_seval(larg0, &args[0]); + ok &= nativevalue_to_se(larg0, args[0]); ok &= nativevalue_to_se(larg1, args[1]); ok &= nativevalue_to_se(larg2, args[2]); ok &= nativevalue_to_se(larg3, args[3]); @@ -321,7 +321,7 @@ static bool js_network_Downloader_setOnError(se::State &s) { // NOLINT(readabili } SE_BIND_FUNC_AS_PROP_SET(js_network_Downloader_setOnError) -bool register_all_network_manual(se::Object * /*obj*/) { +bool register_all_network_manual(se::Object * /*obj*/) { // NOLINT(readability-identifier-naming) __jsb_cc_network_Downloader_proto->defineProperty("onSuccess", nullptr, _SE(js_network_Downloader_setOnSuccess_asSetter)); __jsb_cc_network_Downloader_proto->defineProperty("onError", nullptr, _SE(js_network_Downloader_setOnError_asSetter)); __jsb_cc_network_Downloader_proto->defineFunction("createDownloadTask", diff --git a/native/cocos/bindings/manual/jsb_scene_manual.cpp b/native/cocos/bindings/manual/jsb_scene_manual.cpp index ac9b572c18..77dd585090 100644 --- a/native/cocos/bindings/manual/jsb_scene_manual.cpp +++ b/native/cocos/bindings/manual/jsb_scene_manual.cpp @@ -192,7 +192,7 @@ static void registerOnSiblingOrderChanged(cc::Node *node, se::Object *jsObject) } static void registerOnActiveNode(cc::Node *node, se::Object *jsObject) { - cc::CallbackInfoBase::ID skip; + cc::CallbackID skip; node->on( cc::EventTypesToJS::NODE_ACTIVE_NODE, [jsObject](bool shouldActiveNow) { @@ -205,7 +205,7 @@ static void registerOnActiveNode(cc::Node *node, se::Object *jsObject) { } static void registerOnBatchCreated(cc::Node *node, se::Object *jsObject) { - cc::CallbackInfoBase::ID skip; + cc::CallbackID skip; node->on( cc::EventTypesToJS::NODE_ON_BATCH_CREATED, [jsObject](bool dontChildPrefab) { diff --git a/native/cocos/bindings/manual/jsb_websocket.cpp b/native/cocos/bindings/manual/jsb_websocket.cpp index b52fc92c7f..b7a25f864f 100644 --- a/native/cocos/bindings/manual/jsb_websocket.cpp +++ b/native/cocos/bindings/manual/jsb_websocket.cpp @@ -184,6 +184,7 @@ void JsbWebSocketDelegate::onClose(cc::network::WebSocket *ws) { //JS Websocket object now can be GC, since the connection is closed. wsObj->unroot(); + _JSDelegate.toObject()->unroot(); // Websocket instance is attached to global object in 'WebSocket_close' // It's safe to detach it here since JS 'onclose' method has been already invoked. @@ -224,8 +225,6 @@ void JsbWebSocketDelegate::onError(cc::network::WebSocket *ws, const cc::network } else { SE_REPORT_ERROR("Can't get onerror function!"); } - - wsObj->unroot(); } void JsbWebSocketDelegate::setJSDelegate(const se::Value &jsDelegate) { @@ -398,25 +397,45 @@ static bool webSocketClose(se::State &s) { cobj->closeAsync(); } else if (argc == 1) { if (args[0].isNumber()) { - int reason{0}; - sevalue_to_native(args[0], &reason); - cobj->closeAsync(reason, "no_reason"); + int reasonCode{0}; + sevalue_to_native(args[0], &reasonCode); + cobj->closeAsync(reasonCode, "no_reason"); } else if (args[0].isString()) { - ccstd::string reason; - sevalue_to_native(args[0], &reason); - cobj->closeAsync(1005, reason); + ccstd::string reasonString; + sevalue_to_native(args[0], &reasonString); + cobj->closeAsync(1005, reasonString); } else { CC_ASSERT(false); } } else if (argc == 2) { - CC_ASSERT(args[0].isNumber()); - CC_ASSERT(args[1].isString()); - int reasonCode{0}; - ccstd::string reasonString; - sevalue_to_native(args[0], &reasonCode); - sevalue_to_native(args[1], &reasonString); - cobj->closeAsync(reasonCode, reasonString); + if (args[0].isNumber()) { + int reasonCode{0}; + if (args[1].isString()) { + ccstd::string reasonString; + sevalue_to_native(args[0], &reasonCode); + sevalue_to_native(args[1], &reasonString); + cobj->closeAsync(reasonCode, reasonString); + } else if (args[1].isNullOrUndefined()) { + sevalue_to_native(args[0], &reasonCode); + cobj->closeAsync(reasonCode, "no_reason"); + } else { + CC_ASSERT(false); + } + } else if (args[0].isNullOrUndefined()) { + if (args[1].isString()) { + ccstd::string reasonString; + sevalue_to_native(args[1], &reasonString); + cobj->closeAsync(1005, reasonString); + } else if (args[1].isNullOrUndefined()) { + cobj->closeAsync(); + } else { + CC_ASSERT(false); + } + } else { + CC_ASSERT(false); + } } else { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting <=2", argc); CC_ASSERT(false); } // Attach current WebSocket instance to global object to prevent WebSocket instance diff --git a/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp b/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp index 3f03f89fbc..5b41fb21f2 100644 --- a/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp +++ b/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp @@ -34,6 +34,7 @@ #include #include #include +#include "application/ApplicationManager.h" #include "base/Config.h" #include "base/std/container/string.h" #include "base/std/container/unordered_map.h" @@ -41,10 +42,9 @@ #include "cocos/base/DeferredReleasePool.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_conversions.h" +#include "cocos/engine/BaseEngine.h" #include "cocos/network/HttpClient.h" -#include "application/ApplicationManager.h" - using namespace cc; //NOLINT using namespace cc::network; //NOLINT @@ -172,6 +172,16 @@ public: bool isDiscardedByReset() const { return _isDiscardedByReset; } + inline void clearCallbacks() { + onloadstart = nullptr; + onload = nullptr; + onloadend = nullptr; + onreadystatechange = nullptr; + onabort = nullptr; + onerror = nullptr; + ontimeout = nullptr; + } + private: ~XMLHttpRequest() override; @@ -183,6 +193,7 @@ private: void sendRequest(); void setHttpRequestHeader(); + BaseEngine::SchedulerPtr _scheduler; ccstd::unordered_map _httpHeader; ccstd::unordered_map _requestHeader; @@ -225,10 +236,14 @@ XMLHttpRequest::XMLHttpRequest() _httpRequest(ccnew HttpRequest()), _responseType(ResponseType::STRING), _readyState(ReadyState::UNSENT) { + _httpRequest->addRef(); + _scheduler = CC_CURRENT_ENGINE()->getScheduler(); } XMLHttpRequest::~XMLHttpRequest() { - CC_CURRENT_ENGINE()->getScheduler()->unscheduleAllForTarget(this); + if (_scheduler) { + _scheduler->unscheduleAllForTarget(this); + } // Avoid HttpClient response call a released object! _httpRequest->setResponseCallback(nullptr); CC_SAFE_RELEASE(_httpRequest); @@ -303,6 +318,9 @@ void XMLHttpRequest::abort() { setReadyState(ReadyState::DONE); + // Unregister timeout timer while abort is invoked. + _scheduler->unscheduleAllForTarget(this); + if (onabort != nullptr) { onabort(); } @@ -377,7 +395,8 @@ void XMLHttpRequest::getHeader(const ccstd::string &header) { } void XMLHttpRequest::onResponse(HttpClient * /*client*/, HttpResponse *response) { - CC_CURRENT_ENGINE()->getScheduler()->unscheduleAllForTarget(this); + CC_ASSERT(_scheduler); + _scheduler->unscheduleAllForTarget(this); _isSending = false; if (_isTimeout) { @@ -478,14 +497,15 @@ void XMLHttpRequest::sendRequest() { _isSending = true; _isTimeout = false; if (_timeoutInMilliseconds > 0) { - CC_CURRENT_ENGINE()->getScheduler()->schedule([this](float /* dt */) { + CC_ASSERT(_scheduler); + _scheduler->schedule([this](float /* dt */) { if (ontimeout != nullptr) { ontimeout(); } _isTimeout = true; _readyState = ReadyState::UNSENT; }, - this, static_cast(_timeoutInMilliseconds) / 1000.0F, 0, 0.0F, false, "XMLHttpRequest"); + this, static_cast(_timeoutInMilliseconds) / 1000.0F, 0, 0.0F, false, "XMLHttpRequest"); } setHttpRequestHeader(); @@ -576,6 +596,7 @@ se::Class *__jsb_XMLHttpRequest_class = nullptr; //NOLINT(readability-identifier static bool XMLHttpRequest_finalize(se::State &s) { //NOLINT(readability-identifier-naming, google-runtime-references) auto *request = static_cast(s.nativeThisObject()); SE_LOGD("XMLHttpRequest_finalize, %p ... \n", request); + request->clearCallbacks(); return true; } SE_BIND_FINALIZE_FUNC(XMLHttpRequest_finalize) diff --git a/native/cocos/core/TypedArray.h b/native/cocos/core/TypedArray.h index cf47713800..8d269ce3ac 100644 --- a/native/cocos/core/TypedArray.h +++ b/native/cocos/core/TypedArray.h @@ -136,6 +136,11 @@ public: _byteOffset = o._byteOffset; _byteLength = o._byteLength; _byteEndPos = o._byteEndPos; + + if (_jsTypedArray != nullptr) { + _jsTypedArray->unroot(); + _jsTypedArray->decRef(); + } _jsTypedArray = o._jsTypedArray; o._buffer = nullptr; diff --git a/native/cocos/core/builtin/DebugInfos.cpp b/native/cocos/core/builtin/DebugInfos.cpp index fe37b0cdf0..f6518d4d96 100644 --- a/native/cocos/core/builtin/DebugInfos.cpp +++ b/native/cocos/core/builtin/DebugInfos.cpp @@ -304,6 +304,7 @@ ccstd::unordered_map debugInfos = { { 6032, "cc.ParticleSystem.initWithDictionary() : error loading the texture" }, { 6033, "cc.ParticleSystem: not allowing create to be invoked twice with different particle system" }, { 6034, "cc.ParticleSystem: shouldn't be initialized repetitively, otherwise there will be potential leak" }, +{ 6035, "cc.ParticleSystem: change material failed, please use proper particle material" }, { 6400, "asset.url is not usable in core process" }, { 6402, "AssetLibrary has already been initialized!" }, { 6500, "Widget target must be one of the parent nodes of it" }, diff --git a/native/cocos/core/event/CallbacksInvoker.cpp b/native/cocos/core/event/CallbacksInvoker.cpp index cbbaf4497e..6e7af4a9da 100644 --- a/native/cocos/core/event/CallbacksInvoker.cpp +++ b/native/cocos/core/event/CallbacksInvoker.cpp @@ -27,11 +27,11 @@ namespace cc { -CallbackInfoBase::ID CallbacksInvoker::cbIDCounter{0}; +uint32_t CallbacksInvoker::cbIDCounter{0}; -void CallbackList::removeByCallbackID(CallbackInfoBase::ID cbID) { +void CallbackList::removeByCallbackID(const CallbackID &cbID) { for (int32_t i = 0; i < _callbackInfos.size(); ++i) { - auto &info = _callbackInfos[i]; + const auto &info = _callbackInfos[i]; if (info->_id == cbID) { utils::array::fastRemoveAt(_callbackInfos, i); --i; @@ -111,7 +111,7 @@ bool CallbacksInvoker::hasEventListener(const KeyType &key) const { return !infos.empty(); } -bool CallbacksInvoker::hasEventListener(const KeyType &key, CallbackInfoBase::ID cbID) const { +bool CallbacksInvoker::hasEventListener(const KeyType &key, const CallbackID &cbID) const { auto iter = _callbackTable.find(key); if (iter == _callbackTable.end()) { return false; @@ -149,7 +149,7 @@ bool CallbacksInvoker::hasEventListener(const KeyType &key, void *target) { return false; } -bool CallbacksInvoker::hasEventListener(const KeyType &key, void *target, CallbackInfoBase::ID cbID) const { +bool CallbacksInvoker::hasEventListener(const KeyType &key, void *target, const CallbackID &cbID) const { auto iter = _callbackTable.find(key); if (iter == _callbackTable.end()) { return false; @@ -212,7 +212,7 @@ void CallbacksInvoker::offAll() { } } -void CallbacksInvoker::off(const KeyType &key, CallbackInfoBase::ID cbID) { +void CallbacksInvoker::off(const KeyType &key, const CallbackID &cbID) { auto iter = _callbackTable.find(key); if (iter != _callbackTable.end()) { auto &list = iter->second; @@ -247,7 +247,7 @@ void CallbacksInvoker::offAll(const KeyType &key, void *target) { } } -void CallbacksInvoker::off(CallbackInfoBase::ID cbID) { +void CallbacksInvoker::off(const CallbackID &cbID) { for (auto &cbInfo : _callbackTable) { auto &list = cbInfo.second; const auto &infos = list._callbackInfos; diff --git a/native/cocos/core/event/CallbacksInvoker.h b/native/cocos/core/event/CallbacksInvoker.h index b2e49fe6ae..19cbe18cf7 100644 --- a/native/cocos/core/event/CallbacksInvoker.h +++ b/native/cocos/core/event/CallbacksInvoker.h @@ -42,8 +42,12 @@ namespace cc { #define CC_CALLBACK_INVOKE_2(__selector__, __target__, Arg0, Arg1, ...) std::function(std::bind(&__selector__, __target__, std::placeholders::_1, std::placeholders::_2, ##__VA_ARGS__)), __target__ #define CC_CALLBACK_INVOKE_3(__selector__, __target__, Arg0, Arg1, Arg2, ...) std::function(std::bind(&__selector__, __target__, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, ##__VA_ARGS__)), __target__ +struct CallbackID { + inline bool operator==(const CallbackID &rhs) const noexcept { return value == rhs.value; } + uint32_t value{0}; +}; + struct CallbackInfoBase { - using ID = uint32_t; using FakeCallbackMemberFn = void (CCObject::*)(); CallbackInfoBase() = default; @@ -54,7 +58,7 @@ struct CallbackInfoBase { virtual FakeCallbackMemberFn getMemberFn() const = 0; void *_target{nullptr}; - ID _id{0}; + CallbackID _id; bool _once{false}; bool _isCCObject{false}; #if CC_DEBUG @@ -134,7 +138,7 @@ public: * * @param cbID - The callback id to be removed */ - void removeByCallbackID(CallbackInfoBase::ID cbID); + void removeByCallbackID(const CallbackID &cbID); /** * @zh 从列表中移除与指定目标相同调用者的事件。 @@ -207,18 +211,18 @@ public: // template - void on(const KeyType &key, std::function &&callback, Target *target, CallbackInfoBase::ID &outCallbackID, bool once = false); + void on(const KeyType &key, std::function &&callback, Target *target, CallbackID &outCallbackID, bool once = false); template - void on(const KeyType &key, std::function &&callback, CallbackInfoBase::ID &outCallbackID, bool once = false); + void on(const KeyType &key, std::function &&callback, CallbackID &outCallbackID, bool once = false); template std::enable_if_t::value, void> - on(const KeyType &key, LambdaType &&callback, Target *target, CallbackInfoBase::ID &outCallbackID, bool once = false); + on(const KeyType &key, LambdaType &&callback, Target *target, CallbackID &outCallbackID, bool once = false); template std::enable_if_t::value, void> - on(const KeyType &key, LambdaType &&callback, CallbackInfoBase::ID &outCallbackID, bool once = false); + on(const KeyType &key, LambdaType &&callback, CallbackID &outCallbackID, bool once = false); /** * @zh 检查指定事件是否已注册回调。 @@ -227,9 +231,9 @@ public: * @param cbID - Callback ID */ bool hasEventListener(const KeyType &key) const; - bool hasEventListener(const KeyType &key, CallbackInfoBase::ID cbID) const; + bool hasEventListener(const KeyType &key, const CallbackID &cbID) const; bool hasEventListener(const KeyType &key, void *target); - bool hasEventListener(const KeyType &key, void *target, CallbackInfoBase::ID cbID) const; + bool hasEventListener(const KeyType &key, void *target, const CallbackID &cbID) const; template bool hasEventListener(const KeyType &key, void (Target::*memberFn)(Args...), Target *target) const; /** @@ -249,8 +253,8 @@ public: * @param target callback Target * @param cbID - The callback ID of the event listener, if absent all event listeners for the given type will be removed */ - void off(const KeyType &key, CallbackInfoBase::ID cbID); - void off(CallbackInfoBase::ID cbID); + void off(const KeyType &key, const CallbackID &cbID); + void off(const CallbackID &cbID); template void off(const KeyType &key, void (Target::*memberFn)(Args...), Target *target); @@ -285,7 +289,7 @@ public: private: ccstd::unordered_map _callbackTable; - static CallbackInfoBase::ID cbIDCounter; + static uint32_t cbIDCounter; }; template @@ -294,63 +298,62 @@ void CallbacksInvoker::on(const KeyType &key, void (Target::*memberFn)(Args...), using CallbackInfoType = CallbackInfo; auto &list = _callbackTable[key]; auto info = std::make_shared(); - info->_id = ++cbIDCounter; - CallbackInfoBase::ID cbID = info->_id; + info->_id.value = ++cbIDCounter; info->set(static_cast(memberFn), target, once); list._callbackInfos.emplace_back(std::move(info)); } template -void CallbacksInvoker::on(const KeyType &key, std::function &&callback, Target *target, CallbackInfoBase::ID &outCallbackID, bool once) { +void CallbacksInvoker::on(const KeyType &key, std::function &&callback, Target *target, CallbackID &outCallbackID, bool once) { auto &list = _callbackTable[key]; auto info = std::make_shared>(); - info->_id = ++cbIDCounter; - CallbackInfoBase::ID cbID = info->_id; + info->_id.value = ++cbIDCounter; + CallbackID cbID = info->_id; info->set(std::forward>(callback), target, once); list._callbackInfos.emplace_back(std::move(info)); outCallbackID = cbID; } template -void CallbacksInvoker::on(const KeyType &key, std::function &&callback, CallbackInfoBase::ID &outCallbackID, bool once) { +void CallbacksInvoker::on(const KeyType &key, std::function &&callback, CallbackID &outCallbackID, bool once) { on(key, std::forward>(callback), nullptr, outCallbackID, once); } template std::enable_if_t::value, void> -CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, Target *target, CallbackInfoBase::ID &outCallbackID, bool once) { +CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, Target *target, CallbackID &outCallbackID, bool once) { on(key, toFunction(std::forward(callback)), target, outCallbackID, once); } template std::enable_if_t::value, void> -CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, CallbackInfoBase::ID &outCallbackID, bool once) { +CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, CallbackID &outCallbackID, bool once) { on(key, toFunction(std::forward(callback)), outCallbackID, once); } template void CallbacksInvoker::on(const KeyType &key, std::function &&callback, Target *target, bool once) { - CallbackInfoBase::ID unusedID{0}; + CallbackID unusedID{0}; on(key, callback, target, unusedID, once); } template void CallbacksInvoker::on(const KeyType &key, std::function &&callback, bool once) { - CallbackInfoBase::ID unusedID{0}; + CallbackID unusedID{0}; on(key, std::forward>(callback), nullptr, unusedID, once); } template std::enable_if_t::value, void> CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, Target *target, bool once) { - CallbackInfoBase::ID unusedID{0}; + CallbackID unusedID{0}; on(key, toFunction(std::forward(callback)), target, unusedID, once); } template std::enable_if_t::value, void> CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, bool once) { - CallbackInfoBase::ID unusedID{0}; + CallbackID unusedID{0}; on(key, toFunction(std::forward(callback)), unusedID, once); } @@ -420,7 +423,7 @@ void CallbacksInvoker::emit(const KeyType &key, Args &&...args) { } } else { const auto &callback = info->_callback; - CallbackInfoBase::ID cbID = info->_id; + const CallbackID &cbID = info->_id; // Pre off once callbacks to avoid influence on logic in callback if (info->_once) { off(key, cbID); diff --git a/native/cocos/core/scene-graph/Node.cpp b/native/cocos/core/scene-graph/Node.cpp index bf8fbc7f27..b47be302bc 100644 --- a/native/cocos/core/scene-graph/Node.cpp +++ b/native/cocos/core/scene-graph/Node.cpp @@ -156,7 +156,7 @@ void Node::onHierarchyChangedBase(Node *oldParent) { // NOLINT(misc-unused-param } void Node::off(const CallbacksInvoker::KeyType &type, bool useCapture) { - _eventProcessor->off(type, useCapture); + _eventProcessor->offAll(type, useCapture); bool hasListeners = _eventProcessor->hasEventListener(type); if (!hasListeners) { if (type == NodeEventType::TRANSFORM_CHANGED) { @@ -165,7 +165,7 @@ void Node::off(const CallbacksInvoker::KeyType &type, bool useCapture) { } } -void Node::off(const CallbacksInvoker::KeyType &type, CallbackInfoBase::ID cbID, bool useCapture) { +void Node::off(const CallbacksInvoker::KeyType &type, const CallbackID &cbID, bool useCapture) { _eventProcessor->off(type, cbID, useCapture); bool hasListeners = _eventProcessor->hasEventListener(type); if (!hasListeners) { @@ -193,13 +193,13 @@ bool Node::hasEventListener(const CallbacksInvoker::KeyType &type) const { return _eventProcessor->hasEventListener(type); } -bool Node::hasEventListener(const CallbacksInvoker::KeyType &type, CallbackInfoBase::ID cbID) const { +bool Node::hasEventListener(const CallbacksInvoker::KeyType &type, const CallbackID &cbID) const { return _eventProcessor->hasEventListener(type, cbID); } bool Node::hasEventListener(const CallbacksInvoker::KeyType &type, void *target) const { return _eventProcessor->hasEventListener(type, target); } -bool Node::hasEventListener(const CallbacksInvoker::KeyType &type, void *target, CallbackInfoBase::ID cbID) const { +bool Node::hasEventListener(const CallbacksInvoker::KeyType &type, void *target, const CallbackID &cbID) const { return _eventProcessor->hasEventListener(type, target, cbID); } @@ -886,6 +886,16 @@ void Node::clearNodeArray() { } } +ccstd::string Node::getPathInHierarchy() const { + ccstd::string result = getName(); + Node *curNode = getParent(); + while (curNode && curNode->getParent()) { + result.insert(0, "/").insert(0, curNode->getName()); + curNode = curNode->getParent(); + } + return result; +} + void Node::translate(const Vec3 &trans, NodeSpace ns) { Vec3 v3Temp{trans}; if (ns == NodeSpace::LOCAL) { diff --git a/native/cocos/core/scene-graph/Node.h b/native/cocos/core/scene-graph/Node.h index d042918b8d..0da5314b59 100644 --- a/native/cocos/core/scene-graph/Node.h +++ b/native/cocos/core/scene-graph/Node.h @@ -114,18 +114,18 @@ public: void on(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); template - void on(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackInfoBase::ID &cbID, bool useCapture = false); + void on(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture = false); template - void on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture = false); + void on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture = false); template std::enable_if_t::value, void> - on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture = false); + on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool useCapture = false); template std::enable_if_t::value, void> - on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackInfoBase::ID &cbID, bool useCapture = false); + on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool useCapture = false); template void on(const CallbacksInvoker::KeyType &type, std::function &&callback, bool useCapture = false); @@ -145,18 +145,18 @@ public: void once(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); template - void once(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackInfoBase::ID &cbID, bool useCapture = false); + void once(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture = false); template - void once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture = false); + void once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture = false); template std::enable_if_t::value, void> - once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackInfoBase::ID &cbID, bool useCapture = false); + once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool useCapture = false); template std::enable_if_t::value, void> - once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture = false); + once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool useCapture = false); template void once(const CallbacksInvoker::KeyType &type, std::function &&callback, bool useCapture = false); @@ -174,7 +174,7 @@ public: void off(const CallbacksInvoker::KeyType &type, bool useCapture = false); - void off(const CallbacksInvoker::KeyType &type, CallbackInfoBase::ID cbID, bool useCapture = false); + void off(const CallbacksInvoker::KeyType &type, const CallbackID &cbID, bool useCapture = false); void off(const CallbacksInvoker::KeyType &type, void *target, bool useCapture = false); @@ -186,9 +186,9 @@ public: // void dispatchEvent(event::Event *event); bool hasEventListener(const CallbacksInvoker::KeyType &type) const; - bool hasEventListener(const CallbacksInvoker::KeyType &type, CallbackInfoBase::ID cbID) const; + bool hasEventListener(const CallbacksInvoker::KeyType &type, const CallbackID &cbID) const; bool hasEventListener(const CallbacksInvoker::KeyType &type, void *target) const; - bool hasEventListener(const CallbacksInvoker::KeyType &type, void *target, CallbackInfoBase::ID cbID) const; + bool hasEventListener(const CallbacksInvoker::KeyType &type, void *target, const CallbackID &cbID) const; template bool hasEventListener(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target) const; @@ -284,6 +284,7 @@ public: void pauseSystemEvents(bool recursive) {} // cjh TODO: void resumeSystemEvents(bool recursive) {} // cjh TODO: + ccstd::string getPathInHierarchy() const; // =============================== // transform // =============================== @@ -726,7 +727,7 @@ void Node::on(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Ar } template -void Node::on(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackInfoBase::ID &cbID, bool useCapture) { +void Node::on(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture) { if (type == NodeEventType::TRANSFORM_CHANGED) { _eventMask |= TRANSFORM_ON; } @@ -734,7 +735,7 @@ void Node::on(const CallbacksInvoker::KeyType &type, std::function -void Node::on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture) { +void Node::on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture) { if (type == NodeEventType::TRANSFORM_CHANGED) { _eventMask |= TRANSFORM_ON; } @@ -743,7 +744,7 @@ void Node::on(const CallbacksInvoker::KeyType &type, std::function std::enable_if_t::value, void> -Node::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture) { +Node::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool useCapture) { if (type == NodeEventType::TRANSFORM_CHANGED) { _eventMask |= TRANSFORM_ON; } @@ -752,7 +753,7 @@ Node::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *t template std::enable_if_t::value, void> -Node::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackInfoBase::ID &cbID, bool useCapture) { +Node::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool useCapture) { if (type == NodeEventType::TRANSFORM_CHANGED) { _eventMask |= TRANSFORM_ON; } @@ -761,27 +762,27 @@ Node::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackI template void Node::on(const CallbacksInvoker::KeyType &type, std::function &&callback, bool useCapture) { - CallbackInfoBase::ID unusedID{0}; + CallbackID unusedID{0}; on(type, callback, unusedID, useCapture); } template void Node::on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, bool useCapture) { - CallbackInfoBase::ID unusedID{0}; + CallbackID unusedID{0}; on(type, callback, target, unusedID, useCapture); } template std::enable_if_t::value, void> Node::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, bool useCapture) { - CallbackInfoBase::ID unusedID{0}; + CallbackID unusedID{0}; on(type, callback, target, unusedID, useCapture); } template std::enable_if_t::value, void> Node::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, bool useCapture) { - CallbackInfoBase::ID unusedID{0}; + CallbackID unusedID{0}; on(type, callback, unusedID, useCapture); } template @@ -789,50 +790,50 @@ void Node::once(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)( _eventProcessor->once(type, memberFn, target, useCapture); } template -void Node::once(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackInfoBase::ID &cbID, bool useCapture) { +void Node::once(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture) { _eventProcessor->once(type, callback, cbID, useCapture); } template -void Node::once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture) { +void Node::once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture) { _eventProcessor->once(type, std::forward>(callback), target, cbID, useCapture); } template std::enable_if_t::value, void> -Node::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackInfoBase::ID &cbID, bool useCapture) { +Node::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool useCapture) { _eventProcessor->once(type, callback, cbID, useCapture); } template std::enable_if_t::value, void> -Node::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture) { +Node::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool useCapture) { _eventProcessor->once(type, callback, target, cbID, useCapture); } template void Node::once(const CallbacksInvoker::KeyType &type, std::function &&callback, bool useCapture) { - CallbackInfoBase::ID unusedID{0}; + CallbackID unusedID{0}; once(type, callback, unusedID, useCapture); } template void Node::once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, bool useCapture) { - CallbackInfoBase::ID unusedID{0}; + CallbackID unusedID{0}; once(type, callback, target, unusedID, useCapture); } template std::enable_if_t::value, void> Node::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, bool useCapture) { - CallbackInfoBase::ID unusedID{0}; + CallbackID unusedID{0}; once(type, callback, unusedID, useCapture); } template std::enable_if_t::value, void> Node::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, bool useCapture) { - CallbackInfoBase::ID unusedID{0}; + CallbackID unusedID{0}; once(type, callback, target, unusedID, useCapture); } diff --git a/native/cocos/core/scene-graph/NodeEventProcessor.cpp b/native/cocos/core/scene-graph/NodeEventProcessor.cpp index 22003195ca..356ee9bf7b 100644 --- a/native/cocos/core/scene-graph/NodeEventProcessor.cpp +++ b/native/cocos/core/scene-graph/NodeEventProcessor.cpp @@ -357,7 +357,7 @@ void NodeEventProcessor::off(const CallbacksInvoker::KeyType &type, void *target } } -void NodeEventProcessor::off(const CallbacksInvoker::KeyType &type, CallbackInfoBase::ID cbID, bool /*useCapture*/) { +void NodeEventProcessor::off(const CallbacksInvoker::KeyType &type, const CallbackID &cbID, bool /*useCapture*/) { // bool touchEventExist = std::find(TOUCH_EVENTS.begin(), TOUCH_EVENTS.end(), type) != TOUCH_EVENTS.end(); // bool mouseEventExist = std::find(MOUSE_EVENTS.begin(), MOUSE_EVENTS.end(), type) != MOUSE_EVENTS.end(); // if (touchEventExist || mouseEventExist) { @@ -380,6 +380,29 @@ void NodeEventProcessor::off(const CallbacksInvoker::KeyType &type, CallbackInfo } } +void NodeEventProcessor::offAll(const CallbacksInvoker::KeyType &type, bool /* useCapture = false*/) { + // bool touchEventExist = std::find(TOUCH_EVENTS.begin(), TOUCH_EVENTS.end(), type) != TOUCH_EVENTS.end(); + // bool mouseEventExist = std::find(MOUSE_EVENTS.begin(), MOUSE_EVENTS.end(), type) != MOUSE_EVENTS.end(); + // if (touchEventExist || mouseEventExist) { + // offDispatch(type, target, useCapture); + // + // if (touchEventExist) { + // if (_touchListener && !checkListeners(_node, TOUCH_EVENTS)) { + // event::EventManager::getInstance()->removeEventListener(_touchListener); + // _touchListener = nullptr; + // } + // } else if (mouseEventExist) { + // if (_mouseListener && !checkListeners(_node, MOUSE_EVENTS)) { + // event::EventManager::getInstance()->removeEventListener(_mouseListener); + // _mouseListener = nullptr; + // } + // } + // } else + if (_bubblingTargets != nullptr) { + _bubblingTargets->offAll(type); + } +} + //void NodeEventProcessor::dispatchEvent(event::Event *event) { // doDispatchEvent(_node, event); // cachedArray.clear(); @@ -396,7 +419,7 @@ bool NodeEventProcessor::hasEventListener(const CallbacksInvoker::KeyType &type) return has; } -bool NodeEventProcessor::hasEventListener(const CallbacksInvoker::KeyType &type, CallbackInfoBase::ID cbID) const { +bool NodeEventProcessor::hasEventListener(const CallbacksInvoker::KeyType &type, const CallbackID &cbID) const { bool has = false; if (_bubblingTargets) { has = _bubblingTargets->hasEventListener(type, cbID); @@ -417,7 +440,7 @@ bool NodeEventProcessor::hasEventListener(const CallbacksInvoker::KeyType &type, } return has; } -bool NodeEventProcessor::hasEventListener(const CallbacksInvoker::KeyType &type, void *target, CallbackInfoBase::ID cbID) const { +bool NodeEventProcessor::hasEventListener(const CallbacksInvoker::KeyType &type, void *target, const CallbackID &cbID) const { bool has = false; if (_bubblingTargets) { has = _bubblingTargets->hasEventListener(type, target, cbID); @@ -535,8 +558,8 @@ void NodeEventProcessor::getBubblingTargets(const CallbacksInvoker::KeyType &typ // return forDispatch; //} -void NodeEventProcessor::offDispatch(const CallbacksInvoker::KeyType &type, CallbackInfoBase::ID cbID, bool useCapture) { - if (cbID == 0) { +void NodeEventProcessor::offDispatch(const CallbacksInvoker::KeyType &type, const CallbackID &cbID, bool useCapture) { + if (cbID.value == 0) { if (_capturingTargets != nullptr) { _capturingTargets->offAll(type); } diff --git a/native/cocos/core/scene-graph/NodeEventProcessor.h b/native/cocos/core/scene-graph/NodeEventProcessor.h index a04e420433..ea233fb1a2 100644 --- a/native/cocos/core/scene-graph/NodeEventProcessor.h +++ b/native/cocos/core/scene-graph/NodeEventProcessor.h @@ -70,11 +70,11 @@ public: bool hasEventListener(const CallbacksInvoker::KeyType &type) const; - bool hasEventListener(const CallbacksInvoker::KeyType &type, CallbackInfoBase::ID cbID) const; + bool hasEventListener(const CallbacksInvoker::KeyType &type, const CallbackID &cbID) const; bool hasEventListener(const CallbacksInvoker::KeyType &type, void *target) const; - bool hasEventListener(const CallbacksInvoker::KeyType &type, void *target, CallbackInfoBase::ID cbID) const; + bool hasEventListener(const CallbacksInvoker::KeyType &type, void *target, const CallbackID &cbID) const; template bool hasEventListener(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target) const; @@ -82,43 +82,45 @@ public: static bool checkListeners(Node *node, const ccstd::vector &events); template - void on(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackInfoBase::ID &cbID, bool useCapture = false); + void on(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture = false); template void on(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); template - void on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture = false); + void on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture = false); template std::enable_if_t::value, void> - on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture = false); + on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool useCapture = false); template std::enable_if_t::value, void> - on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackInfoBase::ID &cbID, bool useCapture = false); + on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool useCapture = false); template void once(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); template - void once(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackInfoBase::ID &cbID, bool useCapture = false); + void once(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture = false); template - void once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture = false); + void once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture = false); template std::enable_if_t::value, void> - once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture = false); + once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool useCapture = false); template std::enable_if_t::value, void> - once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackInfoBase::ID &cbID, bool useCapture = false); + once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool useCapture = false); - void off(const CallbacksInvoker::KeyType &type, CallbackInfoBase::ID cbID, bool useCapture = false); + void off(const CallbacksInvoker::KeyType &type, const CallbackID &cbID, bool useCapture = false); void off(const CallbacksInvoker::KeyType &type, void *target, bool useCapture = false); + void offAll(const CallbacksInvoker::KeyType &type, bool useCapture = false); + template void off(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); @@ -172,15 +174,15 @@ private: // bool checknSetupSysEvent(const CallbacksInvoker::KeyType &type); template - void onDispatch(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackInfoBase::ID &cbID, bool useCapture = false); + void onDispatch(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture = false); template void onDispatch(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); template - void onDispatch(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture = false); + void onDispatch(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture = false); - void offDispatch(const CallbacksInvoker::KeyType &type, CallbackInfoBase::ID cbID, bool useCapture = false); + void offDispatch(const CallbacksInvoker::KeyType &type, const CallbackID &cbID, bool useCapture = false); void offDispatch(const CallbacksInvoker::KeyType &type, void *target, bool useCapture = false); template @@ -196,7 +198,7 @@ void NodeEventProcessor::emit(const CallbacksInvoker::KeyType &type, Args &&...a } } template -void NodeEventProcessor::onDispatch(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackInfoBase::ID &cbID, bool useCapture) { +void NodeEventProcessor::onDispatch(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture) { CallbacksInvoker *listeners = nullptr; if (useCapture) { if (_capturingTargets == nullptr) { @@ -215,7 +217,7 @@ void NodeEventProcessor::onDispatch(const CallbacksInvoker::KeyType &type, std:: } template -void NodeEventProcessor::onDispatch(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture) { +void NodeEventProcessor::onDispatch(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture) { CallbacksInvoker *listeners = nullptr; if (useCapture) { if (_capturingTargets == nullptr) { @@ -253,7 +255,7 @@ void NodeEventProcessor::onDispatch(const CallbacksInvoker::KeyType &type, void } template -void NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackInfoBase::ID &cbID, bool /*useCapture*/) { +void NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool /*useCapture*/) { // bool forDispatch = checknSetupSysEvent(type); // if (forDispatch) { // onDispatch(type, std::forward>(callback), cbID, useCapture); @@ -267,7 +269,7 @@ void NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, std::function } template -void NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target * /*target*/, CallbackInfoBase::ID &cbID, bool /*useCapture*/) { +void NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target * /*target*/, CallbackID &cbID, bool /*useCapture*/) { // bool forDispatch = checknSetupSysEvent(type); // if (forDispatch) { // onDispatch(type, std::forward>(callback), target, cbID, useCapture); @@ -282,7 +284,7 @@ void NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, std::function template std::enable_if_t::value, void> -NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackInfoBase::ID &cbID, bool /*useCapture*/) { +NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool /*useCapture*/) { // bool forDispatch = checknSetupSysEvent(type); // if (forDispatch) { // onDispatch(type, CallbacksInvoker::toFunction(std::forward(callback)), target, cbID, useCapture); @@ -297,7 +299,7 @@ NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, LambdaType &&callb template std::enable_if_t::value, void> -NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackInfoBase::ID &cbID, bool /*useCapture*/) { +NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool /*useCapture*/) { // bool forDispatch = checknSetupSysEvent(type); // if (forDispatch) { // onDispatch(type, CallbacksInvoker::toFunction(std::forward(callback)), cbID, useCapture); @@ -326,7 +328,7 @@ void NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, void (Target: } template -void NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackInfoBase::ID &cbID, bool useCapture /* = false*/) { +void NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture /* = false*/) { once(type, std::forward(callback), nullptr, cbID, useCapture); } @@ -351,7 +353,7 @@ void NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, void (Targe } template -void NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture) { +void NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture) { CallbacksInvoker *listeners = nullptr; if (useCapture) { if (_capturingTargets == nullptr) { @@ -365,20 +367,20 @@ void NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, std::functi listeners = _bubblingTargets; } listeners->on(type, std::forward>(callback), target, cbID, true); - CallbackInfoBase::ID cacheID = cbID; + CallbackID cacheID{cbID}; listeners->on( type, [=](Args... /*unused*/) { off(type, cacheID); }, target, true); } template std::enable_if_t::value, void> -NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackInfoBase::ID &cbID, bool useCapture) { +NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool useCapture) { once(type, CallbacksInvoker::toFunction(callback), target, cbID, useCapture); } template std::enable_if_t::value, void> -NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackInfoBase::ID &cbID, bool useCapture) { +NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool useCapture) { once(type, std::forward(callback), nullptr, cbID, useCapture); } diff --git a/native/cocos/editor-support/MeshBuffer.h b/native/cocos/editor-support/MeshBuffer.h index bff57fa389..2023dacd4f 100644 --- a/native/cocos/editor-support/MeshBuffer.h +++ b/native/cocos/editor-support/MeshBuffer.h @@ -48,6 +48,16 @@ public: return _ibArr[bufferPos]->getTypeArray(); } + uint8_t *getVBFromBufferArray(std::size_t index) { + if (_vbArr.size() <= index) return nullptr; + return _vbArr[index]->getBuffer(); + } + + uint8_t *getIBFromBufferArray(std::size_t index) { + if (_ibArr.size() <= index) return nullptr; + return _ibArr[index]->getBuffer(); + } + std::size_t getVBTypedArrayLength(std::size_t bufferPos) { if (_vbArr.size() <= bufferPos) return 0; return _vbArr[bufferPos]->length(); diff --git a/native/cocos/editor-support/MiddlewareMacro.h b/native/cocos/editor-support/MiddlewareMacro.h index f609ffa95c..81899fa2ce 100644 --- a/native/cocos/editor-support/MiddlewareMacro.h +++ b/native/cocos/editor-support/MiddlewareMacro.h @@ -24,8 +24,8 @@ ****************************************************************************/ #pragma once -// index buffer init capacity -#define INIT_INDEX_BUFFER_SIZE 1024000 +// index buffer init capacity 8 * vertex size +#define INIT_INDEX_BUFFER_SIZE 524280 // max vertex buffer size #define MAX_VERTEX_BUFFER_SIZE 65535 // render info int capacity diff --git a/native/cocos/editor-support/dragonbones/core/DragonBones.cpp b/native/cocos/editor-support/dragonbones/core/DragonBones.cpp index 18e7a7f3e5..27e4ca216b 100644 --- a/native/cocos/editor-support/dragonbones/core/DragonBones.cpp +++ b/native/cocos/editor-support/dragonbones/core/DragonBones.cpp @@ -28,6 +28,7 @@ DragonBones::~DragonBones() { } _clock = nullptr; + delete _eventManager; _eventManager = nullptr; } diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.cpp b/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.cpp index 3664ce0376..1f02e7df75 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.cpp +++ b/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.cpp @@ -66,6 +66,14 @@ public: SkeletonDataMgr *SkeletonDataMgr::instance = nullptr; +SkeletonDataMgr::~SkeletonDataMgr() { + _destroyCallback = nullptr; + for (auto &e : _dataMap) { + delete e.second; + } + _dataMap.clear(); +} + bool SkeletonDataMgr::hasSkeletonData(const std::string &uuid) { auto it = _dataMap.find(uuid); return it != _dataMap.end(); diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.h b/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.h index a43768a093..197a881060 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.h +++ b/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.h @@ -44,7 +44,7 @@ class SkeletonDataInfo; /** * Cache skeleton data. */ -class SkeletonDataMgr { +class SkeletonDataMgr final { public: static SkeletonDataMgr *getInstance() { if (instance == nullptr) { @@ -61,10 +61,8 @@ public: } SkeletonDataMgr() = default; + ~SkeletonDataMgr(); - virtual ~SkeletonDataMgr() { - _destroyCallback = nullptr; - } bool hasSkeletonData(const std::string &uuid); void setSkeletonData(const std::string &uuid, SkeletonData *data, Atlas *atlas, AttachmentLoader *attachmentLoader, const std::vector &texturesIndex); // equal to 'findByUUID' diff --git a/native/cocos/engine/Engine.cpp b/native/cocos/engine/Engine.cpp index 1f554b7822..bcf21e6b38 100644 --- a/native/cocos/engine/Engine.cpp +++ b/native/cocos/engine/Engine.cpp @@ -96,10 +96,15 @@ bool setCanvasCallback(se::Object * /*global*/) { namespace cc { -Engine::Engine() = default; +Engine::Engine() { + _scriptEngine = ccnew se::ScriptEngine(); +} Engine::~Engine() { destroy(); + + delete _scriptEngine; + _scriptEngine = nullptr; } int32_t Engine::init() { @@ -118,7 +123,6 @@ int32_t Engine::init() { _profiler = ccnew Profiler(); #endif - _scriptEngine = ccnew se::ScriptEngine(); EventDispatcher::init(); BasePlatform *platform = BasePlatform::getPlatform(); @@ -136,6 +140,7 @@ int32_t Engine::init() { void Engine::destroy() { cc::DeferredReleasePool::clear(); + cc::network::HttpClient::destroyInstance(); _scheduler->removeAllFunctionsToBePerformedInCocosThread(); _scheduler->unscheduleAll(); CCObject::deferredDestroy(); @@ -148,7 +153,9 @@ void Engine::destroy() { // Should delete it before deleting DeviceManager as ScriptEngine will check gpu resource usage, // and ScriptEngine will hold gfx objects. - delete _scriptEngine; + // Because the user registration interface needs to be added during initialization. + // ScriptEngine cannot be released here. + _scriptEngine->cleanup(); #if CC_USE_PROFILER delete _profiler; @@ -271,7 +278,7 @@ void Engine::tick() { ++_totalFrames; // iOS/macOS use its own fps limitation algorithm. -#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_WINDOWS || CC_PLATFORM == CC_PLATFORM_OHOS) +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_WINDOWS || 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/engine/Engine.h b/native/cocos/engine/Engine.h index 9bc26a9bf5..2a37e22a9c 100644 --- a/native/cocos/engine/Engine.h +++ b/native/cocos/engine/Engine.h @@ -137,7 +137,7 @@ private: bool _close{false}; bool _pause{false}; bool _resune{false}; - std::shared_ptr _scheduler{nullptr}; + SchedulerPtr _scheduler{nullptr}; int64_t _prefererredNanosecondsPerFrame{NANOSECONDS_60FPS}; uint _totalFrames{0}; cc::Vec2 _viewLogicalSize{0, 0}; diff --git a/native/cocos/network/HttpClient-apple.mm b/native/cocos/network/HttpClient-apple.mm index 43f5faf575..f1af05e248 100644 --- a/native/cocos/network/HttpClient-apple.mm +++ b/native/cocos/network/HttpClient-apple.mm @@ -36,12 +36,14 @@ #include "application/ApplicationManager.h" #include "base/Scheduler.h" #include "base/memory/Memory.h" +#include "base/ThreadPool.h" namespace cc { namespace network { static HttpClient *_httpClient = nullptr; // pointer to singleton +static LegacyThreadPool *gThreadPool = nullptr; static int processTask(HttpClient *client, HttpRequest *request, NSString *requestType, void *stream, long *errorCode, void *headerStream, char *errorBuffer); @@ -336,6 +338,9 @@ HttpClient::HttpClient() _threadCount(0), _cookie(nullptr) { CC_LOG_DEBUG("In the constructor of HttpClient!"); + if (gThreadPool == nullptr) { + gThreadPool = LegacyThreadPool::newFixedThreadPool(4); + } _requestSentinel = ccnew HttpRequest(); _requestSentinel->addRef(); memset(_responseMessage, 0, sizeof(char) * RESPONSE_BUFFER_SIZE); @@ -395,8 +400,7 @@ void HttpClient::sendImmediate(HttpRequest *request) { HttpResponse *response = ccnew HttpResponse(request); response->addRef(); // NOTE: RefCounted object's reference count is changed to 0 now. so needs to addRef after ccnew. - auto t = std::thread(&HttpClient::networkThreadAlone, this, request, response); - t.detach(); + gThreadPool->pushTask([this, request, response](int /*tid*/) { HttpClient::networkThreadAlone(request, response); }); } // Poll and notify main thread if responses exists in queue diff --git a/native/cocos/network/HttpClient-java.cpp b/native/cocos/network/HttpClient-java.cpp index 82eafc089f..3ac5c1644f 100644 --- a/native/cocos/network/HttpClient-java.cpp +++ b/native/cocos/network/HttpClient-java.cpp @@ -33,6 +33,7 @@ #include #include "application/ApplicationManager.h" #include "base/Log.h" +#include "base/ThreadPool.h" #include "base/UTF8.h" #include "base/std/container/queue.h" #include "platform/FileUtils.h" @@ -52,6 +53,7 @@ using HttpCookies = ccstd::vector; using HttpCookiesIter = HttpCookies::iterator; static HttpClient *gHttpClient = nullptr; // pointer to singleton +static LegacyThreadPool *gThreadPool = nullptr; struct CookiesInfo { ccstd::string domain; @@ -121,8 +123,8 @@ public: if (!headers.empty()) { /* append custom headers one by one */ for (auto &header : headers) { - int len = header.length(); - int pos = header.find(':'); + uint32_t len = header.length(); + uint32_t pos = header.find(':'); if (-1 == pos || pos >= len) { continue; } @@ -213,7 +215,7 @@ public: "sendRequest", "(Ljava/net/HttpURLConnection;[B)V")) { jbyteArray bytearray; - ssize_t dataSize = request->getRequestDataSize(); + auto dataSize = static_cast(request->getRequestDataSize()); bytearray = methodInfo.env->NewByteArray(dataSize); methodInfo.env->SetByteArrayRegion(bytearray, 0, dataSize, reinterpret_cast(request->getRequestData())); methodInfo.env->CallStaticVoidMethod( @@ -595,13 +597,13 @@ void HttpClient::processResponse(HttpResponse *response, char *responseMessage) return; } - int64_t responseCode = -1; + long responseCode = -1L; // NOLINT int retValue = 0; HttpURLConnection urlConnection(this); if (!urlConnection.init(request)) { response->setSucceed(false); - response->setErrorBuffer("HttpURLConnetcion init failed"); + response->setErrorBuffer("HttpURLConnection init failed"); return; } @@ -633,7 +635,7 @@ void HttpClient::processResponse(HttpResponse *response, char *responseMessage) if (0 != suc) { response->setSucceed(false); response->setErrorBuffer("connect failed"); - response->setResponseCode(static_cast(responseCode)); + response->setResponseCode(responseCode); return; } @@ -683,7 +685,7 @@ void HttpClient::processResponse(HttpResponse *response, char *responseMessage) urlConnection.disconnect(); // write data to HttpResponse - response->setResponseCode(static_cast(responseCode)); + response->setResponseCode(responseCode); if (responseCode == -1) { response->setSucceed(false); @@ -831,6 +833,10 @@ HttpClient::HttpClient() _cookie(nullptr), _requestSentinel(ccnew HttpRequest()) { CC_LOG_DEBUG("In the constructor of HttpClient!"); + _requestSentinel->addRef(); + if (gThreadPool == nullptr) { + gThreadPool = LegacyThreadPool::newFixedThreadPool(4); + } increaseThreadCount(); _scheduler = CC_CURRENT_ENGINE()->getScheduler(); } @@ -882,8 +888,8 @@ void HttpClient::sendImmediate(HttpRequest *request) { // Create a HttpResponse object, the default setting is http access failed auto *response = ccnew HttpResponse(request); response->addRef(); // NOTE: RefCounted object's reference count is changed to 0 now. so needs to addRef after ccnew. - auto t = std::thread(&HttpClient::networkThreadAlone, this, request, response); - t.detach(); + + gThreadPool->pushTask([this, request, response](int /*tid*/) { HttpClient::networkThreadAlone(request, response); }); } // Poll and notify main thread if responses exists in queue diff --git a/native/cocos/network/HttpClient.cpp b/native/cocos/network/HttpClient.cpp index a202ceb7ed..f7f9650b2c 100644 --- a/native/cocos/network/HttpClient.cpp +++ b/native/cocos/network/HttpClient.cpp @@ -31,6 +31,7 @@ #include #include "application/ApplicationManager.h" #include "base/Log.h" +#include "base/ThreadPool.h" #include "base/memory/Memory.h" #include "platform/FileUtils.h" #include "platform/StdC.h" @@ -44,6 +45,7 @@ typedef int int32_t; #endif static HttpClient *_httpClient = nullptr; // pointer to singleton +static LegacyThreadPool *gThreadPool = nullptr; typedef size_t (*write_callback)(void *ptr, size_t size, size_t nmemb, void *stream); @@ -363,6 +365,10 @@ HttpClient::HttpClient() _cookie(nullptr), _requestSentinel(ccnew HttpRequest()) { CC_LOG_DEBUG("In the constructor of HttpClient!"); + _requestSentinel->addRef(); + if (gThreadPool == nullptr) { + gThreadPool = LegacyThreadPool::newFixedThreadPool(4); + } memset(_responseMessage, 0, RESPONSE_BUFFER_SIZE * sizeof(char)); _scheduler = CC_CURRENT_ENGINE()->getScheduler(); increaseThreadCount(); @@ -416,8 +422,7 @@ void HttpClient::sendImmediate(HttpRequest *request) { HttpResponse *response = ccnew HttpResponse(request); response->addRef(); // NOTE: RefCounted object's reference count is changed to 0 now. so needs to addRef after ccnew. - auto t = std::thread(&HttpClient::networkThreadAlone, this, request, response); - t.detach(); + gThreadPool->pushTask([this, request, response](int /*tid*/) { HttpClient::networkThreadAlone(request, response); }); } // Poll and notify main thread if responses exists in queue diff --git a/native/cocos/network/WebSocket-libwebsockets.cpp b/native/cocos/network/WebSocket-libwebsockets.cpp index 047ac765a0..7fa9f276fc 100644 --- a/native/cocos/network/WebSocket-libwebsockets.cpp +++ b/native/cocos/network/WebSocket-libwebsockets.cpp @@ -818,7 +818,9 @@ void WebSocketImpl::close() { } void WebSocketImpl::closeAsync(int code, const ccstd::string &reason) { - lws_close_reason(_wsInstance, static_cast(code), reinterpret_cast(const_cast(reason.c_str())), reason.length()); + if (_wsInstance) { + lws_close_reason(_wsInstance, static_cast(code), reinterpret_cast(const_cast(reason.c_str())), reason.length()); + } closeAsync(); } diff --git a/native/cocos/platform/android/AndroidPlatform.cpp b/native/cocos/platform/android/AndroidPlatform.cpp index a91e82d7c5..8d5e6658dc 100644 --- a/native/cocos/platform/android/AndroidPlatform.cpp +++ b/native/cocos/platform/android/AndroidPlatform.cpp @@ -206,13 +206,24 @@ public: if (motionEvent->pointerCount > 0) { int action = motionEvent->action; int actionMasked = action & AMOTION_EVENT_ACTION_MASK; + int eventChangedIndex = -1; if (actionMasked == AMOTION_EVENT_ACTION_DOWN || actionMasked == AMOTION_EVENT_ACTION_POINTER_DOWN) { + if (actionMasked == AMOTION_EVENT_ACTION_POINTER_DOWN) { + eventChangedIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; + } else { + eventChangedIndex = 0; + } touchEvent.type = cc::TouchEvent::Type::BEGAN; } else if (actionMasked == AMOTION_EVENT_ACTION_UP || actionMasked == AMOTION_EVENT_ACTION_POINTER_UP) { touchEvent.type = cc::TouchEvent::Type::ENDED; + if (actionMasked == AMOTION_EVENT_ACTION_POINTER_UP) { + eventChangedIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; + } else { + eventChangedIndex = 0; + } } else if (actionMasked == AMOTION_EVENT_ACTION_CANCEL) { touchEvent.type = cc::TouchEvent::Type::CANCELLED; } else if (actionMasked == AMOTION_EVENT_ACTION_MOVE) { @@ -221,12 +232,14 @@ public: return false; } - for (int i = 0; i < motionEvent->pointerCount; i++) { - int id = motionEvent->pointers[i].id; - float x = GameActivityPointerAxes_getX(&motionEvent->pointers[i]); - float y = GameActivityPointerAxes_getY(&motionEvent->pointers[i]); - touchEvent.touches.emplace_back(x, y, id); + if (eventChangedIndex >= 0) { + addTouchEvent(eventChangedIndex, motionEvent); + } else { + for (int i = 0; i < motionEvent->pointerCount; i++) { + addTouchEvent(i, motionEvent); + } } + _androidPlatform->dispatchEvent(touchEvent); touchEvent.touches.clear(); return true; @@ -409,6 +422,16 @@ public: } private: + static void addTouchEvent(int index, GameActivityMotionEvent *motionEvent) { + if (index < 0 || index >= motionEvent->pointerCount) { + ABORT_IF(false); + } + int id = motionEvent->pointers[index].id; + float x = GameActivityPointerAxes_getX(&motionEvent->pointers[index]); + float y = GameActivityPointerAxes_getY(&motionEvent->pointers[index]); + touchEvent.touches.emplace_back(x, y, id); + } + AppEventCallback _eventCallback{nullptr}; AndroidPlatform *_androidPlatform{nullptr}; JNIEnv *_jniEnv{nullptr}; // JNI environment diff --git a/native/cocos/platform/android/java/src/com/cocos/lib/CocosActivity.java b/native/cocos/platform/android/java/src/com/cocos/lib/CocosActivity.java index fbd5f6e65a..240046251e 100644 --- a/native/cocos/platform/android/java/src/com/cocos/lib/CocosActivity.java +++ b/native/cocos/platform/android/java/src/com/cocos/lib/CocosActivity.java @@ -26,6 +26,7 @@ package com.cocos.lib; import android.app.Activity; import android.content.Context; +import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.media.AudioManager; @@ -79,7 +80,10 @@ public class CocosActivity extends GameActivity { Utils.hideVirtualButton(); - mOrientationHelper = new CocosOrientationHelper(this); + int orientation = getRequestedOrientation(); + if (orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) { + mOrientationHelper = new CocosOrientationHelper(this); + } } private void setImmersiveMode() { @@ -133,14 +137,18 @@ public class CocosActivity extends GameActivity { protected void onPause() { super.onPause(); mSensorHandler.onPause(); - mOrientationHelper.onPause(); + if (null != mOrientationHelper) { + mOrientationHelper.onPause(); + } } @Override protected void onResume() { super.onResume(); mSensorHandler.onResume(); - mOrientationHelper.onResume(); + if (null != mOrientationHelper) { + mOrientationHelper.onResume(); + } Utils.hideVirtualButton(); if (CocosAudioFocusManager.isAudioFocusLoss()) { CocosAudioFocusManager.registerAudioFocusListener(this); diff --git a/native/cocos/platform/apple/JsbBridge.mm b/native/cocos/platform/apple/JsbBridge.mm index c765bcc6a1..908f6325c7 100644 --- a/native/cocos/platform/apple/JsbBridge.mm +++ b/native/cocos/platform/apple/JsbBridge.mm @@ -64,7 +64,9 @@ static JsbBridge *instance = nil; - (id)init { if (self = [super init]) { cc::EventDispatcher::addCustomEventListener(EVENT_CLOSE, [&](const cc::CustomEvent& event){ - [[JsbBridge sharedInstance] release]; + if ([JsbBridge sharedInstance] != nil) { + [[JsbBridge sharedInstance] release]; + } }); } return self; diff --git a/native/cocos/platform/apple/JsbBridgeWrapper.mm b/native/cocos/platform/apple/JsbBridgeWrapper.mm index 4db4627ae1..0699c7c2ae 100644 --- a/native/cocos/platform/apple/JsbBridgeWrapper.mm +++ b/native/cocos/platform/apple/JsbBridgeWrapper.mm @@ -117,7 +117,9 @@ static ICallback cb = ^void(NSString* _event, NSString* _arg) { } [jb setCallback:cb]; cc::EventDispatcher::addCustomEventListener(EVENT_CLOSE, [&](const cc::CustomEvent& event){ - [[JsbBridgeWrapper sharedInstance] release]; + if ([JsbBridgeWrapper sharedInstance] != nil) { + [[JsbBridgeWrapper sharedInstance] release]; + } }); } return self; diff --git a/native/cocos/platform/interfaces/OSInterfaceManager.cpp b/native/cocos/platform/interfaces/OSInterfaceManager.cpp deleted file mode 100644 index dbdea90975..0000000000 --- a/native/cocos/platform/interfaces/OSInterfaceManager.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/**************************************************************************** - 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. -****************************************************************************/ diff --git a/native/cocos/platform/interfaces/OSInterfaceManager.h b/native/cocos/platform/interfaces/OSInterfaceManager.h deleted file mode 100644 index 0ec5195686..0000000000 --- a/native/cocos/platform/interfaces/OSInterfaceManager.h +++ /dev/null @@ -1,39 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021-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. -****************************************************************************/ - -#pragma once - -#include "base/Macros.h" - -namespace cc { - -class CC_DLL OSInterfaceManager { -public: - virtual ~OSInterfaceManager() = default; - -private: -}; - -} // namespace cc diff --git a/native/cocos/platform/mac/MacPlatform.mm b/native/cocos/platform/mac/MacPlatform.mm index 955813e288..b43cb7e656 100644 --- a/native/cocos/platform/mac/MacPlatform.mm +++ b/native/cocos/platform/mac/MacPlatform.mm @@ -121,9 +121,17 @@ int32_t MacPlatform::loop(void) { } int32_t MacPlatform::run(int argc, const char **argv) { +#if defined(CC_SERVER_MODE) + cocos_main(argc, argv); + while (true) { + runTask(); + } + return 0; +#else id delegate = [[AppDelegate alloc] init]; NSApplication.sharedApplication.delegate = delegate; return NSApplicationMain(argc, argv); +#endif } void MacPlatform::setFps(int32_t fps) { diff --git a/native/cocos/platform/mac/modules/SystemWindow.mm b/native/cocos/platform/mac/modules/SystemWindow.mm index e6c88fb325..64744d3e14 100644 --- a/native/cocos/platform/mac/modules/SystemWindow.mm +++ b/native/cocos/platform/mac/modules/SystemWindow.mm @@ -47,9 +47,7 @@ bool SystemWindow::createWindow(const char *title, _height = h; AppDelegate *delegate = [[NSApplication sharedApplication] delegate]; NSString *aString = [NSString stringWithUTF8String:title]; -#if !defined(CC_SERVER_MODE) [delegate createLeftBottomWindow:aString width:w height:h]; -#endif return true; } @@ -64,9 +62,7 @@ bool SystemWindow::createWindow(const char *title, _height = h; AppDelegate *delegate = [[NSApplication sharedApplication] delegate]; NSString *aString = [NSString stringWithUTF8String:title]; -#if !defined(CC_SERVER_MODE) [delegate createWindow:aString xPos:x yPos:y width:w height:h]; -#endif return true; } void SystemWindow::closeWindow() { diff --git a/native/cocos/renderer/gfx-agent/BufferAgent.cpp b/native/cocos/renderer/gfx-agent/BufferAgent.cpp index 3f8ef82282..3478a32d13 100644 --- a/native/cocos/renderer/gfx-agent/BufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/BufferAgent.cpp @@ -38,11 +38,16 @@ BufferAgent::BufferAgent(Buffer *actor) } BufferAgent::~BufferAgent() { - ENQUEUE_MESSAGE_1( + ENQUEUE_MESSAGE_2( DeviceAgent::getInstance()->getMessageQueue(), BufferDestruct, actor, _actor, + stagingBuffers, _stagingBuffers, { + for (auto *buffer : stagingBuffers) { + free(buffer); + } + CC_SAFE_DELETE(actor); }); } diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index 792c72a977..6be244a7db 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -1339,6 +1339,7 @@ struct ALIGNAS(8) GeneralBarrierInfo { AccessFlags nextAccesses{AccessFlagBit::NONE}; BarrierType type{BarrierType::FULL}; + uint32_t _padding{0}; EXPOSE_COPY_FN(GeneralBarrierInfo) }; diff --git a/native/cocos/renderer/gfx-base/SPIRVUtils.cpp b/native/cocos/renderer/gfx-base/SPIRVUtils.cpp index 546e67f539..10b73f7b8c 100644 --- a/native/cocos/renderer/gfx-base/SPIRVUtils.cpp +++ b/native/cocos/renderer/gfx-base/SPIRVUtils.cpp @@ -59,7 +59,12 @@ glslang::EShTargetClientVersion getClientVersion(int vulkanMinorVersion) { case 1: return glslang::EShTargetVulkan_1_1; case 2: return glslang::EShTargetVulkan_1_2; #if GLSLANG_VERSION_LESS_OR_EQUAL_TO(11, 10, 0) + // This macro is defined in glslang/build_info.h. This expression means that the + // lib version is greater than or equal to 11.10.0 (not less than or equal to), + // which is very counterintuitive. But it's the only way to do it. case 3: return glslang::EShTargetVulkan_1_3; +#else + case 3: return glslang::EShTargetVulkan_1_2; #endif default: { CC_ASSERT(false); @@ -74,7 +79,12 @@ glslang::EShTargetLanguageVersion getTargetVersion(int vulkanMinorVersion) { case 1: return glslang::EShTargetSpv_1_3; case 2: return glslang::EShTargetSpv_1_5; #if GLSLANG_VERSION_LESS_OR_EQUAL_TO(11, 10, 0) + // This macro is defined in glslang/build_info.h. This expression means that the + // lib version is greater than or equal to 11.10.0 (not less than or equal to), + // which is very counterintuitive. But it's the only way to do it. case 3: return glslang::EShTargetSpv_1_6; +#else + case 3: return glslang::EShTargetSpv_1_5; #endif default: { CC_ASSERT(false); diff --git a/native/cocos/renderer/gfx-metal/MTLSemaphore.h b/native/cocos/renderer/gfx-metal/MTLSemaphore.h index 011e4eb5dc..ab25a06071 100644 --- a/native/cocos/renderer/gfx-metal/MTLSemaphore.h +++ b/native/cocos/renderer/gfx-metal/MTLSemaphore.h @@ -35,7 +35,16 @@ public: explicit CCMTLSemaphore(uint32_t initialValue) : _semaphoreCount(initialValue) { _semaphore = dispatch_semaphore_create(initialValue); } - ~CCMTLSemaphore() = default; + + ~CCMTLSemaphore() { + if (_semaphore) { + for (size_t i = 0; i < _semaphoreCount; ++i) { + dispatch_semaphore_signal(_semaphore); + } + dispatch_release(_semaphore); + _semaphore = nullptr; + } + }; CCMTLSemaphore(const CCMTLSemaphore &) = delete; CCMTLSemaphore(CCMTLSemaphore &&) = delete; CCMTLSemaphore &operator=(const CCMTLSemaphore &) = delete; diff --git a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp index 3da6327b8a..3706f99643 100644 --- a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp @@ -36,6 +36,7 @@ #include "platform/interfaces/modules/ISystemWindow.h" #if CC_SWAPPY_ENABLED + #include "platform/android/AndroidPlatform.h" #include "swappy/swappyVk.h" #include "swappy/swappy_common.h" #endif @@ -223,6 +224,7 @@ void CCVKSwapchain::doInit(const SwapchainInfo &info) { int32_t fps = cc::BasePlatform::getPlatform()->getFps(); uint64_t frameRefreshIntervalNS; + auto *platform = static_cast(cc::BasePlatform::getPlatform()); SwappyVk_initAndGetRefreshCycleDuration(static_cast(platform->getEnv()), static_cast(platform->getActivity()), gpuContext->physicalDevice, @@ -309,8 +311,6 @@ bool CCVKSwapchain::checkSwapchainStatus(uint32_t width, uint32_t height) { destroySwapchain(gpuDevice); - gpuDevice->curBackBufferIndex = 0; - _gpuSwapchain->curImageIndex = 0; _gpuSwapchain->vkSwapchain = vkSwapchain; uint32_t imageCount; @@ -370,7 +370,7 @@ bool CCVKSwapchain::checkSwapchainStatus(uint32_t width, uint32_t height) { return true; } -void CCVKSwapchain::destroySwapchain(const CCVKGPUDevice *gpuDevice) { +void CCVKSwapchain::destroySwapchain(CCVKGPUDevice *gpuDevice) { if (_gpuSwapchain->vkSwapchain != VK_NULL_HANDLE) { for (auto &it : _gpuSwapchain->vkSwapchainFramebufferListMap) { FramebufferList &list = it.second; @@ -388,12 +388,15 @@ void CCVKSwapchain::destroySwapchain(const CCVKGPUDevice *gpuDevice) { vkDestroySwapchainKHR(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, nullptr); _gpuSwapchain->vkSwapchain = VK_NULL_HANDLE; + // reset index only after device not ready + _gpuSwapchain->curImageIndex = 0; + gpuDevice->curBackBufferIndex = 0; } } void CCVKSwapchain::doDestroySurface() { if (!_gpuSwapchain || _gpuSwapchain->vkSurface == VK_NULL_HANDLE) return; - const auto *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + auto *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); const auto *gpuContext = CCVKDevice::getInstance()->gpuContext(); CCVKDevice::getInstance()->waitAllFences(); diff --git a/native/cocos/renderer/gfx-vulkan/VKSwapchain.h b/native/cocos/renderer/gfx-vulkan/VKSwapchain.h index f44cfa95be..6655e3b961 100644 --- a/native/cocos/renderer/gfx-vulkan/VKSwapchain.h +++ b/native/cocos/renderer/gfx-vulkan/VKSwapchain.h @@ -56,7 +56,7 @@ protected: void doCreateSurface(void *windowHandle) override; void createVkSurface(); - void destroySwapchain(const CCVKGPUDevice *gpuDevice); + void destroySwapchain(CCVKGPUDevice *gpuDevice); CCVKGPUSwapchain *_gpuSwapchain = nullptr; }; diff --git a/native/cocos/renderer/pipeline/PlanarShadowQueue.cpp b/native/cocos/renderer/pipeline/PlanarShadowQueue.cpp index b1e478cd9e..a31cd8bee1 100644 --- a/native/cocos/renderer/pipeline/PlanarShadowQueue.cpp +++ b/native/cocos/renderer/pipeline/PlanarShadowQueue.cpp @@ -47,7 +47,9 @@ PlanarShadowQueue::PlanarShadowQueue(RenderPipeline *pipeline) _instancedQueue = ccnew RenderInstancedQueue; } -PlanarShadowQueue::~PlanarShadowQueue() = default; +PlanarShadowQueue::~PlanarShadowQueue() { + destroy(); +} void PlanarShadowQueue::gatherShadowPasses(scene::Camera *camera, gfx::CommandBuffer *cmdBuffer) { clear(); @@ -138,7 +140,10 @@ void PlanarShadowQueue::recordCommandBuffer(gfx::Device *device, gfx::RenderPass } void PlanarShadowQueue::destroy() { + _pipeline = nullptr; CC_SAFE_DELETE(_instancedQueue); + _castModels.clear(); + _pendingModels.clear(); } } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/RenderFlow.cpp b/native/cocos/renderer/pipeline/RenderFlow.cpp index 2cb35655a9..53db4142c3 100644 --- a/native/cocos/renderer/pipeline/RenderFlow.cpp +++ b/native/cocos/renderer/pipeline/RenderFlow.cpp @@ -40,6 +40,7 @@ bool RenderFlow::initialize(const RenderFlowInfo &info) { _priority = info.priority; _tag = info.tag; _stages = info.stages; + _isResourceOwner = false; return true; } @@ -62,8 +63,14 @@ void RenderFlow::render(scene::Camera *camera) { } void RenderFlow::destroy() { - for (auto *stage : _stages) { - CC_SAFE_DESTROY_AND_DELETE(stage); + if (_isResourceOwner) { + for (auto *stage : _stages) { + CC_SAFE_DESTROY_AND_DELETE(stage); + } + } else { + for (auto *stage : _stages) { + CC_SAFE_DESTROY(stage); + } } _stages.clear(); diff --git a/native/cocos/renderer/pipeline/RenderFlow.h b/native/cocos/renderer/pipeline/RenderFlow.h index ccd5b86f7b..14403b9eeb 100644 --- a/native/cocos/renderer/pipeline/RenderFlow.h +++ b/native/cocos/renderer/pipeline/RenderFlow.h @@ -65,6 +65,7 @@ protected: RenderPipeline *_pipeline{nullptr}; uint32_t _priority{0}; uint32_t _tag{0}; + bool _isResourceOwner{false}; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/RenderPipeline.cpp b/native/cocos/renderer/pipeline/RenderPipeline.cpp index 59cf29464a..9adbf014c8 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.cpp +++ b/native/cocos/renderer/pipeline/RenderPipeline.cpp @@ -75,6 +75,7 @@ RenderPipeline::~RenderPipeline() { bool RenderPipeline::initialize(const RenderPipelineInfo &info) { _flows = info.flows; _tag = info.tag; + _isResourceOwner = false; return true; } @@ -149,8 +150,14 @@ void RenderPipeline::updateGeometryRenderer(const ccstd::vector #endif bool RenderPipeline::destroy() { - for (auto *flow : _flows) { - CC_SAFE_DESTROY_AND_DELETE(flow); + if (_isResourceOwner) { + for (auto *flow : _flows) { + CC_SAFE_DESTROY_AND_DELETE(flow); + } + } else { + for (auto *flow : _flows) { + CC_SAFE_DESTROY(flow); + } } _flows.clear(); diff --git a/native/cocos/renderer/pipeline/RenderPipeline.h b/native/cocos/renderer/pipeline/RenderPipeline.h index d75a2470a0..b5d0cbc058 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.h +++ b/native/cocos/renderer/pipeline/RenderPipeline.h @@ -187,6 +187,7 @@ protected: bool _clusterEnabled{false}; bool _bloomEnabled{false}; bool _occlusionQueryEnabled{false}; + bool _isResourceOwner{false}; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp b/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp index 41aedc2b14..dceaa05585 100644 --- a/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp +++ b/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp @@ -76,6 +76,8 @@ bool DeferredPipeline::initialize(const RenderPipelineInfo &info) { RenderPipeline::initialize(info); if (_flows.empty()) { + _isResourceOwner = true; + auto *shadowFlow = ccnew ShadowFlow; shadowFlow->initialize(ShadowFlow::getInitializeInfo()); _flows.emplace_back(shadowFlow); diff --git a/native/cocos/renderer/pipeline/deferred/MainFlow.cpp b/native/cocos/renderer/pipeline/deferred/MainFlow.cpp index 7601e9710f..5827b4ea3d 100644 --- a/native/cocos/renderer/pipeline/deferred/MainFlow.cpp +++ b/native/cocos/renderer/pipeline/deferred/MainFlow.cpp @@ -50,6 +50,8 @@ bool MainFlow::initialize(const RenderFlowInfo &info) { RenderFlow::initialize(info); if (_stages.empty()) { + _isResourceOwner = true; + auto *gbufferStage = ccnew GbufferStage; gbufferStage->initialize(GbufferStage::getInitializeInfo()); _stages.emplace_back(gbufferStage); diff --git a/native/cocos/renderer/pipeline/forward/ForwardFlow.cpp b/native/cocos/renderer/pipeline/forward/ForwardFlow.cpp index 0907a2e88c..feb0e3487e 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardFlow.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardFlow.cpp @@ -45,6 +45,8 @@ bool ForwardFlow::initialize(const RenderFlowInfo &info) { RenderFlow::initialize(info); if (_stages.empty()) { + _isResourceOwner = true; + auto *forwardStage = ccnew ForwardStage; forwardStage->initialize(ForwardStage::getInitializeInfo()); _stages.emplace_back(forwardStage); diff --git a/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp b/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp index 5330638725..9200453d0b 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp @@ -59,6 +59,8 @@ bool ForwardPipeline::initialize(const RenderPipelineInfo &info) { RenderPipeline::initialize(info); if (_flows.empty()) { + _isResourceOwner = true; + auto *shadowFlow = ccnew ShadowFlow; shadowFlow->initialize(ShadowFlow::getInitializeInfo()); _flows.emplace_back(shadowFlow); diff --git a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp index fb1fb06abd..538757807f 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp @@ -90,7 +90,7 @@ void ForwardStage::destroy() { CC_SAFE_DELETE(_batchedQueue); CC_SAFE_DELETE(_instancedQueue); CC_SAFE_DELETE(_additiveLightQueue); - CC_SAFE_DELETE(_planarShadowQueue); + CC_SAFE_DESTROY_AND_DELETE(_planarShadowQueue); CC_SAFE_DELETE(_uiPhase); RenderStage::destroy(); } diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp index 4a9f72d723..339bce004d 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp +++ b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp @@ -58,6 +58,8 @@ ShadowFlow::~ShadowFlow() = default; bool ShadowFlow::initialize(const RenderFlowInfo &info) { RenderFlow::initialize(info); if (_stages.empty()) { + _isResourceOwner = true; + auto *shadowStage = ccnew ShadowStage; shadowStage->initialize(ShadowStage::getInitializeInfo()); _stages.emplace_back(shadowStage); diff --git a/native/cocos/scene/Camera.cpp b/native/cocos/scene/Camera.cpp index a51bf1a0b5..26ac4471b2 100644 --- a/native/cocos/scene/Camera.cpp +++ b/native/cocos/scene/Camera.cpp @@ -250,8 +250,9 @@ geometry::Ray Camera::screenPointToRay(float x, float y) { (x - cx) / cw * 2 - 1.F, (y - cy) / ch * 2 - 1.F, isProj ? 1.F : -1.F}; - tmpVec3.x = tmpVec3.x * preTransform[0] + tmpVec3.y * preTransform[2] * ySign; - tmpVec3.y = tmpVec3.x * preTransform[1] + tmpVec3.y * preTransform[3] * ySign; + float tmpX = tmpVec3.x; + tmpVec3.x = tmpX * preTransform[0] + tmpVec3.y * preTransform[2] * ySign; + tmpVec3.y = tmpX * preTransform[1] + tmpVec3.y * preTransform[3] * ySign; geometry::Ray out; if (isProj) { @@ -265,7 +266,7 @@ geometry::Ray Camera::screenPointToRay(float x, float y) { geometry::Ray::fromPoints(&out, _node->getWorldPosition(), tmpVec3); } else { out.d.set(0, 0, -1.F); - out.d.transformQuat(_node->getRotation()); + out.d.transformQuat(_node->getWorldRotation()); } return out; @@ -288,8 +289,9 @@ Vec3 Camera::screenToWorld(const Vec3 &screenPos) { 1.0F); // transform to world - out.x = out.x * preTransform[0] + out.y * preTransform[2] * ySign; - out.y = out.x * preTransform[1] + out.y * preTransform[3] * ySign; + float tmpX = out.x; + out.x = tmpX * preTransform[0] + out.y * preTransform[2] * ySign; + out.y = tmpX * preTransform[1] + out.y * preTransform[3] * ySign; out.transformMat4(out, _matViewProjInv); // lerp to depth z Vec3 tmpVec3; @@ -305,8 +307,9 @@ Vec3 Camera::screenToWorld(const Vec3 &screenPos) { screenPos.z * 2 - 1); // transform to world - out.x = out.x * preTransform[0] + out.y * preTransform[2] * ySign; - out.y = out.x * preTransform[1] + out.y * preTransform[3] * ySign; + float tmpX = out.x; + out.x = tmpX * preTransform[0] + out.y * preTransform[2] * ySign; + out.y = tmpX * preTransform[1] + out.y * preTransform[3] * ySign; out.transformMat4(out, _matViewProjInv); } @@ -319,8 +322,9 @@ Vec3 Camera::worldToScreen(const Vec3 &worldPos) { Vec3 out; Vec3::transformMat4(worldPos, _matViewProj, &out); - out.x = out.x * preTransform[0] + out.y * preTransform[2] * ySign; - out.y = out.x * preTransform[1] + out.y * preTransform[3] * ySign; + float tmpX = out.x; + out.x = tmpX * preTransform[0] + out.y * preTransform[2] * ySign; + out.y = tmpX * preTransform[1] + out.y * preTransform[3] * ySign; const float cx = _orientedViewport.x * static_cast(_width); const float cy = _orientedViewport.y * static_cast(_height); diff --git a/native/cocos/scene/Pass.cpp b/native/cocos/scene/Pass.cpp index b672e6dbfa..9f7b0a0a10 100644 --- a/native/cocos/scene/Pass.cpp +++ b/native/cocos/scene/Pass.cpp @@ -656,6 +656,10 @@ void Pass::initPassFromTarget(Pass *target, const gfx::DepthStencilState &dss, c _hash = target->_hash ^ hashFactor; } +void Pass::updatePassHash() { + _hash = Pass::getPassHash(this); +} + gfx::DescriptorSetLayout *Pass::getLocalSetLayout() const { return ProgramLib::getInstance()->getDescriptorSetLayout(_device, _programName, true); } diff --git a/native/cocos/scene/Pass.h b/native/cocos/scene/Pass.h index a5124f536d..18ada8ae06 100644 --- a/native/cocos/scene/Pass.h +++ b/native/cocos/scene/Pass.h @@ -298,6 +298,7 @@ public: // Only for UI void initPassFromTarget(Pass *target, const gfx::DepthStencilState &dss, ccstd::hash_t hashFactor); + void updatePassHash(); // internal use /** diff --git a/native/cocos/scene/Skybox.cpp b/native/cocos/scene/Skybox.cpp index 4a7cda1c70..d7efdb27ce 100644 --- a/native/cocos/scene/Skybox.cpp +++ b/native/cocos/scene/Skybox.cpp @@ -349,17 +349,17 @@ void Skybox::setUseHDR(bool val) { void Skybox::updatePipeline() const { if (isEnabled() && _material != nullptr) { - if (getReflectionMap()) { - _material->recompileShaders({{"USE_RGBE_CUBEMAP", isRGBE()}, {"USE_REFLECTION_CUBEMAP", true}}); - _material->setProperty("environmentMap", getEnvmap()); - } else { - _material->recompileShaders({{"USE_RGBE_CUBEMAP", isRGBE()}, {"USE_REFLECTION_CUBEMAP", false}}); + auto *envmap = getEnvmap(); + if (!envmap) { + envmap = _default.get(); } - } + _material->setProperty("environmentMap", envmap); + _material->recompileShaders({{"USE_RGBE_CUBEMAP", isRGBE()}}); - if (_model != nullptr && _material != nullptr) { - _model->setSubModelMaterial(0, _material); - updateSubModes(); + if (_model != nullptr) { + _model->setSubModelMaterial(0, _material); + updateSubModes(); + } } Root *root = Root::getInstance(); @@ -424,12 +424,7 @@ void Skybox::updatePipeline() const { valueChanged = true; } - //set the macro value first before update the material - if (isEnabled() && _material != nullptr) { - _material->recompileShaders({{"USE_RGBE_CUBEMAP", isRGBE()}}); - } - - if (_model != nullptr && _material != nullptr) { + if (isEnabled() && _model != nullptr && _material != nullptr) { _model->setSubModelMaterial(0, _material); } diff --git a/native/external-config.json b/native/external-config.json index 682ddb16f6..9fcfd89886 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": "v3d-gfx-127" + "checkout": "v3d-gfx-128" } } diff --git a/native/tools/tojs/2d.ini b/native/tools/tojs/2d.ini index 9d2f0aa03d..1ee9861d0a 100644 --- a/native/tools/tojs/2d.ini +++ b/native/tools/tojs/2d.ini @@ -46,15 +46,15 @@ classes = RenderDrawInfo UIMeshBuffer Batcher2d RenderEntity UIModelProxy # add a single "*" as functions. See bellow for several examples. A special class name is "*", which # will apply to all class names. This is a convenience wildcard to be able to skip similar named # functions from all classes. -skip = RenderDrawInfo::[getBatcher setBatcher parseAttrLayout getRender2dLayout getEnumDrawInfoType], - Batcher2d::[addVertDirtyRenderer getMeshBuffer getDevice updateDescriptorSet fillBuffersAndMergeBatches walk generateBatch resetRenderStates handleDrawInfo], - UIMeshBuffer::[requireFreeIA createNewIA recycleIA resetIA parseLayout getByteOffset setByteOffset getVertexOffset setVertexOffset getIndexOffset setIndexOffset getDirty setDirty getFloatsPerVertex setFloatsPerVertex], - RenderEntity::[getDynamicRenderDrawInfo getDynamicRenderDrawInfos getRenderEntityType getColorDirty getColor isEnabled getEnumStencilStage setEnumStencilStage] +skip = RenderDrawInfo::[getBatcher setBatcher parseAttrLayout getRender2dLayout getEnumDrawInfoType resetDrawInfo], + Batcher2d::[addVertDirtyRenderer getMeshBuffer getDevice updateDescriptorSet fillBuffersAndMergeBatches walk generateBatch resetRenderStates handleDrawInfo handleComponentDraw handleModelDraw handleIADraw handleSubNode], + UIMeshBuffer::[requireFreeIA createNewIA recycleIA resetIA parseLayout getByteOffset setByteOffset getVertexOffset setVertexOffset getIndexOffset setIndexOffset getDirty setDirty getFloatsPerVertex setFloatsPerVertex getAttributes], + RenderEntity::[getDynamicRenderDrawInfo getDynamicRenderDrawInfos getRenderEntityType getColorDirty getColor isEnabled getEnumStencilStage setEnumStencilStage getVBColorDirty setVBColorDirty] rename_functions = getter_setter = RenderDrawInfo::[bufferId accId vertexOffset indexOffset vbBuffer ibBuffer vDataBuffer iDataBuffer vbCount ibCount vertDirty dataHash isMeshBuffer material texture sampler model drawInfoType subNode stride], - UIMeshBuffer::[vData iData], + UIMeshBuffer::[vData iData useLinkData], RenderEntity::[node staticDrawInfoSize stencilStage] field = diff --git a/native/tools/tojs/assets.ini b/native/tools/tojs/assets.ini index ff21097b94..0a84487bc9 100644 --- a/native/tools/tojs/assets.ini +++ b/native/tools/tojs/assets.ini @@ -95,7 +95,7 @@ skip_public_fields = rename_functions = ICreateInfo::[structInfo=struct], IPassInfoFull::[switch_=switch], - Material::[getProperty=_getProperty _props=_propsInternal], + Material::[getProperty=_getProperty _props=_propsInternal getHashForMaterial=getHash], EffectAsset::[registerAsset=register], BufferAsset::[getBuffer=buffer], Skeleton::[getBindposes=_getBindposes setBindposes=_setBindposes] @@ -110,7 +110,7 @@ getter_setter= Asset::[_uuid/getUuid/setUuid nativeUrl/getNativeUrl _nativeDep/g Mesh::[_hash:hash/getHash/setHash data:_data/getData jointBufferIndices/getJointBufferIndices maxPosition/getMaxPosition minPosition/getMinPosition renderingSubMeshes/getRenderingSubMeshes subMeshCount/getSubMeshCount _nativeAsset/getAssetData/setAssetData _allowDataAccess:allowDataAccess/isAllowDataAccess/setAllowDataAccess], Material::[effectAsset effectName technique/getTechniqueIndex hash/getHash parent], RenderingSubMesh::[mesh subMeshIdx flatBuffers:_flatBuffers jointMappedBuffers iaInfo:_iaInfo primitiveMode], - Skeleton::[_joints:joints/getJoints?/setJoints? _hash:hash/getHash?/setHash? _invBindposes:invBindposes/getInverseBindposes?/setInverseBindposes?], + Skeleton::[_joints:joints/getJoints?/setJoints? _hash:hash/getHash?/setHash? _invBindposes:inverseBindposes/getInverseBindposes?/setInverseBindposes?], EffectAsset::[techniques shaders combinations] diff --git a/native/tools/tojs/geometry.ini b/native/tools/tojs/geometry.ini index 7e9d1c3ac7..6b5c30605f 100644 --- a/native/tools/tojs/geometry.ini +++ b/native/tools/tojs/geometry.ini @@ -43,7 +43,7 @@ classes = AABB Obb Line Plane Frustum Capsule Sphere Triangle Ray Spline ShapeBa # functions from all classes. skip = AABB::[getBoundary aabbAabb aabbFrustum aabbPlan merge transform transformExtentM4 isValid setValid set fromPoints (g|s)etCenter (g|s)etHalfExtents], Frustum::[update type planes split], - Plane::[clone copy normalize getSpotAngle fromNormalAndPoint fromPoints set], + Plane::[getSpotAngle], Ray::[computeHit], Sphere::[getBoundary] diff --git a/native/tools/tojs/scene.ini b/native/tools/tojs/scene.ini index b895cd32fa..d4a79990fd 100644 --- a/native/tools/tojs/scene.ini +++ b/native/tools/tojs/scene.ini @@ -77,7 +77,7 @@ skip = Pass::[getBlocks initPassFromTarget], RenderScene::[updateBatches addBatch removeBatch removeBatches getBatches], BakedSkinningModel::[updateInstancedJointTextureInfo updateModelBounds], AmbientInfo::[activate], - Node::[setLayerPtr setUIPropsTransformDirtyCallback rotate$ setUserData getUserData getChildren rotateForJS setScale$ setRotation$ setRotationFromEuler$ setPosition$ isActiveInHierarchy setActiveInHierarchy setActiveInHierarchyPtr setRTS$ findComponent findChildComponent findChildComponents addComponent removeComponent getComponent getComponents getComponentInChildren getComponentsInChildren checkMultipleComp getEventProcessor dispatchEvent hasEventListener getUIProps getPosition getRotation getScale getEulerAngles getForward getUp getRight getWorldPosition getWorldRotation getWorldScale getWorldMatrix getWorldRS getWorldRT inverseTransformPoint], + Node::[setLayerPtr setUIPropsTransformDirtyCallback rotate$ setUserData getUserData getChildren rotateForJS setScale$ setRotation$ setRotationFromEuler$ setPosition$ isActiveInHierarchy setActiveInHierarchy setActiveInHierarchyPtr setRTS$ findComponent findChildComponent findChildComponents addComponent removeComponent getComponent getComponents getComponentInChildren getComponentsInChildren checkMultipleComp getEventProcessor dispatchEvent hasEventListener getUIProps getPosition getRotation getScale getEulerAngles getForward getUp getRight getWorldPosition getWorldRotation getWorldScale getWorldMatrix getWorldRS getWorldRT inverseTransformPoint ^on$ ^off$], Camera::[screenPointToRay screenToWorld worldToScreen worldMatrixToScreen syncCameraEditor getMatView getMatProj getMatProjInv getMatViewProj getMatViewProjInv], NodeUiProperties::[getUITransformComp setUITransformComp getUIComp setUIComp], # not impl ProgramLib::[destroyInstance] @@ -89,7 +89,7 @@ rename_functions = Root::[initialize=_initialize], ProgramLib::[registerEffect=register], Model::[initLocalDescriptors=_initLocalDescriptors updateLocalDescriptors=_updateLocalDescriptors updateInstancedAttributes=_updateInstancedAttributes getInstancedAttributeIndex=_getInstancedAttributeIndex], Scene::[load=_load activate=_activate], - Pass::[initPassFromTarget=_initPassFromTarget] + Pass::[initPassFromTarget=_initPassFromTarget updatePassHash=_updatePassHash] getter_setter = Root::[device:_device mainWindow curWindow tempWindow windows scenes cumulativeTime frameTime frameCount fps fixedFPS useDeferredPipeline/isUsingDeferredPipeline usesCustomPipeline/usesCustomPipeline pipeline customPipeline], RenderWindow::[width height framebuffer cameras swapchain], diff --git a/platforms/minigame/openDataContext/index.js b/platforms/minigame/openDataContext/index.js index 3edc46874f..d64d0eb571 100644 --- a/platforms/minigame/openDataContext/index.js +++ b/platforms/minigame/openDataContext/index.js @@ -1,6 +1,6 @@ -import style from './render/style' -import template from './render/template' -import Layout from './engine' +const style = require('./render/style') +const template = require('./render/template') +const Layout = require('./engine').default; let __env = GameGlobal.wx || GameGlobal.tt || GameGlobal.swan; let sharedCanvas = __env.getSharedCanvas(); diff --git a/platforms/minigame/openDataContext/render/dataDemo.js b/platforms/minigame/openDataContext/render/dataDemo.js index 110e2b45fa..854d5d4a65 100644 --- a/platforms/minigame/openDataContext/render/dataDemo.js +++ b/platforms/minigame/openDataContext/render/dataDemo.js @@ -20,4 +20,4 @@ for (let i = 0; i < maxCount; ++i) { } dataDemo.data.sort((a, b) => b.rankScore - a.rankScore); -export default dataDemo; \ No newline at end of file +module.exports = dataDemo; \ No newline at end of file diff --git a/platforms/minigame/openDataContext/render/style.js b/platforms/minigame/openDataContext/render/style.js index 2103b42e98..34ff72346e 100644 --- a/platforms/minigame/openDataContext/render/style.js +++ b/platforms/minigame/openDataContext/render/style.js @@ -1,4 +1,4 @@ -export default { +module.exports = { container: { width: '100%', height: '100%', @@ -78,7 +78,7 @@ export default { height: 100, fontSize: 33, fontWeight: 'bold', - paddingRight : 200, + paddingRight: 200, lineHeight: 100, textAlign: 'center', }, @@ -99,11 +99,11 @@ export default { height: 70, }, - listItemName:{ + listItemName: { width: 210, height: 100, fontSize: 30, lineHeight: 100, marginLeft: 30, }, -} +}; diff --git a/platforms/minigame/openDataContext/render/template.js b/platforms/minigame/openDataContext/render/template.js index d2368d16ff..707646c7f2 100644 --- a/platforms/minigame/openDataContext/render/template.js +++ b/platforms/minigame/openDataContext/render/template.js @@ -1,4 +1,4 @@ -import dataDemo from './dataDemo' +const dataDemo = require('./dataDemo') /* @@ -30,4 +30,4 @@ import dataDemo from './dataDemo' // 上述模板经过模板引擎编译成版本函数,可通过 olado.github.io/doT/index.html 在线获得 function anonymous(it ) { var out=' ';var arr1=it.data;if(arr1){var item,index=-1,l1=arr1.length-1;while(index ';} } out+=' ';return out; } -export default anonymous(dataDemo); \ No newline at end of file +module.exports = anonymous(dataDemo); \ No newline at end of file diff --git a/platforms/native/engine/jsb-dragonbones.js b/platforms/native/engine/jsb-dragonbones.js index d172536cbe..bdfe3677c7 100644 --- a/platforms/native/engine/jsb-dragonbones.js +++ b/platforms/native/engine/jsb-dragonbones.js @@ -334,7 +334,7 @@ const cacheManager = require('./jsb-cache-manager'); //////////////////////////////////////////////////////////// // override ArmatureDisplay //////////////////////////////////////////////////////////// - const superProto = cc.internal.Renderable2D.prototype; + const superProto = cc.internal.UIRenderer.prototype; const armatureDisplayProto = cc.internal.ArmatureDisplay.prototype; const AnimationCacheMode = cc.internal.ArmatureDisplay.AnimationCacheMode; const armatureSystem = cc.internal.ArmatureSystem; @@ -778,11 +778,11 @@ const cacheManager = require('./jsb-cache-manager'); const renderData = middleware.RenderInfoLookup[middleware.vfmtPosUvColor][_tempBufferIndex]; const drawInfo = this.requestDrawInfo(index); + drawInfo.setDrawInfoType(renderData.drawInfoType); + drawInfo.setAccAndBuffer(renderData.accessor.id, renderData.chunk.bufferId); drawInfo.setTexture(realTexture.getGFXTexture()); drawInfo.setSampler(realTexture.getGFXSampler()); drawInfo.setMaterial(this.material); - renderData.fillDrawInfoAttributes(drawInfo); - drawInfo.setIndexOffset(_tempIndicesOffset); drawInfo.setIBCount(_tempIndicesCount); diff --git a/platforms/native/engine/jsb-editor-support.js b/platforms/native/engine/jsb-editor-support.js index 793ccaa841..3ab80d5b30 100644 --- a/platforms/native/engine/jsb-editor-support.js +++ b/platforms/native/engine/jsb-editor-support.js @@ -84,32 +84,20 @@ const bufferCount = middlewareMgr.getBufferCount(nativeFormat); for (let i = 0; i < bufferCount; i++) { - const ibBytesLength = middlewareMgr.getIBTypedArrayLength(nativeFormat, i); - const vbBytesLength = middlewareMgr.getVBTypedArrayLength(nativeFormat, i); - const srcIndicesCount = ibBytesLength / 2; // USHORT - const srcVertexCount = vbBytesLength / nativeFormat / 4; - const srcVertexFloatCount = srcVertexCount * nativeFormat; - let buffer = renderInfoLookup[nativeFormat][i]; if (!buffer) { if (!_accessors[jsFormat]) { - _accessors[jsFormat] = cc.UI.RenderData.createStaticVBAccessor(jsFormat, 65535); + _accessors[jsFormat] = cc.UI.RenderData.createStaticVBAccessor(jsFormat, 65535, 524280); } buffer = cc.UI.RenderData.add(jsFormat, _accessors[jsFormat]); buffer.multiOwner = true; buffer.drawInfoType = RenderDrawInfoType_IA; + // vertex count 65535, indices count 8 * 65535 + buffer.resize(65535, 524280); + const meshBuffer = buffer.getMeshBuffer(); + meshBuffer.useLinkedData = true; + renderInfoLookup[nativeFormat][i] = buffer; } - - const srcVBuf = middlewareMgr.getVBTypedArray(nativeFormat, i); - const srcIBuf = middlewareMgr.getIBTypedArray(nativeFormat, i); - - buffer.resize(srcVertexCount, srcIndicesCount); - const vData = buffer.chunk.vb; - const iData = buffer.chunk.meshBuffer.iData; - vData.set(srcVBuf.subarray(0, srcVertexFloatCount), 0); - iData.set(srcIBuf.subarray(0, srcIndicesCount), 0); - - renderInfoLookup[nativeFormat][i] = buffer; } } diff --git a/platforms/native/engine/jsb-spine-skeleton.js b/platforms/native/engine/jsb-spine-skeleton.js index 64a1c96acd..48b5b70236 100644 --- a/platforms/native/engine/jsb-spine-skeleton.js +++ b/platforms/native/engine/jsb-spine-skeleton.js @@ -885,11 +885,11 @@ const cacheManager = require('./jsb-cache-manager'); const renderData = middleware.RenderInfoLookup[_tempVfmt][_tempBufferIndex]; const drawInfo = this.requestDrawInfo(index); + drawInfo.setDrawInfoType(renderData.drawInfoType); + drawInfo.setAccAndBuffer(renderData.accessor.id, renderData.chunk.bufferId); drawInfo.setTexture(realTexture.getGFXTexture()); drawInfo.setSampler(realTexture.getGFXSampler()); drawInfo.setMaterial(this.material); - renderData.fillDrawInfoAttributes(drawInfo); - drawInfo.setIndexOffset(_tempIndicesOffset); drawInfo.setIBCount(_tempIndicesCount); diff --git a/scripts/build-engine/package-lock.json b/scripts/build-engine/package-lock.json index fa01022480..14c2b40d0b 100644 --- a/scripts/build-engine/package-lock.json +++ b/scripts/build-engine/package-lock.json @@ -1,6 +1,6 @@ { "name": "@cocos/build-engine", - "version": "4.3.14", + "version": "4.3.15", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/scripts/build-engine/package.json b/scripts/build-engine/package.json index 834275d04d..8aff389813 100644 --- a/scripts/build-engine/package.json +++ b/scripts/build-engine/package.json @@ -1,6 +1,6 @@ { "name": "@cocos/build-engine", - "version": "4.3.14", + "version": "4.3.15", "description": "", "repository": { "type": "git", diff --git a/scripts/build-engine/src/index.ts b/scripts/build-engine/src/index.ts index 9b7200dcbc..8de4598f80 100644 --- a/scripts/build-engine/src/index.ts +++ b/scripts/build-engine/src/index.ts @@ -28,6 +28,7 @@ import { StatsQuery } from './stats-query'; import { filePathToModuleRequest } from './utils'; import { assetRef as rpAssetRef, pathToAssetRefURL } from './rollup-plugins/asset-ref'; import { codeAsset } from './rollup-plugins/code-asset'; +import { ModeType, PlatformType } from './constant-manager'; export { ModeType, PlatformType, FlagType, ConstantOptions, BuildTimeConstants, CCEnvConstants } from './constant-manager'; export { StatsQuery }; @@ -272,10 +273,18 @@ async function doBuild ({ const featureUnits = statsQuery.getUnitsOfFeatures(features); + // HACK: get flags from build time constants + const flags: Record = {}; + ['SERVER_MODE', 'NOT_PACK_PHYSX_LIBS', 'DEBUG', 'NET_MODE'].forEach(key => { + flags[key] = buildTimeConstants[key]; + }); + const rpVirtualOptions: Record = {}; - const vmInternalConstants = statsQuery.evaluateEnvModuleSourceFromRecord({ - EXPORT_TO_GLOBAL: true, - ...buildTimeConstants, + + const vmInternalConstants = statsQuery.constantManager.exportStaticConstants({ + platform: options.platform as PlatformType, + mode: options.mode as ModeType, + flags, }); console.debug(`Module source "internal-constants":\n${vmInternalConstants}`); rpVirtualOptions['internal:constants'] = vmInternalConstants; diff --git a/templates/cmake/common.cmake b/templates/cmake/common.cmake index 4fc6b1f99f..a07ec4c37c 100644 --- a/templates/cmake/common.cmake +++ b/templates/cmake/common.cmake @@ -75,7 +75,7 @@ function(cc_gen_plugin_cmake_hook) file(APPEND ${plugin_args_info} "${abs_dir}\n") endforeach() if("${NODE_EXECUTABLE}" STREQUAL "NODE_EXECUTABLE-NOTFOUND") - message(AUTHOR_WARNING "NodeJS is not found in $PATH") + message(STATUS "NodeJS is not found in $PATH, skip searching native plugins.") else() message(STATUS " execute plugin_parser.js ${NODE_EXECUTABLE-NOTFOUND}") execute_process(COMMAND ${NODE_EXECUTABLE} ${COCOS_X_PATH}/cmake/scripts/plugins_parser.js diff --git a/tests/animation/embedded-player/evaluate-embedded-players-in-animation-state.test.ts b/tests/animation/embedded-player/evaluate-embedded-players-in-animation-state.test.ts index 04ba2e1239..7c708d49bd 100644 --- a/tests/animation/embedded-player/evaluate-embedded-players-in-animation-state.test.ts +++ b/tests/animation/embedded-player/evaluate-embedded-players-in-animation-state.test.ts @@ -15,6 +15,9 @@ test('Evaluate embedded players in animation state', () => { expect(targetNode).toBe(node); return embeddedPlayerEvaluation as unknown as ReturnType; }); + jest.spyOn(clip, 'containsAnyEmbeddedPlayer').mockImplementation(() => { + return true; + }); const animationState = new AnimationState(clip); animationState.initialize(node); diff --git a/tests/animation/newgenanim.test.ts b/tests/animation/newgenanim.test.ts index a86af4c213..b0937a2039 100644 --- a/tests/animation/newgenanim.test.ts +++ b/tests/animation/newgenanim.test.ts @@ -74,9 +74,16 @@ describe('NewGen Anim', () => { expect(animTransition.exitConditionEnabled).toBe(true); expect(animTransition.exitCondition).toBe(1.0); expect(animTransition.destinationStart).toBe(0.0); + expect(animTransition.relativeDestinationStart).toBe(false); expect(animTransition.interruptionSource).toBe(TransitionInterruptionSource.NONE); expect(animTransition.interruptible).toBe(false); + const emptyState = layerGraph.addEmpty(); + const emptyTransition = layerGraph.connect(emptyState, animState); + expect(emptyTransition.duration).toBe(0.3); + expect(emptyTransition.destinationStart).toBe(0.0); + expect(emptyTransition.relativeDestinationStart).toBe(false); + function testGraphDefaults(graph: StateMachine) { expect(Array.from(graph.states())).toStrictEqual(expect.arrayContaining([ graph.entryState, @@ -1478,7 +1485,90 @@ describe('NewGen Anim', () => { }); }); - test(`Transition destination start`, () => { + test(`Transition destination start: absolute`, () => { + const animationGraph = new AnimationGraph(); + const layer = animationGraph.addLayer(); + const graph = layer.stateMachine; + const animState1 = graph.addMotion(); + animState1.name = 'Motion1'; + animState1.motion = createClipMotionPositionXLinear(4.0, 0.6, 0.8); + const animState2 = graph.addMotion(); + animState2.name = 'Motion2'; + animState2.motion = createClipMotionPositionXLinear(2.2, 3.0, 0.1415); + graph.connect(graph.entryState, animState1); + const transition = graph.connect(animState1, animState2); + transition.exitConditionEnabled = true; + transition.exitCondition = 0.1; + transition.duration = 0.3; + transition.relativeDuration = false; + const TRANSITION_DESTINATION_START = 0.17; + transition.destinationStart = TRANSITION_DESTINATION_START * 2.2; // 2.2: duration of `animState2` + transition.relativeDestinationStart = false; + + // Also test the attribute on empty transition + const layer2 = animationGraph.addLayer(); + const emptyState = layer2.stateMachine.addEmpty(); + layer2.stateMachine.connect(layer2.stateMachine.entryState, emptyState); + const animState3 = layer2.stateMachine.addMotion(); + animState3.name = 'Motion3'; + animState3.motion = createClipMotionPositionXLinear(6.0, 7.0, -1.9); + const emptyTransition = layer2.stateMachine.connect(emptyState, animState3); + emptyTransition.duration = 0.4; + const EMPTY_TRANSITION_DESTINATION_START = 0.13; + emptyTransition.destinationStart = EMPTY_TRANSITION_DESTINATION_START * 6.0; // 6.0: duration of `animState3` + const [emptyTransitionCondition] = emptyTransition.conditions = [new UnaryCondition()]; + emptyTransitionCondition.operator = UnaryCondition.Operator.TRUTHY; + const emptyTransitionEnablingVarName = emptyTransitionCondition.operand.variable = 'EmptyTransitionEnabling'; + animationGraph.addBoolean(emptyTransitionEnablingVarName); + + const node = new Node(); + const graphEval = createAnimationGraphEval(animationGraph, node); + + const graphUpdater = new GraphUpdater(graphEval); + graphUpdater.goto(4.0 * 0.1 + 0.2); + + expectAnimationGraphEvalStatusLayer0(graphEval, { + currentNode: { + __DEBUG_ID__: 'Motion1', + progress: 0.1 + 0.2 / 4.0, + }, + transition: { + nextNode: { + __DEBUG_ID__: 'Motion2', + progress: TRANSITION_DESTINATION_START + 0.2 / 2.2, + }, + }, + }); + + expect(node.position.x).toBeCloseTo( + lerp( + lerp(0.6, 0.8, 0.1 + 0.2 / 4.0), + lerp(3.0, 0.1415, TRANSITION_DESTINATION_START + 0.2 / 2.2), + 0.2 / 0.3, + ), + ); + + // Start the empty transition + graphEval.setValue(emptyTransitionEnablingVarName, true); + graphUpdater.step(0.16); + expect(node.position.x).toBeCloseTo( + lerp( + lerp( // Layer 1 + 3.0, + 0.1415, + TRANSITION_DESTINATION_START + (0.2 + 0.16) / 2.2, + ), + lerp( // Layer 2 + 7.0, + -1.9, + EMPTY_TRANSITION_DESTINATION_START + 0.16 / 6.0, + ), + 0.16 / 0.4, // Empty transition ratio + ), + ); + }); + + test(`Transition destination start: relative`, () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; @@ -1495,6 +1585,7 @@ describe('NewGen Anim', () => { transition.duration = 0.3; transition.relativeDuration = false; const TRANSITION_DESTINATION_START = transition.destinationStart = 0.17; + transition.relativeDestinationStart = true; // Also test the attribute on empty transition const layer2 = animationGraph.addLayer(); @@ -1506,6 +1597,7 @@ describe('NewGen Anim', () => { const emptyTransition = layer2.stateMachine.connect(emptyState, animState3); emptyTransition.duration = 0.4; const EMPTY_TRANSITION_DESTINATION_START = emptyTransition.destinationStart = 0.13; + emptyTransition.relativeDestinationStart = true; const [emptyTransitionCondition] = emptyTransition.conditions = [new UnaryCondition()]; emptyTransitionCondition.operator = UnaryCondition.Operator.TRUTHY; const emptyTransitionEnablingVarName = emptyTransitionCondition.operand.variable = 'EmptyTransitionEnabling'; diff --git a/tests/core/deserialize.test.ts b/tests/core/deserialize.test.ts index d3f57da9ac..a105da754f 100644 --- a/tests/core/deserialize.test.ts +++ b/tests/core/deserialize.test.ts @@ -1,7 +1,8 @@ - +import { CCClass, ccenum } from '../../cocos/core'; import { property } from '../../cocos/core/data/class-decorator'; -import { ccclass } from '../../cocos/core/data/decorators'; +import { ccclass, type } from '../../cocos/core/data/decorators'; import { deserialize } from '../../cocos/core/data/deserialize'; +import { BitMask, ccbitmask } from '../../cocos/core/value-types/bitmask'; describe('Deserialize', () => { test('Object array element', () => { @@ -32,4 +33,83 @@ describe('Deserialize', () => { expect(deserialized.array[1]).toBeInstanceOf(Foo); expect(deserialized.array[1].name).toBe('foo2'); }); + + test('Enum and Bitmask deserialize without default value', () => { + enum MyEnum { + EnumOption1, + EnumOption2, + EnumOption3, + } + ccenum(MyEnum); + + const MyBitMask = BitMask({ + BitMask1: 1, + BitMask2: 1 << 1, + BitMask3: 1 << 2, + BitMask4: 1 << 3, + }); + @ccclass('cc.TestDeserialization') + class TestClass { + @type(MyEnum) + enumOption1 = MyEnum.EnumOption1; + @type(MyEnum) + enumOption2 = MyEnum.EnumOption2; + @type(MyEnum) + enumOption3 = MyEnum.EnumOption3; + @type(MyBitMask) + bitmask1 = MyBitMask.BitMask1; + @type(MyBitMask) + bitmask2 = MyBitMask.BitMask1 | MyBitMask.BitMask4; + } + + CCClass.Attr.setClassAttr(TestClass, 'enumOption1', 'default', undefined); + CCClass.Attr.setClassAttr(TestClass, 'enumOption2', 'default', undefined); + CCClass.Attr.setClassAttr(TestClass, 'enumOption3', 'default', undefined); + CCClass.Attr.setClassAttr(TestClass, 'bitmask1', 'default', undefined); + CCClass.Attr.setClassAttr(TestClass, 'bitmask2', 'default', undefined); + + const dataSnippets = [ + { + __type__: 'cc.TestDeserialization', + 'enumOption1': MyEnum.EnumOption2, + 'enumOption2': MyEnum.EnumOption3, + 'bitmask1': MyBitMask.BitMask2 | MyBitMask.BitMask3 + }, + { + __type__: 'cc.TestDeserialization', + 'enumOption2': MyEnum.EnumOption3, + 'enumOption3': MyEnum.EnumOption2, + 'bitmask2': MyBitMask.BitMask2 | MyBitMask.BitMask3 + }, + { + __type__: 'cc.TestDeserialization', + 'enumOption1': MyEnum.EnumOption3, + 'enumOption2': MyEnum.EnumOption2, + 'enumOption3': MyEnum.EnumOption1, + 'bitmask1': MyBitMask.BitMask2 | MyBitMask.BitMask3 | MyBitMask.BitMask4, + 'bitmask2': 0 + }, + ]; + + const deserialized = deserialize(dataSnippets[0], null) as TestClass; + expect(deserialized.enumOption1).toBe(MyEnum.EnumOption2); + expect(deserialized.enumOption2).toBe(MyEnum.EnumOption3); + expect(deserialized.enumOption3).toBe(MyEnum.EnumOption3); + expect(deserialized.bitmask1).toBe(MyBitMask.BitMask2 | MyBitMask.BitMask3); + expect(deserialized.bitmask2).toBe(MyBitMask.BitMask1 | MyBitMask.BitMask4); + + const deserialized1 = deserialize(dataSnippets[1], null) as TestClass; + expect(deserialized1.enumOption1).toBe(MyEnum.EnumOption1); + expect(deserialized1.enumOption2).toBe(MyEnum.EnumOption3); + expect(deserialized1.enumOption3).toBe(MyEnum.EnumOption2); + expect(deserialized1.bitmask1).toBe(MyBitMask.BitMask1); + expect(deserialized1.bitmask2).toBe(MyBitMask.BitMask2 | MyBitMask.BitMask3); + + const deserialized2 = deserialize(dataSnippets[2], null) as TestClass; + expect(deserialized2.enumOption1).toBe(MyEnum.EnumOption3); + expect(deserialized2.enumOption2).toBe(MyEnum.EnumOption2); + expect(deserialized2.enumOption3).toBe(MyEnum.EnumOption1); + expect(deserialized2.bitmask1).toBe(MyBitMask.BitMask2 | MyBitMask.BitMask3 | MyBitMask.BitMask4); + expect(deserialized2.bitmask2).toBe(0); + }); }); diff --git a/typedoc-index.ts b/typedoc-index.ts index 3547beb8a0..9ea123a61c 100644 --- a/typedoc-index.ts +++ b/typedoc-index.ts @@ -5,7 +5,6 @@ export * from './exports/3d'; export * from './exports/animation'; export * from './exports/audio'; export * from './exports/base'; -export * from './exports/native'; export * from './exports/dragon-bones'; export * from './exports/gfx-empty'; export * from './exports/intersection-2d';