From 1dc3142fbbb4ee93421e3fc2754366c0abcd3517 Mon Sep 17 00:00:00 2001 From: Ling Zhan Date: Thu, 17 Aug 2023 17:34:04 +0800 Subject: [PATCH] [opt] when move() is called, character controller sync physics position to scene; change default stepOffset; set minimum skinWidth (#15966) * [opt] [character controller] when move() is called, character controller sync physics position to scene immediately; change default stepOffset from 1.0 to 0.5; set minimum skinWidth 0.001 * tweak * native * eslint * eslint * eslint --- cocos/physics/bullet/bullet-world.ts | 107 ++++++++++++------ .../bullet-character-controller.ts | 30 +++-- .../character-controller.ts | 15 ++- cocos/physics/framework/physics-selector.ts | 2 + cocos/physics/physx/physx-world.ts | 8 +- cocos/physics/spec/i-character-controller.ts | 1 + native/cocos/physics/physx/PhysXWorld.cpp | 3 - .../PhysXCharacterController.h | 2 +- .../cocos/physics/sdk/CharacterController.cpp | 4 + .../cocos/physics/sdk/CharacterController.h | 1 + .../cocos/physics/spec/ICharacterController.h | 1 + platforms/native/engine/jsb-physics.js | 1 + 12 files changed, 117 insertions(+), 58 deletions(-) diff --git a/cocos/physics/bullet/bullet-world.ts b/cocos/physics/bullet/bullet-world.ts index aa4514d28a..298b168332 100644 --- a/cocos/physics/bullet/bullet-world.ts +++ b/cocos/physics/bullet/bullet-world.ts @@ -45,7 +45,9 @@ const v3_1 = CC_V3_1; const v3_2 = CC_V3_2; const emitHit = new CharacterControllerContact(); export class BulletWorld implements IPhysicsWorld { - setDefaultMaterial (v: PhysicsMaterial): void { } + setDefaultMaterial (v: PhysicsMaterial): void { + //empty + } setAllowSleep (v: boolean): void { bt.ccDiscreteDynamicsWorld_setAllowSleep(this._world, v); @@ -128,9 +130,9 @@ export class BulletWorld implements IPhysicsWorld { readonly oldContactsDic = new TupleDictionary(); readonly cctShapeEventDic = new TupleDictionary(); - private static _sweepBoxGeometry: any; - private static _sweepSphereGeometry: any; - private static _sweepCapsuleGeometry: any; + private static _sweepBoxGeometry: number; + private static _sweepSphereGeometry: number; + private static _sweepCapsuleGeometry: number; constructor () { this._broadphase = bt.DbvtBroadphase_new(); @@ -159,15 +161,9 @@ export class BulletWorld implements IPhysicsWorld { } step (deltaTime: number, timeSinceLastCalled?: number, maxSubStep = 0): void { - if (!this.bodies.length && !this.ghosts.length && !this.ccts.length) return; + if (!this.bodies.length && !this.ghosts.length) return; if (timeSinceLastCalled === undefined) timeSinceLastCalled = deltaTime; bt.DynamicsWorld_stepSimulation(this._world, timeSinceLastCalled, maxSubStep, deltaTime); - - const ccts = this.ccts; - const length = ccts.length; - for (let i = 0; i < length; i++) { - ccts[i].syncPhysicsToScene(); - } } syncSceneToPhysics (): void { @@ -240,8 +236,14 @@ export class BulletWorld implements IPhysicsWorld { return false; } - sweepBox (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, - options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + sweepBox ( + worldRay: geometry.Ray, + halfExtent: IVec3Like, + orientation: IQuatLike, + options: IRaycastOptions, + pool: RecyclePool, + results: PhysicsRayResult[], + ): boolean { // cast shape const hf = BulletCache.instance.BT_V3_0; cocos2BulletVec3(hf, halfExtent); @@ -253,8 +255,13 @@ export class BulletWorld implements IPhysicsWorld { return this.sweep(worldRay, BulletWorld._sweepBoxGeometry, orientation, options, pool, results); } - sweepBoxClosest (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, - options: IRaycastOptions, result: PhysicsRayResult): boolean { + sweepBoxClosest ( + worldRay: geometry.Ray, + halfExtent: IVec3Like, + orientation: IQuatLike, + options: IRaycastOptions, + result: PhysicsRayResult, + ): boolean { // cast shape const hf = BulletCache.instance.BT_V3_0; cocos2BulletVec3(hf, halfExtent); @@ -266,8 +273,13 @@ export class BulletWorld implements IPhysicsWorld { return this.sweepClosest(worldRay, BulletWorld._sweepBoxGeometry, orientation, options, result); } - sweepSphere (worldRay: geometry.Ray, radius: number, - options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + sweepSphere ( + worldRay: geometry.Ray, + radius: number, + options: IRaycastOptions, + pool: RecyclePool, + results: PhysicsRayResult[], + ): boolean { // cast shape if (!BulletWorld._sweepSphereGeometry) { BulletWorld._sweepSphereGeometry = bt.SphereShape_new(radius); @@ -276,8 +288,12 @@ export class BulletWorld implements IPhysicsWorld { return this.sweep(worldRay, BulletWorld._sweepSphereGeometry, Quat.IDENTITY, options, pool, results); } - sweepSphereClosest (worldRay: geometry.Ray, radius: number, - options: IRaycastOptions, result: PhysicsRayResult): boolean { + sweepSphereClosest ( + worldRay: geometry.Ray, + radius: number, + options: IRaycastOptions, + result: PhysicsRayResult, + ): boolean { // cast shape if (!BulletWorld._sweepSphereGeometry) { BulletWorld._sweepSphereGeometry = bt.SphereShape_new(radius); @@ -287,8 +303,15 @@ export class BulletWorld implements IPhysicsWorld { return this.sweepClosest(worldRay, BulletWorld._sweepSphereGeometry, Quat.IDENTITY, options, result); } - sweepCapsule (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike, - options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + sweepCapsule ( + worldRay: geometry.Ray, + radius: number, + height: number, + orientation: IQuatLike, + options: IRaycastOptions, + pool: RecyclePool, + results: PhysicsRayResult[], + ): boolean { // cast shape if (!BulletWorld._sweepCapsuleGeometry) { BulletWorld._sweepCapsuleGeometry = bt.CapsuleShape_new(radius, height); @@ -297,8 +320,14 @@ export class BulletWorld implements IPhysicsWorld { return this.sweep(worldRay, BulletWorld._sweepCapsuleGeometry, orientation, options, pool, results); } - sweepCapsuleClosest (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike, - options: IRaycastOptions, result: PhysicsRayResult): boolean { + sweepCapsuleClosest ( + worldRay: geometry.Ray, + radius: number, + height: number, + orientation: IQuatLike, + options: IRaycastOptions, + result: PhysicsRayResult, + ): boolean { // cast shape if (!BulletWorld._sweepCapsuleGeometry) { BulletWorld._sweepCapsuleGeometry = bt.CapsuleShape_new(radius, height); @@ -308,8 +337,14 @@ export class BulletWorld implements IPhysicsWorld { return this.sweepClosest(worldRay, BulletWorld._sweepCapsuleGeometry, orientation, options, result); } - sweep (worldRay: geometry.Ray, btShapePtr: any, orientation: IQuatLike, - options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + sweep ( + worldRay: geometry.Ray, + btShapePtr: number, + orientation: IQuatLike, + options: IRaycastOptions, + pool: RecyclePool, + results: PhysicsRayResult[], + ): boolean { const BT_fromTransform = BulletCache.instance.BT_TRANSFORM_0; const BT_toTransform = BulletCache.instance.BT_TRANSFORM_1; const BT_orientation = BulletCache.instance.BT_QUAT_0; @@ -344,8 +379,13 @@ export class BulletWorld implements IPhysicsWorld { return false; } - sweepClosest (worldRay: geometry.Ray, btShapePtr: any, orientation: IQuatLike, - options: IRaycastOptions, result: PhysicsRayResult): boolean { + sweepClosest ( + worldRay: geometry.Ray, + btShapePtr: number, + orientation: IQuatLike, + options: IRaycastOptions, + result: PhysicsRayResult, + ): boolean { const BT_fromTransform = BulletCache.instance.BT_TRANSFORM_0; const BT_toTransform = BulletCache.instance.BT_TRANSFORM_1; const BT_orientation = BulletCache.instance.BT_QUAT_0; @@ -588,9 +628,9 @@ export class BulletWorld implements IPhysicsWorld { const data = this.cctShapeEventDic.getDataByKey(key); const cct: BulletCharacterController = data.BulletCharacterController; const shape: BulletShape = data.BulletShape; - const worldPos = data.worldPos; - const worldNormal = data.worldNormal; - const motionDir = data.motionDir; + const worldPos = data.worldPos as IVec3Like; + const worldNormal = data.worldNormal as IVec3Like; + const motionDir = data.motionDir as IVec3Like; const motionLength = data.motionLength; emitHit.controller = cct.characterController; emitHit.collider = shape.collider; @@ -623,8 +663,11 @@ export class BulletWorld implements IPhysicsWorld { // current contact let item = this.contactsDic.get(shape0.id, shape1.id); if (!item) { - item = this.contactsDic.set(shape0.id, shape1.id, - { shape0, shape1, contacts: [], impl: manifold }); + item = this.contactsDic.set( + shape0.id, + shape1.id, + { shape0, shape1, contacts: [], impl: manifold }, + ); } item.contacts.push(manifoldPoint);//btManifoldPoint } diff --git a/cocos/physics/bullet/character-controllers/bullet-character-controller.ts b/cocos/physics/bullet/character-controllers/bullet-character-controller.ts index 1913564814..4d6ed88d53 100644 --- a/cocos/physics/bullet/character-controllers/bullet-character-controller.ts +++ b/cocos/physics/bullet/character-controllers/bullet-character-controller.ts @@ -41,7 +41,7 @@ const v3_2 = new Vec3(0, 0, 0); export abstract class BulletCharacterController implements IBaseCharacterController { readonly wrappedWorld: BulletWorld; private _isEnabled = false; - protected _impl: any = null; //btCapsuleCharacterController + protected _impl: number = 0; //btCapsuleCharacterController protected _comp: CharacterController = null as any; private _btCollisionFlags = 0;//: btControllerCollisionFlag protected _word3 = 0; @@ -50,8 +50,7 @@ export abstract class BulletCharacterController implements IBaseCharacterControl private _collisionFilterMask = -1; get isEnabled (): boolean { return this._isEnabled; } - get impl (): any { - /* eslint-disable @typescript-eslint/no-unsafe-return */ + get impl (): number { return this._impl; } get characterController (): CharacterController { return this._comp; } @@ -61,8 +60,12 @@ export abstract class BulletCharacterController implements IBaseCharacterControl } // virtual - protected onComponentSet (): void { } - protected updateScale (): void { } + protected onComponentSet (): void { + //empty + } + protected updateScale (): void { + //empty + } initialize (comp: CharacterController): boolean { this._comp = comp; @@ -73,7 +76,7 @@ export abstract class BulletCharacterController implements IBaseCharacterControl this.onComponentSet(); - if (this._impl == null) { + if (this._impl === 0) { error('[Physics]: Initialize BulletCharacterController failed'); return false; } else { @@ -106,22 +109,22 @@ export abstract class BulletCharacterController implements IBaseCharacterControl //(this._comp as any) = null; bt._safe_delete(this._impl, EBulletType.EBulletTypeCharacterController); BulletCache.delWrapper(this._impl, bt.CCT_CACHE_NAME); - this._impl = null; + this._impl = 0; //(this.wrappedWorld as any) = null; } onLoad (): void { - + //empty } getPosition (out: IVec3Like): void { if (!this._impl) return; - bullet2CocosVec3(out, bt.CharacterController_getPosition(this.impl)); + bullet2CocosVec3(out, bt.CharacterController_getPosition(this.impl) as number); } setPosition (value: IVec3Like): void { if (!this._impl) return; - cocos2BulletVec3(bt.CharacterController_getPosition(this.impl), value); + cocos2BulletVec3(bt.CharacterController_getPosition(this.impl) as number, value); this.syncPhysicsToScene(); } @@ -257,8 +260,11 @@ export abstract class BulletCharacterController implements IBaseCharacterControl const motionLength = bt.ControllerHit_getHitMotionLength(hit); const s: BulletShape = BulletCache.getWrapper(shapePtr, BulletShape.TYPE); if (s) { - item = bulletWorld.cctShapeEventDic.set(this.impl, shapePtr, - { BulletCharacterController: this, BulletShape: s, worldPos, worldNormal, motionDir, motionLength }); + item = bulletWorld.cctShapeEventDic.set( + this.impl, + shapePtr, + { BulletCharacterController: this, BulletShape: s, worldPos, worldNormal, motionDir, motionLength }, + ); } } } diff --git a/cocos/physics/framework/components/character-controllers/character-controller.ts b/cocos/physics/framework/components/character-controllers/character-controller.ts index f61d683bab..73fa1e0df9 100644 --- a/cocos/physics/framework/components/character-controllers/character-controller.ts +++ b/cocos/physics/framework/components/character-controllers/character-controller.ts @@ -145,7 +145,7 @@ export class CharacterController extends Eventify(Component) { if (this._skinWidth === value) return; this._skinWidth = Math.abs(value); if (this._cct) { - this._cct.setContactOffset(value); + this._cct.setContactOffset(Math.max(0.0001, value)); } } @@ -232,11 +232,11 @@ export class CharacterController extends Eventify(Component) { @serializable private _minMoveDistance = 0.001; //[ 0, infinity ] @serializable - private _stepOffset = 1.0; + private _stepOffset = 0.5; @serializable private _slopeLimit = 45.0; //degree[ 0, 180] @serializable - private _skinWidth = 0.01; + private _skinWidth = 0.01; //[ 0.0001, infinity ] // @serializable // private _detectCollisions = true; // @serializable @@ -307,8 +307,11 @@ export class CharacterController extends Eventify(Component) { /** * @en * Sets world position of center. + * Note: Calling this function will immediately synchronize the position of + * the character controller in the physics world to the node. * @zh * 设置中心的世界坐标。 + * 注意:调用该函数会立刻将角色控制器在物理世界中的位置同步到节点上。 */ public set centerWorldPosition (value: Readonly) { if (this._isInitialized) this._cct!.setPosition(value); @@ -317,8 +320,10 @@ export class CharacterController extends Eventify(Component) { /** * @en * Gets the velocity. + * Note: velocity is only updated after move() is called. * @zh * 获取速度。 + * 注意:velocity 只会在 move() 调用后更新。 */ public get velocity (): Readonly { return this._velocity; @@ -327,8 +332,10 @@ export class CharacterController extends Eventify(Component) { /** * @en * Gets whether the character is on the ground. + * Note: isGrounded is only updated after move() is called. * @zh * 获取是否在地面上。 + * 注意:isGrounded 只会在 move() 调用后更新。 */ public get isGrounded (): boolean { return this._cct!.onGround(); @@ -351,6 +358,8 @@ export class CharacterController extends Eventify(Component) { this._currentPos.set(this.centerWorldPosition); this._velocity = this._currentPos.subtract(this._prevPos).multiplyScalar(1.0 / elapsedTime); + + this._cct!.syncPhysicsToScene(); } /// EVENT INTERFACE /// diff --git a/cocos/physics/framework/physics-selector.ts b/cocos/physics/framework/physics-selector.ts index 4cd1131ce6..306613dc6d 100644 --- a/cocos/physics/framework/physics-selector.ts +++ b/cocos/physics/framework/physics-selector.ts @@ -39,6 +39,7 @@ import { errorID, IVec3Like, warn, cclegacy } from '../../core'; import { EColliderType, EConstraintType, ECharacterControllerType } from './physics-enum'; import { PhysicsMaterial } from '.'; +// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents export type IPhysicsEngineId = 'builtin' | 'cannon.js' | 'bullet' | 'physx' | string; interface IPhysicsWrapperObject { @@ -524,6 +525,7 @@ const ENTIRE_CHARACTER_CONTROLLER: IEntireCharacterController = { addMask: FUNC, removeMask: FUNC, move: FUNC, + syncPhysicsToScene: FUNC, updateEventListener: FUNC, //IBoxCharacterController setHalfHeight: FUNC, diff --git a/cocos/physics/physx/physx-world.ts b/cocos/physics/physx/physx-world.ts index 0916c8b32d..d0ee6c1185 100644 --- a/cocos/physics/physx/physx-world.ts +++ b/cocos/physics/physx/physx-world.ts @@ -76,7 +76,7 @@ export class PhysXWorld extends PhysXInstance implements IPhysicsWorld { } step (deltaTime: number, _timeSinceLastCalled?: number, _maxSubStep = 0): void { - if (this.wrappedBodies.length === 0 && this.ccts.length === 0) return; + if (this.wrappedBodies.length === 0) return; this._simulate(deltaTime); if (!PX.MULTI_THREAD) { this._fetchResults(); @@ -84,12 +84,6 @@ export class PhysXWorld extends PhysXInstance implements IPhysicsWorld { const body = this.wrappedBodies[i]; body.syncPhysicsToScene(); } - const ccts = this.ccts; - const length = ccts.length; - for (let i = 0; i < length; i++) { - const cct = ccts[i]; - cct.syncPhysicsToScene(); - } } } diff --git a/cocos/physics/spec/i-character-controller.ts b/cocos/physics/spec/i-character-controller.ts index 6617e58f0f..5faa80e14a 100644 --- a/cocos/physics/spec/i-character-controller.ts +++ b/cocos/physics/spec/i-character-controller.ts @@ -40,6 +40,7 @@ export interface IBaseCharacterController extends ILifecycle, IGroupMask { setDetectCollisions (value: boolean): void; setOverlapRecovery (value: boolean): void; move(movement: IVec3Like, minDist: number, elapsedTime: number): void; + syncPhysicsToScene (): void; } export interface ICapsuleCharacterController extends IBaseCharacterController { diff --git a/native/cocos/physics/physx/PhysXWorld.cpp b/native/cocos/physics/physx/PhysXWorld.cpp index 3adedea71f..96f0d4084f 100644 --- a/native/cocos/physics/physx/PhysXWorld.cpp +++ b/native/cocos/physics/physx/PhysXWorld.cpp @@ -240,9 +240,6 @@ void PhysXWorld::syncPhysicsToScene() { for (auto const &sb : _mSharedBodies) { sb->syncPhysicsToScene(); } - for (auto const &cct : _mCCTs) { - cct->syncPhysicsToScene(); - } } void PhysXWorld::syncSceneWithCheck() { diff --git a/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h b/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h index 4aba1bbe3f..5ec9197a65 100644 --- a/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h +++ b/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h @@ -56,7 +56,7 @@ public: void syncScale(); void syncSceneToPhysics(); - void syncPhysicsToScene(); + virtual void syncPhysicsToScene() override; //ILifecycle void onEnable() override; diff --git a/native/cocos/physics/sdk/CharacterController.cpp b/native/cocos/physics/sdk/CharacterController.cpp index 1bd9a5569f..fc53ac4a0f 100644 --- a/native/cocos/physics/sdk/CharacterController.cpp +++ b/native/cocos/physics/sdk/CharacterController.cpp @@ -68,6 +68,10 @@ void CLASS::move(float x, float y, float z, float minDist, float elapsedTime) { _impl->move(x, y, z, minDist, elapsedTime); \ } \ \ +void CLASS::syncPhysicsToScene() { \ + _impl->syncPhysicsToScene(); \ +} \ + \ void CLASS::setStepOffset(float v) { \ _impl->setStepOffset(v); \ } \ diff --git a/native/cocos/physics/sdk/CharacterController.h b/native/cocos/physics/sdk/CharacterController.h index 9096663092..e87e34dc66 100644 --- a/native/cocos/physics/sdk/CharacterController.h +++ b/native/cocos/physics/sdk/CharacterController.h @@ -47,6 +47,7 @@ virtual bool onGround() override; \ virtual void move(float x, float y, float z, float minDist, \ float elapsedTime) override; \ + void syncPhysicsToScene() override; \ virtual void setStepOffset(float v) override; \ virtual float getStepOffset() override; \ virtual void setSlopeLimit(float v) override; \ diff --git a/native/cocos/physics/spec/ICharacterController.h b/native/cocos/physics/spec/ICharacterController.h index 1e56bda9b8..26adcfbdbb 100644 --- a/native/cocos/physics/spec/ICharacterController.h +++ b/native/cocos/physics/spec/ICharacterController.h @@ -51,6 +51,7 @@ public: virtual void setPosition(float x, float y, float z) = 0; virtual bool onGround() = 0; virtual void move(float x, float y, float z, float minDist, float elapsedTime) = 0; + virtual void syncPhysicsToScene() = 0; virtual uint32_t getGroup() = 0; virtual void setGroup(uint32_t g) = 0; diff --git a/platforms/native/engine/jsb-physics.js b/platforms/native/engine/jsb-physics.js index fe95077574..49973ef4c9 100644 --- a/platforms/native/engine/jsb-physics.js +++ b/platforms/native/engine/jsb-physics.js @@ -929,6 +929,7 @@ class CharacterController { onGround () { return this._impl.onGround(); } move (v, minDist, dt) { return this._impl.move(v.x, v.y, v.z, minDist, dt); } + syncPhysicsToScene () { this._impl.syncPhysicsToScene(); } setPosition (v) { this._impl.setPosition(v.x, v.y, v.z); } getPosition () { return this._impl.getPosition(); }