Compare commits
50 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e2795f9ecd | |||
| 89a412e0d6 | |||
| aef31099d8 | |||
| 89f8768e57 | |||
| 424be5d0b2 | |||
| e5183b796a | |||
| 32478c1a9c | |||
| 74e632a3d6 | |||
| 26883ba6f4 | |||
| 055c70f8d2 | |||
| 99f6db401c | |||
| 9390ee6bc0 | |||
| 7f258dac58 | |||
| 5c99570616 | |||
| 821928733b | |||
| f567861ff6 | |||
| a7a20b64ab | |||
| 7c75834010 | |||
| 8fd985af75 | |||
| cc97bc8af4 | |||
| 92124590fe | |||
| 822ac6026c | |||
| 4a6f83bd6d | |||
| 04f063eb2b | |||
| 910865bd8b | |||
| e384f54ed2 | |||
| 5964835c83 | |||
| f4ae16247c | |||
| 4b4a3ca13f | |||
| f1c5d21be6 | |||
| da75e89f4a | |||
| aba27a715d | |||
| 62c1eb58c3 | |||
| 5b09978eb1 | |||
| 1b8da1df9b | |||
| ea6ff53aad | |||
| b7ba9f76bb | |||
| ab670c4f99 | |||
| ba0a042ef5 | |||
| 8aa41cc3e7 | |||
| db7666f821 | |||
| 37abbf226a | |||
| c890b69a9e | |||
| 5f4f091c3e | |||
| 1519043126 | |||
| b7e83d3460 | |||
| a64e164e82 | |||
| 8e0412beab | |||
| 35e7bb2d5e | |||
| 315800edf9 |
@@ -659,6 +659,13 @@
|
||||
"ccGlobal": true,
|
||||
"internal": false
|
||||
},
|
||||
"SUDV2": {
|
||||
"comment": "Running in the sud v2's quick game.",
|
||||
"type": "boolean",
|
||||
"value": false,
|
||||
"ccGlobal": true,
|
||||
"internal": false
|
||||
},
|
||||
"NODEJS": {
|
||||
"comment": "Running in the Node.js environment.",
|
||||
"type": "boolean",
|
||||
@@ -738,7 +745,7 @@
|
||||
"RUNTIME_BASED": {
|
||||
"comment": "Running in runtime based environment.",
|
||||
"type": "boolean",
|
||||
"value": "$OPPO || $VIVO || $HUAWEI || $MIGU || $HONOR || $COCOS_RUNTIME || $SUD",
|
||||
"value": "$OPPO || $VIVO || $HUAWEI || $MIGU || $HONOR || $COCOS_RUNTIME || $SUD || $SUDV2",
|
||||
"ccGlobal": true,
|
||||
"internal": false
|
||||
},
|
||||
|
||||
@@ -64,10 +64,10 @@ function _calculateCircle (center: Vec3, radius: Vec3, segments: number): Vec3[]
|
||||
*/
|
||||
export enum MaskType {
|
||||
/**
|
||||
* @en Rect mask.
|
||||
* @en Rect mask, supports rounded corners by setting radius.
|
||||
*
|
||||
* @zh
|
||||
* 使用矩形作为遮罩。
|
||||
* 使用矩形作为遮罩,可通过 radius 设置圆角。
|
||||
*/
|
||||
GRAPHICS_RECT = 0,
|
||||
|
||||
@@ -215,6 +215,32 @@ export class Mask extends Component {
|
||||
this._updateGraphics();
|
||||
}
|
||||
|
||||
/**
|
||||
* @en
|
||||
* The radius for rounded corners of rect mask.
|
||||
*
|
||||
* @zh
|
||||
* 矩形遮罩的圆角半径。
|
||||
*/
|
||||
@visible(function (this: Mask) {
|
||||
return this.type === MaskType.GRAPHICS_RECT;
|
||||
})
|
||||
@tooltip('i18n:mask.radius')
|
||||
@range([0, Number.POSITIVE_INFINITY])
|
||||
get radius (): number {
|
||||
return this._radius;
|
||||
}
|
||||
|
||||
set radius (value) {
|
||||
const radius = clamp(value, 0, Number.POSITIVE_INFINITY);
|
||||
if (this._radius === radius) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._radius = radius;
|
||||
this._updateGraphics();
|
||||
}
|
||||
|
||||
/**
|
||||
* @en
|
||||
* The mask image.
|
||||
@@ -289,6 +315,9 @@ export class Mask extends Component {
|
||||
@serializable
|
||||
protected _segments = 64;
|
||||
|
||||
@serializable
|
||||
protected _radius = 0;
|
||||
|
||||
@serializable
|
||||
protected _alphaThreshold = 0.1;
|
||||
|
||||
@@ -350,7 +379,25 @@ export class Mask extends Component {
|
||||
testPt.y += ap.y * h;
|
||||
|
||||
let result = false;
|
||||
if (this.type === MaskType.GRAPHICS_RECT || this.type === MaskType.GRAPHICS_STENCIL || this.type === MaskType.SPRITE_STENCIL) {
|
||||
if (this.type === MaskType.GRAPHICS_RECT) {
|
||||
result = testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h;
|
||||
const radius = Math.min(this._radius, w / 2, h / 2);
|
||||
if (result && radius > 0) {
|
||||
let dx = 0;
|
||||
let dy = 0;
|
||||
if (testPt.x < radius) {
|
||||
dx = testPt.x - radius;
|
||||
} else if (testPt.x > w - radius) {
|
||||
dx = testPt.x - (w - radius);
|
||||
}
|
||||
if (testPt.y < radius) {
|
||||
dy = testPt.y - radius;
|
||||
} else if (testPt.y > h - radius) {
|
||||
dy = testPt.y - (h - radius);
|
||||
}
|
||||
result = dx * dx + dy * dy <= radius * radius;
|
||||
}
|
||||
} else if (this.type === MaskType.GRAPHICS_STENCIL || this.type === MaskType.SPRITE_STENCIL) {
|
||||
result = testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h;
|
||||
} else if (this.type === MaskType.GRAPHICS_ELLIPSE) {
|
||||
const rx = w / 2;
|
||||
@@ -423,7 +470,12 @@ export class Mask extends Component {
|
||||
const x = -width * ap.x;
|
||||
const y = -height * ap.y;
|
||||
if (this._type === MaskType.GRAPHICS_RECT) {
|
||||
graphics.rect(x, y, width, height);
|
||||
const radius = Math.min(this._radius, width / 2, height / 2);
|
||||
if (radius > 0) {
|
||||
graphics.roundRect(x, y, width, height, radius);
|
||||
} else {
|
||||
graphics.rect(x, y, width, height);
|
||||
}
|
||||
} else if (this._type === MaskType.GRAPHICS_ELLIPSE) {
|
||||
const center = new Vec3(x + width / 2, y + height / 2, 0);
|
||||
const radius = new Vec3(width / 2, height / 2, 0);
|
||||
|
||||
@@ -567,7 +567,7 @@ export class Sprite extends UIRenderer {
|
||||
if (this.spriteFrame && this.spriteFrame.texture instanceof RenderTexture) {
|
||||
const rtMatName = `rt-${mat.name}`;
|
||||
let rtMat = builtinResMgr.get(rtMatName) as Material | null;
|
||||
if (!rtMat) {
|
||||
if (!rtMat || !rtMat.passes.length) {
|
||||
rtMat = new Material(rtMatName);
|
||||
rtMat.copy(mat, { defines: { SAMPLE_FROM_RT: true } });
|
||||
builtinResMgr.addAsset(rtMatName, rtMat);
|
||||
|
||||
@@ -536,7 +536,7 @@ export class UIRenderer extends Renderer {
|
||||
const mat = this._updateBuiltinMaterial();
|
||||
this.setSharedMaterial(mat, 0);
|
||||
if (this.stencilStage === Stage.ENTER_LEVEL || this.stencilStage === Stage.ENTER_LEVEL_INVERTED) {
|
||||
this.getMaterialInstance(0)!.recompileShaders({ USE_ALPHA_TEST: true });
|
||||
this.getMaterialInstance(0)?.recompileShaders({ USE_ALPHA_TEST: true });
|
||||
}
|
||||
this._updateBlendFunc();
|
||||
}
|
||||
@@ -600,16 +600,24 @@ export class UIRenderer extends Renderer {
|
||||
*/
|
||||
public _updateBlendFunc (): void {
|
||||
// todo: Not only Pass[0].target[0]
|
||||
let target = this.getRenderMaterial(0)!.passes[0].blendState.targets[0];
|
||||
const renderMat = this.getRenderMaterial(0);
|
||||
if (!renderMat || !renderMat.passes[0]) {
|
||||
return;
|
||||
}
|
||||
let target = renderMat.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];
|
||||
const matInstance = this.getMaterialInstance(0);
|
||||
if (!matInstance || !matInstance.passes[0]) {
|
||||
return;
|
||||
}
|
||||
target = matInstance.passes[0].blendState.targets[0];
|
||||
target.blend = true;
|
||||
target.blendDstAlpha = BlendFactor.ONE_MINUS_SRC_ALPHA;
|
||||
target.blendDst = this._dstBlendFactor;
|
||||
target.blendSrc = this._srcBlendFactor;
|
||||
const targetPass = this.getMaterialInstance(0)!.passes[0];
|
||||
const targetPass = matInstance.passes[0];
|
||||
targetPass.blendState.setTarget(0, target);
|
||||
targetPass._updatePassHash();
|
||||
this._dstBlendFactorCache = this._dstBlendFactor;
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
import { CULL_MESHOPT, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
|
||||
import { ensureWasmModuleReady, instantiateWasm } from 'pal/wasm';
|
||||
|
||||
import { sys, logID, error } from '../../core';
|
||||
import { sys, error, debugID } from '../../core';
|
||||
|
||||
import { game } from '../../game';
|
||||
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
|
||||
@@ -53,7 +53,7 @@ function initDecoderASM (asm_factory: any): Promise<void> {
|
||||
MeshoptDecoder.decodeGltfBuffer = asm_factory.decodeGltfBuffer;
|
||||
MeshoptDecoder.useWorkers = asm_factory.useWorkers;
|
||||
MeshoptDecoder.decodeGltfBufferAsync = asm_factory.decodeGltfBufferAsync;
|
||||
logID(14202);
|
||||
debugID(14202);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ function initDecoderWASM (wasm_factory: any, wasm_url: string): Promise<void> {
|
||||
MeshoptDecoder.decodeGltfBuffer = wasm_factory.decodeGltfBuffer;
|
||||
MeshoptDecoder.useWorkers = wasm_factory.useWorkers;
|
||||
MeshoptDecoder.decodeGltfBufferAsync = wasm_factory.decodeGltfBufferAsync;
|
||||
logID(14203);
|
||||
debugID(14203);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -160,7 +160,8 @@ class ClipMotionEval implements MotionEval {
|
||||
|
||||
public overrideClips (context: AnimationGraphBindingContext): void {
|
||||
const { _originalClip: originalClip } = this;
|
||||
const overriding = context.clipOverrides?.get(originalClip);
|
||||
const clipOverrides: any = context.clipOverrides;
|
||||
const overriding: AnimationClip | null = clipOverrides && clipOverrides.get ? clipOverrides.get(originalClip) : null;
|
||||
if (overriding) {
|
||||
this._setClip(overriding, context);
|
||||
}
|
||||
|
||||
@@ -195,8 +195,9 @@ function define (className, baseClass, options): any {
|
||||
renderName = 'render_stage';
|
||||
}
|
||||
// 增加了 hidden: 开头标识,使它最终不会显示在 Editor inspector 的添加组件列表里
|
||||
|
||||
window.EditorExtends && window.EditorExtends.Component.addMenu(cls, `hidden:${renderName}/${className}`, -1);
|
||||
if (window.EditorExtends) {
|
||||
window.EditorExtends.Component.addMenu(cls, `hidden:${renderName}/${className}`, -1);
|
||||
}
|
||||
}
|
||||
|
||||
// Note: `options.ctor` should be the same as `cls` except if
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
import { PhysicsContact, b2ContactExtends } from './physics-contact';
|
||||
|
||||
const contactMap = new Map<b2ContactExtends, PhysicsContact>();
|
||||
const pools: PhysicsContact[] = [];
|
||||
|
||||
export class PhysicsContactManager {
|
||||
static get (b2contact: b2ContactExtends): PhysicsContact {
|
||||
let c = pools.pop();
|
||||
if (!c) {
|
||||
c = new PhysicsContact();
|
||||
}
|
||||
c.init(b2contact);
|
||||
contactMap.set(b2contact, c);
|
||||
return c;
|
||||
}
|
||||
|
||||
static find (b2contact: b2ContactExtends): PhysicsContact | null {
|
||||
return contactMap.get(b2contact) ?? null;
|
||||
}
|
||||
|
||||
static put (b2contact: b2ContactExtends): void {
|
||||
const c = contactMap.get(b2contact);
|
||||
if (!c) return;
|
||||
pools.push(c);
|
||||
c.reset();
|
||||
contactMap.delete(b2contact);
|
||||
}
|
||||
|
||||
static clear (): void {
|
||||
contactMap.clear();
|
||||
pools.length = 0;
|
||||
}
|
||||
}
|
||||
@@ -31,8 +31,6 @@ export type b2ContactExtends = b2jsb.Contact & {
|
||||
m_userData: any
|
||||
}
|
||||
|
||||
const pools: PhysicsContact[] = [];
|
||||
|
||||
// temp world manifold
|
||||
const pointCache = [new Vec2(), new Vec2()];
|
||||
|
||||
@@ -74,25 +72,6 @@ const impulse: IPhysics2DImpulse = {
|
||||
};
|
||||
|
||||
export class PhysicsContact implements IPhysics2DContact {
|
||||
static get (b2contact: b2ContactExtends): PhysicsContact {
|
||||
let c = pools.pop();
|
||||
|
||||
if (!c) {
|
||||
c = new PhysicsContact();
|
||||
}
|
||||
|
||||
c.init(b2contact);
|
||||
return c;
|
||||
}
|
||||
|
||||
static put (b2contact: b2ContactExtends): void {
|
||||
const c: PhysicsContact = b2contact.m_userData as PhysicsContact;
|
||||
if (!c) return;
|
||||
|
||||
pools.push(c);
|
||||
c.reset();
|
||||
}
|
||||
|
||||
colliderA: Collider2D | null = null;
|
||||
colliderB: Collider2D | null = null;
|
||||
|
||||
@@ -108,16 +87,13 @@ export class PhysicsContact implements IPhysics2DContact {
|
||||
}
|
||||
|
||||
init (b2contact: b2ContactExtends): void {
|
||||
this._b2contact = b2contact;
|
||||
this.colliderA = (b2contact.GetFixtureA().m_userData as b2Shape2D).collider;
|
||||
this.colliderB = (b2contact.GetFixtureB().m_userData as b2Shape2D).collider;
|
||||
this.disabled = false;
|
||||
this.disabledOnce = false;
|
||||
this._impulse = null!;
|
||||
|
||||
this._inverted = false;
|
||||
|
||||
this._b2contact = b2contact;
|
||||
b2contact.m_userData = this;
|
||||
}
|
||||
|
||||
reset (): void {
|
||||
@@ -130,7 +106,6 @@ export class PhysicsContact implements IPhysics2DContact {
|
||||
this.disabled = false;
|
||||
this._impulse = null!;
|
||||
|
||||
this._b2contact.m_userData = null;
|
||||
this._b2contact = null!;
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ import { PhysicsContactListener } from './platform/physics-contact-listener';
|
||||
import { PhysicsAABBQueryCallback } from './platform/physics-aabb-query-callback';
|
||||
import { PhysicsRayCastCallback } from './platform/physics-ray-cast-callback';
|
||||
import { PhysicsContact, b2ContactExtends } from './physics-contact';
|
||||
import { PhysicsContactManager } from './physics-contact-manager';
|
||||
import { Contact2DType, Collider2D, RaycastResult2D } from '../framework';
|
||||
import { b2Shape2D } from './shapes/shape-2d';
|
||||
import { PhysicsDebugDraw } from './platform/physics-debug-draw';
|
||||
@@ -140,7 +141,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
|
||||
if (!v) {
|
||||
if (this._debugGraphics) {
|
||||
this._debugGraphics.node.parent = null;
|
||||
this._debugGraphics.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -444,22 +445,22 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
}
|
||||
|
||||
_onBeginContact (b2contact: b2ContactExtends): void {
|
||||
const c = PhysicsContact.get(b2contact);
|
||||
const c = PhysicsContactManager.get(b2contact);
|
||||
c.emit(Contact2DType.BEGIN_CONTACT);
|
||||
}
|
||||
|
||||
_onEndContact (b2contact: b2ContactExtends): void {
|
||||
const c = b2contact.m_userData as PhysicsContact;
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
c.emit(Contact2DType.END_CONTACT);
|
||||
|
||||
PhysicsContact.put(b2contact);
|
||||
PhysicsContactManager.put(b2contact);
|
||||
}
|
||||
|
||||
_onPreSolve (b2contact: b2ContactExtends): void {
|
||||
const c = b2contact.m_userData as PhysicsContact;
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
@@ -468,7 +469,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
}
|
||||
|
||||
_onPostSolve (b2contact: b2ContactExtends, impulse: b2jsb.ContactImpulse): void {
|
||||
const c: PhysicsContact = b2contact.m_userData as PhysicsContact;
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
@@ -478,4 +479,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
c.emit(Contact2DType.POST_SOLVE);
|
||||
c._setImpulse(null);
|
||||
}
|
||||
clearContacts (): void {
|
||||
PhysicsContactManager.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,8 +34,8 @@ export class b2CircleShape extends b2Shape2D implements ICircleShape {
|
||||
|
||||
_worldPosition = new Vec2();
|
||||
get worldPosition (): Vec2 {
|
||||
const p = (this._shapes[0] as b2jsb.CircleShape).m_p;
|
||||
return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO);
|
||||
const comp = this.collider as CircleCollider2D;
|
||||
return Vec2.transformMat4(this._worldPosition, comp.offset, comp.node.worldMatrix);
|
||||
}
|
||||
|
||||
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): any[] {
|
||||
|
||||
@@ -26,7 +26,7 @@ import { instantiateWasm, ensureWasmModuleReady } from 'pal/wasm';
|
||||
import { BUILD, LOAD_BOX2D_MANUALLY, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
|
||||
|
||||
import { game } from '../../game';
|
||||
import { error, sys, IVec2Like, log } from '../../core';
|
||||
import { error, sys, IVec2Like, log, debug } from '../../core';
|
||||
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
|
||||
|
||||
// eslint-disable-next-line import/no-mutable-exports
|
||||
@@ -148,7 +148,7 @@ function initWasm (wasmFactory, wasmUrl: string): Promise<void> {
|
||||
}).catch((err) => reject(errorMessage(err)));
|
||||
},
|
||||
}).then((Instance: any) => {
|
||||
log('[box2d]:box2d wasm lib loaded.');
|
||||
debug('[box2d]:box2d wasm lib loaded.');
|
||||
B2 = Instance;
|
||||
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
|
||||
});
|
||||
@@ -158,7 +158,7 @@ function initAsm (asmFactory): Promise<void> {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const errorMessage = (err: any): string => `[box2d]: box2d asm lib load failed: ${err}`;
|
||||
asmFactory().then((instance: any) => {
|
||||
log('[box2d]:box2d asm lib loaded.');
|
||||
debug('[box2d]:box2d asm lib loaded.');
|
||||
B2 = instance;
|
||||
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
|
||||
https://www.cocos.com/
|
||||
*/
|
||||
import { B2ObjectType, getTSObjectFromWASMObjectPtr } from './instantiated';
|
||||
import { PhysicsContact } from './physics-contact';
|
||||
|
||||
const pools: PhysicsContact[] = [];
|
||||
|
||||
export class PhysicsContactManager {
|
||||
static get (b2contact: number): PhysicsContact {
|
||||
let c = pools.pop();
|
||||
if (!c) {
|
||||
c = new PhysicsContact();
|
||||
}
|
||||
c.init(b2contact);
|
||||
return c;
|
||||
}
|
||||
static find (b2contact: number): PhysicsContact | null {
|
||||
return getTSObjectFromWASMObjectPtr<PhysicsContact>(B2ObjectType.Contact, b2contact);
|
||||
}
|
||||
|
||||
static put (b2contact: number): void {
|
||||
const c = getTSObjectFromWASMObjectPtr<PhysicsContact>(B2ObjectType.Contact, b2contact);
|
||||
if (!c) return;
|
||||
|
||||
pools.push(c);
|
||||
c.reset();
|
||||
}
|
||||
|
||||
static clear (): void {
|
||||
pools.length = 0;
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ import { Collider2D, Contact2DType, PhysicsSystem2D } from '../framework';
|
||||
import { B2Shape2D } from './shapes/shape-2d';
|
||||
import { IPhysics2DContact, IPhysics2DImpulse, IPhysics2DManifoldPoint, IPhysics2DWorldManifold } from '../spec/i-physics-contact';
|
||||
|
||||
const pools: PhysicsContact[] = [];
|
||||
/* pools moved to PhysicsContactManager */
|
||||
|
||||
// temp world manifold
|
||||
const pointCache = [new Vec2(), new Vec2()];
|
||||
@@ -62,24 +62,7 @@ const impulse: IPhysics2DImpulse = {
|
||||
|
||||
/** @mangle */
|
||||
export class PhysicsContact implements IPhysics2DContact {
|
||||
static get (b2contact: number): PhysicsContact {
|
||||
let c = pools.pop();
|
||||
|
||||
if (!c) {
|
||||
c = new PhysicsContact();
|
||||
}
|
||||
|
||||
c.init(b2contact);
|
||||
return c;
|
||||
}
|
||||
|
||||
static put (b2contact: number): void {
|
||||
const c = getTSObjectFromWASMObjectPtr<PhysicsContact>(B2ObjectType.Contact, b2contact);
|
||||
if (!c) return;
|
||||
|
||||
pools.push(c);
|
||||
c.reset();
|
||||
}
|
||||
/* static get/put/clear moved to PhysicsContactManager */
|
||||
|
||||
colliderA: Collider2D | null = null;
|
||||
colliderB: Collider2D | null = null;
|
||||
|
||||
@@ -35,7 +35,7 @@ import { B2RigidBody2D } from './rigid-body';
|
||||
import { PhysicsContactListener } from './platform/physics-contact-listener';
|
||||
import { PhysicsAABBQueryCallback } from './platform/physics-aabb-query-callback';
|
||||
import { PhysicsRayCastCallback } from './platform/physics-ray-cast-callback';
|
||||
import { PhysicsContact } from './physics-contact';
|
||||
import { PhysicsContactManager } from './physics-contact-manager';
|
||||
import { Contact2DType, Collider2D, RaycastResult2D } from '../framework';
|
||||
import { B2Shape2D } from './shapes/shape-2d';
|
||||
import { PhysicsDebugDraw } from './platform/physics-debug-draw';
|
||||
@@ -82,6 +82,16 @@ export class B2PhysicsWorld implements IPhysicsWorld {
|
||||
PhysicsContactListener._PreSolve = this._onPreSolve;
|
||||
PhysicsContactListener._PostSolve = this._onPostSolve;
|
||||
this._contactListener = B2.ContactListener.implement(PhysicsContactListener.callback);
|
||||
const orgRegisterContactFixture = this._contactListener.registerContactFixture.bind(this._contactListener);
|
||||
this._contactListener.registerContactFixture = (contactFixture: number): void => {
|
||||
PhysicsContactListener.registerContactFixture(contactFixture);
|
||||
orgRegisterContactFixture(contactFixture);
|
||||
};
|
||||
const orgUnregisterContactFixture = this._contactListener.unregisterContactFixture.bind(this._contactListener);
|
||||
this._contactListener.unregisterContactFixture = (contactFixture: number): void => {
|
||||
PhysicsContactListener.unregisterContactFixture(contactFixture);
|
||||
orgUnregisterContactFixture(contactFixture);
|
||||
};
|
||||
this._world.SetContactListener(this._contactListener);
|
||||
|
||||
this._aabbQueryCallback = B2.QueryCallback.implement(PhysicsAABBQueryCallback.callback);
|
||||
@@ -104,7 +114,7 @@ export class B2PhysicsWorld implements IPhysicsWorld {
|
||||
|
||||
if (!v) {
|
||||
if (this._debugGraphics) {
|
||||
this._debugGraphics.node.parent = null;
|
||||
this._debugGraphics.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -427,22 +437,22 @@ export class B2PhysicsWorld implements IPhysicsWorld {
|
||||
}
|
||||
|
||||
_onBeginContact (b2contact: number): void {
|
||||
const c = PhysicsContact.get(b2contact);
|
||||
const c = PhysicsContactManager.get(b2contact);
|
||||
c.emit(Contact2DType.BEGIN_CONTACT);
|
||||
}
|
||||
|
||||
_onEndContact (b2contact: number): void {
|
||||
const c = getTSObjectFromWASMObjectPtr<PhysicsContact>(B2ObjectType.Contact, b2contact);
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
c.emit(Contact2DType.END_CONTACT);
|
||||
|
||||
PhysicsContact.put(b2contact);
|
||||
PhysicsContactManager.put(b2contact);
|
||||
}
|
||||
|
||||
_onPreSolve (b2contact: number): void {
|
||||
const c = getTSObjectFromWASMObjectPtr<PhysicsContact>(B2ObjectType.Contact, b2contact);
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
@@ -451,7 +461,7 @@ export class B2PhysicsWorld implements IPhysicsWorld {
|
||||
}
|
||||
|
||||
_onPostSolve (b2contact: number, impulse: number): void {
|
||||
const c = getTSObjectFromWASMObjectPtr<PhysicsContact>(B2ObjectType.Contact, b2contact);
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
@@ -461,4 +471,8 @@ export class B2PhysicsWorld implements IPhysicsWorld {
|
||||
c.emit(Contact2DType.POST_SOLVE);
|
||||
c._setImpulse(0);
|
||||
}
|
||||
|
||||
clearContacts (): void {
|
||||
PhysicsContactManager.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,37 +22,56 @@
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { B2 } from '../instantiated';
|
||||
|
||||
type BeginContactCallback = (contact: number) => void;
|
||||
type EndContactCallback = (contact: number) => void;
|
||||
type PreSolveCallback = (contact: number, oldManifold: number) => void;
|
||||
type PostSolveCallback = (contact: number, impulse: number) => void;
|
||||
|
||||
export class PhysicsContactListener {
|
||||
static _contactFixtures: Set<number> = new Set<number>();
|
||||
static _BeginContact: BeginContactCallback | null = null;
|
||||
static _EndContact: EndContactCallback | null = null;
|
||||
static _PreSolve: PreSolveCallback | null = null;
|
||||
static _PostSolve: PostSolveCallback | null = null;
|
||||
static _shouldReportContacts: Set<number> = new Set<number>();
|
||||
|
||||
static BeginContact (contact: number): void {
|
||||
if (this._BeginContact) {
|
||||
if (!this._BeginContact) return;
|
||||
const fixtureA = B2.ContactGetFixtureA(contact) as number;
|
||||
const fixtureB = B2.ContactGetFixtureB(contact) as number;
|
||||
const fixtures = this._contactFixtures;
|
||||
this._shouldReportContacts.delete(contact);
|
||||
|
||||
if (fixtures.has(fixtureA) || fixtures.has(fixtureB)) {
|
||||
this._shouldReportContacts.add(contact);
|
||||
this._BeginContact(contact);
|
||||
}
|
||||
}
|
||||
|
||||
static EndContact (contact: number): void {
|
||||
if (this._EndContact) {
|
||||
if (this._EndContact && this._shouldReportContacts.has(contact)) {
|
||||
this._shouldReportContacts.delete(contact);
|
||||
this._EndContact(contact);
|
||||
}
|
||||
}
|
||||
|
||||
static PreSolve (contact: number, oldManifold: number): void {
|
||||
if (this._PreSolve) {
|
||||
if (this._PreSolve && this._shouldReportContacts.has(contact)) {
|
||||
this._PreSolve(contact, oldManifold);
|
||||
}
|
||||
}
|
||||
static registerContactFixture (fixture: number): void {
|
||||
this._contactFixtures.add(fixture);
|
||||
}
|
||||
|
||||
static unregisterContactFixture (fixture: number): void {
|
||||
this._contactFixtures.delete(fixture);
|
||||
}
|
||||
|
||||
static PostSolve (contact: number, impulse: number): void {
|
||||
if (this._PostSolve) {
|
||||
if (this._PostSolve && this._shouldReportContacts.has(contact)) {
|
||||
this._PostSolve(contact, impulse);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,8 +37,8 @@ export class B2CircleShape extends B2Shape2D implements ICircleShape {
|
||||
|
||||
_worldPosition = new Vec2();
|
||||
get worldPosition (): Vec2 {
|
||||
const p = B2.CircleShapeGetPosition(this._shapes[0]) as B2.Vec2;
|
||||
return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO);
|
||||
const comp = this.collider as CircleCollider2D;
|
||||
return Vec2.transformMat4(this._worldPosition, comp.offset, comp.node.worldMatrix);
|
||||
}
|
||||
|
||||
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): number[] { //B2.CircleShape[]
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
import { PhysicsContact, b2ContactExtends } from './physics-contact';
|
||||
|
||||
const contactMap = new Map<b2ContactExtends, PhysicsContact>();
|
||||
const pools: PhysicsContact[] = [];
|
||||
|
||||
export class PhysicsContactManager {
|
||||
static get (b2contact: b2ContactExtends): PhysicsContact {
|
||||
let c = pools.pop();
|
||||
if (!c) {
|
||||
c = new PhysicsContact();
|
||||
}
|
||||
c.init(b2contact);
|
||||
contactMap.set(b2contact, c);
|
||||
return c;
|
||||
}
|
||||
|
||||
static find (b2contact: b2ContactExtends): PhysicsContact | null {
|
||||
return contactMap.get(b2contact) ?? null;
|
||||
}
|
||||
|
||||
static put (b2contact: b2ContactExtends): void {
|
||||
const c = contactMap.get(b2contact);
|
||||
if (!c) return;
|
||||
pools.push(c);
|
||||
c.reset();
|
||||
contactMap.delete(b2contact);
|
||||
}
|
||||
|
||||
static clear (): void {
|
||||
contactMap.clear();
|
||||
pools.length = 0;
|
||||
}
|
||||
}
|
||||
@@ -33,8 +33,6 @@ export type b2ContactExtends = b2.Contact & {
|
||||
m_userData: any;
|
||||
}
|
||||
|
||||
const pools: PhysicsContact[] = [];
|
||||
|
||||
// temp world manifold
|
||||
const pointCache = [new Vec2(), new Vec2()];
|
||||
|
||||
@@ -68,25 +66,6 @@ const impulse: IPhysics2DImpulse = {
|
||||
|
||||
/** @mangle */
|
||||
export class PhysicsContact implements IPhysics2DContact {
|
||||
static get (b2contact: b2ContactExtends): PhysicsContact {
|
||||
let c = pools.pop();
|
||||
|
||||
if (!c) {
|
||||
c = new PhysicsContact();
|
||||
}
|
||||
|
||||
c.init(b2contact);
|
||||
return c;
|
||||
}
|
||||
|
||||
static put (b2contact: b2ContactExtends): void {
|
||||
const c: PhysicsContact = b2contact.m_userData as PhysicsContact;
|
||||
if (!c) return;
|
||||
|
||||
pools.push(c);
|
||||
c.reset();
|
||||
}
|
||||
|
||||
colliderA: Collider2D | null = null;
|
||||
colliderB: Collider2D | null = null;
|
||||
|
||||
@@ -111,7 +90,6 @@ export class PhysicsContact implements IPhysics2DContact {
|
||||
this._inverted = false;
|
||||
|
||||
this._b2contact = b2contact;
|
||||
b2contact.m_userData = this;
|
||||
}
|
||||
|
||||
reset (): void {
|
||||
@@ -124,7 +102,6 @@ export class PhysicsContact implements IPhysics2DContact {
|
||||
this.disabled = false;
|
||||
this._impulse = null;
|
||||
|
||||
this._b2contact!.m_userData = null;
|
||||
this._b2contact = null;
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ import { PhysicsDebugDraw } from './platform/physics-debug-draw';
|
||||
import { Node, find, Layers } from '../../scene-graph';
|
||||
import { director } from '../../game';
|
||||
import type { Graphics } from '../../2d/components/graphics';
|
||||
import { PhysicsContactManager } from './physics-contact-manager';
|
||||
|
||||
const tempVec3 = new Vec3();
|
||||
const tempVec2_1 = new Vec2();
|
||||
@@ -99,7 +100,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
|
||||
if (!v) {
|
||||
if (this._debugGraphics) {
|
||||
this._debugGraphics.node.parent = null;
|
||||
this._debugGraphics.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -414,22 +415,22 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
}
|
||||
|
||||
_onBeginContact (b2contact: b2ContactExtends): void {
|
||||
const c = PhysicsContact.get(b2contact);
|
||||
const c = PhysicsContactManager.get(b2contact);
|
||||
c.emit(Contact2DType.BEGIN_CONTACT);
|
||||
}
|
||||
|
||||
_onEndContact (b2contact: b2ContactExtends): void {
|
||||
const c = b2contact.m_userData as PhysicsContact;
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
c.emit(Contact2DType.END_CONTACT);
|
||||
|
||||
PhysicsContact.put(b2contact);
|
||||
PhysicsContactManager.put(b2contact);
|
||||
}
|
||||
|
||||
_onPreSolve (b2contact: b2ContactExtends): void {
|
||||
const c = b2contact.m_userData as PhysicsContact;
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
@@ -438,7 +439,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
}
|
||||
|
||||
_onPostSolve (b2contact: b2ContactExtends, impulse: b2.ContactImpulse): void {
|
||||
const c: PhysicsContact = b2contact.m_userData as PhysicsContact;
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
@@ -448,4 +449,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
c.emit(Contact2DType.POST_SOLVE);
|
||||
c._setImpulse(null);
|
||||
}
|
||||
clearContacts (): void {
|
||||
PhysicsContactManager.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,8 +37,8 @@ export class b2CircleShape extends b2Shape2D implements ICircleShape {
|
||||
|
||||
_worldPosition = new Vec2();
|
||||
get worldPosition (): Vec2 {
|
||||
const p = (this._shapes[0] as b2.CircleShape).m_p;
|
||||
return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO);
|
||||
const comp = this.collider as CircleCollider2D;
|
||||
return Vec2.transformMat4(this._worldPosition, comp.offset, comp.node.worldMatrix);
|
||||
}
|
||||
|
||||
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): any[] {
|
||||
|
||||
@@ -285,4 +285,6 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld {
|
||||
raycast (p1: IVec2Like, p2: IVec2Like, type: ERaycast2DType): RaycastResult2D[] {
|
||||
return [];
|
||||
}
|
||||
clearContacts (): void {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ import { EDITOR, DEBUG, TEST, EDITOR_NOT_IN_PREVIEW } from 'internal:constants';
|
||||
import { IRigidBody2D } from '../spec/i-rigid-body';
|
||||
import { IBoxShape, ICircleShape, IPolygonShape, IBaseShape } from '../spec/i-physics-shape';
|
||||
import { IPhysicsWorld } from '../spec/i-physics-world';
|
||||
import { errorID, log } from '../../core';
|
||||
import { debug, errorID, log } from '../../core';
|
||||
import { ECollider2DType, EJoint2DType } from './physics-types';
|
||||
import { IJoint2D, IDistanceJoint, ISpringJoint, IFixedJoint, IMouseJoint,
|
||||
IRelativeJoint, ISliderJoint, IWheelJoint, IHingeJoint } from '../spec/i-physics-joint';
|
||||
@@ -110,7 +110,7 @@ export interface IPhysicsSelector {
|
||||
}
|
||||
|
||||
function register (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject): void {
|
||||
if (!EDITOR && !TEST) log(`[PHYSICS2D]: register ${id}.`);
|
||||
if (!EDITOR && !TEST) debug(`[PHYSICS2D]: register ${id}.`);
|
||||
selector.backend[id] = wrapper;
|
||||
if (!selector.physicsWorld || selector.id === id) {
|
||||
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
||||
@@ -124,12 +124,12 @@ function switchTo (id: IPhysicsEngineId): void {
|
||||
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
||||
if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) {
|
||||
//selector.physicsWorld.destroy();//todo
|
||||
if (!TEST) log(`[PHYSICS2D]: switch from ${selector.id} to ${id}.`);
|
||||
if (!TEST) debug(`[PHYSICS2D]: switch from ${selector.id} to ${id}.`);
|
||||
mutableSelector.id = id;
|
||||
mutableSelector.wrapper = selector.backend[id];
|
||||
mutableSelector.physicsWorld = createPhysicsWorld();
|
||||
} else {
|
||||
if (!EDITOR && !TEST) log(`[PHYSICS2D]: using ${mutableSelector.id}.`);
|
||||
if (!EDITOR && !TEST) debug(`[PHYSICS2D]: using ${mutableSelector.id}.`);
|
||||
mutableSelector.physicsWorld = createPhysicsWorld();
|
||||
}
|
||||
}
|
||||
@@ -165,6 +165,7 @@ const ENTIRE_WORLD: IPhysicsWorld = {
|
||||
testPoint: FUNC,
|
||||
testAABB: FUNC,
|
||||
drawDebug: FUNC,
|
||||
clearContacts: FUNC,
|
||||
};
|
||||
|
||||
export function checkPhysicsModule (obj: any): boolean {
|
||||
|
||||
@@ -381,8 +381,12 @@ export class PhysicsSystem2D extends Eventify(System) {
|
||||
static constructAndRegister (): void {
|
||||
director.registerSystem(PhysicsSystem2D.ID, PhysicsSystem2D.instance, SystemPriority.LOW);
|
||||
}
|
||||
clearContacts (): void {
|
||||
this.physicsWorld.clearContacts();
|
||||
}
|
||||
}
|
||||
|
||||
if (!BUILD || !LOAD_BOX2D_MANUALLY) {
|
||||
director.once(DirectorEvent.INIT, (): void => { PhysicsSystem2D.constructAndRegister(); });
|
||||
director.once(DirectorEvent.RESET, (): void => { PhysicsSystem2D.instance.clearContacts(); });
|
||||
}
|
||||
|
||||
@@ -38,4 +38,5 @@ export interface IPhysicsWorld {
|
||||
testPoint (p: Vec2): readonly Collider2D[];
|
||||
testAABB (rect: Rect): readonly Collider2D[];
|
||||
drawDebug (): void;
|
||||
clearContacts (): void;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
import { ensureWasmModuleReady, instantiateWasm } from 'pal/wasm';
|
||||
import { BUILD, LOAD_BULLET_MANUALLY, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
|
||||
import { game } from '../../game';
|
||||
import { error, log, sys } from '../../core';
|
||||
import { debug, error, sys } from '../../core';
|
||||
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
|
||||
import type { BulletCache } from './bullet-cache';
|
||||
|
||||
@@ -106,7 +106,7 @@ function initWASM (wasmFactory, wasmUrl: string): Promise<void> {
|
||||
}).catch((err) => reject(errorMessage(err)));
|
||||
},
|
||||
}).then((instance: any) => {
|
||||
log('[bullet]:bullet wasm lib loaded.');
|
||||
debug('[bullet]:bullet wasm lib loaded.');
|
||||
bt = instance as Bullet.instance;
|
||||
globalThis.Bullet = bt as any;
|
||||
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
|
||||
@@ -117,7 +117,7 @@ function initASM (asmFactory): Promise<void> {
|
||||
if (asmFactory != null) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return asmFactory().then((instance: any) => {
|
||||
log('[bullet]:bullet asm lib loaded.');
|
||||
debug('[bullet]:bullet asm lib loaded.');
|
||||
bt = instance as Bullet.instance;
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -35,7 +35,7 @@ import {
|
||||
import { IPhysicsWorld } from '../spec/i-physics-world';
|
||||
import { IRigidBody } from '../spec/i-rigid-body';
|
||||
import { IBoxCharacterController, ICapsuleCharacterController } from '../spec/i-character-controller';
|
||||
import { errorID, IVec3Like, warn, cclegacy, log } from '../../core';
|
||||
import { errorID, IVec3Like, warn, cclegacy, debug } from '../../core';
|
||||
import { EColliderType, EConstraintType, ECharacterControllerType } from './physics-enum';
|
||||
import { PhysicsMaterial } from '.';
|
||||
|
||||
@@ -125,7 +125,7 @@ function updateLegacyMacro (id: string): void {
|
||||
}
|
||||
|
||||
function register (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject): void {
|
||||
if (!EDITOR && !TEST) log(`[PHYSICS]: register ${id}.`);
|
||||
if (!EDITOR && !TEST) debug(`[PHYSICS]: register ${id}.`);
|
||||
selector.backend[id] = wrapper;
|
||||
if (!selector.physicsWorld || selector.id === id) {
|
||||
updateLegacyMacro(id);
|
||||
@@ -147,13 +147,13 @@ function switchTo (id: IPhysicsEngineId): void {
|
||||
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
||||
if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) {
|
||||
selector.physicsWorld.destroy();
|
||||
if (!TEST) log(`[PHYSICS]: switch from ${selector.id} to ${id}.`);
|
||||
if (!TEST) debug(`[PHYSICS]: switch from ${selector.id} to ${id}.`);
|
||||
updateLegacyMacro(id);
|
||||
mutableSelector.id = id;
|
||||
mutableSelector.wrapper = selector.backend[id];
|
||||
mutableSelector.physicsWorld = createPhysicsWorld();
|
||||
} else {
|
||||
if (!EDITOR && !TEST) log(`[PHYSICS]: using ${id}.`);
|
||||
if (!EDITOR && !TEST) debug(`[PHYSICS]: using ${id}.`);
|
||||
mutableSelector.physicsWorld = createPhysicsWorld();
|
||||
}
|
||||
if (worldInitData) {
|
||||
@@ -185,7 +185,7 @@ export function constructDefaultWorld (data: IWorldInitData): void {
|
||||
if (!worldInitData) worldInitData = data;
|
||||
if (!selector.runInEditor) return;
|
||||
if (!selector.physicsWorld) {
|
||||
if (!TEST) log(`[PHYSICS]: using ${selector.id}.`);
|
||||
if (!TEST) debug(`[PHYSICS]: using ${selector.id}.`);
|
||||
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
||||
const world = mutableSelector.physicsWorld = createPhysicsWorld();
|
||||
world.setGravity(worldInitData.gravity);
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
import { cclegacy } from './core/global-exports';
|
||||
import { DataPoolManager } from './3d/skeletal-animation/data-pool-manager';
|
||||
import { Device, deviceManager } from './gfx';
|
||||
import { settings, Settings, warnID, Pool, macro, log } from './core';
|
||||
import { settings, Settings, warnID, Pool, macro, log, debug } from './core';
|
||||
import { PipelineEventProcessor } from './rendering/pipeline-event';
|
||||
import type { Root as JsbRoot } from './root';
|
||||
|
||||
@@ -242,7 +242,7 @@ rootProto.setRenderPipeline = function (customPipeline: boolean) {
|
||||
if (customPipeline) {
|
||||
cclegacy.rendering.createCustomPipeline();
|
||||
ppl = oldSetPipeline.call(this, null);
|
||||
log(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
|
||||
debug(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
|
||||
} else {
|
||||
// pipeline should not be created in C++, ._ctor need to be triggered
|
||||
if (cclegacy.legacy_rendering) {
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
*/
|
||||
|
||||
import { USE_XR } from 'internal:constants';
|
||||
import { Pool, cclegacy, warnID, settings, macro, log, errorID, SettingsCategory } from './core';
|
||||
import { Pool, cclegacy, warnID, settings, macro, log, errorID, SettingsCategory, debug } from './core';
|
||||
import { DebugView } from './rendering/debug-view';
|
||||
import { Camera, CameraType, Light, Model, TrackingType } from './render-scene/scene';
|
||||
import type { DataPoolManager } from './3d/skeletal-animation/data-pool-manager';
|
||||
@@ -380,11 +380,11 @@ export class Root {
|
||||
isCreateDefaultPipeline = true;
|
||||
this._pipeline = this._customPipeline!;
|
||||
// Use default _pipelineEvent
|
||||
log(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
|
||||
debug(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
|
||||
} else {
|
||||
const rppl: (PipelineRuntime & IPipelineEvent) = legacy_rendering.createDefaultPipeline();
|
||||
isCreateDefaultPipeline = true;
|
||||
log(`Using legacy pipeline`);
|
||||
debug(`Using legacy pipeline`);
|
||||
|
||||
this._classicPipeline = rppl!;
|
||||
this._pipeline = this._classicPipeline;
|
||||
|
||||
@@ -33,16 +33,16 @@ const MAGIC = 0x4E4F4343;
|
||||
const CHUNK_ALIGN_AS = 8;
|
||||
|
||||
export class CCON {
|
||||
constructor (document: unknown, chunks: Uint8Array[]) {
|
||||
constructor(document: unknown, chunks: Uint8Array[]) {
|
||||
this._document = document;
|
||||
this._chunks = chunks;
|
||||
}
|
||||
|
||||
get document (): unknown {
|
||||
get document(): unknown {
|
||||
return this._document;
|
||||
}
|
||||
|
||||
get chunks (): Uint8Array[] {
|
||||
get chunks(): Uint8Array[] {
|
||||
return this._chunks;
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ export class CCON {
|
||||
private declare _chunks: Uint8Array[];
|
||||
}
|
||||
|
||||
export function encodeCCONBinary (ccon: CCON): Uint8Array {
|
||||
export function encodeCCONBinary(ccon: CCON): Uint8Array {
|
||||
const { document, chunks } = ccon;
|
||||
|
||||
const jsonBytes = new Uint8Array(notepackEncode(document));
|
||||
@@ -75,7 +75,7 @@ export function encodeCCONBinary (ccon: CCON): Uint8Array {
|
||||
headerView.setUint32(8, ccobBuilder.byteLength, true);
|
||||
return ccobBuilder.get();
|
||||
|
||||
function uint32Bytes (value: number): ArrayBufferView {
|
||||
function uint32Bytes(value: number): ArrayBufferView {
|
||||
const bytes = new ArrayBuffer(4);
|
||||
const view = new DataView(bytes);
|
||||
view.setUint32(0, value, true);
|
||||
@@ -83,7 +83,7 @@ export function encodeCCONBinary (ccon: CCON): Uint8Array {
|
||||
}
|
||||
}
|
||||
|
||||
export function decodeCCONBinary (bytes: Uint8Array): CCON {
|
||||
export function decodeCCONBinary(bytes: Uint8Array): CCON {
|
||||
if (bytes.length < 16) {
|
||||
throw new InvalidCCONError(getError(13102));
|
||||
}
|
||||
@@ -159,7 +159,7 @@ interface BufferConstructor {
|
||||
from(buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): Buffer;
|
||||
}
|
||||
|
||||
function decodeJson (data: Uint8Array): string {
|
||||
function decodeJson(data: Uint8Array): string {
|
||||
if (typeof TextDecoder !== 'undefined') {
|
||||
return new TextDecoder().decode(data);
|
||||
} else if ('Buffer' in globalThis) {
|
||||
@@ -177,13 +177,13 @@ export class BufferBuilder {
|
||||
private _viewOrPaddings: (ArrayBufferView | number)[] = [];
|
||||
private _length = 0;
|
||||
|
||||
constructor () {}
|
||||
constructor() { }
|
||||
|
||||
get byteLength (): number {
|
||||
get byteLength(): number {
|
||||
return this._length;
|
||||
}
|
||||
|
||||
public alignAs (align: number): number {
|
||||
public alignAs(align: number): number {
|
||||
if (align !== 0) {
|
||||
const remainder = this._length % align;
|
||||
if (remainder !== 0) {
|
||||
@@ -196,14 +196,14 @@ export class BufferBuilder {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public append (view: ArrayBufferView): number {
|
||||
public append(view: ArrayBufferView): number {
|
||||
const result = this._length;
|
||||
this._viewOrPaddings.push(view);
|
||||
this._length += view.byteLength;
|
||||
return result;
|
||||
}
|
||||
|
||||
public get (): Uint8Array {
|
||||
public get(): Uint8Array {
|
||||
const result = new Uint8Array(this._length);
|
||||
let counter = 0;
|
||||
this._viewOrPaddings.forEach((viewOrPadding) => {
|
||||
@@ -219,4 +219,6 @@ export class BufferBuilder {
|
||||
}
|
||||
|
||||
cclegacy.internal.decodeCCONBinary = decodeCCONBinary;
|
||||
cclegacy.internal.encodeCCONBinary = encodeCCONBinary;
|
||||
cclegacy.internal.CCON = CCON;
|
||||
cclegacy.internal.BufferBuilder = BufferBuilder;
|
||||
|
||||
@@ -42,6 +42,24 @@ declare namespace spine {
|
||||
delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
class SPVectorPhysicsConstraintPtr {
|
||||
size(): number;
|
||||
get(index: number): PhysicsConstraint;
|
||||
delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
class SPVectorPhysicsConstraintDataPtr {
|
||||
size(): number;
|
||||
get(index: number): PhysicsConstraintData;
|
||||
delete();
|
||||
}
|
||||
|
||||
class Animation {
|
||||
constructor(name: string, timelines: Array<Timeline>, duration: number);
|
||||
duration: number;
|
||||
@@ -708,6 +726,10 @@ declare namespace spine {
|
||||
ikConstraints: Array<IkConstraint>;
|
||||
transformConstraints: Array<TransformConstraint>;
|
||||
pathConstraints: Array<PathConstraint>;
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
physicsConstraints: Array<PhysicsConstraint>;
|
||||
_updateCache: Updatable[];
|
||||
skin: Skin;
|
||||
color: Color;
|
||||
@@ -735,8 +757,24 @@ declare namespace spine {
|
||||
findIkConstraint(constraintName: string): IkConstraint;
|
||||
findTransformConstraint(constraintName: string): TransformConstraint;
|
||||
findPathConstraint(constraintName: string): PathConstraint;
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
findPhysicsConstraint(constraintName: string): PhysicsConstraint;
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
getPhysicsConstraints(): SPVectorPhysicsConstraintPtr;
|
||||
//getBounds(offset: Vector2, size: Vector2, temp?: Array<number>): void;
|
||||
update(delta: number): void;
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
updateWorldTransform(physics: Physics): void;
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
updateWorldTransform(physics: Physics, parent: Bone): void;
|
||||
}
|
||||
class SkeletonBinary {
|
||||
static AttachmentTypeValues: number[];
|
||||
@@ -812,6 +850,10 @@ declare namespace spine {
|
||||
ikConstraints: IkConstraintData[];
|
||||
transformConstraints: TransformConstraintData[];
|
||||
pathConstraints: PathConstraintData[];
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
physicsConstraints: PhysicsConstraintData[];
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
@@ -835,6 +877,14 @@ declare namespace spine {
|
||||
findTransformConstraint(constraintName: string): TransformConstraintData;
|
||||
findPathConstraint(constraintName: string): PathConstraintData;
|
||||
findPathConstraintIndex(pathConstraintName: string): number;
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
findPhysicsConstraint(constraintName: string): PhysicsConstraintData;
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
getPhysicsConstraints(): SPVectorPhysicsConstraintDataPtr;
|
||||
}
|
||||
class SkeletonJson {
|
||||
attachmentLoader: AttachmentLoader;
|
||||
@@ -1005,6 +1055,82 @@ declare namespace spine {
|
||||
local: boolean;
|
||||
constructor(name: string);
|
||||
}
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
enum Physics {
|
||||
none = 0,
|
||||
reset = 1,
|
||||
update = 2,
|
||||
pose = 3
|
||||
}
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
class PhysicsConstraint implements Updatable {
|
||||
data: PhysicsConstraintData;
|
||||
bone: Bone;
|
||||
inertia: number;
|
||||
strength: number;
|
||||
damping: number;
|
||||
massInverse: number;
|
||||
wind: number;
|
||||
gravity: number;
|
||||
mix: number;
|
||||
_reset: boolean;
|
||||
ux: number;
|
||||
uy: number;
|
||||
cx: number;
|
||||
cy: number;
|
||||
tx: number;
|
||||
ty: number;
|
||||
xOffset: number;
|
||||
xVelocity: number;
|
||||
yOffset: number;
|
||||
yVelocity: number;
|
||||
rotateOffset: number;
|
||||
rotateVelocity: number;
|
||||
scaleOffset: number;
|
||||
scaleVelocity: number;
|
||||
remaining: number;
|
||||
lastTime: number;
|
||||
active: boolean;
|
||||
constructor(data: PhysicsConstraintData, skeleton: Skeleton);
|
||||
isActive(): boolean;
|
||||
reset(): void;
|
||||
setToSetupPose(): void;
|
||||
update(): void;
|
||||
translate(x: number, y: number): void;
|
||||
rotate(x: number, y: number, degrees: number): void;
|
||||
}
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
class PhysicsConstraintData extends ConstraintData {
|
||||
bone: BoneData;
|
||||
x: number;
|
||||
y: number;
|
||||
rotate: number;
|
||||
scaleX: number;
|
||||
shearX: number;
|
||||
limit: number;
|
||||
step: number;
|
||||
inertia: number;
|
||||
strength: number;
|
||||
damping: number;
|
||||
massInverse: number;
|
||||
wind: number;
|
||||
gravity: number;
|
||||
mix: number;
|
||||
inertiaGlobal: boolean;
|
||||
strengthGlobal: boolean;
|
||||
dampingGlobal: boolean;
|
||||
massGlobal: boolean;
|
||||
windGlobal: boolean;
|
||||
gravityGlobal: boolean;
|
||||
mixGlobal: boolean;
|
||||
constructor(name: string);
|
||||
}
|
||||
class Triangulator {
|
||||
private convexPolygons;
|
||||
private convexPolygonsIndices;
|
||||
|
||||
|
Before Width: | Height: | Size: 8.4 KiB After Width: | Height: | Size: 6.8 KiB |
|
Before Width: | Height: | Size: 8.8 KiB After Width: | Height: | Size: 945 B |
|
Before Width: | Height: | Size: 9.4 KiB After Width: | Height: | Size: 5.2 KiB |
|
Before Width: | Height: | Size: 9.2 KiB After Width: | Height: | Size: 7.2 KiB |
|
Before Width: | Height: | Size: 9.4 KiB After Width: | Height: | Size: 6.0 KiB |
|
Before Width: | Height: | Size: 9.2 KiB After Width: | Height: | Size: 4.5 KiB |
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"ver": "1.2.0",
|
||||
"importer": "directory",
|
||||
"imported": true,
|
||||
"uuid": "6ef37a33-5db9-4231-9855-f72b8428f6fa",
|
||||
"files": [],
|
||||
"subMetas": {},
|
||||
"userData": {}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"ver": "1.0.4",
|
||||
"importer": "texture-cube",
|
||||
"imported": true,
|
||||
"uuid": "a4063d6c-c46e-482a-bf84-99eb9fbb2789",
|
||||
"files": [
|
||||
".json"
|
||||
],
|
||||
"subMetas": {},
|
||||
"userData": {
|
||||
"wrapModeS": "repeat",
|
||||
"wrapModeT": "repeat",
|
||||
"minfilter": "linear",
|
||||
"magfilter": "linear",
|
||||
"mipfilter": "none",
|
||||
"anisotropy": 0,
|
||||
"isRGBE": false
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,11 @@ module.exports = {
|
||||
newCubeMap: 'CubeMap',
|
||||
newRenderTexture: 'Render Texture',
|
||||
newScene: 'Scene',
|
||||
newScene:{
|
||||
'2d': '2D Scene',
|
||||
'3d': '3D Scene',
|
||||
quality: 'High Quality Scene',
|
||||
},
|
||||
newPrefab: 'Node Prefab',
|
||||
newMaterial: 'Material',
|
||||
newPhysicsMaterial: 'Physics Material',
|
||||
|
||||
@@ -779,6 +779,7 @@ module.exports = link(mixin({
|
||||
},
|
||||
mask: {
|
||||
type: 'The mask type',
|
||||
radius: 'The radius for rounded corners of rect mask',
|
||||
spriteFrame: 'The mask image',
|
||||
inverted: 'The Reverse mask (Not supported Canvas Mode)',
|
||||
alphaThreshold:
|
||||
|
||||
@@ -37,6 +37,11 @@ module.exports = {
|
||||
newTypeScript: '脚本 (TypeScript)',
|
||||
newCubeMap: '立方体贴图',
|
||||
newScene: '场景',
|
||||
newScene:{
|
||||
'2d': '2D 场景',
|
||||
'3d': '3D 场景',
|
||||
quality: '高质量场景',
|
||||
},
|
||||
newPrefab: '预制 (Prefab)',
|
||||
newRenderTexture: '渲染纹理 (Render Texture)',
|
||||
newMaterial: '材质',
|
||||
|
||||
@@ -760,6 +760,7 @@ module.exports = link(mixin({
|
||||
},
|
||||
mask: {
|
||||
type: '遮罩类型',
|
||||
radius: '矩形遮罩的圆角半径',
|
||||
spriteFrame: '遮罩所需要的贴图',
|
||||
inverted: '反向遮罩(不支持 Canvas 模式)',
|
||||
alphaThreshold: 'Alpha 阈值,只有当模板的像素的 Alpha 大于 Alpha Threshold 时,才会绘制内容(不支持 Canvas 模式)',
|
||||
|
||||
@@ -55,7 +55,18 @@ MeshBuffer *MiddlewareManager::getMeshBuffer(int format) {
|
||||
}
|
||||
|
||||
void MiddlewareManager::updateOperateCache() {
|
||||
for (const auto &op : _operateCacheQueue) {
|
||||
if (_operateCacheQueue.empty()) return;
|
||||
|
||||
ccstd::vector<IMiddleware*> seen;
|
||||
ccstd::vector<std::pair<IMiddleware*, bool>> finalOperations;
|
||||
for (auto it = _operateCacheQueue.rbegin(); it != _operateCacheQueue.rend(); ++it) {
|
||||
if (std::find(seen.begin(), seen.end(), it->first) == seen.end()) {
|
||||
seen.push_back(it->first);
|
||||
finalOperations.emplace_back(it->first, it->second);
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto &op : finalOperations) {
|
||||
IMiddleware *editor = op.first;
|
||||
bool isAddOperation = op.second;
|
||||
|
||||
@@ -88,12 +99,19 @@ void MiddlewareManager::update(float dt) {
|
||||
}
|
||||
|
||||
void MiddlewareManager::render(float dt) {
|
||||
// Object._deferredDestroy is called after component update in Director.tick and before emitting BEFORE_DRAW event in which MiddlewareManager::render is invoked,
|
||||
// so the native object may be released here and it needs to be erased from _updateList.
|
||||
for (auto &iter : _operateCacheQueue) {
|
||||
auto it = std::find(_updateList.begin(), _updateList.end(), iter.first);
|
||||
if (!iter.second && it != _updateList.end()) {
|
||||
_updateList.erase(it);
|
||||
ccstd::vector<IMiddleware*> skipRenderList;
|
||||
if (!_operateCacheQueue.empty()) {
|
||||
ccstd::vector<IMiddleware*> seen;
|
||||
// Object._deferredDestroy is called after component update in Director.tick and before emitting BEFORE_DRAW event in which MiddlewareManager::render is invoked,
|
||||
// so the native object may be released here.
|
||||
// We shouldn't execute editor->render(dt) if it's already removed in _operateCacheQueue.
|
||||
for (auto it = _operateCacheQueue.rbegin(); it != _operateCacheQueue.rend(); ++it) {
|
||||
if (std::find(seen.begin(), seen.end(), it->first) == seen.end()) {
|
||||
seen.push_back(it->first);
|
||||
if (!it->second) {
|
||||
skipRenderList.push_back(it->first);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,6 +124,9 @@ void MiddlewareManager::render(float dt) {
|
||||
|
||||
for (size_t i = 0, len = _updateList.size(); i < len; ++i) {
|
||||
auto *editor = _updateList[i];
|
||||
if (!skipRenderList.empty() && std::find(skipRenderList.begin(), skipRenderList.end(), editor) != skipRenderList.end()) {
|
||||
continue;
|
||||
}
|
||||
editor->render(dt);
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ using SPVectorIkConstraintPtr = Vector<IkConstraint*>;
|
||||
using SPVectorIkConstraintDataPtr = Vector<IkConstraintData*>;
|
||||
using SPVectorTransformConstraintPtr = Vector<TransformConstraint*>;
|
||||
using SPVectorPathConstraintPtr = Vector<PathConstraint*>;
|
||||
using SPVectorPhysicsConstraintPtr = Vector<PhysicsConstraint*>;
|
||||
using SPVectorTimelinePtr = Vector<Timeline*>;
|
||||
using SPVectorTrackEntryPtr = Vector<TrackEntry*>;
|
||||
using SPVectorUpdatablePtr = Vector<Updatable*>;
|
||||
@@ -207,6 +208,8 @@ DEFINE_ALLOW_RAW_POINTER(TrackEntry)
|
||||
DEFINE_ALLOW_RAW_POINTER(IkConstraintData)
|
||||
DEFINE_ALLOW_RAW_POINTER(PathConstraintData)
|
||||
DEFINE_ALLOW_RAW_POINTER(TransformConstraintData)
|
||||
DEFINE_ALLOW_RAW_POINTER(PhysicsConstraintData)
|
||||
DEFINE_ALLOW_RAW_POINTER(PhysicsConstraint)
|
||||
DEFINE_ALLOW_RAW_POINTER(SPVectorUnsignedShort)
|
||||
DEFINE_ALLOW_RAW_POINTER(SPVectorFloat)
|
||||
DEFINE_ALLOW_RAW_POINTER(SPVectorEventPtr)
|
||||
@@ -516,7 +519,7 @@ EMSCRIPTEN_BINDINGS(spine) {
|
||||
REGISTER_SPINE_ENUM(TextureFilter);
|
||||
REGISTER_SPINE_ENUM(TextureWrap);
|
||||
REGISTER_SPINE_ENUM(AttachmentType);
|
||||
|
||||
REGISTER_SPINE_ENUM(Physics);
|
||||
|
||||
REGISTER_SPINE_VECTOR(SPVectorDebugShape, false);
|
||||
|
||||
@@ -544,7 +547,9 @@ EMSCRIPTEN_BINDINGS(spine) {
|
||||
REGISTER_SPINE_VECTOR(SPVectorIkConstraintDataPtr, false);
|
||||
REGISTER_SPINE_VECTOR(SPVectorTransformConstraintPtr, false);
|
||||
REGISTER_SPINE_VECTOR(SPVectorPathConstraintPtr, false);
|
||||
REGISTER_SPINE_VECTOR(SPVectorTimelinePtr, true); // .set used in Animation constructor
|
||||
REGISTER_SPINE_VECTOR(SPVectorTimelinePtr, true); // .set used in Animation constructor
|
||||
REGISTER_SPINE_VECTOR(SPVectorPhysicsConstraintDataPtr, false);
|
||||
REGISTER_SPINE_VECTOR(SPVectorPhysicsConstraintPtr, false);
|
||||
REGISTER_SPINE_VECTOR(SPVectorTrackEntryPtr, false);
|
||||
REGISTER_SPINE_VECTOR(SPVectorUpdatablePtr, false);
|
||||
REGISTER_SPINE_VECTOR(SPVectorSkinEntryPtr, false);
|
||||
@@ -879,6 +884,64 @@ EMSCRIPTEN_BINDINGS(spine) {
|
||||
.property("mixScaleY", &TransformConstraint::getMixScaleY)
|
||||
.property("mixShearY", &TransformConstraint::getMixShearY);
|
||||
|
||||
class_<PhysicsConstraintData, base<ConstraintData>>("PhysicsConstraintData")
|
||||
.constructor<const String &>()
|
||||
.property("bone", &PhysicsConstraintData::getBone)
|
||||
.property("x", &PhysicsConstraintData::getX, &PhysicsConstraintData::setX)
|
||||
.property("y", &PhysicsConstraintData::getY, &PhysicsConstraintData::setY)
|
||||
.property("rotate", &PhysicsConstraintData::getRotate, &PhysicsConstraintData::setRotate)
|
||||
.property("scaleX", &PhysicsConstraintData::getScaleX, &PhysicsConstraintData::setScaleX)
|
||||
.property("shearX", &PhysicsConstraintData::getShearX, &PhysicsConstraintData::setShearX)
|
||||
.property("limit", &PhysicsConstraintData::getLimit, &PhysicsConstraintData::setLimit)
|
||||
.property("step", &PhysicsConstraintData::getStep, &PhysicsConstraintData::setStep)
|
||||
.property("inertia", &PhysicsConstraintData::getInertia, &PhysicsConstraintData::setInertia)
|
||||
.property("strength", &PhysicsConstraintData::getStrength, &PhysicsConstraintData::setStrength)
|
||||
.property("damping", &PhysicsConstraintData::getDamping, &PhysicsConstraintData::setDamping)
|
||||
.property("massInverse", &PhysicsConstraintData::getMassInverse, &PhysicsConstraintData::setMassInverse)
|
||||
.property("wind", &PhysicsConstraintData::getWind, &PhysicsConstraintData::setWind)
|
||||
.property("gravity", &PhysicsConstraintData::getGravity, &PhysicsConstraintData::setGravity)
|
||||
.property("mix", &PhysicsConstraintData::getMix, &PhysicsConstraintData::setMix)
|
||||
.property("inertiaGlobal", &PhysicsConstraintData::isInertiaGlobal, &PhysicsConstraintData::setInertiaGlobal)
|
||||
.property("strengthGlobal", &PhysicsConstraintData::isStrengthGlobal, &PhysicsConstraintData::setStrengthGlobal)
|
||||
.property("dampingGlobal", &PhysicsConstraintData::isDampingGlobal, &PhysicsConstraintData::setDampingGlobal)
|
||||
.property("massGlobal", &PhysicsConstraintData::isMassGlobal, &PhysicsConstraintData::setMassGlobal)
|
||||
.property("windGlobal", &PhysicsConstraintData::isWindGlobal, &PhysicsConstraintData::setWindGlobal)
|
||||
.property("gravityGlobal", &PhysicsConstraintData::isGravityGlobal, &PhysicsConstraintData::setGravityGlobal)
|
||||
.property("mixGlobal", &PhysicsConstraintData::isMixGlobal, &PhysicsConstraintData::setMixGlobal);
|
||||
|
||||
class_<PhysicsConstraint, base<Updatable>>("PhysicsConstraint")
|
||||
.constructor<PhysicsConstraintData &, Skeleton &>()
|
||||
.property("data", GETTER_RVAL_TO_PTR(PhysicsConstraint, getData, PhysicsConstraintData*))
|
||||
.property("bone", &PhysicsConstraint::getBone, &PhysicsConstraint::setBone)
|
||||
.property("inertia", &PhysicsConstraint::getInertia, &PhysicsConstraint::setInertia)
|
||||
.property("strength", &PhysicsConstraint::getStrength, &PhysicsConstraint::setStrength)
|
||||
.property("damping", &PhysicsConstraint::getDamping, &PhysicsConstraint::setDamping)
|
||||
.property("massInverse", &PhysicsConstraint::getMassInverse, &PhysicsConstraint::setMassInverse)
|
||||
.property("wind", &PhysicsConstraint::getWind, &PhysicsConstraint::setWind)
|
||||
.property("gravity", &PhysicsConstraint::getGravity, &PhysicsConstraint::setGravity)
|
||||
.property("mix", &PhysicsConstraint::getMix, &PhysicsConstraint::setMix)
|
||||
.property("_reset", &PhysicsConstraint::getReset, &PhysicsConstraint::setReset)
|
||||
.property("ux", &PhysicsConstraint::getUx, &PhysicsConstraint::setUx)
|
||||
.property("uy", &PhysicsConstraint::getUy, &PhysicsConstraint::setUy)
|
||||
.property("cx", &PhysicsConstraint::getCx, &PhysicsConstraint::setCx)
|
||||
.property("cy", &PhysicsConstraint::getCy, &PhysicsConstraint::setCy)
|
||||
.property("tx", &PhysicsConstraint::getTx, &PhysicsConstraint::setTx)
|
||||
.property("ty", &PhysicsConstraint::getTy, &PhysicsConstraint::setTy)
|
||||
.property("xOffset", &PhysicsConstraint::getXOffset, &PhysicsConstraint::setXOffset)
|
||||
.property("xVelocity", &PhysicsConstraint::getXVelocity, &PhysicsConstraint::setXVelocity)
|
||||
.property("yOffset", &PhysicsConstraint::getYOffset, &PhysicsConstraint::setYOffset)
|
||||
.property("yVelocity", &PhysicsConstraint::getYVelocity, &PhysicsConstraint::setYVelocity)
|
||||
.property("rotateOffset", &PhysicsConstraint::getRotateOffset, &PhysicsConstraint::setRotateOffset)
|
||||
.property("rotateVelocity", &PhysicsConstraint::getRotateVelocity, &PhysicsConstraint::setRotateVelocity)
|
||||
.property("scaleOffset", &PhysicsConstraint::getScaleOffset, &PhysicsConstraint::setScaleOffset)
|
||||
.property("scaleVelocity", &PhysicsConstraint::getScaleVelocity, &PhysicsConstraint::setScaleVelocity)
|
||||
.property("remaining", &PhysicsConstraint::getRemaining, &PhysicsConstraint::setRemaining)
|
||||
.property("lastTime", &PhysicsConstraint::getLastTime, &PhysicsConstraint::setLastTime)
|
||||
.function("reset", &PhysicsConstraint::reset)
|
||||
.function("setToSetupPose", &PhysicsConstraint::setToSetupPose)
|
||||
.function("translate", &PhysicsConstraint::translate)
|
||||
.function("rotate", &PhysicsConstraint::rotate);
|
||||
|
||||
class_<Bone, base<Updatable>>("Bone")
|
||||
.constructor<BoneData &, Skeleton &, Bone *>()
|
||||
.property("data", GETTER_RVAL_TO_PTR(Bone, getData, BoneData*))
|
||||
@@ -1058,7 +1121,7 @@ EMSCRIPTEN_BINDINGS(spine) {
|
||||
.function("findAnimation", &SkeletonData::findAnimation, allow_raw_pointers())
|
||||
.function("findIkConstraint", &SkeletonData::findIkConstraint, allow_raw_pointers())
|
||||
.function("findTransformConstraint", &SkeletonData::findTransformConstraint, allow_raw_pointers())
|
||||
.function("findPhysicsConstraint", &SkeletonData::findPathConstraint, allow_raw_pointers())
|
||||
.function("findPhysicsConstraint", &SkeletonData::findPhysicsConstraint, allow_raw_pointers())
|
||||
.function("findPathConstraint", &SkeletonData::findPathConstraint, allow_raw_pointers());
|
||||
|
||||
class_<Animation>("Animation")
|
||||
@@ -1295,6 +1358,8 @@ EMSCRIPTEN_BINDINGS(spine) {
|
||||
return &obj.getTransformConstraints(); }), allow_raw_pointer<SPVectorTransformConstraintPtr>())
|
||||
.function("getPathConstraints", optional_override([](Skeleton &obj){
|
||||
return &obj.getPathConstraints(); }), allow_raw_pointer<SPVectorPathConstraintPtr>())
|
||||
.function("getPhysicsConstraints", optional_override([](Skeleton &obj){
|
||||
return &obj.getPhysicsConstraints(); }), allow_raw_pointer<SPVectorPhysicsConstraintPtr>())
|
||||
.function("getUpdateCacheList", optional_override([](Skeleton &obj){
|
||||
return &obj.getUpdateCacheList(); }), allow_raw_pointer<SPVectorUpdatablePtr>())
|
||||
.property("skin", &Skeleton::_skin)
|
||||
@@ -1322,6 +1387,7 @@ EMSCRIPTEN_BINDINGS(spine) {
|
||||
.function("findIkConstraint", &Skeleton::findIkConstraint, allow_raw_pointers())
|
||||
.function("findTransformConstraint", &Skeleton::findTransformConstraint, allow_raw_pointers())
|
||||
.function("findPathConstraint", &Skeleton::findPathConstraint, allow_raw_pointers())
|
||||
.function("findPhysicsConstraint", &Skeleton::findPhysicsConstraint, allow_raw_pointers())
|
||||
//.function("getBounds", optional_override([](Skeleton &obj, &outX, ) {}), allow_raw_pointers())
|
||||
.function("update", &Skeleton::update);
|
||||
|
||||
|
||||
@@ -14,6 +14,10 @@ using namespace spine;
|
||||
HashMap<SkeletonData *, HashMap<Attachment *, AttachmentVertices *>*> spineAttachmentVerticesMap{};
|
||||
HashMap<SkeletonData *, HashMap<spine::String, spine::String>*> spineTexturesMap{};
|
||||
|
||||
#ifdef CC_SPINE_VERSION_4_2
|
||||
HashMap<SkeletonData *, Atlas*> spineAtlasMap{};
|
||||
#endif
|
||||
|
||||
|
||||
static const uint16_t quadTriangles[6] = {0, 1, 2, 2, 3, 0};
|
||||
|
||||
@@ -193,7 +197,12 @@ SkeletonData* SpineWasmUtil::createSpineSkeletonDataWithJson(const String& jsonS
|
||||
|
||||
saveAttachmentVertices(skeletonData, textureNames, textureUUIDs);
|
||||
}
|
||||
#ifdef CC_SPINE_VERSION_3_8
|
||||
delete atlas;
|
||||
#else
|
||||
spineAtlasMap.put(skeletonData, atlas);
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
return skeletonData;
|
||||
@@ -222,7 +231,12 @@ SkeletonData* SpineWasmUtil::createSpineSkeletonDataWithBinary(uint32_t byteSize
|
||||
|
||||
saveAttachmentVertices(skeletonData, textureNames, textureUUIDs);
|
||||
}
|
||||
#ifdef CC_SPINE_VERSION_3_8
|
||||
delete atlas;
|
||||
#else
|
||||
spineAtlasMap.put(skeletonData, atlas);
|
||||
#endif
|
||||
|
||||
#endif
|
||||
return skeletonData;
|
||||
}
|
||||
@@ -249,6 +263,10 @@ void SpineWasmUtil::destroySpineSkeletonDataWithUUID(const String& uuid) {
|
||||
|
||||
spineAttachmentVerticesMap.remove(data);
|
||||
}
|
||||
#ifndef CC_SPINE_VERSION_3_8
|
||||
auto* atlas = spineAtlasMap[data];
|
||||
delete atlas;
|
||||
#endif
|
||||
delete data;
|
||||
skeletonDataMap.remove(uuid);
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#include "application/ApplicationManager.h"
|
||||
#include "base/memory/Memory.h"
|
||||
#include "base/std/container/queue.h"
|
||||
#include "base/std/container/list.h"
|
||||
#include "base/UTF8.h"
|
||||
#include "network/Downloader.h"
|
||||
#include "platform/FileUtils.h"
|
||||
@@ -54,7 +54,8 @@
|
||||
@interface DownloaderAppleImpl : NSObject <NSURLSessionDataDelegate, NSURLSessionDownloadDelegate> {
|
||||
const cc::network::DownloaderApple *_outer;
|
||||
cc::network::DownloaderHints _hints;
|
||||
ccstd::queue<NSURLSessionTask *> _taskQueue;
|
||||
ccstd::list<NSURLSessionTask *> _waitingList;
|
||||
int _runningCount;
|
||||
}
|
||||
@property (nonatomic, strong) NSURLSession *downloadSession;
|
||||
@property (nonatomic, strong) NSMutableDictionary *taskDict; // ocTask: DownloadTaskWrapper
|
||||
@@ -203,6 +204,7 @@ void DownloaderApple::abort(const std::unique_ptr<IDownloadTask> &task) {
|
||||
_hints = hints;
|
||||
// create task dictionary
|
||||
self.taskDict = [NSMutableDictionary dictionary];
|
||||
_runningCount = 0;
|
||||
|
||||
#if CC_PLATFORM == CC_PLATFORM_IOS
|
||||
// create backgroundSession for iOS to support background download
|
||||
@@ -264,11 +266,11 @@ void DownloaderApple::abort(const std::unique_ptr<IDownloadTask> &task) {
|
||||
[self.taskDict setObject:taskWrapper forKey:ocTask];
|
||||
[taskWrapper release];
|
||||
|
||||
if (_taskQueue.size() < _hints.countOfMaxProcessingTasks) {
|
||||
if (_runningCount < _hints.countOfMaxProcessingTasks) {
|
||||
[ocTask resume];
|
||||
_taskQueue.push(nil);
|
||||
_runningCount++;
|
||||
} else {
|
||||
_taskQueue.push(ocTask);
|
||||
_waitingList.push_back(ocTask);
|
||||
}
|
||||
return ocTask;
|
||||
};
|
||||
@@ -315,11 +317,11 @@ void DownloaderApple::abort(const std::unique_ptr<IDownloadTask> &task) {
|
||||
[self.taskDict setObject:taskWrapper forKey:ocTask];
|
||||
[taskWrapper release];
|
||||
|
||||
if (_taskQueue.size() < _hints.countOfMaxProcessingTasks) {
|
||||
if (_runningCount < _hints.countOfMaxProcessingTasks) {
|
||||
[ocTask resume];
|
||||
_taskQueue.push(nil);
|
||||
_runningCount++;
|
||||
} else {
|
||||
_taskQueue.push(ocTask);
|
||||
_waitingList.push_back(ocTask);
|
||||
}
|
||||
return ocTask;
|
||||
};
|
||||
@@ -390,8 +392,8 @@ void DownloaderApple::abort(const std::unique_ptr<IDownloadTask> &task) {
|
||||
}
|
||||
_outer = nullptr;
|
||||
|
||||
while (!_taskQueue.empty())
|
||||
_taskQueue.pop();
|
||||
_waitingList.clear();
|
||||
_runningCount = 0;
|
||||
|
||||
[self.downloadSession invalidateAndCancel];
|
||||
[self release];
|
||||
@@ -518,12 +520,18 @@ void DownloaderApple::abort(const std::unique_ptr<IDownloadTask> &task) {
|
||||
}
|
||||
[self.taskDict removeObjectForKey:task];
|
||||
|
||||
while (!_taskQueue.empty() && _taskQueue.front() == nil) {
|
||||
_taskQueue.pop();
|
||||
auto it = std::find(_waitingList.begin(), _waitingList.end(), task);
|
||||
if (it != _waitingList.end()) {
|
||||
_waitingList.erase(it);
|
||||
} else {
|
||||
_runningCount--;
|
||||
}
|
||||
if (!_taskQueue.empty()) {
|
||||
[_taskQueue.front() resume];
|
||||
_taskQueue.pop();
|
||||
|
||||
if (_runningCount < _hints.countOfMaxProcessingTasks && !_waitingList.empty()) {
|
||||
NSURLSessionTask *nextTask = _waitingList.front();
|
||||
_waitingList.pop_front();
|
||||
[nextTask resume];
|
||||
_runningCount++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -134,7 +134,6 @@ void HttpClient::networkThread() {
|
||||
|
||||
// Worker thread
|
||||
void HttpClient::networkThreadAlone(HttpRequest *request, HttpResponse *response) {
|
||||
increaseThreadCount();
|
||||
|
||||
char responseMessage[RESPONSE_BUFFER_SIZE] = {0};
|
||||
processResponse(response, responseMessage);
|
||||
@@ -431,6 +430,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.
|
||||
|
||||
increaseThreadCount();
|
||||
gThreadPool->pushTask([this, request, response](int /*tid*/) { HttpClient::networkThreadAlone(request, response); });
|
||||
}
|
||||
|
||||
@@ -552,6 +552,11 @@ void HttpClient::increaseThreadCount() {
|
||||
|
||||
void HttpClient::decreaseThreadCountAndMayDeleteThis() {
|
||||
bool needDeleteThis = false;
|
||||
// if _threadCount is 0, it means that this HttpClient object is not used anymore.
|
||||
// so return.
|
||||
if (_threadCount == 0) {
|
||||
return;
|
||||
}
|
||||
_threadCountMutex.lock();
|
||||
--_threadCount;
|
||||
if (0 == _threadCount) {
|
||||
|
||||
@@ -178,6 +178,11 @@ long FileUtilsOpenHarmony::getFileSize(const std::string &filepath) {
|
||||
if (fullPath.empty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if(fullPath[0] == '/') {
|
||||
return FileUtils::getFileSize(fullPath);
|
||||
}
|
||||
|
||||
if (nullptr == _nativeResourceManager) {
|
||||
CC_LOG_ERROR("nativeResourceManager is nullptr");
|
||||
return 0;
|
||||
@@ -201,11 +206,11 @@ bool FileUtilsOpenHarmony::isFileExistInternal(const std::string &strFilePath) c
|
||||
return false;
|
||||
}
|
||||
|
||||
if (strFilePath[0] != '/') {
|
||||
if (strFilePath[0] != '/') {
|
||||
const char *s = strFilePath.c_str();
|
||||
// Found "@assets/" at the beginning of the path and we don't want it
|
||||
if (strFilePath.find(ASSETS_FOLDER_NAME) == 0) s += strlen(ASSETS_FOLDER_NAME);
|
||||
|
||||
|
||||
if (nullptr == _nativeResourceManager) {
|
||||
CC_LOG_ERROR("nativeResourceManager is nullptr");
|
||||
return false;
|
||||
@@ -217,7 +222,7 @@ bool FileUtilsOpenHarmony::isFileExistInternal(const std::string &strFilePath) c
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
FILE *fp = fopen(strFilePath.c_str(), "r");
|
||||
if (fp) {
|
||||
fclose(fp);
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
"type": "github",
|
||||
"owner": "cocos",
|
||||
"name": "cocos-engine-external",
|
||||
"checkout": "v4.0.0-2"
|
||||
"checkout": "v4.0.0-4"
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "cocos-creator",
|
||||
"version": "4.0.0-alpha.5",
|
||||
"version": "4.0.0-alpha.23",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "cocos-creator",
|
||||
"version": "4.0.0-alpha.5",
|
||||
"version": "4.0.0-alpha.23",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -9532,14 +9532,6 @@
|
||||
"integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/growly": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/growly/-/growly-1.3.0.tgz",
|
||||
"integrity": "sha512-+xGQY0YyAWCnqy7Cd++hc2JqMYzlm0dG30Jd0beaA64sROr8C4nt8Yc9V5Ro3avlSUDTN0ulqP/VBKi1/lLygw==",
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/gulp": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/gulp/-/gulp-4.0.2.tgz",
|
||||
@@ -14590,39 +14582,6 @@
|
||||
"integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/node-notifier": {
|
||||
"version": "8.0.2",
|
||||
"resolved": "https://registry.npmjs.org/node-notifier/-/node-notifier-8.0.2.tgz",
|
||||
"integrity": "sha512-oJP/9NAdd9+x2Q+rfphB2RJCHjod70RcRLjosiPMMu5gjIfwVnOUGq2nbTjTUbmy0DJ/tFIVT30+Qe3nzl4TJg==",
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"growly": "^1.3.0",
|
||||
"is-wsl": "^2.2.0",
|
||||
"semver": "^7.3.2",
|
||||
"shellwords": "^0.1.1",
|
||||
"uuid": "^8.3.0",
|
||||
"which": "^2.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/node-notifier/node_modules/semver": {
|
||||
"version": "7.5.4",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz",
|
||||
"integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==",
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"lru-cache": "^6.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/node-releases": {
|
||||
"version": "2.0.13",
|
||||
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.13.tgz",
|
||||
@@ -16490,14 +16449,6 @@
|
||||
"integrity": "sha512-Vpfqwm4EnqGdlsBFNmHhxhElJYrdfcxPThu+ryKS5J8L/fhAwLazFZtq+S+TWZ9ANj2piSQLGj6NQg+lKPmxrw==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/shellwords": {
|
||||
"version": "0.1.1",
|
||||
"resolved": "https://registry.npmjs.org/shellwords/-/shellwords-0.1.1.tgz",
|
||||
"integrity": "sha512-vFwSUfQvqybiICwZY5+DAWIPLKsWO31Q91JSKl3UYv+K5c2QRPzn0qzec6QPu1Qc9eHYItiP3NdJqNVqetYAww==",
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/side-channel": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmmirror.com/side-channel/-/side-channel-1.0.4.tgz",
|
||||
@@ -18165,17 +18116,6 @@
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
|
||||
"integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4="
|
||||
},
|
||||
"node_modules/uuid": {
|
||||
"version": "8.3.2",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
|
||||
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"uuid": "dist/bin/uuid"
|
||||
}
|
||||
},
|
||||
"node_modules/v8-to-istanbul": {
|
||||
"version": "9.1.0",
|
||||
"resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.1.0.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cocos-creator",
|
||||
"version": "4.0.0-alpha.5",
|
||||
"version": "4.0.0-alpha.23",
|
||||
"description": "Cocos Creator is a cross-platform 2D & 3D game engine written in C++ and TypeScript, licensed under MIT.",
|
||||
"homepage": "http://www.cocos.com",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -149,8 +149,12 @@ minigame.stopAccelerometer = function (res: any): void {
|
||||
|
||||
// #region SafeArea
|
||||
minigame.getSafeArea = function (): SafeArea {
|
||||
if (typeof minigame.getWindowInfo === "function") {
|
||||
const windowInfo = minigame.getWindowInfo();
|
||||
return windowInfo.safeArea;
|
||||
}
|
||||
console.warn('getSafeArea is not supported on this platform');
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
return {
|
||||
top: 0,
|
||||
left: 0,
|
||||
|
||||
@@ -52,4 +52,5 @@ export enum Platform {
|
||||
MIGU_MINI_GAME = 'MIGU_MINI_GAME',
|
||||
HONOR_MINI_GAME = 'HONOR_MINI_GAME',
|
||||
SUD_MINI_GAME = 'SUD_MINI_GAME',
|
||||
SUDV2_MINI_GAME = 'SUDV2_MINI_GAME',
|
||||
}
|
||||
|
||||
@@ -23,8 +23,8 @@
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { ALIPAY, BYTEDANCE, HUAWEI, OPPO, RUNTIME_BASED, SUD, VIVO, MIGU, HONOR, WECHAT, XIAOMI, DEBUG, TEST, TAOBAO, TAOBAO_MINIGAME, WECHAT_MINI_PROGRAM } from 'internal:constants';
|
||||
import { minigame, SystemInfo as MinigameSystemInfo } from 'pal/minigame';
|
||||
import { ALIPAY, BYTEDANCE, HUAWEI, OPPO, RUNTIME_BASED, SUD, SUDV2, VIVO, MIGU, HONOR, WECHAT, XIAOMI, DEBUG, TEST, TAOBAO, TAOBAO_MINIGAME, WECHAT_MINI_PROGRAM } from 'internal:constants';
|
||||
import { minigame, SystemInfo as MinigameSystemInfo, WindowInfo } from 'pal/minigame';
|
||||
import { IFeatureMap } from 'pal/system-info';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
@@ -60,6 +60,8 @@ if (WECHAT) {
|
||||
currentPlatform = Platform.HONOR_MINI_GAME;
|
||||
} else if (SUD) {
|
||||
currentPlatform = Platform.SUD_MINI_GAME;
|
||||
} else if (SUDV2) {
|
||||
currentPlatform = Platform.SUDV2_MINI_GAME;
|
||||
}
|
||||
|
||||
let isVersionGreaterOrEqualTo;
|
||||
@@ -98,7 +100,10 @@ if (BYTEDANCE) {
|
||||
}
|
||||
|
||||
const originalGetSystemInfoSync = minigame.getSystemInfoSync;
|
||||
// Some platforms may not have this interface(getWindowInfo).
|
||||
const originalGetWindowInfo = minigame.getWindowInfo;
|
||||
let _cachedSystemInfo: MinigameSystemInfo = originalGetSystemInfoSync.call(minigame);
|
||||
let _cachedWindowInfo: WindowInfo | undefined = originalGetWindowInfo?.call(minigame);
|
||||
|
||||
function testAndUpdateSystemInfoCache (testAmount: number, testInterval: number): void {
|
||||
let successfullyTestTimes = 0;
|
||||
@@ -125,12 +130,19 @@ if (WECHAT && versionCompare(minigame.getAppBaseInfo().SDKVersion, '2.25.3') < 0
|
||||
minigame.onWindowResize?.(() => {
|
||||
// update cached system info
|
||||
_cachedSystemInfo = originalGetSystemInfoSync.call(minigame);
|
||||
_cachedWindowInfo = originalGetWindowInfo?.call(minigame);
|
||||
});
|
||||
|
||||
minigame.getSystemInfoSync = function (): MinigameSystemInfo {
|
||||
return _cachedSystemInfo;
|
||||
};
|
||||
|
||||
if (originalGetWindowInfo !== undefined) {
|
||||
minigame.getWindowInfo = function (): WindowInfo {
|
||||
return _cachedWindowInfo!;
|
||||
};
|
||||
}
|
||||
|
||||
class SystemInfo extends EventTarget {
|
||||
public declare readonly networkType: NetworkType;
|
||||
public declare readonly isNative: boolean;
|
||||
|
||||
@@ -24,12 +24,15 @@
|
||||
****************************************************************************/
|
||||
const {
|
||||
getUserDataPath, readJsonSync, makeDirSync,
|
||||
writeFileSync, copyFile, downloadFile, deleteFile,
|
||||
writeFileSync, writeFile, copyFile, downloadFile, deleteFile,
|
||||
rmdirSync, unzip, isOutOfStorage,
|
||||
} = window.fsUtils;
|
||||
|
||||
let checkNextPeriod = false;
|
||||
let writeCacheFileList = null;
|
||||
let startWrite = false;
|
||||
let nextCallbacks = [];
|
||||
let callbacks = [];
|
||||
let cleaning = false;
|
||||
let suffix = 0;
|
||||
const REGEX = /^https?:\/\/.*/;
|
||||
@@ -96,58 +99,74 @@ const cacheManager = {
|
||||
|
||||
_write () {
|
||||
writeCacheFileList = null;
|
||||
writeFileSync(`${this.cacheDir}/${this.cachedFileName}`, JSON.stringify({ files: this.cachedFiles._map, version: this.version }), 'utf8');
|
||||
startWrite = true;
|
||||
writeFile(this.cacheDir + '/' + this.cachedFileName, JSON.stringify({ files: this.cachedFiles._map, version: this.version }), 'utf8', function () {
|
||||
startWrite = false;
|
||||
for (let i = 0, j = callbacks.length; i < j; i++) {
|
||||
callbacks[i]();
|
||||
}
|
||||
callbacks.length = 0;
|
||||
callbacks.push.apply(callbacks, nextCallbacks);
|
||||
nextCallbacks.length = 0;
|
||||
});
|
||||
},
|
||||
|
||||
writeCacheFile () {
|
||||
writeCacheFile (cb) {
|
||||
if (!writeCacheFileList) {
|
||||
writeCacheFileList = setTimeout(this._write.bind(this), this.writeFileInterval);
|
||||
if (startWrite === true) {
|
||||
cb && nextCallbacks.push(cb);
|
||||
}
|
||||
else {
|
||||
cb && callbacks.push(cb);
|
||||
}
|
||||
} else {
|
||||
cb && callbacks.push(cb);
|
||||
}
|
||||
},
|
||||
|
||||
_cache () {
|
||||
checkNextPeriod = false;
|
||||
const self = this;
|
||||
let id = '';
|
||||
// eslint-disable-next-line no-unreachable-loop
|
||||
for (const key in this.cacheQueue) {
|
||||
id = key;
|
||||
break;
|
||||
}
|
||||
if (!id) return;
|
||||
const { srcUrl, isCopy, cacheBundleRoot } = this.cacheQueue[id];
|
||||
const time = Date.now().toString();
|
||||
for (const id in this.cacheQueue) {
|
||||
const { srcUrl, isCopy, cacheBundleRoot } = this.cacheQueue[id];
|
||||
const time = Date.now().toString();
|
||||
|
||||
let localPath = '';
|
||||
let localPath = '';
|
||||
|
||||
if (cacheBundleRoot) {
|
||||
localPath = `${this.cacheDir}/${cacheBundleRoot}/${time}${suffix++}${cc.path.extname(id)}`;
|
||||
} else {
|
||||
localPath = `${this.cacheDir}/${time}${suffix++}${cc.path.extname(id)}`;
|
||||
}
|
||||
|
||||
function callback (err) {
|
||||
if (err) {
|
||||
if (isOutOfStorage(err.message)) {
|
||||
self.outOfStorage = true;
|
||||
self.autoClear && self.clearLRU();
|
||||
return;
|
||||
if (cacheBundleRoot) {
|
||||
localPath = `${this.cacheDir}/${cacheBundleRoot}/${time}${suffix++}${cc.path.extname(id)}`;
|
||||
}
|
||||
else {
|
||||
localPath = `${this.cacheDir}/${time}${suffix++}${cc.path.extname(id)}`;
|
||||
}
|
||||
|
||||
function callback (err) {
|
||||
checkNextPeriod = false;
|
||||
if (err) {
|
||||
if (isOutOfStorage(err.message)) {
|
||||
self.outOfStorage = true;
|
||||
self.autoClear && self.clearLRU();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
self.cachedFiles.add(id, { bundle: cacheBundleRoot, url: localPath, lastTime: time });
|
||||
delete self.cacheQueue[id];
|
||||
self.writeCacheFile();
|
||||
}
|
||||
if (!cc.js.isEmptyObject(self.cacheQueue)) {
|
||||
checkNextPeriod = true;
|
||||
setTimeout(self._cache.bind(self), self.cacheInterval);
|
||||
}
|
||||
} else {
|
||||
self.cachedFiles.add(id, { bundle: cacheBundleRoot, url: localPath, lastTime: time });
|
||||
self.writeCacheFile();
|
||||
}
|
||||
delete self.cacheQueue[id];
|
||||
if (!cc.js.isEmptyObject(self.cacheQueue) && !checkNextPeriod) {
|
||||
checkNextPeriod = true;
|
||||
setTimeout(self._cache.bind(self), self.cacheInterval);
|
||||
if (!isCopy) {
|
||||
downloadFile(srcUrl, localPath, null, callback);
|
||||
}
|
||||
else {
|
||||
copyFile(srcUrl, localPath, callback);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!isCopy) {
|
||||
downloadFile(srcUrl, localPath, null, callback);
|
||||
} else {
|
||||
copyFile(srcUrl, localPath, callback);
|
||||
}
|
||||
checkNextPeriod = false;
|
||||
},
|
||||
|
||||
cacheFile (id, srcUrl, cacheEnabled, cacheBundleRoot, isCopy) {
|
||||
@@ -155,9 +174,14 @@ const cacheManager = {
|
||||
if (!cacheEnabled || this.cacheQueue[id] || this.cachedFiles.has(id)) return;
|
||||
|
||||
this.cacheQueue[id] = { srcUrl, cacheBundleRoot, isCopy };
|
||||
if (!checkNextPeriod && !this.outOfStorage) {
|
||||
if (!checkNextPeriod) {
|
||||
checkNextPeriod = true;
|
||||
setTimeout(this._cache.bind(this), this.cacheInterval);
|
||||
if (!this.outOfStorage) {
|
||||
setTimeout(this._cache.bind(this), this.cacheInterval);
|
||||
}
|
||||
else {
|
||||
checkNextPeriod = false;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -165,10 +189,12 @@ const cacheManager = {
|
||||
rmdirSync(this.cacheDir, true);
|
||||
this.cachedFiles = new cc.AssetManager.Cache();
|
||||
makeDirSync(this.cacheDir, true);
|
||||
const cacheFilePath = this.cacheDir + '/' + this.cachedFileName;
|
||||
this.outOfStorage = false;
|
||||
clearTimeout(writeCacheFileList);
|
||||
this._write();
|
||||
cc.assetManager.bundles.forEach((bundle) => {
|
||||
writeCacheFileList = null;
|
||||
writeFileSync(cacheFilePath, JSON.stringify({ files: this.cachedFiles._map, version: this.version }), 'utf8');
|
||||
cc.assetManager.bundles.forEach(bundle => {
|
||||
if (REGEX.test(bundle.base)) this.makeBundleFolder(bundle.name);
|
||||
});
|
||||
},
|
||||
@@ -194,27 +220,33 @@ const cacheManager = {
|
||||
cc.assetManager.files.remove(cacheKey);
|
||||
this.cachedFiles.remove(caches[i].originUrl);
|
||||
}
|
||||
|
||||
|
||||
clearTimeout(writeCacheFileList);
|
||||
this._write();
|
||||
function deferredDelete () {
|
||||
const item = caches.pop();
|
||||
self._removePathOrFile(item.originUrl, item.url);
|
||||
if (caches.length > 0) {
|
||||
setTimeout(deferredDelete, self.deleteInterval);
|
||||
} else {
|
||||
cleaning = false;
|
||||
writeCacheFileList = null;
|
||||
this.writeCacheFile(function () {
|
||||
function deferredDelete () {
|
||||
const item = caches.pop();
|
||||
self._removePathOrFile(item.originUrl, item.url);
|
||||
if (caches.length > 0) {
|
||||
setTimeout(deferredDelete, self.deleteInterval);
|
||||
}
|
||||
else {
|
||||
cleaning = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
setTimeout(deferredDelete, self.deleteInterval);
|
||||
setTimeout(deferredDelete, self.deleteInterval);
|
||||
});
|
||||
},
|
||||
|
||||
removeCache (url) {
|
||||
if (this.cachedFiles.has(url)) {
|
||||
const self = this;
|
||||
const path = this.cachedFiles.remove(url).url;
|
||||
clearTimeout(writeCacheFileList);
|
||||
this._write();
|
||||
this._removePathOrFile(url, path);
|
||||
writeCacheFileList = null;
|
||||
this.writeCacheFile(function () {
|
||||
self._removePathOrFile(url, path);
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
@@ -1,30 +1,31 @@
|
||||
const cacheManager = require('./cache-manager');
|
||||
const { readText, readArrayBuffer, readJson, loadSubpackage, getUserDataPath, _subpackagesPath } = require('./fs-utils');
|
||||
|
||||
//cc.assetManager.fsUtils = ral.fsUtils;
|
||||
const { readText, readArrayBuffer, readJson, getUserDataPath } = require('./fs-utils');
|
||||
|
||||
const REGEX = /^https?:\/\/.*/;
|
||||
|
||||
const downloader = cc.assetManager.downloader;
|
||||
const parser = cc.assetManager.parser;
|
||||
const presets = cc.assetManager.presets;
|
||||
downloader.maxConcurrency = 12;
|
||||
downloader.maxRequestsPerFrame = 64;
|
||||
presets.scene.maxConcurrency = 12;
|
||||
downloader.maxConcurrency = 30;
|
||||
downloader.maxRequestsPerFrame = 60;
|
||||
presets.preload.maxConcurrency = 15;
|
||||
presets.preload.maxRequestsPerFrame = 30;
|
||||
presets.scene.maxConcurrency = 32;
|
||||
presets.scene.maxRequestsPerFrame = 64;
|
||||
presets.bundle.maxConcurrency = 32;
|
||||
presets.bundle.maxRequestsPerFrame = 64;
|
||||
|
||||
const subpackages = {};
|
||||
const loadedScripts = {};
|
||||
|
||||
function downloadScript (url, options, onComplete) {
|
||||
if (typeof options === 'function') {
|
||||
onComplete = options;
|
||||
options = null;
|
||||
options = {};
|
||||
}
|
||||
|
||||
if (loadedScripts[url]) {
|
||||
onComplete && onComplete();
|
||||
return;
|
||||
onComplete && onComplete();
|
||||
return;
|
||||
}
|
||||
|
||||
download(url, (src, options, onComplete) => {
|
||||
@@ -97,19 +98,14 @@ function downloadJson (url, options, onComplete) {
|
||||
download(url, parseJson, options, options.onFileProgress, onComplete);
|
||||
}
|
||||
|
||||
function downloadArrayBuffer (url, options, onComplete) {
|
||||
download(url, parseArrayBuffer, options, options.onFileProgress, onComplete);
|
||||
}
|
||||
|
||||
function loadFont (url, options, onComplete) {
|
||||
// nodejs 环境没有 document/FontFace API,不支持字体加载
|
||||
const fontFamilyName = _getFontFamily(url);
|
||||
|
||||
const fontFace = new FontFace(fontFamilyName, `url('${url}')`);
|
||||
document.fonts.add(fontFace);
|
||||
|
||||
fontFace.load();
|
||||
fontFace.loaded.then(() => {
|
||||
onComplete(null, fontFamilyName);
|
||||
}, () => {
|
||||
cc.warnID(4933, fontFamilyName);
|
||||
onComplete(null, fontFamilyName);
|
||||
});
|
||||
onComplete(null, fontFamilyName);
|
||||
}
|
||||
|
||||
function _getFontFamily (fontHandle) {
|
||||
@@ -126,6 +122,9 @@ function _getFontFamily (fontHandle) {
|
||||
} else {
|
||||
fontFamilyName = `${fontHandle.substring(slashPos + 1, ttfIndex)}_LABEL`;
|
||||
}
|
||||
if (fontFamilyName.indexOf(' ') !== -1) {
|
||||
fontFamilyName = `"${fontFamilyName}"`;
|
||||
}
|
||||
return fontFamilyName;
|
||||
}
|
||||
|
||||
@@ -143,11 +142,11 @@ function downloadBundle (nameOrUrl, options, onComplete) {
|
||||
url = nameOrUrl;
|
||||
cacheManager.makeBundleFolder(bundleName);
|
||||
} else if (downloader.remoteBundles.indexOf(bundleName) !== -1) {
|
||||
url = `${downloader.remoteServerAddress}remote/${bundleName}`;
|
||||
cacheManager.makeBundleFolder(bundleName);
|
||||
} else {
|
||||
url = `assets/${bundleName}`;
|
||||
}
|
||||
url = `${downloader.remoteServerAddress}remote/${bundleName}`;
|
||||
cacheManager.makeBundleFolder(bundleName);
|
||||
} else {
|
||||
url = `assets/${bundleName}`;
|
||||
}
|
||||
const config = `${url}/cc.config.${version ? `${version}.` : ''}json`;
|
||||
options.__cacheBundleRoot__ = bundleName;
|
||||
downloadJson(config, options, (err, response) => {
|
||||
@@ -159,7 +158,7 @@ function downloadBundle (nameOrUrl, options, onComplete) {
|
||||
out && (out.base = `${url}/`);
|
||||
|
||||
if (out.hasPreloadScript) {
|
||||
const js = `${url}/index.${version ? `${version}.` : ''}${out.encrypted ? 'jsc' : `js`}`;
|
||||
const js = `${url}/index.${version ? `${version}.` : ''}${out.encrypted ? 'jsc' : 'js'}`;
|
||||
downloadScript(js, options, (err) => {
|
||||
if (err) {
|
||||
onComplete(err, null);
|
||||
@@ -173,10 +172,6 @@ function downloadBundle (nameOrUrl, options, onComplete) {
|
||||
});
|
||||
}
|
||||
|
||||
function downloadArrayBuffer (url, options, onComplete) {
|
||||
download(url, parseArrayBuffer, options, options.onFileProgress, onComplete);
|
||||
}
|
||||
|
||||
const originParsePVRTex = parser.parsePVRTex;
|
||||
const parsePVRTex = function (file, options, onComplete) {
|
||||
readArrayBuffer(file, (err, data) => {
|
||||
@@ -240,6 +235,7 @@ downloader.register({
|
||||
'.pkm': downloadAsset,
|
||||
'.astc': downloadAsset,
|
||||
|
||||
// Font
|
||||
'.font': downloadAsset,
|
||||
'.eot': downloadAsset,
|
||||
'.ttf': downloadAsset,
|
||||
@@ -267,6 +263,7 @@ downloader.register({
|
||||
'.dbbin': downloadAsset,
|
||||
'.skel': downloadAsset,
|
||||
|
||||
// Video
|
||||
'.mp4': downloadAsset,
|
||||
'.avi': downloadAsset,
|
||||
'.mov': downloadAsset,
|
||||
@@ -281,6 +278,7 @@ downloader.register({
|
||||
});
|
||||
|
||||
parser.register({
|
||||
// Image
|
||||
'.png': downloader.downloadDomImage,
|
||||
'.jpg': downloader.downloadDomImage,
|
||||
'.bmp': downloader.downloadDomImage,
|
||||
@@ -290,10 +288,13 @@ parser.register({
|
||||
'.tiff': downloader.downloadDomImage,
|
||||
'.image': downloader.downloadDomImage,
|
||||
'.webp': downloader.downloadDomImage,
|
||||
|
||||
// Compressed texture
|
||||
'.pvr': parsePVRTex,
|
||||
'.pkm': parsePKMTex,
|
||||
'.astc': parseASTCTex,
|
||||
|
||||
// Font
|
||||
'.font': loadFont,
|
||||
'.eot': loadFont,
|
||||
'.ttf': loadFont,
|
||||
@@ -319,6 +320,7 @@ parser.register({
|
||||
'.fnt': parseText,
|
||||
'.plist': parsePlist,
|
||||
|
||||
// Binary
|
||||
'.binary': parseArrayBuffer,
|
||||
'.bin': parseArrayBuffer,
|
||||
'.dbbin': parseArrayBuffer,
|
||||
@@ -327,10 +329,9 @@ parser.register({
|
||||
'.ExportJson': parseJson,
|
||||
});
|
||||
|
||||
var transformUrl = function (url, options) {
|
||||
function transformUrl (url, options) {
|
||||
let inLocal = false;
|
||||
let inCache = false;
|
||||
|
||||
if (REGEX.test(url) && !url.startsWith('file://')) {
|
||||
if (options.reload) {
|
||||
return { url };
|
||||
@@ -339,16 +340,22 @@ var transformUrl = function (url, options) {
|
||||
if (cache) {
|
||||
inCache = true;
|
||||
url = cache;
|
||||
} else {
|
||||
const tempUrl = cacheManager.getTemp(url);
|
||||
if (tempUrl) {
|
||||
inLocal = true;
|
||||
url = tempUrl;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
inLocal = true;
|
||||
if(url.startsWith('file://')) {
|
||||
if (url.startsWith('file://')) {
|
||||
url = globalThis.nodeEnv.require('url').fileURLToPath(url);
|
||||
}
|
||||
}
|
||||
return { url, inLocal, inCache };
|
||||
};
|
||||
}
|
||||
|
||||
cc.assetManager.transformPipeline.append((task) => {
|
||||
const input = task.output = task.input;
|
||||
@@ -372,7 +379,5 @@ cc.assetManager.transformPipeline.append((task) => {
|
||||
const originInit = cc.assetManager.init;
|
||||
cc.assetManager.init = function (options) {
|
||||
originInit.call(cc.assetManager, options);
|
||||
const subpacks = cc.settings.querySettings('assets', 'subpackages');
|
||||
subpacks && subpacks.forEach((x) => subpackages[x] = `${_subpackagesPath}${x}`);
|
||||
cacheManager.init();
|
||||
};
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
const { makeDirSync, copyFile, downloadFile, deleteFile, rmdirSync, getUserDataPath } = require('./fs-utils');
|
||||
const { makeDirSync, copyFile, deleteFile, readJsonSync, writeFileSync, rmdirSync, getUserDataPath, isOutOfStorage } = require('./fs-utils');
|
||||
|
||||
let checkNextPeriod = false;
|
||||
let writeCacheFileList = null;
|
||||
@@ -65,9 +65,17 @@ const cacheManager = {
|
||||
},
|
||||
|
||||
init () {
|
||||
//TODO(qgh): Read the configuration file
|
||||
this.cacheDir = `${getUserDataPath()}/${this.cacheDir}`;
|
||||
this.cachedFiles = new cc.AssetManager.Cache();
|
||||
const cacheFilePath = `${this.cacheDir}/${this.cachedFileName}`;
|
||||
const result = readJsonSync(cacheFilePath);
|
||||
if (result instanceof Error || !result.version) {
|
||||
if (!(result instanceof Error)) rmdirSync(this.cacheDir, true);
|
||||
this.cachedFiles = new cc.AssetManager.Cache();
|
||||
makeDirSync(this.cacheDir, true);
|
||||
writeFileSync(cacheFilePath, JSON.stringify({ files: this.cachedFiles._map, version: this.version }), 'utf8');
|
||||
} else {
|
||||
this.cachedFiles = new cc.AssetManager.Cache(result.files);
|
||||
}
|
||||
this.tempFiles = new cc.AssetManager.Cache();
|
||||
},
|
||||
|
||||
@@ -80,7 +88,7 @@ const cacheManager = {
|
||||
|
||||
_write () {
|
||||
writeCacheFileList = null;
|
||||
//TODO(qgh): Write to the configuration file
|
||||
writeFileSync(`${this.cacheDir}/${this.cachedFileName}`, JSON.stringify({ files: this.cachedFiles._map, version: this.version }), 'utf8');
|
||||
},
|
||||
|
||||
writeCacheFile () {
|
||||
@@ -102,22 +110,20 @@ const cacheManager = {
|
||||
const { srcUrl, isCopy, cacheBundleRoot } = this.cacheQueue[id];
|
||||
const time = Date.now().toString();
|
||||
|
||||
let localPath = '';
|
||||
|
||||
if (cacheBundleRoot) {
|
||||
localPath = `${this.cacheDir}/${cacheBundleRoot}/${time}${suffix++}${cc.path.extname(id)}`;
|
||||
} else {
|
||||
localPath = `${this.cacheDir}/${time}${suffix++}${cc.path.extname(id)}`;
|
||||
}
|
||||
|
||||
const localPath = cacheBundleRoot
|
||||
? `${this.cacheDir}/${cacheBundleRoot}/${time}${suffix++}${cc.path.extname(id)}`
|
||||
: `${this.cacheDir}/${time}${suffix++}${cc.path.extname(id)}`;
|
||||
function callback (err) {
|
||||
if (err) {
|
||||
console.log('cannot support');
|
||||
// if (isOutOfStorage(err.message)) {
|
||||
// self.outOfStorage = true;
|
||||
// self.autoClear && self.clearLRU();
|
||||
// return;
|
||||
// }
|
||||
if (err) {
|
||||
// 不确定错误是否和runtime一致,得测试下
|
||||
if (isOutOfStorage(err.message)) {
|
||||
self.outOfStorage = true;
|
||||
self.autoClear && self.clearLRU();
|
||||
return;
|
||||
} else {
|
||||
// 打印出错信息
|
||||
console.warn(err);
|
||||
}
|
||||
} else {
|
||||
self.cachedFiles.add(id, { bundle: cacheBundleRoot, url: localPath, lastTime: time });
|
||||
self.writeCacheFile();
|
||||
@@ -138,7 +144,6 @@ const cacheManager = {
|
||||
cacheFile (id, srcUrl, cacheEnabled, cacheBundleRoot, isCopy) {
|
||||
cacheEnabled = cacheEnabled !== undefined ? cacheEnabled : this.cacheEnabled;
|
||||
if (!cacheEnabled || this.cacheQueue[id] || this.cachedFiles.has(id)) return;
|
||||
|
||||
this.cacheQueue[id] = { srcUrl, cacheBundleRoot, isCopy };
|
||||
if (!checkNextPeriod && !this.outOfStorage) {
|
||||
checkNextPeriod = true;
|
||||
@@ -164,28 +169,25 @@ const cacheManager = {
|
||||
const caches = [];
|
||||
const self = this;
|
||||
this.cachedFiles.forEach((val, key) => {
|
||||
if (self._isZipFile(key) && cc.assetManager.bundles.find((bundle) => bundle.base.indexOf(val.url) !== -1)) return;
|
||||
if (val.bundle === 'internal') return;
|
||||
caches.push({ originUrl: key, url: val.url, lastTime: val.lastTime });
|
||||
});
|
||||
caches.sort((a, b) => a.lastTime - b.lastTime);
|
||||
caches.length = Math.floor(caches.length / 3);
|
||||
// cache length above 3 then clear 1/3, or clear all caches
|
||||
if (caches.length < 3) {
|
||||
console.warn('Insufficient storage, cleaning now');
|
||||
} else {
|
||||
caches.length = Math.floor(caches.length / 3);
|
||||
if (caches.length === 0) {
|
||||
cleaning = false;
|
||||
return;
|
||||
}
|
||||
for (let i = 0, l = caches.length; i < l; i++) {
|
||||
const cacheKey = `${cc.assetManager.utils.getUuidFromURL(caches[i].originUrl)}@native`;
|
||||
cc.assetManager.files.remove(cacheKey);
|
||||
this.cachedFiles.remove(caches[i].originUrl);
|
||||
}
|
||||
|
||||
clearTimeout(writeCacheFileList);
|
||||
this._write();
|
||||
function deferredDelete () {
|
||||
const item = caches.pop();
|
||||
self._removePathOrFile(item.originUrl, item.url);
|
||||
deleteFile(item.url, self._deleteFileCB.bind(self));
|
||||
if (caches.length > 0) {
|
||||
setTimeout(deferredDelete, self.deleteInterval);
|
||||
} else {
|
||||
@@ -200,19 +202,6 @@ const cacheManager = {
|
||||
const path = this.cachedFiles.remove(url).url;
|
||||
clearTimeout(writeCacheFileList);
|
||||
this._write();
|
||||
this._removePathOrFile(url, path);
|
||||
}
|
||||
},
|
||||
|
||||
_removePathOrFile (url, path) {
|
||||
if (this._isZipFile(url)) {
|
||||
if (this._isZipFile(path)) {
|
||||
deleteFile(path, this._deleteFileCB.bind(this));
|
||||
} else {
|
||||
rmdirSync(path, true);
|
||||
this._deleteFileCB();
|
||||
}
|
||||
} else {
|
||||
deleteFile(path, this._deleteFileCB.bind(this));
|
||||
}
|
||||
},
|
||||
@@ -225,18 +214,6 @@ const cacheManager = {
|
||||
makeDirSync(`${this.cacheDir}/${bundleName}`, true);
|
||||
},
|
||||
|
||||
unzipAndCacheBundle (id, zipFilePath, cacheBundleRoot, onComplete) {
|
||||
const time = Date.now().toString();
|
||||
const targetPath = `${this.cacheDir}/${cacheBundleRoot}/${time}${suffix++}`;
|
||||
const self = this;
|
||||
makeDirSync(targetPath, true);
|
||||
console.log('cannot support');
|
||||
},
|
||||
|
||||
_isZipFile (url) {
|
||||
return url.slice(-4) === '.zip';
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
cc.assetManager.cacheManager = module.exports = cacheManager;
|
||||
|
||||
@@ -26,15 +26,19 @@ const fsUtils = {
|
||||
|
||||
fs,
|
||||
|
||||
initJsbDownloader(jsbDownloaderMaxTasks, jsbDownloaderTimeout) {
|
||||
console.log("initJsbDownloader: nodejs does not support")
|
||||
isOutOfStorage (errMsg) {
|
||||
return errMsg.indexOf('ENOSPC') !== -1;
|
||||
},
|
||||
|
||||
getUserDataPath() {
|
||||
return path.join(globalThis.nodeEnv.userDataPath, "writablePath");
|
||||
initJsbDownloader (jsbDownloaderMaxTasks, jsbDownloaderTimeout) {
|
||||
console.log('initJsbDownloader: nodejs does not support');
|
||||
},
|
||||
|
||||
checkFsValid() {
|
||||
getUserDataPath () {
|
||||
return path.join(globalThis.nodeEnv.userDataPath, 'writablePath');
|
||||
},
|
||||
|
||||
checkFsValid () {
|
||||
if (!fs) {
|
||||
cc.warn('can not get the file system!');
|
||||
return false;
|
||||
@@ -42,7 +46,7 @@ const fsUtils = {
|
||||
return true;
|
||||
},
|
||||
|
||||
deleteFile(filePath, onComplete) {
|
||||
deleteFile (filePath, onComplete) {
|
||||
const fullFilePath = fsUtils.fullPathForFilename(filePath);
|
||||
fs.unlink(fullFilePath, (e) => {
|
||||
if (e) {
|
||||
@@ -54,24 +58,24 @@ const fsUtils = {
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
fullPathForFilename(filename, forceReturnFullpath = false) {
|
||||
if(filename.length <= 0){
|
||||
return "";
|
||||
|
||||
fullPathForFilename (filename, forceReturnFullpath = false) {
|
||||
if (filename.length <= 0) {
|
||||
return '';
|
||||
}
|
||||
if(path.isAbsolute(filename)) {
|
||||
if (path.isAbsolute(filename)) {
|
||||
return filename;
|
||||
}
|
||||
const newFilename = path.normalize(filename);
|
||||
const projectPath = '';
|
||||
const fullpath = path.join(projectPath, newFilename);
|
||||
if(fs.pathExistsSync(fullpath) || forceReturnFullpath) {
|
||||
if (fs.pathExistsSync(fullpath) || forceReturnFullpath) {
|
||||
return fullpath;
|
||||
}
|
||||
return "";
|
||||
return '';
|
||||
},
|
||||
|
||||
saveFile(srcPath, destPath, onComplete) {
|
||||
saveFile (srcPath, destPath, onComplete) {
|
||||
const fullSrcPath = fsUtils.fullPathForFilename(srcPath);
|
||||
const fullDestPath = fsUtils.fullPathForFilename(destPath, true);
|
||||
fs.ensureDirSync(path.dirname(fullDestPath));
|
||||
@@ -89,7 +93,7 @@ const fsUtils = {
|
||||
});
|
||||
},
|
||||
|
||||
copyFile(srcPath, destPath, onComplete) {
|
||||
copyFile (srcPath, destPath, onComplete) {
|
||||
const fullSrcPath = fsUtils.fullPathForFilename(srcPath);
|
||||
const fullDestPath = fsUtils.fullPathForFilename(destPath, true);
|
||||
fs.ensureDirSync(path.dirname(fullDestPath));
|
||||
@@ -106,7 +110,7 @@ const fsUtils = {
|
||||
});
|
||||
},
|
||||
|
||||
writeFile(filePath, data, encoding, onComplete) {
|
||||
writeFile (filePath, data, encoding, onComplete) {
|
||||
const fullFilePath = fsUtils.fullPathForFilename(filePath, true);
|
||||
fs.writeFile(fullFilePath, data, encoding, (e) => {
|
||||
if (e) {
|
||||
@@ -116,13 +120,13 @@ const fsUtils = {
|
||||
} else {
|
||||
onComplete && onComplete(null);
|
||||
}
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
writeFileSync(filePath, data, encoding) {
|
||||
writeFileSync (filePath, data, encoding) {
|
||||
const fullFilePath = fsUtils.fullPathForFilename(filePath, true);
|
||||
try {
|
||||
fs.writeFile(fullFilePath, data, encoding);
|
||||
fs.writeFileSync(fullFilePath, data, encoding);
|
||||
return null;
|
||||
} catch (e) {
|
||||
const err = new Error(`Failed to write file synchronously: "${filePath}" (resolved: "${fullFilePath}") - ${e.message}`);
|
||||
@@ -131,7 +135,7 @@ const fsUtils = {
|
||||
}
|
||||
},
|
||||
|
||||
readFile(filePath, encoding, onComplete) {
|
||||
readFile (filePath, encoding, onComplete) {
|
||||
const fullFilePath = fsUtils.fullPathForFilename(filePath);
|
||||
fs.readFile(fullFilePath, encoding, (e, data) => {
|
||||
if (e) {
|
||||
@@ -141,10 +145,10 @@ const fsUtils = {
|
||||
} else {
|
||||
onComplete && onComplete(null, data);
|
||||
}
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
readDir(dirPath, onComplete) {
|
||||
readDir (dirPath, onComplete) {
|
||||
const fullDirPath = fsUtils.fullPathForFilename(dirPath);
|
||||
fs.readdir(fullDirPath, (e, files) => {
|
||||
if (e) {
|
||||
@@ -154,18 +158,18 @@ const fsUtils = {
|
||||
} else {
|
||||
onComplete && onComplete(null, files);
|
||||
}
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
readText(filePath, onComplete) {
|
||||
readText (filePath, onComplete) {
|
||||
fsUtils.readFile(filePath, 'utf8', onComplete);
|
||||
},
|
||||
|
||||
readArrayBuffer(filePath, onComplete) {
|
||||
readArrayBuffer (filePath, onComplete) {
|
||||
fsUtils.readFile(filePath, '', onComplete);
|
||||
},
|
||||
|
||||
readJson(filePath, onComplete) {
|
||||
readJson (filePath, onComplete) {
|
||||
const fullFilePath = fsUtils.fullPathForFilename(filePath);
|
||||
fs.readJson(fullFilePath, (e, jsonObj) => {
|
||||
if (e) {
|
||||
@@ -175,10 +179,10 @@ const fsUtils = {
|
||||
} else {
|
||||
onComplete && onComplete(null, jsonObj);
|
||||
}
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
readJsonSync(filePath) {
|
||||
readJsonSync (filePath) {
|
||||
const fullFilePath = fsUtils.fullPathForFilename(filePath);
|
||||
try {
|
||||
return fs.readJsonSync(fullFilePath);
|
||||
@@ -189,10 +193,10 @@ const fsUtils = {
|
||||
}
|
||||
},
|
||||
|
||||
makeDirSync(dirPath, recursive) {
|
||||
makeDirSync (dirPath, recursive) {
|
||||
const fullDirPath = fsUtils.fullPathForFilename(dirPath, true);
|
||||
try {
|
||||
fs.mkdirSync(fullDirPath, { recursive: recursive });
|
||||
fs.mkdirSync(fullDirPath, { recursive });
|
||||
return null;
|
||||
} catch (e) {
|
||||
const err = new Error(`Make directory failed: "${dirPath}" (resolved: "${fullDirPath}") - ${e.message}`);
|
||||
@@ -201,10 +205,10 @@ const fsUtils = {
|
||||
}
|
||||
},
|
||||
|
||||
rmdirSync(dirPath, recursive) {
|
||||
rmdirSync (dirPath, recursive) {
|
||||
const fullDirPath = fsUtils.fullPathForFilename(dirPath);
|
||||
try {
|
||||
fs.rmSync(fullDirPath, { recursive: recursive });
|
||||
fs.rmSync(fullDirPath, { recursive });
|
||||
return null;
|
||||
} catch (e) {
|
||||
const err = new Error(`Remove directory failed: "${dirPath}" (resolved: "${fullDirPath}") - ${e.message}`);
|
||||
@@ -213,10 +217,10 @@ const fsUtils = {
|
||||
}
|
||||
},
|
||||
|
||||
exists(filePath, onComplete) {
|
||||
exists (filePath, onComplete) {
|
||||
const fullFilePath = fsUtils.fullPathForFilename(filePath);
|
||||
fs.pathExists(fullFilePath, function (e, exists) {
|
||||
if(e) {
|
||||
fs.pathExists(fullFilePath, (e, exists) => {
|
||||
if (e) {
|
||||
const err = new Error(`File existence check failed: "${filePath}" (resolved: "${fullFilePath}") - ${e.message}`);
|
||||
cc.warn(err.message);
|
||||
return err;
|
||||
@@ -225,7 +229,7 @@ const fsUtils = {
|
||||
});
|
||||
},
|
||||
|
||||
loadSubpackage(name, onProgress, onComplete) {
|
||||
loadSubpackage (name, onProgress, onComplete) {
|
||||
throw new Error('nodejs not implement');
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/// <reference types="jest" />
|
||||
|
||||
import { EPSILON, Quat, Vec2, Vec3 } from "../../cocos/core";
|
||||
import { director } from "../../cocos/game";
|
||||
import { Node } from "../../cocos/scene-graph";
|
||||
@@ -40,4 +42,21 @@ export default function (parent: Node, _steps = 0) {
|
||||
parent.removeAllChildren();
|
||||
}
|
||||
|
||||
}
|
||||
// circle worldPosition
|
||||
{
|
||||
const nodeCollider = new Node('CircleCollider2D');
|
||||
parent.addChild(nodeCollider);
|
||||
nodeCollider.worldPosition = new Vec3(10, 20, 0);
|
||||
|
||||
nodeCollider.addComponent(physics2d.RigidBody2D);
|
||||
const collider = nodeCollider.addComponent(physics2d.CircleCollider2D) as physics2d.CircleCollider2D;
|
||||
collider.offset = new Vec2(2, -3);
|
||||
collider.apply();
|
||||
|
||||
expect(Vec2.equals(collider.worldPosition, new Vec2(12, 17))).toBe(true);
|
||||
|
||||
parent.destroyAllChildren();
|
||||
parent.removeAllChildren();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import * as physics2d from "../../exports/physics-2d-framework";
|
||||
|
||||
/**
|
||||
* 验证 Box2D 后端关闭调试绘制时保留调试节点,避免再次开启时父节点为空。
|
||||
*/
|
||||
export default function DebugDrawTest (): void {
|
||||
if (physics2d.selector.id === 'builtin') {
|
||||
return;
|
||||
}
|
||||
|
||||
const parent = {};
|
||||
const clear = jest.fn();
|
||||
const debugGraphics = {
|
||||
clear,
|
||||
node: {
|
||||
parent,
|
||||
},
|
||||
};
|
||||
const physicsWorld = physics2d.PhysicsSystem2D.instance.physicsWorld as unknown as {
|
||||
_debugGraphics: typeof debugGraphics | null;
|
||||
};
|
||||
|
||||
physicsWorld._debugGraphics = debugGraphics;
|
||||
|
||||
try {
|
||||
physics2d.PhysicsSystem2D.instance.debugDrawFlags = physics2d.EPhysics2DDrawFlags.Shape;
|
||||
physics2d.PhysicsSystem2D.instance.debugDrawFlags = physics2d.EPhysics2DDrawFlags.None;
|
||||
expect(clear).toHaveBeenCalledTimes(1);
|
||||
expect(debugGraphics.node.parent).toBe(parent);
|
||||
|
||||
physics2d.PhysicsSystem2D.instance.debugDrawFlags = physics2d.EPhysics2DDrawFlags.Shape;
|
||||
expect(debugGraphics.node.parent).toBe(parent);
|
||||
} finally {
|
||||
physics2d.PhysicsSystem2D.instance.debugDrawFlags = physics2d.EPhysics2DDrawFlags.None;
|
||||
physicsWorld._debugGraphics = null;
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import RigidBodyTest from "./rigid-body";
|
||||
import ColliderTest from "./collider";
|
||||
import SceneQueryTest from "./scene-query";
|
||||
import EventTest from "./events";
|
||||
import DebugDrawTest from "./debug-draw";
|
||||
|
||||
game.emit(Game.EVENT_PRE_SUBSYSTEM_INIT);
|
||||
physics2d.PhysicsSystem2D.constructAndRegister();
|
||||
@@ -50,10 +51,13 @@ for (const id in physics2d.selector.backend) {
|
||||
//test events
|
||||
EventTest(temp0);
|
||||
|
||||
//test debug draw
|
||||
DebugDrawTest();
|
||||
|
||||
// destroy test scene
|
||||
temp0.destroy();
|
||||
scene.destroy();
|
||||
// all works done
|
||||
done();
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||