Compare commits

..

50 Commits

Author SHA1 Message Date
hyde zhou 4a6f83bd6d Revert "refactor platforms (#126)" (#128) 2026-04-28 23:12:10 +08:00
tangkai 04f063eb2b add key value to assets.js (#127) 2026-04-28 23:09:53 +08:00
hyde zhou 910865bd8b refactor platforms (#126) 2026-04-28 18:53:46 +08:00
hyde zhou e384f54ed2 bump version to 4.0.0-alpha.15 (#125) 2026-04-28 16:46:44 +08:00
hyde zhou 5964835c83 bump version to 4.0.0-alpha.14 (#122) 2026-04-22 15:36:07 +08:00
tangkai f4ae16247c overrideClips_experimental error handle (#121) 2026-04-22 15:30:17 +08:00
qiuguohua 4b4a3ca13f Fix the issue where getWindowInfo does not have a cache, which causes lag. (#120) 2026-04-22 15:29:46 +08:00
hyde zhou f1c5d21be6 bump version to 4.0.0-alpha.13 (#119) 2026-04-15 14:09:42 +08:00
bofeng-song da75e89f4a export interface for CLI (#118) 2026-04-15 10:07:46 +08:00
hyde zhou aba27a715d bump version to 4.0.0-alpha.12 (#116) 2026-04-08 16:41:15 +08:00
hyde zhou 62c1eb58c3 bump version to 4.0.0-alpha.11 (#112) 2026-04-01 15:15:56 +08:00
hyde zhou 5b09978eb1 bump version to 4.0.0-alpha.10 (#108) 2026-03-25 15:59:52 +08:00
hyde zhou 1b8da1df9b fix HarmonyOS Next file size error. ((port from https://github.com/cocos/cocos-engine/pull/19100) (#106) 2026-03-25 14:23:12 +08:00
Raz ea6ff53aad [Spine] Complete spine 4.2 PhysicsConstraint wasm binding (#98) 2026-03-25 14:22:44 +08:00
tangkai b7ba9f76bb 1.适配DirectorEvent.RESET后调用physicscontactmanager.clear. (#99)
* 1.适配DirectorEvent.RESET后调用physicscontactmanager.clear. 2.根据1来调整,box2d, box2d-jsb, box2d-wam

* add empty clearContacts

* add clearContacts interface
2026-03-18 14:18:49 +08:00
hyde zhou ab670c4f99 bump version to 4.0.0-alpha.9 (#101) 2026-03-13 13:28:08 +08:00
tangkai ba0a042ef5 add SUDV2 platform (#100) 2026-03-13 12:06:51 +08:00
hyde zhou 8aa41cc3e7 bump version to 4.0.0-alpha.8 (#97) 2026-03-11 16:00:29 +08:00
tangkai db7666f821 the logic is consistent with box2d-jsb & box2d (#93)
* the logic is consistent with box2d-jsb & box2d

* Add return type to register/unregisterContactFixture, fix lint
2026-03-11 15:32:57 +08:00
tangkai 37abbf226a 1.Fix Box2D JSB collision end callback 2.fix BeginContact/EndContact mismatch (#89)
* 1.基于 Box2D JSB 的2D物理系统 结束碰撞但不回调 2.回调个数BeginContact和EndContact不一致。

* recover logic of physics-2d/box2d-jsb/platform/physics-contact-listener.ts

* add physics-2d/box2d-jsb/physics-contact-manager.ts
2026-03-11 14:01:37 +08:00
hyde zhou c890b69a9e bump version to 4.0.0-alpha.7 (#90) 2026-03-04 15:10:30 +08:00
bofeng-song 5f4f091c3e Fix the flickering issue in Spine that may occur when setting false first and then true within the same frame. (#84) 2026-03-04 15:05:15 +08:00
pengchengo 1519043126 fixing bytedance minigame file downloading blocking problem, using solution in 2.4.16
* 参考2.4.16,解决cocos在字节小游戏上下载文件,每隔2秒掉帧到30-40帧的问题。原因是_write方法里使用writeFileSync方法在字节小游戏上可能时长700ms,卡主游戏。修改方法是改成2.x的版本使用异步方法writeFile,cache-manager基本改成和2.4.16一样了

* 解决cocos在字节小游戏上下载文件,每隔2秒掉帧到30-40帧的问题。
2026-03-04 14:39:09 +08:00
tangkai b7e83d3460 change increaseThreadCount position before sendImmediate (#87) 2026-03-04 11:00:58 +08:00
bofeng-song a64e164e82 Fix crash on iOS when resuming download task. (#83) 2026-02-27 17:10:44 +08:00
hyde zhou 8e0412beab bump version to 4.0.0-alpha.6 (#77) 2026-02-11 11:49:15 +08:00
orchid-world 35e7bb2d5e feat(minigame): 支付宝小程序添加安全区域获取功能 (#44) 2026-02-11 11:22:30 +08:00
bofeng-song 315800edf9 TextureRegion in Spine 4.2 is used during runtime, and the atlas must be released last. (#75)
* Fix out of memory for spine4.2

* update external version
2026-02-10 10:40:13 +08:00
hyde zhou c3d974152d bump version (#71) 2026-02-04 10:44:38 +08:00
bofeng-song b534fab05e Remove unneed function (#70)
* Remove unneed function

* Reorder import statement for approx in model.ts

---------

Co-authored-by: hyde zhou <zlzhou.sh@outlook.com>
2026-02-04 10:07:23 +08:00
bofeng-song e913d77704 Fix the issue that the implementation of Vec3 equals is inconsistent with the implementations of Vec2 and Vec4. (#57)
* Fix the issue that the implementation of Vec3 equals is inconsistent with the implementations of Vec2 and Vec4.

* Change approxEquals method to return boolean

* Fix formatting of approxEquals method

---------

Co-authored-by: hyde zhou <zlzhou.sh@outlook.com>
2026-02-03 17:26:06 +08:00
hyde zhou 8081beab5e use cocos4 (#68) 2026-02-03 17:25:04 +08:00
Leslie Leigh (李的序) 5b2b5f9dfc Fix the issue where the character controller’s group/mask was not set correctly (#64) 2026-02-03 12:26:14 +08:00
bofeng-song 535a593a9a Fix memory leaks in Spine resource parsing on the web-side. (#65)
* Fix memory leaks in Spine resource parsing on the web-side.

* update external version
2026-02-03 11:38:10 +08:00
hyde zhou 5f4d70d989 Update version check (#67) 2026-02-03 11:09:12 +08:00
orchid-world 100bccaf9e fix(ui): ensure Layout recalculates layout when a child node’s scale changes 2026-02-03 10:15:23 +08:00
hyde zhou c04e6e0698 Revert "Fix crash caused by float canvas size on minigame platform for some mobile phones." (#62)
This reverts commit 7fdf0fda6b.
2026-01-29 14:46:02 +08:00
hyde zhou 999035011b update package-lock.json (#61) 2026-01-28 16:54:15 +08:00
hyde zhou bccf90d104 bump version (#60) 2026-01-28 16:50:23 +08:00
bofeng-song f347f51d30 Fix the issue on the native platform where miniMaps are not updated after calling initDefault on a texture, resulting in the inability to retrieve texture.image. (#59) 2026-01-28 16:32:10 +08:00
bofeng-song c7cb618d6f Fix the issue of macro usage errors. (#58) 2026-01-28 16:31:53 +08:00
orchid-world 16797c4d49 fix(ui): 修复slider组件在不同锚点下进度计算错误 (#53) 2026-01-28 14:45:04 +08:00
hyde zhou 7fdf0fda6b Fix crash caused by float canvas size on minigame platform for some mobile phones. 2026-01-27 09:59:56 +08:00
hyde zhou d9e3cff3b6 update version (#49) 2026-01-20 11:29:13 +08:00
orchid-world 9997cb63e0 feat(node): make setWorldPosition parameter z optional 2026-01-19 17:34:57 +08:00
tangkai 22c8d6a0a4 Add feedstatuscontroller execution order (#48)
* add executionOrder to FeedStatusController.ts

* adjust executionOrder
2026-01-19 17:33:15 +08:00
hyde zhou 8c55d2d233 fix feed status (#46) 2026-01-19 12:03:45 +08:00
hyde zhou 401ba60083 bump version (#43) 2026-01-13 18:24:13 +08:00
bofeng-song e6f1fe9fc5 Update external version (#36) 2026-01-08 14:19:33 +08:00
hyde zhou 6a2698978f remove twitter follow and change ui (#26) 2026-01-04 13:43:07 +08:00
55 changed files with 745 additions and 333 deletions
+1 -1
View File
@@ -9,7 +9,7 @@ body:
Please write a descriptive issue title above.
**Before You Start:**
- Search [open](https://github.com/cocos/cocos-engine/issues) and [closed](https://github.com/cocos/cocos-engine/issues?q=is%3Aissue+is%3Aclosed) issues to ensure it has not already been reported.
- Search [open](https://github.com/cocos/cocos4/issues) and [closed](https://github.com/cocos/cocos4/issues?q=is%3Aissue+is%3Aclosed) issues to ensure it has not already been reported.
- Verify that your issue is reproducible in the latest stable version of [Cocos Creator](https://www.cocos.com/creator).
**For usage questions, please use the following resources:**
+1 -1
View File
@@ -7,7 +7,7 @@ body:
attributes:
value: |
- Please write a descriptive proposal title above.
- Search [open](https://github.com/cocos/cocos-engine/issues) and [closed](https://github.com/cocos/cocos-engine/issues?q=is%3Aissue+is%3Aclosed) issues to ensure it has not already been suggested.
- Search [open](https://github.com/cocos/cocos4/issues) and [closed](https://github.com/cocos/cocos4/issues?q=is%3Aissue+is%3Aclosed) issues to ensure it has not already been suggested.
- type: textarea
attributes:
+1 -1
View File
@@ -66,7 +66,7 @@ jobs:
author: cocos-robot <cocos-robot@cocos.com>
commit-message: "[ci skip][AUTO]: Automated code generating update: ${{ github.event.pull_request.head.sha }} (#${{ github.event.number }})"
token: ${{ secrets.PR_TOKEN }}
push-to-fork: cocos-robot/engine
push-to-fork: cocos-robot/cocos4
branch: t/bot/genbindings
branch-suffix: short-commit-hash
delete-branch: true
+1 -1
View File
@@ -49,7 +49,7 @@ jobs:
author: cocos-robot <cocos-robot@cocos.com>
commit-message: "[ci skip][AUTO]: Automated clang-format update: ${{ github.event.pull_request.head.sha }} (#${{ github.event.number }})"
token: ${{ secrets.PR_TOKEN }}
push-to-fork: cocos-robot/engine
push-to-fork: cocos-robot/cocos4
branch: t/bot/fix-format
branch-suffix: short-commit-hash
delete-branch: true
+8 -8
View File
@@ -28,7 +28,7 @@ jobs:
id: pr_details
uses: octokit/request-action@v2.x
with:
route: GET /repos/cocos/cocos-engine/pulls/${{ env.PR_NUMBER }}
route: GET /repos/cocos/cocos4/pulls/${{ env.PR_NUMBER }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -169,7 +169,7 @@ jobs:
- Editor Version: ${process.env.EDITOR_VERSION}
- Task Result: ${process.env.TASK_STATUS}
- Task URL: https://cctest.cocos.org/#/reportview/PR-TEST/${process.env.JOB_ID}/-1
- GitHub Action: https://github.com/cocos/cocos-engine/actions/runs/${process.env.GITHUB_RUN_ID}
- GitHub Action: https://github.com/cocos/cocos4/actions/runs/${process.env.GITHUB_RUN_ID}
## Task Details
${process.env.TASK_REPORT}`);
@@ -191,7 +191,7 @@ jobs:
id: pr_details
uses: octokit/request-action@v2.x
with:
route: GET /repos/cocos/cocos-engine/pulls/${{ env.PR_NUMBER }}
route: GET /repos/cocos/cocos4/pulls/${{ env.PR_NUMBER }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -327,7 +327,7 @@ jobs:
- Editor Version: ${process.env.EDITOR_VERSION}
- Task Result: ${process.env.TASK_STATUS}
- Task URL: https://cctest.cocos.org/#/reportview/PR-TEST/${process.env.JOB_ID}/-1
- GitHub Action: https://github.com/cocos/cocos-engine/actions/runs/${process.env.GITHUB_RUN_ID}
- GitHub Action: https://github.com/cocos/cocos4/actions/runs/${process.env.GITHUB_RUN_ID}
## Task Details
${process.env.TASK_REPORT}`);
@@ -357,7 +357,7 @@ jobs:
id: pr_details
uses: octokit/request-action@v2.x
with:
route: GET /repos/cocos/cocos-engine/pulls/${{ env.PR_NUMBER }}
route: GET /repos/cocos/cocos4/pulls/${{ env.PR_NUMBER }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -498,7 +498,7 @@ jobs:
- Editor Version: ${process.env.EDITOR_VERSION}
- Task Result: ${process.env.TASK_STATUS}
- Task URL: https://cctest.cocos.org/#/reportview/PR-TEST/${process.env.JOB_ID}/-1
- GitHub Action: https://github.com/cocos/cocos-engine/actions/runs/${process.env.GITHUB_RUN_ID}
- GitHub Action: https://github.com/cocos/cocos4/actions/runs/${process.env.GITHUB_RUN_ID}
## Task Details
${process.env.TASK_REPORT}`);
@@ -519,7 +519,7 @@ jobs:
id: pr_details
uses: octokit/request-action@v2.x
with:
route: GET /repos/cocos/cocos-engine/pulls/${{ env.PR_NUMBER }}
route: GET /repos/cocos/cocos4/pulls/${{ env.PR_NUMBER }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -655,7 +655,7 @@ jobs:
- Editor Version: ${process.env.EDITOR_VERSION}
- Task Result: ${process.env.TASK_STATUS}
- Task URL: https://cctest.cocos.org/#/reportview/PR-TEST/${process.env.JOB_ID}/-1
- GitHub Action: https://github.com/cocos/cocos-engine/actions/runs/${process.env.GITHUB_RUN_ID}
- GitHub Action: https://github.com/cocos/cocos4/actions/runs/${process.env.GITHUB_RUN_ID}
## Task Details
${process.env.TASK_REPORT}`);
-4
View File
@@ -17,10 +17,6 @@
<img src="https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square&colorB=4183c4"
alt="license">
</a>
<a href="https://twitter.com/CocosEngine">
<img src="https://img.shields.io/twitter/follow/CocosEngine.svg?logo=twitter&label=follow&style=flat-square&colorB=4183c4"
alt="twitter">
</a>
</p>
# COCOS 4
+8 -1
View File
@@ -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
},
@@ -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);
}
+6
View File
@@ -56,6 +56,12 @@ texture2DProto._ctor = function () {
this._mipmaps = [];
};
const oldInitDefault = texture2DProto.initDefault;
texture2DProto.initDefault = function (uuid: string) {
oldInitDefault.call(this, uuid);
this._mipmaps = this.getMipmaps();
}
texture2DProto._serialize = function (ctxForExporting: any) {
if (EDITOR || NODEJS || TEST) {
return {
+5 -10
View File
@@ -959,11 +959,7 @@ export class Vec3 extends ValueType {
* @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`.
*/
public equals (other: Vec3, epsilon = EPSILON): boolean {
return (
abs(this.x - other.x) <= epsilon
&& abs(this.y - other.y) <= epsilon
&& abs(this.z - other.z) <= epsilon
);
return Vec3.equals(this, other, epsilon);
}
/**
@@ -976,11 +972,10 @@ export class Vec3 extends ValueType {
* @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`.
*/
public equals3f (x: number, y: number, z: number, epsilon = EPSILON): boolean {
return (
abs(this.x - x) <= epsilon
&& abs(this.y - y) <= epsilon
&& abs(this.z - z) <= epsilon
);
const self = this;
return (abs(self.x - x) <= epsilon * max(1.0, abs(self.x), abs(x))
&& abs(self.y - y) <= epsilon * max(1.0, abs(self.y), abs(y))
&& abs(self.z - z) <= epsilon * max(1.0, abs(self.z), abs(z)));
}
/**
+6 -1
View File
@@ -36,11 +36,16 @@
import { _decorator } from '../core';
import { Component } from '../scene-graph/component';
const { ccclass } = _decorator;
const { ccclass, menu, executionOrder } = _decorator;
declare const minigame: any;
@ccclass('FeedStatusController')
@executionOrder(90)
@menu('Miscellaneous/FeedStatusController')
export class FeedStatusController extends Component {
constructor () {
super();
}
protected start (): void {
if (minigame && minigame.onFeedStatusChange) {
minigame.onFeedStatusChange(this.feedStatusChangeCallBack);
@@ -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;
}
}
+1 -26
View File
@@ -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!;
}
+9 -5
View File
@@ -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';
@@ -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();
}
}
@@ -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;
}
}
+2 -19
View File
@@ -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;
+20 -6
View File
@@ -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);
@@ -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);
}
}
@@ -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;
}
}
-23
View File
@@ -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;
}
+9 -5
View File
@@ -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();
@@ -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();
}
}
@@ -285,4 +285,6 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld {
raycast (p1: IVec2Like, p2: IVec2Like, type: ERaycast2DType): RaycastResult2D[] {
return [];
}
clearContacts (): void {
}
}
@@ -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(); });
}
+1
View File
@@ -38,4 +38,5 @@ export interface IPhysicsWorld {
testPoint (p: Vec2): readonly Collider2D[];
testAABB (rect: Rect): readonly Collider2D[];
drawDebug (): void;
clearContacts (): void;
}
@@ -67,11 +67,12 @@ export class PhysXBoxCharacterController extends PhysXCharacterController implem
controllerDesc.position = { x: v3_0.x, y: v3_0.y, z: v3_0.z };//PxExtendedVec3
controllerDesc.setMaterial(pxMtl);
controllerDesc.setReportCallback(PX.PxUserControllerHitReport.implement(physxWorld.callback.controllerHitReportCB));
this._impl = PX.createBoxCharacterController(physxWorld.controllerManager, controllerDesc);
const impl = PX.createBoxCharacterController(physxWorld.controllerManager, controllerDesc);
this.setImpl(impl);
if (this._impl.$$) {
PX.IMPL_PTR[this._impl.$$.ptr] = this;
const shapePtr = this._impl.getShape().$$.ptr;
if (impl.$$) {
PX.IMPL_PTR[impl.$$.ptr] = this;
const shapePtr = impl.getShape().$$.ptr;
PX.IMPL_PTR[shapePtr] = this;
}
@@ -68,11 +68,12 @@ export class PhysXCapsuleCharacterController extends PhysXCharacterController im
controllerDesc.position = { x: v3_0.x, y: v3_0.y, z: v3_0.z };//PxExtendedVec3
controllerDesc.setMaterial(pxMtl);
controllerDesc.setReportCallback(PX.PxUserControllerHitReport.implement(physxWorld.callback.controllerHitReportCB));
this._impl = PX.createCapsuleCharacterController(physxWorld.controllerManager, controllerDesc);
const impl = PX.createCapsuleCharacterController(physxWorld.controllerManager, controllerDesc);
this.setImpl(impl);
if (this._impl.$$) {
PX.IMPL_PTR[this._impl.$$.ptr] = this;
const shapePtr = this._impl.getShape().$$.ptr;
if (impl.$$) {
PX.IMPL_PTR[impl.$$.ptr] = this;
const shapePtr = impl.getShape().$$.ptr;
PX.IMPL_PTR[shapePtr] = this;
}
@@ -31,6 +31,7 @@ import { PhysXWorld } from '../physx-world';
import { PhysXShape } from '../shapes/physx-shape';
import { degreesToRadians } from '../../../core/utils/misc';
import { TransformBit } from '../../../scene-graph';
import { PhysXFilterData } from '../filter-data';
const v3_0 = new Vec3(0, 0, 0);
const v3_1 = new Vec3(0, 0, 0);
@@ -41,7 +42,7 @@ export class PhysXCharacterController implements IBaseCharacterController {
protected _impl: any = null;
protected _comp: CharacterController = null as any;
private _pxCollisionFlags = 0;//: PX.PxControllerCollisionFlags;
private _filterData: any;
private _filterData: PhysXFilterData;
private _queryFilterCB: any = null;
protected _word3 = 0;
protected _overlapRecovery = true;
@@ -85,6 +86,7 @@ export class PhysXCharacterController implements IBaseCharacterController {
this._filterData.word0 = this._comp.group;
const mask = PhysicsSystem.instance.collisionMatrix[group];
this._filterData.word1 = mask;
this.updateFilterData();
this.onComponentSet();
@@ -292,4 +294,9 @@ export class PhysXCharacterController implements IBaseCharacterController {
// this._impl.setQueryFilterData(filterData);//set inside move()
this._impl.setSimulationFilterData(this.filterData);
}
protected setImpl (impl: any): void {
this._impl = impl;
this.updateFilterData();
}
}
+6
View File
@@ -0,0 +1,6 @@
export interface PhysXFilterData {
word0: number;
word1: number;
word2: number;
word3: number;
}
+2 -1
View File
@@ -37,6 +37,7 @@ import { ERigidBodyType, PhysicsSystem } from '../framework';
import { PhysXJoint } from './joints/physx-joint';
import { PhysicsGroup } from '../framework/physics-enum';
import { Node } from '../../scene-graph';
import { PhysXFilterData } from './filter-data';
/** @mangle */
export class PhysXSharedBody {
@@ -89,7 +90,7 @@ export class PhysXSharedBody {
private _dynamicActor!: PhysX.RigidActor | any;
private _staticActor!: PhysX.RigidActor | any;
private _wrappedBody: PhysXRigidBody | null = null;
private _filterData: any;
private _filterData: PhysXFilterData;
set reference (v: boolean) {
this._ref = v ? this._ref + 1 : this._ref - 1;
+3 -2
View File
@@ -33,7 +33,7 @@ import { RenderScene } from '../core/render-scene';
import { Texture2D } from '../../asset/assets/texture-2d';
import { SubModel } from './submodel';
import { IMacroPatch } from '../core/pass';
import { Mat4, Vec3, Vec4, geometry, cclegacy, EPSILON, v3, v4 } from '../../core';
import { approx, Mat4, Vec3, Vec4, geometry, cclegacy, EPSILON, v3, v4 } from '../../core';
import { Attribute, DescriptorSet, Device, Buffer, BufferInfo,
BufferUsageBit, MemoryUsageBit, Filter, Address, SamplerInfo, deviceManager, Texture } from '../../gfx';
import {
@@ -824,7 +824,8 @@ export class Model {
}
const center = this._worldBounds!.center;
if (!EDITOR && center.equals(this._lastWorldBoundCenter, EPSILON)) {
const last = this._lastWorldBoundCenter;
if (!EDITOR && approx(center.x, last.x) && approx(center.y, last.y) && approx(center.z, last.z)) {
return;
}
+6 -2
View File
@@ -2616,7 +2616,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable {
* @param y Y axis position
* @param z Z axis position
*/
public setWorldPosition(x: number, y: number, z: number): void;
public setWorldPosition(x: number, y: number, z?: number): void;
public setWorldPosition (val: Vec3 | number, y?: number, z?: number): void {
const worldPosition = this._pos;
@@ -2624,7 +2624,11 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable {
if (y === undefined) {
Vec3.copy(worldPosition, val as Vec3);
} else {
Vec3.set(worldPosition, val as number, y, z!);
if (z === undefined) {
z = worldPosition.z;
}
Vec3.set(worldPosition, val as number, y, z);
}
const parent = this._parent;
+14 -12
View File
@@ -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;
+126
View File
@@ -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;
+3 -4
View File
@@ -1144,11 +1144,10 @@ export class Layout extends Component {
}
protected _transformDirty (type: TransformBit): void {
if (!(type & TransformBit.SCALE) || !(type & TransformBit.POSITION) || !this._affectedByScale) {
return;
// Invalidate layout when scale is affected and changed, or position is changed.
if ((type & TransformBit.SCALE && this._affectedByScale) || (type & TransformBit.POSITION)) {
this._doLayoutDirty();
}
this._doLayoutDirty();
}
protected _doLayoutDirty (): void {
+4 -2
View File
@@ -303,10 +303,12 @@ export class Slider extends Component {
Vec3.set(this._touchPos, touchPos.x, touchPos.y, 0);
const uiTrans = this.node._getUITransformComp()!;
const localTouchPos = uiTrans.convertToNodeSpaceAR(this._touchPos, _tempPos);
localTouchPos.x += uiTrans.anchorX * uiTrans.width;
localTouchPos.y += uiTrans.anchorY * uiTrans.height;
if (this.direction === Direction.Horizontal as number) {
this.progress = clamp01(0.5 + (localTouchPos.x - this._offset.x) / uiTrans.width);
this.progress = clamp01((localTouchPos.x - this._offset.x) / uiTrans.width);
} else {
this.progress = clamp01(0.5 + (localTouchPos.y - this._offset.y) / uiTrans.height);
this.progress = clamp01((localTouchPos.y - this._offset.y) / uiTrans.height);
}
}
+5
View File
@@ -38,6 +38,11 @@ module.exports = {
newCubeMap: 'CubeMap',
newRenderTexture: 'Render Texture',
newScene: 'Scene',
newScene:{
'2d': '2D',
'3d': '3D',
quality: 'Quality',
},
newPrefab: 'Node Prefab',
newMaterial: 'Material',
newPhysicsMaterial: 'Physics Material',
+5
View File
@@ -37,6 +37,11 @@ module.exports = {
newTypeScript: '脚本 (TypeScript)',
newCubeMap: '立方体贴图',
newScene: '场景',
newScene:{
'2d': '2D',
'3d': '3D',
quality: '质量',
},
newPrefab: '预制 (Prefab)',
newRenderTexture: '渲染纹理 (Render Texture)',
newMaterial: '材质',
+1 -1
View File
@@ -100,7 +100,7 @@ void AudioPlayer::destroy() {
_rotateBufferThread = nullptr;
ALOGVV("rotateBufferThread exited!");
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#if CC_PLATFORM == CC_PLATFORM_IOS
// some specific OpenAL implement defects existed on iOS platform
// refer to: https://github.com/cocos2d/cocos2d-x/issues/18597
ALint sourceState;
@@ -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};
@@ -171,57 +175,70 @@ SkeletonData* SpineWasmUtil::querySpineSkeletonDataByUUID(const String& uuid) {
}
SkeletonData* SpineWasmUtil::createSpineSkeletonDataWithJson(const String& jsonStr, const String& altasStr, const spine::Vector<spine::String>& textureNames, const spine::Vector<spine::String>& textureUUIDs) {
SkeletonData* skeletonData = nullptr;
#if ENABLE_JSON_PARSER
auto* atlas = new Atlas(altasStr.buffer(), altasStr.length(), "", nullptr, false);
if (!atlas) {
return nullptr;
}
AttachmentLoader* attachmentLoader = new AtlasAttachmentLoaderExtension(atlas);
#ifdef CC_SPINE_VERSION_3_8
SkeletonJson json(attachmentLoader);
#else
SkeletonJson json(attachmentLoader, true);
#endif
json.setScale(1.0F);
SkeletonData* skeletonData = json.readSkeletonData(jsonStr.buffer());
auto& errorMsg = json.getError();
if (!errorMsg.isEmpty()) {
logToConsole(errorMsg.buffer(), LOG_LEVEL_WARN);
}
{
AttachmentLoader* attachmentLoader = new AtlasAttachmentLoaderExtension(atlas);
#ifdef CC_SPINE_VERSION_3_8
SkeletonJson json(attachmentLoader);
#else
SkeletonJson json(attachmentLoader, true);
#endif
json.setScale(1.0F);
skeletonData = json.readSkeletonData(jsonStr.buffer());
auto& errorMsg = json.getError();
if (!errorMsg.isEmpty()) {
logToConsole(errorMsg.buffer(), LOG_LEVEL_WARN);
}
saveAttachmentVertices(skeletonData, textureNames, textureUUIDs);
saveAttachmentVertices(skeletonData, textureNames, textureUUIDs);
}
#ifdef CC_SPINE_VERSION_3_8
delete atlas;
#else
spineAtlasMap.put(skeletonData, atlas);
#endif
#endif
return skeletonData;
#else
return nullptr;
#endif
}
SkeletonData* SpineWasmUtil::createSpineSkeletonDataWithBinary(uint32_t byteSize, const String& altasStr, const spine::Vector<spine::String>& textureNames, const spine::Vector<spine::String>& textureUUIDs) {
SkeletonData* skeletonData = nullptr;
#if ENABLE_BINARY_PARSER
auto* atlas = new Atlas(altasStr.buffer(), altasStr.length(), "", nullptr, false);
if (!atlas) {
return nullptr;
}
AttachmentLoader* attachmentLoader = new AtlasAttachmentLoaderExtension(atlas);
#ifdef CC_SPINE_VERSION_3_8
SkeletonBinary binary(attachmentLoader);
#else
SkeletonBinary binary(attachmentLoader, true);
#endif
binary.setScale(1.0F);
SkeletonData* skeletonData = binary.readSkeletonData(s_mem, byteSize);
auto& errorMsg = binary.getError();
if (!errorMsg.isEmpty()) {
logToConsole(errorMsg.buffer(), LOG_LEVEL_WARN);
{
AttachmentLoader* attachmentLoader = new AtlasAttachmentLoaderExtension(atlas);
#ifdef CC_SPINE_VERSION_3_8
SkeletonBinary binary(attachmentLoader);
#else
SkeletonBinary binary(attachmentLoader, true);
#endif
binary.setScale(1.0F);
skeletonData = binary.readSkeletonData(s_mem, byteSize);
auto& errorMsg = binary.getError();
if (!errorMsg.isEmpty()) {
logToConsole(errorMsg.buffer(), LOG_LEVEL_WARN);
}
saveAttachmentVertices(skeletonData, textureNames, textureUUIDs);
}
saveAttachmentVertices(skeletonData, textureNames, textureUUIDs);
return skeletonData;
#ifdef CC_SPINE_VERSION_3_8
delete atlas;
#else
return nullptr;
spineAtlasMap.put(skeletonData, atlas);
#endif
#endif
return skeletonData;
}
void SpineWasmUtil::registerSpineSkeletonDataWithUUID(SkeletonData* data, const String& uuid) {
@@ -246,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);
}
+23 -15
View File
@@ -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++;
}
}
+6 -1
View File
@@ -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);
+1 -1
View File
@@ -3,6 +3,6 @@
"type": "github",
"owner": "cocos",
"name": "cocos-engine-external",
"checkout": "v3.8.8-2"
"checkout": "v4.0.0-4"
}
}
+2 -62
View File
@@ -1,12 +1,12 @@
{
"name": "cocos-creator",
"version": "3.8.8",
"version": "4.0.0-alpha.15",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "cocos-creator",
"version": "3.8.8",
"version": "4.0.0-alpha.15",
"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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cocos-creator",
"version": "4.0.0",
"version": "4.0.0-alpha.15",
"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",
+5 -1
View File
@@ -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,
+7
View File
@@ -124,6 +124,13 @@ minigame.createInnerAudioContext = createInnerAudioContextPolyfill(wx, {
onSeek: false,
}, true);
let _cachedSystemInfo: SystemInfo = wx.getWindowInfo();
minigame.onWindowResize?.((): void => {
// update cached system info
_cachedSystemInfo = wx.getWindowInfo() as SystemInfo;
});
minigame.getWindowInfo = (): SystemInfo => _cachedSystemInfo;
// #region SafeArea
// FIX_ME: wrong safe area when orientation is landscape left
minigame.getSafeArea = (): SafeArea => {
+1
View File
@@ -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',
}
+3 -1
View File
@@ -23,7 +23,7 @@
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 { 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 } from 'pal/minigame';
import { IFeatureMap } from 'pal/system-info';
import { EventTarget } from '../../../cocos/core/event';
@@ -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;
@@ -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 -1
View File
@@ -14,7 +14,7 @@ if (!(matchResult && matchResult[1])) {
const branchVersion = matchResult[1];
const versionRegExpMap = {
'./package.json': /"version": "(.*)"/,
'./package.json': /"version": "(\d+\.\d+\.\d+)(?:-.*)?"/,
'./cocos/core/global-exports.ts': /engineVersion = '(.*)'/,
};
for (const filePath in versionRegExpMap) {
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 16 KiB