From 5330e7ee5aa89e99226ec9c16303b81aba0ca7a8 Mon Sep 17 00:00:00 2001 From: Yiwen <15225434259xue@gmail.com> Date: Fri, 19 May 2023 11:28:09 +0800 Subject: [PATCH 1/8] Configurable constraint (#14778) * add support to configurable constraint * add missing files * update packages * fix PhysX bugs,update error info * fix exports, deserialization. * just stage * Revert "just stage" This reverts commit 41dc157afec00bfeb077b12e64c45a951ab1f894. * fix problems * improve perf * tweak * fix merge errors * update errormap --- .../bullet-configurable-constraint.ts | 419 ++++++++ .../constraints/bullet-fixed-constraint.ts | 4 +- cocos/physics/bullet/instantiate.ts | 2 + .../framework/assets/physics-material.ts | 16 +- .../constraints/configurable-constraint.ts | 893 ++++++++++++++++++ .../components/constraints/constraint.ts | 5 +- .../constraints/fixed-constraint.ts | 7 +- .../constraints/hinge-constraint.ts | 18 +- .../constraints/point-to-point-constraint.ts | 11 +- cocos/physics/framework/index.ts | 2 + cocos/physics/framework/physics-enum.ts | 126 +++ cocos/physics/framework/physics-selector.ts | 38 +- cocos/physics/physx/instantiate.ts | 2 + .../physx/joints/physx-configurable-joint.ts | 453 +++++++++ cocos/physics/physx/physx-adapter.ts | 8 + cocos/physics/spec/i-physics-constraint.ts | 44 +- editor/i18n/en/localization.js | 79 +- editor/i18n/zh/localization.js | 79 +- exports/physics-framework.ts | 2 + native/CMakeLists.txt | 2 + native/cocos/physics/PhysicsSelector.h | 31 +- native/cocos/physics/physx/PhysX.h | 1 + .../physx/joints/PhysXGenericJoint.cpp | 506 ++++++++++ .../physics/physx/joints/PhysXGenericJoint.h | 143 +++ .../physics/physx/joints/PhysXSpherical.h | 2 +- native/cocos/physics/sdk/Joint.cpp | 99 +- native/cocos/physics/sdk/Joint.h | 43 +- native/cocos/physics/spec/IJoint.h | 45 +- platforms/native/engine/jsb-physics.js | 102 +- tests/physics/constraint.ts | 131 +++ tests/physics/physics.test.ts | 4 + 31 files changed, 3253 insertions(+), 64 deletions(-) create mode 100644 cocos/physics/bullet/constraints/bullet-configurable-constraint.ts create mode 100644 cocos/physics/framework/components/constraints/configurable-constraint.ts create mode 100644 cocos/physics/physx/joints/physx-configurable-joint.ts create mode 100644 native/cocos/physics/physx/joints/PhysXGenericJoint.cpp create mode 100644 native/cocos/physics/physx/joints/PhysXGenericJoint.h create mode 100644 tests/physics/constraint.ts diff --git a/cocos/physics/bullet/constraints/bullet-configurable-constraint.ts b/cocos/physics/bullet/constraints/bullet-configurable-constraint.ts new file mode 100644 index 0000000000..9fed63c59b --- /dev/null +++ b/cocos/physics/bullet/constraints/bullet-configurable-constraint.ts @@ -0,0 +1,419 @@ +/* + Copyright (c) 2023 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. +*/ + +/* eslint-disable new-cap */ +import { BulletConstraint } from './bullet-constraint'; +import { IConfigurableConstraint } from '../../spec/i-physics-constraint'; +import { error, IVec3Like, Mat4, Quat, Vec3, toRadian } from '../../../core'; +import { ConfigurableConstraint, EConstraintMode, EConstraintType, EDriverMode, PhysicsSystem } from '../../framework'; +import { bt } from '../instantiated'; +import { BulletRigidBody } from '../bullet-rigid-body'; +import { BulletCache, CC_QUAT_0, CC_QUAT_1, CC_V3_0, CC_MAT4_0, CC_V3_1 } from '../bullet-cache'; +import { cocos2BulletQuat, cocos2BulletVec3, force2Impulse } from '../bullet-utils'; + +enum RotateOrder { + RO_XYZ = 0, + RO_XZY, + RO_YXZ, + RO_YZX, + RO_ZXY, + RO_ZYX +} + +enum BulletDofAxis { + X = 0, + Y = 1, + Z = 2, + TWIST = 3, + SWING1 = 4, + SWING2 = 5, +} + +export class BulletConfigurableConstraint extends BulletConstraint implements IConfigurableConstraint { + private _setLimit (v: EConstraintMode, axis: number, lower: number, upper: number): void { + switch (v) { + case EConstraintMode.LOCKED: + bt.Generic6DofSpring2Constraint_setLimit(this._impl, axis, 0, 0); + break; + case EConstraintMode.LIMITED: + bt.Generic6DofSpring2Constraint_setLimit(this._impl, axis, lower, upper); + break; + case EConstraintMode.FREE: + bt.Generic6DofSpring2Constraint_setLimit(this._impl, axis, 1, 0); + break; + default: + break; + } + } + + setConstraintMode (idx: number, v: EConstraintMode): void { + const ll = this.constraint.linearLimitSettings; + const al = this.constraint.angularLimitSettings; + + const lowers: number[] = [0, 0, 0]; + const uppers: number[] = [0, 0, 0]; + + let upper = 0; let lower = 0; + + switch (idx) { + case 0: + case 1: + case 2: + Vec3.toArray(lowers, ll.lower); + Vec3.toArray(uppers, ll.upper); + lower = lowers[idx]; + upper = uppers[idx]; + break; + case 3: + upper = toRadian(al.twistExtent) * 0.5; + lower = -upper; + break; + case 4: + upper = toRadian(al.swingExtent1) * 0.5; + lower = -upper; + break; + case 5: + upper = toRadian(al.swingExtent2) * 0.5; + lower = -upper; + break; + + default: + error(`idx should be in [0, 5], but give ${idx}`); + break; + } + + this._setLimit(v, idx, lower, upper); + } + + setLinearLimit (idx: number, lower: number, upper: number): void { + let cm = 0; + const ll = this.constraint.linearLimitSettings; + switch (idx) { + case 0: cm = ll.xMotion; break; + case 1: cm = ll.yMotion; break; + case 2: cm = ll.zMotion; break; + default: break; + } + this._setLimit(cm, idx, lower, upper); + } + setAngularExtent (twist: number, swing1: number, swing2: number): void { + const al = this.constraint.angularLimitSettings; + this._setLimit(al.twistMotion, BulletDofAxis.TWIST, -toRadian(twist) * 0.5, toRadian(twist) * 0.5); + this._setLimit(al.swingMotion1, BulletDofAxis.SWING1, -toRadian(swing1) * 0.5, toRadian(swing1) * 0.5); + this._setLimit(al.swingMotion2, BulletDofAxis.SWING2, -toRadian(swing2) * 0.5, toRadian(swing2) * 0.5); + } + setSwingSoftConstraint (v: boolean): void { + bt.Generic6DofSpring2Constraint_enableSpring(this._impl, BulletDofAxis.SWING1, v); + bt.Generic6DofSpring2Constraint_enableSpring(this._impl, BulletDofAxis.SWING2, v); + } + setTwistSoftConstraint (v: boolean): void { + bt.Generic6DofSpring2Constraint_enableSpring(this._impl, BulletDofAxis.TWIST, v); + } + setLinearSoftConstraint (v: boolean): void { + bt.Generic6DofSpring2Constraint_enableSpring(this._impl, BulletDofAxis.X, v); + bt.Generic6DofSpring2Constraint_enableSpring(this._impl, BulletDofAxis.Y, v); + bt.Generic6DofSpring2Constraint_enableSpring(this._impl, BulletDofAxis.Z, v); + } + setLinearStiffness (v: number): void { + bt.Generic6DofSpring2Constraint_setStiffness(this._impl, BulletDofAxis.X, v); + bt.Generic6DofSpring2Constraint_setStiffness(this._impl, BulletDofAxis.Y, v); + bt.Generic6DofSpring2Constraint_setStiffness(this._impl, BulletDofAxis.Z, v); + } + setLinearDamping (v: number): void { + bt.Generic6DofSpring2Constraint_setDamping(this._impl, BulletDofAxis.X, v); + bt.Generic6DofSpring2Constraint_setDamping(this._impl, BulletDofAxis.Y, v); + bt.Generic6DofSpring2Constraint_setDamping(this._impl, BulletDofAxis.Z, v); + } + setLinearRestitution (v: number): void { + bt.Generic6DofSpring2Constraint_setBounce(this._impl, BulletDofAxis.X, v); + bt.Generic6DofSpring2Constraint_setBounce(this._impl, BulletDofAxis.Y, v); + bt.Generic6DofSpring2Constraint_setBounce(this._impl, BulletDofAxis.Z, v); + } + setSwingStiffness (v: number): void { + bt.Generic6DofSpring2Constraint_setStiffness(this._impl, BulletDofAxis.SWING1, v); + bt.Generic6DofSpring2Constraint_setStiffness(this._impl, BulletDofAxis.SWING2, v); + } + setSwingDamping (v: number): void { + bt.Generic6DofSpring2Constraint_setDamping(this._impl, BulletDofAxis.SWING1, v); + bt.Generic6DofSpring2Constraint_setDamping(this._impl, BulletDofAxis.SWING2, v); + } + setSwingRestitution (v: number): void { + bt.Generic6DofSpring2Constraint_setBounce(this._impl, BulletDofAxis.SWING1, v); + bt.Generic6DofSpring2Constraint_setBounce(this._impl, BulletDofAxis.SWING2, v); + } + setTwistStiffness (v: number): void { + bt.Generic6DofSpring2Constraint_setStiffness(this._impl, BulletDofAxis.TWIST, v); + } + setTwistDamping (v: number): void { + bt.Generic6DofSpring2Constraint_setDamping(this._impl, BulletDofAxis.TWIST, v); + } + setTwistRestitution (v: number): void { + bt.Generic6DofSpring2Constraint_setBounce(this._impl, BulletDofAxis.TWIST, v); + } + + setDriverMode (idx: number, v: EDriverMode): void { + if (v === EDriverMode.DISABLED) { + bt.Generic6DofSpring2Constraint_enableMotor(this._impl, idx, false); + } else if (v === EDriverMode.SERVO) { + bt.Generic6DofSpring2Constraint_enableMotor(this._impl, idx, true); + bt.Generic6DofSpring2Constraint_setServo(this._impl, idx, true); + } else if (v === EDriverMode.INDUCTION) { + bt.Generic6DofSpring2Constraint_enableMotor(this._impl, idx, true); + bt.Generic6DofSpring2Constraint_setServo(this._impl, idx, false); + } + } + + _updateMotorTargetAndVelocity (index: number) { + let mode = EDriverMode.DISABLED; + let axis = 0; + let target = 0; + let velocity = 0; + const ld = this.constraint.linearDriverSettings; + const ad = this.constraint.angularDriverSettings; + switch (index) { + case 0: + axis = BulletDofAxis.X; + mode = ld.xDrive; + target = ld.targetPosition.x; + velocity = ld.targetVelocity.x; + break; + case 1: + axis = BulletDofAxis.Y; + mode = ld.yDrive; + target = ld.targetPosition.y; + velocity = ld.targetVelocity.y; + break; + case 2: + axis = BulletDofAxis.Z; + mode = ld.zDrive; + target = ld.targetPosition.z; + velocity = ld.targetVelocity.z; + break; + case 3: + axis = BulletDofAxis.TWIST; + mode = ad.twistDrive; + target = -toRadian(ad.targetOrientation.x); + velocity = -toRadian(ad.targetVelocity.x); + break; + case 4: axis = BulletDofAxis.SWING1; + mode = ad.swingDrive1; + target = -toRadian(ad.targetOrientation.y); + velocity = -toRadian(ad.targetVelocity.y); + break; + case 5: axis = BulletDofAxis.SWING2; + mode = ad.swingDrive2; + target = -toRadian(ad.targetOrientation.z); + velocity = -toRadian(ad.targetVelocity.z); + break; + default: break; + } + const strength = index > 2 ? ad.strength : ld.strength; + bt.Generic6DofSpring2Constraint_setServoTarget(this._impl, axis, target); + if (mode === EDriverMode.SERVO) { + bt.Generic6DofSpring2Constraint_setTargetVelocity(this._impl, axis, target * strength * 0.1); + } else if (mode === EDriverMode.INDUCTION) { + bt.Generic6DofSpring2Constraint_setTargetVelocity(this._impl, axis, velocity); + } + } + + setLinearMotorTarget (v: IVec3Like): void { + this._updateMotorTargetAndVelocity(0); + this._updateMotorTargetAndVelocity(1); + this._updateMotorTargetAndVelocity(2); + } + setLinearMotorVelocity (v: IVec3Like): void { + this._updateMotorTargetAndVelocity(0); + this._updateMotorTargetAndVelocity(1); + this._updateMotorTargetAndVelocity(2); + } + setLinearMotorForceLimit (v: number): void { + bt.Generic6DofSpring2Constraint_setMaxMotorForce(this._impl, BulletDofAxis.X, v); + bt.Generic6DofSpring2Constraint_setMaxMotorForce(this._impl, BulletDofAxis.Y, v); + bt.Generic6DofSpring2Constraint_setMaxMotorForce(this._impl, BulletDofAxis.Z, v); + } + + setAngularMotorTarget (v: IVec3Like): void { + this._updateMotorTargetAndVelocity(3); + this._updateMotorTargetAndVelocity(4); + this._updateMotorTargetAndVelocity(5); + } + setAngularMotorVelocity (v: IVec3Like): void { + this._updateMotorTargetAndVelocity(3); + this._updateMotorTargetAndVelocity(4); + this._updateMotorTargetAndVelocity(5); + } + setAngularMotorForceLimit (v: number): void { + bt.Generic6DofSpring2Constraint_setMaxMotorForce(this._impl, BulletDofAxis.TWIST, v); + bt.Generic6DofSpring2Constraint_setMaxMotorForce(this._impl, BulletDofAxis.SWING1, v); + bt.Generic6DofSpring2Constraint_setMaxMotorForce(this._impl, BulletDofAxis.SWING2, v); + } + + setPivotA (v: IVec3Like): void { + this.updateFrames(); + } + setPivotB (v: IVec3Like): void { + this.updateFrames(); + } + + setAutoPivotB (v: boolean): void { + this.updateFrames(); + } + + setAxis (v: IVec3Like): void { + this.updateFrames(); + } + setSecondaryAxis (v: IVec3Like): void { + this.updateFrames(); + } + setBreakForce (v: number): void { + const maxForce = Math.max(this.constraint.breakForce, this.constraint.breakTorque); + const impulse = force2Impulse(maxForce, PhysicsSystem.instance.fixedTimeStep); + bt.TypedConstraint_setMaxImpulseThreshold(this._impl, impulse); + } + setBreakTorque (v: number): void { + const maxForce = Math.max(this.constraint.breakForce, this.constraint.breakTorque); + const impulse = force2Impulse(maxForce, PhysicsSystem.instance.fixedTimeStep); + bt.TypedConstraint_setMaxImpulseThreshold(this._impl, impulse); + } + + get constraint (): ConfigurableConstraint { + return this._com as ConfigurableConstraint; + } + + onComponentSet () { + const cb = this.constraint.connectedBody; + const bodyA = (this._rigidBody.body as BulletRigidBody).impl; + const bodyB = (cb && (cb.body as BulletRigidBody).impl) || bt.TypedConstraint_getFixedBody(); + const trans0 = BulletCache.instance.BT_TRANSFORM_0; + const trans1 = BulletCache.instance.BT_TRANSFORM_1; + this._impl = bt.Generic6DofSpring2Constraint_new(bodyA, bodyB, trans0, trans1, RotateOrder.RO_YZX); + + const linearLimit = this.constraint.linearLimitSettings; + const angularLimit = this.constraint.angularLimitSettings; + // they set limits implicitly + this.setConstraintMode(0, linearLimit.xMotion); + this.setConstraintMode(1, linearLimit.yMotion); + this.setConstraintMode(2, linearLimit.zMotion); + this.setConstraintMode(3, angularLimit.twistMotion); + this.setConstraintMode(4, angularLimit.swingMotion1); + this.setConstraintMode(5, angularLimit.swingMotion2); + + this.setLinearSoftConstraint(linearLimit.enableSoftConstraint); + this.setLinearStiffness(linearLimit.stiffness); + this.setLinearDamping(linearLimit.damping); + this.setLinearRestitution(linearLimit.restitution); + + this.setSwingSoftConstraint(angularLimit.enableSoftConstraintSwing); + this.setSwingRestitution(angularLimit.swingRestitution); + this.setSwingStiffness(angularLimit.swingStiffness); + this.setSwingDamping(angularLimit.swingDamping); + + this.setTwistSoftConstraint(angularLimit.enableSoftConstraintTwist); + this.setTwistRestitution(angularLimit.twistRestitution); + this.setTwistStiffness(angularLimit.twistStiffness); + this.setTwistDamping(angularLimit.twistDamping); + + const linearMotor = this.constraint.linearDriverSettings; + const angularMotor = this.constraint.angularDriverSettings; + + this.setDriverMode(0, linearMotor.xDrive); + this.setDriverMode(1, linearMotor.yDrive); + this.setDriverMode(2, linearMotor.zDrive); + this.setDriverMode(3, angularMotor.twistDrive); + this.setDriverMode(4, angularMotor.swingDrive1); + this.setDriverMode(5, angularMotor.swingDrive2); + + this.setLinearMotorTarget(linearMotor.targetPosition); + this.setLinearMotorVelocity(linearMotor.targetVelocity); + this.setLinearMotorForceLimit(linearMotor.strength); + + this.setAngularMotorTarget(angularMotor.targetOrientation); + this.setAngularMotorVelocity(angularMotor.targetVelocity); + this.setAngularMotorForceLimit(angularMotor.strength); + + this.setBreakForce(this.constraint.breakForce); + this.setBreakTorque(this.constraint.breakTorque); + + this.updateFrames(); + } + + updateFrames () { + const cs = this.constraint; + const node = cs.node; + const v3_0 = CC_V3_0; + const rot_0 = CC_QUAT_0; + const rot_1 = CC_QUAT_1; + const trans0 = BulletCache.instance.BT_TRANSFORM_0; + Vec3.multiply(v3_0, node.worldScale, cs.pivotA); + cocos2BulletVec3(bt.Transform_getOrigin(trans0), v3_0); + const quat = BulletCache.instance.BT_QUAT_0; + + const axisX = cs.axis; + const axisY = cs.secondaryAxis; + const axisZ = Vec3.cross(CC_V3_1, axisX, axisY); + + const mat = Mat4.set(CC_MAT4_0, + axisX.x, axisX.y, axisX.z, 0, + axisY.x, axisY.y, axisY.z, 0, + axisZ.x, axisZ.y, axisZ.z, 0, + 0, 0, 0, 1); + mat.getRotation(rot_0); + + cocos2BulletQuat(quat, rot_0); + bt.Transform_setRotation(trans0, quat); + + const trans1 = BulletCache.instance.BT_TRANSFORM_1; + const cb = this.constraint.connectedBody; + if (cb) { + Quat.multiply(rot_0, node.worldRotation, rot_0); + Quat.invert(rot_1, cb.node.worldRotation); + Quat.multiply(rot_0, rot_1, rot_0); + if (cs.autoPivotB) { + Vec3.multiply(v3_0, cb.node.worldScale, cs.pivotA); + Vec3.transformQuat(v3_0, v3_0, node.worldRotation); + Vec3.add(v3_0, v3_0, cs.node.worldPosition); + Vec3.subtract(v3_0, v3_0, cb.node.worldPosition); + Vec3.transformQuat(v3_0, v3_0, rot_1); + } else { + Vec3.multiply(v3_0, cb.node.worldScale, cs.pivotB); + } + } else { + Vec3.multiply(v3_0, node.worldScale, cs.pivotA); + Vec3.transformQuat(v3_0, v3_0, node.worldRotation); + Vec3.add(v3_0, v3_0, node.worldPosition); + Quat.multiply(rot_0, node.worldRotation, rot_0); + } + cocos2BulletVec3(bt.Transform_getOrigin(trans1), v3_0); + cocos2BulletQuat(quat, rot_0); + bt.Transform_setRotation(trans1, quat); + bt.Generic6DofSpring2Constraint_setFrames(this._impl, trans0, trans1); + } + + updateScale0 (): void { + this.updateFrames(); + } + updateScale1 (): void { + this.updateFrames(); + } +} diff --git a/cocos/physics/bullet/constraints/bullet-fixed-constraint.ts b/cocos/physics/bullet/constraints/bullet-fixed-constraint.ts index c05209062c..3c8b550b66 100644 --- a/cocos/physics/bullet/constraints/bullet-fixed-constraint.ts +++ b/cocos/physics/bullet/constraints/bullet-fixed-constraint.ts @@ -25,8 +25,8 @@ /* eslint-disable new-cap */ import { BulletConstraint } from './bullet-constraint'; import { IFixedConstraint } from '../../spec/i-physics-constraint'; -import { IVec3Like, Quat, Vec3, Mat4 } from '../../../core'; -import { FixedConstraint, HingeConstraint, PhysicsSystem } from '../../framework'; +import { Quat, Vec3, Mat4 } from '../../../core'; +import { FixedConstraint, PhysicsSystem } from '../../framework'; import { BulletRigidBody } from '../bullet-rigid-body'; import { BulletCache, CC_MAT4_0, CC_QUAT_0, CC_V3_0 } from '../bullet-cache'; import { bt } from '../instantiated'; diff --git a/cocos/physics/bullet/instantiate.ts b/cocos/physics/bullet/instantiate.ts index ef50ba821e..c6d2082ac7 100644 --- a/cocos/physics/bullet/instantiate.ts +++ b/cocos/physics/bullet/instantiate.ts @@ -38,6 +38,7 @@ import { BulletPlaneShape } from './shapes/bullet-plane-shape'; import { BulletP2PConstraint } from './constraints/bullet-p2p-constraint'; import { BulletFixedConstraint } from './constraints/bullet-fixed-constraint'; import { BulletHingeConstraint } from './constraints/bullet-hinge-constraint'; +import { BulletConfigurableConstraint } from './constraints/bullet-configurable-constraint'; import { BulletCapsuleCharacterController } from './character-controllers/bullet-capsule-character-controller'; import { BulletBoxCharacterController } from './character-controllers/bullet-box-character-controller'; @@ -60,6 +61,7 @@ game.once(Game.EVENT_PRE_SUBSYSTEM_INIT, () => { PointToPointConstraint: BulletP2PConstraint, HingeConstraint: BulletHingeConstraint, FixedConstraint: BulletFixedConstraint, + ConfigurableConstraint: BulletConfigurableConstraint, BoxCharacterController: BulletBoxCharacterController, CapsuleCharacterController: BulletCapsuleCharacterController, diff --git a/cocos/physics/framework/assets/physics-material.ts b/cocos/physics/framework/assets/physics-material.ts index b29dd89536..5e14c14c56 100644 --- a/cocos/physics/framework/assets/physics-material.ts +++ b/cocos/physics/framework/assets/physics-material.ts @@ -22,9 +22,11 @@ THE SOFTWARE. */ -import { ccclass, editable, serializable } from 'cc.decorator'; +// @ts-check + +import { ccclass, editable, help, menu, serializable, tooltip, type } from 'cc.decorator'; import { Asset } from '../../../asset/assets/asset'; -import { math } from '../../../core'; +import { CCFloat, math } from '../../../core'; /** * @en @@ -33,6 +35,8 @@ import { math } from '../../../core'; * 物理材质。 */ @ccclass('cc.PhysicsMaterial') +@help('i18n:cc.PhysicsMaterial') +@menu('Physics/PhysicsMaterial') export class PhysicsMaterial extends Asset { /** * @en @@ -58,6 +62,8 @@ export class PhysicsMaterial extends Asset { * 此材质的摩擦系数。 */ @editable + @type(CCFloat) + @tooltip('i18n:physics3d.material.friction') get friction () { return this._friction; } @@ -76,6 +82,8 @@ export class PhysicsMaterial extends Asset { * 此材质的滚动摩擦系数。 */ @editable + @type(CCFloat) + @tooltip('i18n:physics3d.material.rollingFriction') get rollingFriction () { return this._rollingFriction; } @@ -94,6 +102,8 @@ export class PhysicsMaterial extends Asset { * 此材质的自旋摩擦系数。 */ @editable + @type(CCFloat) + @tooltip('i18n:physics3d.material.spinningFriction') get spinningFriction () { return this._spinningFriction; } @@ -112,6 +122,8 @@ export class PhysicsMaterial extends Asset { * 此材质的回弹系数。 */ @editable + @type(CCFloat) + @tooltip('i18n:physics3d.material.restitution') get restitution () { return this._restitution; } diff --git a/cocos/physics/framework/components/constraints/configurable-constraint.ts b/cocos/physics/framework/components/constraints/configurable-constraint.ts new file mode 100644 index 0000000000..544f0d4250 --- /dev/null +++ b/cocos/physics/framework/components/constraints/configurable-constraint.ts @@ -0,0 +1,893 @@ +/* + Copyright (c) 2023 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 { + ccclass, + help, + menu, + serializable, + formerlySerializedAs, + type, + tooltip, + editable, + group, +} from 'cc.decorator'; +import { EDITOR } from 'internal:constants'; +import { Constraint } from './constraint'; +import { Vec3, cclegacy, CCFloat, CCBoolean } from '../../../../core'; +import { EConstraintType, EConstraintMode, EDriverMode } from '../../physics-enum'; +import { IConfigurableConstraint } from '../../../spec/i-physics-constraint'; + +@ccclass('cc.LinearLimitSettings') +export class LinearLimitSettings { + @type(EConstraintMode) + @tooltip('i18n:physics3d.constraint.linearLimit.xMotion') + get xMotion () { + return this._xMotion; + } + set xMotion (v: EConstraintMode) { + this._xMotion = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setConstraintMode(0, v); + } + } + + @type(EConstraintMode) + @tooltip('i18n:physics3d.constraint.linearLimit.yMotion') + get yMotion () { + return this._yMotion; + } + set yMotion (v: EConstraintMode) { + this._yMotion = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setConstraintMode(1, v); + } + } + + @type(EConstraintMode) + @tooltip('i18n:physics3d.constraint.linearLimit.zMotion') + get zMotion () { + return this._zMotion; + } + set zMotion (v: EConstraintMode) { + this._zMotion = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setConstraintMode(2, v); + } + } + + @type(Vec3) + @tooltip('i18n:physics3d.constraint.linearLimit.upper') + get upper () { + return this._upper; + } + set upper (v: Vec3) { + Vec3.copy(this._upper, v); + if (!EDITOR || cclegacy.GAME_VIEW) { + const lower = this.lower; + this._impl.setLinearLimit(0, lower.x, v.x); + this._impl.setLinearLimit(1, lower.y, v.y); + this._impl.setLinearLimit(2, lower.z, v.z); + } + } + + @type(Vec3) + @tooltip('i18n:physics3d.constraint.linearLimit.lower') + get lower () { + return this._lower; + } + set lower (v: Vec3) { + Vec3.copy(this._lower, v); + if (!EDITOR || cclegacy.GAME_VIEW) { + const upper = this.upper; + this._impl.setLinearLimit(0, v.x, upper.x); + this._impl.setLinearLimit(1, v.y, upper.y); + this._impl.setLinearLimit(2, v.z, upper.z); + } + } + + @type(CCFloat) + @tooltip('i18n:physics3d.constraint.linearLimit.restitution') + get restitution () { + return this._bounciness; + } + set restitution (v: number) { + this._bounciness = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setLinearRestitution(v); + } + } + + @type(CCBoolean) + @tooltip('i18n:physics3d.constraint.linearLimit.enableSoftConstraint') + @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) + get enableSoftConstraint () { + return this._enableSoftConstraint; + } + set enableSoftConstraint (v: boolean) { + this._enableSoftConstraint = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setLinearSoftConstraint(v); + } + } + + @type(CCFloat) + @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) + @tooltip('i18n:physics3d.constraint.linearLimit.stiffness') + get stiffness () { + return this._stiffness; + } + set stiffness (v: number) { + this._stiffness = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setLinearStiffness(v); + } + } + + @type(CCFloat) + @tooltip('i18n:physics3d.constraint.linearLimit.damping') + @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) + get damping () { + return this._damping; + } + set damping (v: number) { + this._damping = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setLinearDamping(v); + } + } + + @serializable + private _xMotion = EConstraintMode.FREE; + @serializable + private _yMotion = EConstraintMode.FREE; + @serializable + private _zMotion = EConstraintMode.FREE; + @serializable + private _upper = new Vec3(); + @serializable + private _lower = new Vec3(); + @serializable + private _enableSoftConstraint = false; + @serializable + private _bounciness = 0; // restitution [0,1] + @serializable + private _stiffness = 0; + @serializable + private _damping = 0; + + private _impl: IConfigurableConstraint; + constructor (configurableConstraint: IConfigurableConstraint) { + this._impl = configurableConstraint; + } +} + +@ccclass('cc.AngularLimitSettings') +export class AngularLimitSettings { + @type(EConstraintMode) + @tooltip('i18n:physics3d.constraint.angularLimit.twistMotion') + get twistMotion () { + return this._twistMotion; + } + set twistMotion (v: EConstraintMode) { + this._twistMotion = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setConstraintMode(3, v); + } + } + @type(EConstraintMode) + @tooltip('i18n:physics3d.constraint.angularLimit.swingMotion1') + get swingMotion1 () { + return this._swing1Motion; + } + set swingMotion1 (v: EConstraintMode) { + this._swing1Motion = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setConstraintMode(4, v); + } + } + @type(EConstraintMode) + @tooltip('i18n:physics3d.constraint.angularLimit.swingMotion2') + get swingMotion2 () { + return this._swing2Motion; + } + set swingMotion2 (v: EConstraintMode) { + this._swing2Motion = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setConstraintMode(5, v); + } + } + + @type(CCFloat) + @tooltip('i18n:physics3d.constraint.angularLimit.twistExtent') + get twistExtent () { + return this._twistExtent; + } + set twistExtent (v: number) { + this._twistExtent = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setAngularExtent(v, this.swingExtent1, this.swingExtent2); + } + } + + @type(CCFloat) + @tooltip('i18n:physics3d.constraint.angularLimit.swingExtent1') + get swingExtent1 () { + return this._swingExtent1; + } + set swingExtent1 (v: number) { + this._swingExtent1 = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setAngularExtent(this.twistExtent, v, this.swingExtent2); + } + } + + @type(CCFloat) + @tooltip('i18n:physics3d.constraint.angularLimit.swingExtent2') + get swingExtent2 () { + return this._swingExtent2; + } + set swingExtent2 (v: number) { + this._swingExtent2 = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setAngularExtent(this.twistExtent, this.swingExtent1, v); + } + } + + @type(CCFloat) + @tooltip('i18n:physics3d.constraint.angularLimit.twistRestitution') + get twistRestitution () { + return this._twistBounciness; + } + set twistRestitution (v: number) { + this._twistBounciness = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setTwistRestitution(v); + } + } + + @type(CCFloat) + @tooltip('i18n:physics3d.constraint.angularLimit.swingRestitution') + get swingRestitution () { + return this._swingBounciness; + } + set swingRestitution (v: number) { + this._swingBounciness = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setSwingRestitution(v); + } + } + + @type(CCBoolean) + @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) + @tooltip('i18n:physics3d.constraint.angularLimit.enableSoftConstraintTwist') + get enableSoftConstraintTwist () { + return this._enableSoftConstraintTwist; + } + set enableSoftConstraintTwist (v: boolean) { + this._enableSoftConstraintTwist = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setTwistSoftConstraint(v); + } + } + + @type(CCFloat) + @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) + @tooltip('i18n:physics3d.constraint.angularLimit.twistStiffness') + get twistStiffness () { + return this._twistStiffness; + } + set twistStiffness (v: number) { + this._twistStiffness = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setTwistStiffness(v); + } + } + + @type(CCFloat) + @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) + @tooltip('i18n:physics3d.constraint.angularLimit.twistDamping') + get twistDamping () { + return this._twistDamping; + } + set twistDamping (v: number) { + this._twistDamping = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setTwistDamping(v); + } + } + + @type(CCBoolean) + @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) + @tooltip('i18n:physics3d.constraint.angularLimit.enableSoftConstraintSwing') + get enableSoftConstraintSwing () { + return this._enableSoftConstraintSwing; + } + set enableSoftConstraintSwing (v: boolean) { + this._enableSoftConstraintSwing = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setSwingSoftConstraint(v); + } + } + + @type(CCFloat) + @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) + @tooltip('i18n:physics3d.constraint.angularLimit.swingStiffness') + get swingStiffness () { + return this._swingStiffness; + } + set swingStiffness (v: number) { + this._swingStiffness = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setSwingStiffness(v); + } + } + + @type(CCFloat) + @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) + @tooltip('i18n:physics3d.constraint.angularLimit.swingDamping') + get swingDamping () { + return this._swingDamping; + } + set swingDamping (v: number) { + this._swingDamping = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setSwingDamping(v); + } + } + + @serializable + private _swing1Motion = EConstraintMode.FREE; + @serializable + private _swing2Motion = EConstraintMode.FREE; + @serializable + private _twistMotion = EConstraintMode.FREE; + + @serializable + private _twistExtent = 0; + @serializable + private _swingExtent1 = 0; + @serializable + private _swingExtent2 = 0; + + @serializable + private _enableSoftConstraintSwing = false; + @serializable + private _swingBounciness = 0; + @serializable + private _swingStiffness = 0; + @serializable + private _swingDamping = 0; + + @serializable + private _enableSoftConstraintTwist = false; + @serializable + private _twistBounciness = 0; + @serializable + private _twistStiffness = 0; + @serializable + private _twistDamping = 0; + + private _impl: IConfigurableConstraint; + constructor (configurableConstraint: IConfigurableConstraint) { + this._impl = configurableConstraint; + } +} + +@ccclass('cc.LinearDriverSettings') +export class LinearDriverSettings { + @type(EDriverMode) + @tooltip('i18n:physics3d.constraint.linearDriver.xMode') + get xDrive () { + return this._xDrive; + } + set xDrive (v: EDriverMode) { + this._xDrive = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setDriverMode(0, v); + } + } + + @type(EDriverMode) + @tooltip('i18n:physics3d.constraint.linearDriver.yMode') + get yDrive () { + return this._yDrive; + } + set yDrive (v: EDriverMode) { + this._yDrive = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setDriverMode(1, v); + } + } + + @type(EDriverMode) + @tooltip('i18n:physics3d.constraint.linearDriver.zMode') + get zDrive () { + return this._zDrive; + } + set zDrive (v: EDriverMode) { + this._zDrive = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setDriverMode(2, v); + } + } + + @type(Vec3) + @tooltip('i18n:physics3d.constraint.linearDriver.targetPosition') + get targetPosition () { + return this._target; + } + set targetPosition (v: Vec3) { + Vec3.copy(this._target, v); + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setLinearMotorTarget(v); + } + } + + @type(Vec3) + @tooltip('i18n:physics3d.constraint.linearDriver.targetVelocity') + get targetVelocity () { + return this._velocity; + } + set targetVelocity (v: Vec3) { + Vec3.copy(this._velocity, v); + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setLinearMotorVelocity(v); + } + } + + @type(CCFloat) + @tooltip('i18n:physics3d.constraint.linearDriver.strength') + get strength () { + return this._strength; + } + set strength (v) { + this._strength = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setLinearMotorForceLimit(v); + } + } + + @serializable + private _target = new Vec3(); + @serializable + private _velocity = new Vec3(); + + @serializable + private _xDrive = EDriverMode.DISABLED; + @serializable + private _yDrive = EDriverMode.DISABLED; + @serializable + private _zDrive = EDriverMode.DISABLED; + + @serializable + private _strength = 0; + + private _impl: IConfigurableConstraint; + constructor (configurableConstraint: IConfigurableConstraint) { + this._impl = configurableConstraint; + } +} + +@ccclass('cc.AngularDriverSettings') +export class AngularDriverSettings { + @type(EDriverMode) + @tooltip('i18n:physics3d.constraint.angularDriver.twistMode') + get twistDrive () { + return this._twistDrive; + } + set twistDrive (v: EDriverMode) { + this._twistDrive = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setDriverMode(3, v); + } + } + + @type(EDriverMode) + @tooltip('i18n:physics3d.constraint.angularDriver.swingMode1') + get swingDrive1 () { + return this._swingDrive1; + } + set swingDrive1 (v: EDriverMode) { + this._swingDrive1 = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setDriverMode(4, v); + } + } + + @type(EDriverMode) + @tooltip('i18n:physics3d.constraint.angularDriver.swingMode2') + get swingDrive2 () { + return this._swingDrive2; + } + set swingDrive2 (v: EDriverMode) { + this._swingDrive2 = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setDriverMode(5, v); + } + } + + @type(Vec3) + @tooltip('i18n:physics3d.constraint.angularDriver.targetOrientation') + get targetOrientation () { + return this._targetOrientation; + } + set targetOrientation (v) { + Vec3.copy(this._targetOrientation, v); + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setAngularMotorTarget(v); + } + } + + @type(Vec3) + @tooltip('i18n:physics3d.constraint.angularDriver.targetAngularVelocity') + get targetVelocity () { + return this._targetVelocity; + } + set targetVelocity (v) { + Vec3.copy(this._targetVelocity, v); + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setAngularMotorVelocity(v); + } + } + + @type(CCFloat) + @tooltip('i18n:physics3d.constraint.angularDriver.strength') + get strength () { + return this._strength; + } + set strength (v) { + this._strength = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this._impl.setAngularMotorForceLimit(v); + } + } + + @serializable + private _swingDrive1 = EDriverMode.DISABLED; + @serializable + private _swingDrive2 = EDriverMode.DISABLED; + @serializable + private _twistDrive = EDriverMode.DISABLED; + + @serializable + private _targetOrientation = new Vec3(); + @serializable + private _targetVelocity = new Vec3(); + + @serializable + private _strength = 0; + + private _impl: IConfigurableConstraint; + constructor (configurableConstraint: IConfigurableConstraint) { + this._impl = configurableConstraint; + } +} + +@ccclass('cc.ConfigurableConstraint') +@help('i18n:cc.ConfigurableConstraint') +@menu('Physics/ConfigurableConstraint(beta)') +export class ConfigurableConstraint extends Constraint { + /** + * @en + * The axis of the constraint in the local coordinate system of the attached rigid body. + * @zh + * 约束关节在连接刚体的本地坐标系中的轴。 + */ + @type(Vec3) + @tooltip('i18n:physics3d.constraint.axis') + get axis (): Vec3 { + return this._axis; + } + set axis (v: Vec3) { + Vec3.copy(this._axis, v); + if (!EDITOR || cclegacy.GAME_VIEW) { + this.constraint.setAxis(this._axis); + } + } + + /** + * @en The secondary axis of the constraint in the local coordinate system of the attached rigid body. + * @zh 约束关节在连接刚体的本地坐标系中的第二轴。 + */ + @type(Vec3) + @tooltip('i18n:physics3d.constraint.secondaryAxis') + get secondaryAxis (): Vec3 { + return this._secondaryAxis; + } + set secondaryAxis (v: Vec3) { + Vec3.copy(this._secondaryAxis, v); + if (!EDITOR || cclegacy.GAME_VIEW) { + this.constraint.setSecondaryAxis(this._secondaryAxis); + } + } + + /** + * @en + * The pivot point of the constraint in the local coordinate system of the attached rigid body. + * @zh + * 约束关节在连接刚体的本地坐标系中的锚点。 + */ + @type(Vec3) + @tooltip('i18n:physics3d.constraint.pivotA') + get pivotA (): Vec3 { + return this._pivotA; + } + + set pivotA (v: Vec3) { + Vec3.copy(this._pivotA, v); + if (!EDITOR || cclegacy.GAME_VIEW) { + this.constraint.setPivotA(this._pivotA); + } + } + + /** + * @en + * The pivot point of the constraint in the local coordinate system of the connected rigid body. + * @zh + * 约束关节在连接刚体的本地坐标系中的锚点。 + */ + @type(Vec3) + @tooltip('i18n:physics3d.constraint.pivotB') + get pivotB (): Vec3 { + return this._pivotB; + } + + set pivotB (v: Vec3) { + Vec3.copy(this._pivotB, v); + if (!EDITOR || cclegacy.GAME_VIEW) { + this.constraint.setPivotB(this._pivotB); + } + } + + /** + * @en + * The pivotB is derived automatically. + * @zh + * pivotB 会自动计算。 + */ + @type(CCBoolean) + @tooltip('i18n:physics3d.constraint.autoCalculatePivotB') + get autoPivotB (): boolean { + return this._autoPivotB; + } + + set autoPivotB (v: boolean) { + this._autoPivotB = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this.constraint.setAutoPivotB(this._autoPivotB); + } + } + + /** + * @en + * The break force threshold of the constraint. + * @zh + * 约束的断裂力阈值。 + */ + @type(CCFloat) + @tooltip('i18n:physics3d.constraint.breakForce') + get breakForce () { + return this._breakForce; + } + set breakForce (v) { + this._breakForce = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this.constraint.setBreakForce(v); + } + } + + /** + * @en + * The break torque threshold of the constraint. + * @zh + * 约束的断裂扭矩阈值。 + */ + @type(CCFloat) + @tooltip('i18n:physics3d.constraint.breakTorque') + get breakTorque () { + return this._breakTorque; + } + set breakTorque (v) { + this._breakTorque = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + this.constraint.setBreakTorque(v); + } + } + + /** + * @en + * The linear limit settings of the constraint. + * @zh + * 线性限制设置。 + */ + @type(LinearLimitSettings) + @tooltip('i18n:physics3d.constraint.linearLimit') + get linearLimitSettings () { + return this._linearLimitSettings; + } + set linearLimitSettings (v) { + this._linearLimitSettings = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + const constraint = this.constraint; + constraint.setConstraintMode(0, v.xMotion); + constraint.setConstraintMode(1, v.yMotion); + constraint.setConstraintMode(2, v.zMotion); + const upper = v.upper; + const lower = v.lower; + constraint.setLinearLimit(0, lower.x, upper.x); + constraint.setLinearLimit(1, lower.y, upper.y); + constraint.setLinearLimit(2, lower.z, upper.z); + constraint.setLinearSoftConstraint(v.enableSoftConstraint); + constraint.setLinearDamping(v.damping); + constraint.setLinearStiffness(v.stiffness); + constraint.setLinearRestitution(v.restitution); + } + } + + /** + * @en + * The angular limit settings of the constraint. + * @zh + * 角度限制设置。 + */ + @type(AngularLimitSettings) + @tooltip('i18n:physics3d.constraint.angularLimit') + get angularLimitSettings () { + return this._angularLimitSettings; + } + set angularLimitSettings (v) { + this._angularLimitSettings = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + const constraint = this.constraint; + constraint.setConstraintMode(3, v.twistMotion); + constraint.setConstraintMode(4, v.swingMotion1); + constraint.setConstraintMode(5, v.swingMotion2); + constraint.setAngularExtent(v.twistExtent, v.swingExtent1, v.swingExtent2); + constraint.setTwistRestitution(v.twistRestitution); + constraint.setSwingRestitution(v.swingRestitution); + constraint.setTwistSoftConstraint(v.enableSoftConstraintTwist); + constraint.setSwingSoftConstraint(v.enableSoftConstraintSwing); + constraint.setTwistDamping(v.twistDamping); + constraint.setSwingDamping(v.swingDamping); + constraint.setTwistStiffness(v.twistStiffness); + constraint.setSwingStiffness(v.swingStiffness); + } + } + + /** + * @en + * The linear drive settings of the constraint. + * @zh + * 线性驱动设置。 + */ + @type(LinearDriverSettings) + @tooltip('i18n:physics3d.constraint.linearDrive') + get linearDriverSettings () { + return this._linearDriverSettings; + } + set linearDriverSettings (v) { + this._linearDriverSettings = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + const constraint = this.constraint; + constraint.setDriverMode(0, v.xDrive); + constraint.setDriverMode(1, v.yDrive); + constraint.setDriverMode(2, v.zDrive); + constraint.setLinearMotorTarget(v.targetPosition); + constraint.setLinearMotorVelocity(v.targetVelocity); + constraint.setLinearMotorForceLimit(v.strength); + } + } + + /** + * @en + * The angular drive settings of the constraint. + * @zh + * 角度驱动设置。 + */ + @type(AngularDriverSettings) + @tooltip('i18n:physics3d.constraint.angularDrive') + get angularDriverSettings () { + return this._angularDriverSettings; + } + set angularDriverSettings (v) { + this._angularDriverSettings = v; + if (!EDITOR || cclegacy.GAME_VIEW) { + const constraint = this.constraint; + constraint.setDriverMode(3, v.twistDrive); + constraint.setDriverMode(4, v.swingDrive1); + constraint.setDriverMode(5, v.swingDrive2); + constraint.setAngularMotorTarget(v.targetOrientation); + constraint.setAngularMotorVelocity(v.targetVelocity); + constraint.setAngularMotorForceLimit(v.strength); + } + } + + @serializable + private _breakForce = 1e8; + + @serializable + private _breakTorque = 1e8; + + @serializable + @formerlySerializedAs('linearLimitSettings') + private _linearLimitSettings: LinearLimitSettings; + + @serializable + @formerlySerializedAs('angularLimitSettings') + private _angularLimitSettings: AngularLimitSettings; + + @serializable + @formerlySerializedAs('linearDriverSettings') + private _linearDriverSettings: LinearDriverSettings; + + @serializable + @formerlySerializedAs('angularDriverSettings') + private _angularDriverSettings: AngularDriverSettings; + + @serializable + private readonly _pivotA: Vec3 = new Vec3(); + + @serializable + private readonly _pivotB: Vec3 = new Vec3(); + + @serializable + private _autoPivotB = false; + + @serializable + private readonly _axis: Vec3 = new Vec3(0, 1, 0); + + @serializable + private readonly _secondaryAxis: Vec3 = new Vec3(1, 0, 0); + + get constraint (): IConfigurableConstraint { + return this._constraint as IConfigurableConstraint; + } + + constructor () { + super(EConstraintType.CONFIGURABLE); + this._linearLimitSettings = new LinearLimitSettings(this.constraint); + this._angularLimitSettings = new AngularLimitSettings(this.constraint); + this._linearDriverSettings = new LinearDriverSettings(this.constraint); + this._angularDriverSettings = new AngularDriverSettings(this.constraint); + } + + onLoad () { + super.onLoad(); + if (!EDITOR || cclegacy.GAME_VIEW) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error private member access + this.linearLimitSettings._impl = this.constraint; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error private member access + this.angularLimitSettings._impl = this.constraint; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error private member access + this.linearDriverSettings._impl = this.constraint; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error private member access + this.angularDriverSettings._impl = this.constraint; + } + } +} diff --git a/cocos/physics/framework/components/constraints/constraint.ts b/cocos/physics/framework/components/constraints/constraint.ts index beb31e4b42..4da9223128 100644 --- a/cocos/physics/framework/components/constraints/constraint.ts +++ b/cocos/physics/framework/components/constraints/constraint.ts @@ -23,7 +23,7 @@ THE SOFTWARE. */ -import { ccclass, requireComponent, displayOrder, type, readOnly, serializable } from 'cc.decorator'; +import { ccclass, requireComponent, displayOrder, type, readOnly, serializable, tooltip } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { Component } from '../../../../scene-graph'; import { RigidBody } from '../rigid-body'; @@ -58,6 +58,7 @@ export class Constraint extends Eventify(Component) { @type(RigidBody) @readOnly @displayOrder(-2) + @tooltip('i18n:physics3d.constraint.attachedBody') get attachedBody (): RigidBody | null { return this.getComponent(RigidBody); } @@ -70,6 +71,7 @@ export class Constraint extends Eventify(Component) { */ @type(RigidBody) @displayOrder(-1) + @tooltip('i18n:physics3d.constraint.connectedBody') get connectedBody (): RigidBody | null { return this._connectedBody; } @@ -88,6 +90,7 @@ export class Constraint extends Eventify(Component) { * 获取或设置关节连接的两刚体之间是否开启碰撞。 */ @displayOrder(0) + @tooltip('i18n:physics3d.constraint.enableCollision') get enableCollision () { return this._enableCollision; } diff --git a/cocos/physics/framework/components/constraints/fixed-constraint.ts b/cocos/physics/framework/components/constraints/fixed-constraint.ts index ec5973961a..f20671e2db 100644 --- a/cocos/physics/framework/components/constraints/fixed-constraint.ts +++ b/cocos/physics/framework/components/constraints/fixed-constraint.ts @@ -29,6 +29,7 @@ import { serializable, formerlySerializedAs, type, + tooltip, } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { Constraint } from './constraint'; @@ -43,11 +44,12 @@ import { legacyCC } from '../../../../core/global-exports'; export class FixedConstraint extends Constraint { /** * @en - * The break force threshold of the constraint. + * The maximum force that can be applied to the constraint before it breaks. * @zh * 约束的断裂力阈值。 */ @type(CCFloat) + @tooltip('i18n:physics3d.constraint.breakForce') get breakForce (): number { return this._breakForce; } @@ -61,11 +63,12 @@ export class FixedConstraint extends Constraint { /** * @en - * The break torque threshold of the constraint. + * The maximum torque that can be applied to the constraint before it breaks. * @zh * 约束的断裂扭矩阈值。 */ @type(CCFloat) + @tooltip('i18n:physics3d.constraint.breakTorque') get breakTorque (): number { return this._breakTorque; } diff --git a/cocos/physics/framework/components/constraints/hinge-constraint.ts b/cocos/physics/framework/components/constraints/hinge-constraint.ts index bee2cd0cc3..a0424e0510 100644 --- a/cocos/physics/framework/components/constraints/hinge-constraint.ts +++ b/cocos/physics/framework/components/constraints/hinge-constraint.ts @@ -165,12 +165,12 @@ export class HingeMotorData { export class HingeConstraint extends Constraint { /** * @en - * The pivot point of the hinge in the local coordinate system of the own rigid body. + * The pivot point of the constraint in the local coordinate system of the attached rigid body. * @zh - * 在自身刚体的本地坐标系中,旋转轴的锚点位置。 + * 约束关节在连接刚体的本地坐标系中的锚点。 */ @type(Vec3) - @tooltip('i18n:physics3d.constraint.hinge.pivotA') + @tooltip('i18n:physics3d.constraint.pivotA') get pivotA (): Vec3 { return this._pivotA; } @@ -184,12 +184,12 @@ export class HingeConstraint extends Constraint { /** * @en - * The pivot point of the hinge in the local coordinate system of the connected rigid body. + * The pivot point of the constraint in the local coordinate system of the connected rigid body. * @zh - * 在连接刚体的本地坐标系中,旋转轴的锚点位置。 + * 约束关节在连接刚体的本地坐标系中的锚点。 */ @type(Vec3) - @tooltip('i18n:physics3d.constraint.hinge.pivotB') + @tooltip('i18n:physics3d.constraint.pivotB') get pivotB (): Vec3 { return this._pivotB; } @@ -203,12 +203,12 @@ export class HingeConstraint extends Constraint { /** * @en - * The axis of the hinge in the local coordinate system of the own rigid body. + * The axis of the constraint in the local coordinate system of the attached rigid body. * @zh - * 在自身刚体的本地坐标系中,旋转轴的方向。 + * 约束关节在连接刚体的本地坐标系中的轴。 */ @type(Vec3) - @tooltip('i18n:physics3d.constraint.hinge.axis') + @tooltip('i18n:physics3d.constraint.axis') get axis (): Vec3 { return this._axis; } diff --git a/cocos/physics/framework/components/constraints/point-to-point-constraint.ts b/cocos/physics/framework/components/constraints/point-to-point-constraint.ts index 3e16fbe295..9ff8a8d8e0 100644 --- a/cocos/physics/framework/components/constraints/point-to-point-constraint.ts +++ b/cocos/physics/framework/components/constraints/point-to-point-constraint.ts @@ -28,6 +28,7 @@ import { menu, type, serializable, + tooltip, } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { Constraint } from './constraint'; @@ -41,11 +42,12 @@ import { IPointToPointConstraint } from '../../../spec/i-physics-constraint'; export class PointToPointConstraint extends Constraint { /** * @en - * The position of the own rigid body in local space with respect to the constraint axis. + * The pivot point of the constraint in the local coordinate system of the attached rigid body. * @zh - * 在本地空间中,自身刚体相对于约束关节的位置。 + * 约束关节在连接刚体本地坐标系中的位置。 */ @type(Vec3) + @tooltip('i18n:physics3d.constraint.pivotA') get pivotA () { return this._pivotA; } @@ -59,11 +61,12 @@ export class PointToPointConstraint extends Constraint { /** * @en - * The position of the connected rigid body in the local space with respect to the constraint axis. + * The pivot point of the constraint in the local coordinate system of the connected rigid body. * @zh - * 在本地空间中,连接刚体相对于约束关节的位置。 + * 约束关节在连接刚体本地坐标系中的位置。 */ @type(Vec3) + @tooltip('i18n:physics3d.constraint.pivotB') get pivotB () { return this._pivotB; } diff --git a/cocos/physics/framework/index.ts b/cocos/physics/framework/index.ts index 0b250d1f81..e75f54251f 100644 --- a/cocos/physics/framework/index.ts +++ b/cocos/physics/framework/index.ts @@ -42,6 +42,7 @@ import { PlaneCollider } from './components/colliders/plane-collider'; import { Constraint } from './components/constraints/constraint'; import { HingeConstraint } from './components/constraints/hinge-constraint'; import { FixedConstraint } from './components/constraints/fixed-constraint'; +import { ConfigurableConstraint } from './components/constraints/configurable-constraint'; import { PointToPointConstraint } from './components/constraints/point-to-point-constraint'; @@ -73,6 +74,7 @@ export { HingeConstraint, FixedConstraint, PointToPointConstraint, + ConfigurableConstraint, RigidBody, PhysicsMaterial, diff --git a/cocos/physics/framework/physics-enum.ts b/cocos/physics/framework/physics-enum.ts index c8d0efdf31..4ea4538a92 100644 --- a/cocos/physics/framework/physics-enum.ts +++ b/cocos/physics/framework/physics-enum.ts @@ -86,6 +86,58 @@ export enum EAxisDirection { } Enum(EAxisDirection); +/** + * @en + * Degree of freedom. + * @zh + * 自由度。 + */ +export enum ED6Axis { + /** + * @en + * X axis. + * @zh + * X 轴。 + */ + X = 0, + /** + * @en + * Y axis. + * @zh + * Y 轴。 + */ + Y = 1, + /** + * @en + * Z axis. + * @zh + * Z 轴。 + */ + Z = 2, + /** + * @en + * Swing 1, directs toward the local Y axis. + * @zh + * 摆动 1,其方向朝向 Y 轴。 + */ + SWING1 = 3, + /** + * @en + * Swing 2, directs toward the local Z axis. + * @zh + * 摆动 2,其方向朝向 Z 轴。 + */ + SWING2 = 4, + /** + * @en + * Twist, directs toward the local X axis. + * @zh + * 扭转,其方向朝向 X 轴。 + */ + TWIST = 5, +} +Enum(ED6Axis); + /** * @en * Simplex Type. @@ -232,9 +284,83 @@ export enum EConstraintType { * 固定约束。 */ FIXED, + + /** + * @en + * Configurable constraint. + * @zh + * 可配置约束。 + */ + CONFIGURABLE, } Enum(EConstraintType); +/** + * @en + * Constraint Mode for degrees of freedom. + * @zh + * 自由度约束模式。 + */ +export enum EConstraintMode { + /** + * @en + * Free mode, the specified degrees of freedom are free to move. + * @zh + * 自由模式,指定的自由度可以自由移动。 + */ + FREE = 0, + + /** + * @en + * Limited mode, the specified degrees of freedom are limited. + * @zh + * 限制模式,指定的自由度受到限制。 + */ + LIMITED = 1, + + /** + * @en + * Locked mode, the specified degrees of freedom are locked. + * @zh + * 锁定模式,指定的自由度被锁定。 + */ + LOCKED = 2, +} +Enum(EConstraintMode); + +/** + * @en + * Driver Type. + * @zh + * 驱动类型。 + */ +export enum EDriverMode { + /** + * @en + * Disabled. + * @zh + * 禁用。 + */ + DISABLED = 0, + + /** + * @en + * Servo motor, which targets the specified rotation angle. + * @zh + * 伺服电机,旋转到特定角度。 + */ + SERVO = 1, + + /** + * @en + * Induction motor, which targets the specified velocity. + * @zh + * 感应电机,旋转到特定速度。 + */ + INDUCTION = 2, +} +Enum(EDriverMode); + /** * @en * Character Controller Type. diff --git a/cocos/physics/framework/physics-selector.ts b/cocos/physics/framework/physics-selector.ts index 1ee0ff701a..3e803b2c7e 100644 --- a/cocos/physics/framework/physics-selector.ts +++ b/cocos/physics/framework/physics-selector.ts @@ -26,7 +26,8 @@ /* eslint-disable @typescript-eslint/restrict-template-expressions */ /* eslint-disable @typescript-eslint/no-unsafe-return */ import { EDITOR, TEST } from 'internal:constants'; -import { IBaseConstraint, IPointToPointConstraint, IHingeConstraint, IConeTwistConstraint, IFixedConstraint } from '../spec/i-physics-constraint'; +import { IBaseConstraint, IPointToPointConstraint, IHingeConstraint, IConeTwistConstraint, IFixedConstraint, + IConfigurableConstraint } from '../spec/i-physics-constraint'; import { IBoxShape, ISphereShape, ICapsuleShape, ITrimeshShape, ICylinderShape, IConeShape, ITerrainShape, ISimplexShape, IPlaneShape, IBaseShape, @@ -58,9 +59,10 @@ interface IPhysicsWrapperObject { HingeConstraint?: Constructor, ConeTwistConstraint?: Constructor, FixedConstraint?: Constructor, + ConfigurableConstraint?: Constructor, } -type IPhysicsBackend = { [key: string]: IPhysicsWrapperObject; } +interface IPhysicsBackend { [key: string]: IPhysicsWrapperObject; } interface IPhysicsSelector { /** @@ -232,6 +234,7 @@ enum ECheckType { HingeConstraint, ConeTwistConstraint, FixedConstraint, + ConfigurableConstraint, // CHARACTER CONTROLLER // BoxCharacterController, CapsuleCharacterController, @@ -412,7 +415,7 @@ function initColliderProxy () { const CREATE_CONSTRAINT_PROXY = { INITED: false }; -interface IEntireConstraint extends IPointToPointConstraint, IHingeConstraint, IConeTwistConstraint, IFixedConstraint { } +interface IEntireConstraint extends IPointToPointConstraint, IHingeConstraint, IConeTwistConstraint, IFixedConstraint, IConfigurableConstraint { } const ENTIRE_CONSTRAINT: IEntireConstraint = { impl: null, initialize: FUNC, @@ -425,8 +428,32 @@ const ENTIRE_CONSTRAINT: IEntireConstraint = { setPivotA: FUNC, setPivotB: FUNC, setAxis: FUNC, + setSecondaryAxis: FUNC, setBreakForce: FUNC, setBreakTorque: FUNC, + setConstraintMode: FUNC, + setLinearLimit: FUNC, + setAngularExtent: FUNC, + setLinearSoftConstraint: FUNC, + setLinearStiffness: FUNC, + setLinearDamping: FUNC, + setLinearRestitution: FUNC, + setSwingSoftConstraint: FUNC, + setTwistSoftConstraint: FUNC, + setSwingStiffness: FUNC, + setSwingDamping: FUNC, + setSwingRestitution: FUNC, + setTwistStiffness: FUNC, + setTwistDamping: FUNC, + setTwistRestitution: FUNC, + setDriverMode: FUNC, + setLinearMotorTarget: FUNC, + setLinearMotorVelocity: FUNC, + setLinearMotorForceLimit: FUNC, + setAngularMotorTarget: FUNC, + setAngularMotorVelocity: FUNC, + setAngularMotorForceLimit: FUNC, + setAutoPivotB: FUNC, setLimitEnabled: FUNC, setLowerLimit: FUNC, setUpperLimit: FUNC, @@ -463,6 +490,11 @@ function initConstraintProxy () { if (check(selector.wrapper.FixedConstraint, ECheckType.FixedConstraint)) { return ENTIRE_CONSTRAINT; } return new selector.wrapper.FixedConstraint!(); }; + + CREATE_CONSTRAINT_PROXY[EConstraintType.CONFIGURABLE] = function createConfigurableConstraint (): IConfigurableConstraint { + if (check(selector.wrapper.ConfigurableConstraint, ECheckType.ConfigurableConstraint)) { return ENTIRE_CONSTRAINT; } + return new selector.wrapper.ConfigurableConstraint!(); + }; } /// CREATE CHARACTER CONTROLLER /// diff --git a/cocos/physics/physx/instantiate.ts b/cocos/physics/physx/instantiate.ts index 0071ad9f45..3a083bba0b 100644 --- a/cocos/physics/physx/instantiate.ts +++ b/cocos/physics/physx/instantiate.ts @@ -39,6 +39,7 @@ import { PhysXConeShape } from './shapes/physx-cone-shape'; import { PhysXFixedJoint } from './joints/physx-fixed-joint'; import { PhysXSphericalJoint } from './joints/physx-spherical-joint'; import { PhysXRevoluteJoint } from './joints/physx-revolute-joint'; +import { PhysXConfigurableJoint } from './joints/physx-configurable-joint'; import { PhysXBoxCharacterController } from './character-controllers/physx-box-character-controller'; import { PhysXCapsuleCharacterController } from './character-controllers/physx-capsule-character-controller'; @@ -64,6 +65,7 @@ game.once(Game.EVENT_PRE_SUBSYSTEM_INIT, () => { // PointToPointConstraint: PhysXFixedJoint, HingeConstraint: PhysXRevoluteJoint, FixedConstraint: PhysXFixedJoint, + ConfigurableConstraint: PhysXConfigurableJoint, BoxCharacterController: PhysXBoxCharacterController, CapsuleCharacterController: PhysXCapsuleCharacterController, diff --git a/cocos/physics/physx/joints/physx-configurable-joint.ts b/cocos/physics/physx/joints/physx-configurable-joint.ts new file mode 100644 index 0000000000..c3d64bdc1d --- /dev/null +++ b/cocos/physics/physx/joints/physx-configurable-joint.ts @@ -0,0 +1,453 @@ +/* +Copyright (c) 2023 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. + */ + +/* eslint-disable @typescript-eslint/no-unsafe-return */ + +import { IVec3Like, Vec3, Quat, Mat4, error, math, toRadian } from '../../../core'; +import { ConfigurableConstraint, EConstraintMode, EDriverMode } from '../../framework'; +import { IConfigurableConstraint } from '../../spec/i-physics-constraint'; +import { PX, _trans, getTempTransform, _pxtrans } from '../physx-adapter'; +import { PhysXInstance } from '../physx-instance'; +import { PhysXJoint } from './physx-joint'; + +const CC_V3_0 = new Vec3(); +const CC_V3_1 = new Vec3(); +const CC_QUAT_0 = new Quat(); +const CC_QUAT_1 = new Quat(); +const CC_MAT4_0 = new Mat4(); + +function getConstraintFlag (v: EConstraintMode) { + switch (v) { + case EConstraintMode.FREE: return PX.D6Motion.eFREE; + case EConstraintMode.LIMITED: return PX.D6Motion.eLIMITED; + case EConstraintMode.LOCKED: return PX.D6Motion.eLOCKED; + default: + return PX.D6Motion.eFREE; + } +} + +export class PhysXConfigurableJoint extends PhysXJoint implements IConfigurableConstraint { + protected _setLinearLimit () { + const linearLimit = this.constraint.linearLimitSettings; + + const limitPairX = PhysXConfigurableJoint._linearLimitX; + const limitPairY = PhysXConfigurableJoint._linearLimitY; + const limitPairZ = PhysXConfigurableJoint._linearLimitZ; + + const setLimitPair = (limitPair: any) => { + if (linearLimit.enableSoftConstraint) { + limitPair.stiffness = linearLimit.stiffness; + limitPair.damping = linearLimit.damping; + } else { + limitPair.stiffness = 0; + limitPair.damping = 0; + } + limitPair.bounceThreshold = 0.1; + limitPair.contactDistance = 0.1; + limitPair.restitution = linearLimit.restitution; + }; + + setLimitPair(limitPairX); + setLimitPair(limitPairY); + setLimitPair(limitPairZ); + + const lower = linearLimit.lower; + const upper = linearLimit.upper; + if (linearLimit.xMotion === EConstraintMode.LIMITED) { + limitPairX.lower = lower.x; + limitPairX.upper = upper.x; + this._impl.setLinearLimit(PX.D6Axis.eX, limitPairX); + } + + if (linearLimit.yMotion === EConstraintMode.LIMITED) { + limitPairY.lower = lower.y; + limitPairY.upper = upper.y; + this._impl.setLinearLimit(PX.D6Axis.eY, limitPairY); + } + + if (linearLimit.zMotion === EConstraintMode.LIMITED) { + limitPairZ.lower = lower.z; + limitPairZ.upper = upper.z; + this._impl.setLinearLimit(PX.D6Axis.eZ, limitPairZ); + } + } + + protected _setSwingLimit () { + const angularLimit = this.constraint.angularLimitSettings; + const limitCone = PhysXConfigurableJoint._swingLimit; + + if (angularLimit.enableSoftConstraintSwing) { + limitCone.stiffness = angularLimit.swingStiffness; + limitCone.damping = angularLimit.swingDamping; + } else { + limitCone.stiffness = 0; + limitCone.springDamping = 0; + } + + limitCone.yAngle = Math.PI; + limitCone.zAngle = Math.PI; + limitCone.contactDistance = 0.1; + limitCone.bounceThreshold = 0.1; + limitCone.restitution = angularLimit.swingRestitution; + + if (angularLimit.swingMotion1 === EConstraintMode.LIMITED) { + limitCone.yAngle = toRadian(angularLimit.swingExtent1) * 0.5; + this._impl.setSwingLimit(limitCone); + } + if (angularLimit.swingMotion2 === EConstraintMode.LIMITED) { + limitCone.zAngle = toRadian(angularLimit.swingExtent2) * 0.5; + this._impl.setSwingLimit(limitCone); + } + } + + protected _setTwistLimit () { + const angularLimit = this.constraint.angularLimitSettings; + const limitPair = PhysXConfigurableJoint._twistLimit; + + if (angularLimit.enableSoftConstraintTwist) { + limitPair.stiffness = angularLimit.twistStiffness; + limitPair.damping = angularLimit.twistDamping; + } else { + limitPair.stiffness = 0; + limitPair.damping = 0; + } + + limitPair.contactDistance = 0.1; + limitPair.bounceThreshold = 0.1; + limitPair.restitution = angularLimit.twistRestitution; + + if (angularLimit.twistMotion === EConstraintMode.LIMITED) { + limitPair.lower = toRadian(angularLimit.twistExtent) * -0.5; + limitPair.upper = toRadian(angularLimit.twistExtent) * 0.5; + this._impl.setTwistLimit(limitPair); + } + } + + protected _updateDrive (idx: number) { + let axis = PX.D6Axis.eX; + let driveMode = EDriverMode.DISABLED; + const com = this.constraint; + const ld = com.linearDriverSettings; + const ad = com.angularDriverSettings; + + const getSwingDriveMode = () => { + const ad = this.constraint.angularDriverSettings; + if (ad.swingDrive1 === EDriverMode.INDUCTION || ad.swingDrive2 === EDriverMode.INDUCTION) { + return EDriverMode.INDUCTION; + } else if (ad.swingDrive1 === EDriverMode.SERVO || ad.swingDrive2 === EDriverMode.SERVO) { + return EDriverMode.SERVO; + } else { + return EDriverMode.DISABLED; + } + }; + + switch (idx) { + case 0: axis = PX.D6Drive.eX; driveMode = ld.xDrive; break; + case 1: axis = PX.D6Drive.eY; driveMode = ld.yDrive; break; + case 2: axis = PX.D6Drive.eZ; driveMode = ld.zDrive; break; + case 3: axis = PX.D6Drive.eTWIST; driveMode = ad.twistDrive; break; + case 4: axis = PX.D6Drive.eSWING; driveMode = getSwingDriveMode(); break; + case 5: axis = PX.D6Drive.eSWING; driveMode = getSwingDriveMode(); break; + default: break; + } + const drive = PhysXConfigurableJoint._drive[idx]; + if (idx >= 0 && idx < 3) { + drive.forceLimit = com.linearDriverSettings.strength; + } else if (idx < 6) { + drive.forceLimit = com.angularDriverSettings.strength; + } + if (driveMode === EDriverMode.DISABLED) { + drive.forceLimit = 0; + } else if (driveMode === EDriverMode.SERVO) { + drive.damping = 0; + drive.stiffness = 1000; + } else if (driveMode === EDriverMode.INDUCTION) { + drive.damping = 1000; + drive.stiffness = 0; + } + this._impl.setDrive(axis, drive); + } + + protected _updateDriveTarget () { + const linearTarget = this.constraint.linearDriverSettings.targetPosition; + const angularTarget = this.constraint.angularDriverSettings.targetOrientation; + const quat = Quat.fromEuler(CC_QUAT_0, angularTarget.x, angularTarget.y, angularTarget.z); + getTempTransform(linearTarget, quat); + this._impl.setDrivePosition(_pxtrans, true); + } + + protected _updateDriveVelocity () { + const linearVelocity = this.constraint.linearDriverSettings.targetVelocity; + const angularVelocity = this.constraint.angularDriverSettings.targetVelocity; + const lv = Vec3.set(CC_V3_0, linearVelocity.x, linearVelocity.y, linearVelocity.z); + const av = Vec3.set(CC_V3_1, toRadian(-angularVelocity.x), toRadian(-angularVelocity.y), toRadian(-angularVelocity.z)); + this._impl.setDriveVelocity(lv, av, true); + } + + protected _updateDriveSettings () { + this._updateDrive(0); + this._updateDrive(1); + this._updateDrive(2); + this._updateDrive(3); + this._updateDrive(4); + this._updateDrive(5); + this._updateDriveTarget(); + this._updateDriveVelocity(); + } + + setConstraintMode (idx: number, v: EConstraintMode): void { + let axis = PX.D6Axis.eX; + switch (idx) { + case 0: axis = PX.D6Axis.eX; break; + case 1: axis = PX.D6Axis.eY; break; + case 2: axis = PX.D6Axis.eZ; break; + case 3: axis = PX.D6Axis.eTWIST; break; + case 4: axis = PX.D6Axis.eSWING1; break; + case 5: axis = PX.D6Axis.eSWING2; break; + default: break; + } + const mode = getConstraintFlag(v); + this._impl.setMotion(axis, mode); + } + + setLinearLimit (idx: number, lower: number, upper: number): void { + this._setLinearLimit(); + } + setAngularExtent (twist: number, swing1: number, swing2: number): void { + this._setSwingLimit(); + this._setTwistLimit(); + } + setLinearRestitution (v: number): void { + this._setLinearLimit(); + } + setSwingRestitution (v: number): void { + this._setSwingLimit(); + } + setTwistRestitution (v: number): void { + this._setTwistLimit(); + } + + setLinearSoftConstraint (v: boolean): void { + this._setLinearLimit(); + } + setLinearStiffness (v: number): void { + this._setLinearLimit(); + } + setLinearDamping (v: number): void { + this._setLinearLimit(); + } + + setSwingSoftConstraint (v: boolean): void { + this._setSwingLimit(); + } + setSwingStiffness (v: number): void { + this._setSwingLimit(); + } + setSwingDamping (v: number): void { + this._setSwingLimit(); + } + + setTwistSoftConstraint (v: boolean): void { + this._setTwistLimit(); + } + setTwistStiffness (v: number): void { + this._setTwistLimit(); + } + setTwistDamping (v: number): void { + this._setTwistLimit(); + } + + setDriverMode (idx: number, v: EDriverMode): void { + this._updateDrive(idx); + } + setLinearMotorTarget (v: IVec3Like): void { + this._updateDriveTarget(); + } + setLinearMotorVelocity (v: IVec3Like): void { + this._updateDriveVelocity(); + } + setLinearMotorForceLimit (v: number): void { + this._updateDrive(0); + this._updateDrive(1); + this._updateDrive(2); + } + setAngularMotorTarget (v: IVec3Like): void { + this._updateDriveTarget(); + } + setAngularMotorVelocity (v: IVec3Like): void { + this._updateDriveVelocity(); + } + setAngularMotorForceLimit (v: number): void { + this._updateDrive(3); + this._updateDrive(4); + this._updateDrive(5); + } + + setPivotA (v: IVec3Like): void { + this.updateFrames(); + } + setPivotB (v: IVec3Like): void { + this.updateFrames(); + } + setAutoPivotB (v: boolean): void { + this.updateFrames(); + } + + setAxis (v: IVec3Like): void { + this.updateFrames(); + } + setSecondaryAxis (v: IVec3Like): void { + this.updateFrames(); + } + + setBreakForce (v: number): void { + const force = this.constraint.breakForce; + const torque = this.constraint.breakTorque; + this._impl.setBreakForce(force, torque); + } + setBreakTorque (v: number): void { + const force = this.constraint.breakForce; + const torque = this.constraint.breakTorque; + this._impl.setBreakForce(force, torque); + } + + get constraint (): ConfigurableConstraint { + return this._com as ConfigurableConstraint; + } + + onComponentSet (): void { + PhysXConfigurableJoint._initCache(); + + const cs = this.constraint; + this._impl = PX.createD6Joint(PhysXJoint.tempActor, _pxtrans, null, _pxtrans); + this.setBreakForce(cs.breakForce); + this.setBreakTorque(cs.breakTorque); + + const ll = cs.linearLimitSettings; + const al = cs.angularLimitSettings; + this.setConstraintMode(0, ll.xMotion); + this.setConstraintMode(1, ll.yMotion); + this.setConstraintMode(2, ll.zMotion); + this.setConstraintMode(3, al.twistMotion); + this.setConstraintMode(4, al.swingMotion1); + this.setConstraintMode(5, al.swingMotion2); + this._setLinearLimit(); + this._setSwingLimit(); + this._setTwistLimit(); + + this._updateDriveSettings(); + + this.updateFrames(); + } + + updateFrames () { + const cs = this.constraint; + const node = cs.node; + const pos = _trans.translation; + const rot = _trans.rotation; + const cb = cs.connectedBody; + + const axisX = cs.axis; + const axisY = cs.secondaryAxis; + const axisZ = Vec3.cross(CC_V3_0, axisX, axisY); + + const _rot = CC_QUAT_0; + const mat = Mat4.set(CC_MAT4_0, + axisX.x, axisX.y, axisX.z, 0, + axisY.x, axisY.y, axisY.z, 0, + axisZ.x, axisZ.y, axisZ.z, 0, + 0, 0, 0, 1); + mat.getRotation(_rot); + + Vec3.multiply(pos, cs.node.worldScale, cs.pivotA); + this._impl.setLocalPose(0, getTempTransform(pos, _rot)); + + if (cb) { + Quat.multiply(_rot, node.worldRotation, _rot); + Quat.invert(rot, cb.node.worldRotation); + Quat.multiply(_rot, rot, _rot); + if (cs.autoPivotB) { + Vec3.multiply(pos, cs.node.worldScale, cs.pivotA); + Vec3.transformQuat(pos, pos, node.worldRotation); + Vec3.add(pos, pos, node.worldPosition); + Vec3.subtract(pos, pos, cb.node.worldPosition); + Vec3.transformQuat(pos, pos, rot); + } else { + Vec3.multiply(pos, cb.node.worldScale, cs.pivotB); + } + } else { + Vec3.multiply(pos, node.worldScale, cs.pivotA); + Vec3.transformQuat(pos, pos, node.worldRotation); + Vec3.add(pos, pos, node.worldPosition); + Quat.multiply(_rot, node.worldRotation, _rot); + } + this._impl.setLocalPose(1, getTempTransform(pos, _rot)); + } + + updateScale0 (): void { + this.updateFrames(); + } + + updateScale1 (): void { + this.updateFrames(); + } + + private static _jointToleranceScale: any = null; + private static _linearLimitX: any = null; + private static _linearLimitY: any = null; + private static _linearLimitZ: any = null; + private static _twistLimit: any = null; + private static _swingLimit: any = null; + private static _drive_x: any = null; + private static _drive_y: any = null; + private static _drive_z: any = null; + private static _drive_twist: any= null; + private static _drive_swing1: any= null; + private static _drive_swing2: any= null; + private static _drive: any[] = []; + private static _initCache () { + if (!PhysXConfigurableJoint._jointToleranceScale) { + PhysXConfigurableJoint._jointToleranceScale = PhysXInstance.physics.getTolerancesScale(); + PhysXConfigurableJoint._linearLimitX = new PX.PxJointLinearLimitPair(PhysXConfigurableJoint._jointToleranceScale, 0, 0); + PhysXConfigurableJoint._linearLimitY = new PX.PxJointLinearLimitPair(PhysXConfigurableJoint._jointToleranceScale, 0, 0); + PhysXConfigurableJoint._linearLimitZ = new PX.PxJointLinearLimitPair(PhysXConfigurableJoint._jointToleranceScale, 0, 0); + PhysXConfigurableJoint._twistLimit = new PX.PxJointAngularLimitPair(0, 0); + PhysXConfigurableJoint._swingLimit = new PX.PxJointLimitCone(1.5, 1.5); + PhysXConfigurableJoint._drive_x = new PX.D6JointDrive(); + PhysXConfigurableJoint._drive_y = new PX.D6JointDrive(); + PhysXConfigurableJoint._drive_z = new PX.D6JointDrive(); + PhysXConfigurableJoint._drive_twist = new PX.D6JointDrive(); + PhysXConfigurableJoint._drive_swing1 = new PX.D6JointDrive(); + PhysXConfigurableJoint._drive_swing2 = new PX.D6JointDrive(); + PhysXConfigurableJoint._drive = [ + PhysXConfigurableJoint._drive_x, + PhysXConfigurableJoint._drive_y, + PhysXConfigurableJoint._drive_z, + PhysXConfigurableJoint._drive_twist, + PhysXConfigurableJoint._drive_swing1, + PhysXConfigurableJoint._drive_swing2, + ]; + } + } +} diff --git a/cocos/physics/physx/physx-adapter.ts b/cocos/physics/physx/physx-adapter.ts index a6b488686b..105f6258a7 100644 --- a/cocos/physics/physx/physx-adapter.ts +++ b/cocos/physics/physx/physx-adapter.ts @@ -147,13 +147,21 @@ function initAdaptWrapper (obj: any) { obj.SphereGeometry = obj.PxSphereGeometry; obj.CapsuleGeometry = obj.PxCapsuleGeometry; obj.ConvexMeshGeometry = obj.PxConvexMeshGeometry; + obj.D6Motion = obj.PxD6Motion; + obj.D6Axis = obj.PxD6Axis; + obj.D6Drive = obj.PxD6Drive; + obj.D6JointDrive = obj.PxD6JointDrive; + obj.LinearLimitPair = obj.PxJointLinearLimitPair; + obj.AngularLimitPair = obj.PxJointAngularLimitPair; obj.TriangleMeshGeometry = obj.PxTriangleMeshGeometry; obj.RigidDynamicLockFlag = obj.PxRigidDynamicLockFlag; + obj.TolerancesScale = obj.PxTolerancesScale; obj.RevoluteJointFlags = { eLIMIT_ENABLED: 1 << 0, eDRIVE_ENABLED: 1 << 1, eDRIVE_FREESPIN: 1 << 2 }; obj.JointAngularLimitPair = obj.PxJointAngularLimitPair; obj.createRevoluteJoint = (a: any, b: any, c: any, d: any): any => obj.PxRevoluteJointCreate(PX.physics, a, b, c, d); obj.createFixedConstraint = (a: any, b: any, c: any, d: any): any => obj.PxFixedJointCreate(PX.physics, a, b, c, d); obj.createSphericalJoint = (a: any, b: any, c: any, d: any): any => obj.PxSphericalJointCreate(PX.physics, a, b, c, d); + obj.createD6Joint = (a: any, b: any, c: any, d: any): any => obj.PxD6JointCreate(PX.physics, a, b, c, d); } const _v3: IVec3Like = { x: 0, y: 0, z: 0 }; diff --git a/cocos/physics/spec/i-physics-constraint.ts b/cocos/physics/spec/i-physics-constraint.ts index 49f3d03a2b..76985a0df6 100644 --- a/cocos/physics/spec/i-physics-constraint.ts +++ b/cocos/physics/spec/i-physics-constraint.ts @@ -23,7 +23,7 @@ */ import { ILifecycle } from './i-lifecycle'; -import { Constraint, RigidBody } from '../framework'; +import { Constraint, RigidBody, EConstraintMode, EDriverMode } from '../framework'; import { IVec3Like } from '../../core'; export interface IBaseConstraint extends ILifecycle { @@ -55,4 +55,46 @@ export interface IFixedConstraint extends IBaseConstraint { setBreakTorque(v: number): void; } +export interface IConfigurableConstraint extends IBaseConstraint { + setConstraintMode (idx: number, v: EConstraintMode): void; + + // limit + setLinearLimit (idx: number, lower: number, upper: number): void; + setAngularExtent(twist: number, swing1: number, swing2: number): void; + + setLinearRestitution (v: number): void; + setSwingRestitution (v: number): void; + setTwistRestitution (v: number): void; + + setLinearSoftConstraint (v: boolean): void; + setLinearStiffness (v: number): void; + setLinearDamping (v: number): void; + + setSwingSoftConstraint (v: boolean): void; + setTwistSoftConstraint (v: boolean): void; + setSwingStiffness (v: number): void; + setSwingDamping (v: number): void; + setTwistStiffness (v: number): void; + setTwistDamping (v: number): void; + + // motor + setDriverMode (idx: number, v: EDriverMode): void; + setLinearMotorTarget (v: IVec3Like): void; + setLinearMotorVelocity (v: IVec3Like): void; + setLinearMotorForceLimit (v: number): void; + + setAngularMotorTarget (v: IVec3Like): void; // (cone) + setAngularMotorVelocity (v: IVec3Like): void; + setAngularMotorForceLimit (v: number): void; + + setPivotA (v: IVec3Like): void; + setPivotB (v: IVec3Like): void; + setAutoPivotB (v: boolean): void; + setAxis (v: IVec3Like): void; + setSecondaryAxis (v: IVec3Like): void; + + setBreakForce(v: number): void; + setBreakTorque(v: number): void; +} + export type IConeTwistConstraint = IBaseConstraint diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 9e2a4b217e..6a3984edde 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -58,11 +58,20 @@ module.exports = { RigidBody2D: `${url}/${version}/manual/en/physics-2d/physics-2d-rigid-body.html`, Joint2D: `${url}/${version}/manual/en/physics-2d/physics-2d-joint.html`, BoxCollider: `${url}/${version}/manual/en/physics/physics-collider.html`, - SphereCollider: `${url}/${version}/manual/en/physics/physics-component.html`, - CapsuleCollider: `${url}/${version}/manual/en/physics/physics-component.html`, - CylinderCollider: `${url}/${version}/manual/en/physics/physics-component.html`, - MeshCollider: `${url}/${version}/manual/en/physics/physics-component.html`, + CapsuleCollider: `${url}/${version}/manual/en/physics/physics-collider.html`, + ConeCollider: `${url}/${version}/manual/en/physics/physics-collider.html`, + CylinderCollider: `${url}/${version}/manual/en/physics/physics-collider.html`, + MeshCollider: `${url}/${version}/manual/en/physics/physics-collider.html`, + PlaneCollider: `${url}/${version}/manual/en/physics/physics-collider.html`, + SphereCollider: `${url}/${version}/manual/en/physics/physics-collider.html`, + SimplexCollider: `${url}/${version}/manual/en/physics/physics-collider.html`, + TerrainCollider: `${url}/${version}/manual/en/physics/physics-collider.html`, + ConfigurableConstraint: `${url}/${version}/manual/en/physics/physics-constraint.html`, + FixedConstraint: `${url}/${version}/manual/en/physics/physics-constraint.html`, + HingeConstraint: `${url}/${version}/manual/en/physics/physics-constraint.html`, + PointToPointConstraint: `${url}/${version}/manual/en/physics/physics-constraint.html`, RigidBody: `${url}/${version}/manual/en/physics/physics-rigidbody.html`, + PhysicsMaterial: `${url}/${version}/manual/en/physics/physics-material.html`, ConstantForce: `${url}/${version}/manual/en/physics/physics-component.html`, VideoPlayer: `${url}/${version}/manual/en/ui-system/components/editor/videoplayer.html`, WebView: `${url}/${version}/manual/en/ui-system/components/editor/webview.html`, @@ -1107,11 +1116,65 @@ module.exports = { localTorque: 'The torque applied to the rigid body in the local coordinate system', }, constraint: { - hinge: { - pivotA: 'The pivot point of the hinge in the local coordinate system of the own rigid body', - pivotB: 'The pivot point of the hinge in the local coordinate system of the connected rigid body', - axis: 'The axis of the hinge in the local coordinate system of the own rigid body', + attachedBody: 'The rigid body where the constraint is attached to', + connectedBody: 'The rigid body connected to the constraint,
if not set, the world object will be used', + enableCollision: 'Whether to enable collision between the two rigid bodies', + pivotA: 'The pivot point of the constraint in the local coordinate system of the attached rigid body', + pivotB: 'The pivot point of the constraint in the local coordinate system of the connected rigid body', + breakForce: 'The maximum force that can be applied to the constraint before it breaks', + breakTorque: 'The maximum torque that can be applied to the constraint before it breaks', + axis: 'The axis of the constraint in the local coordinate system of the attached rigid body', + secondaryAxis: 'The secondary axis of the constraint in the local coordinate system of the attached rigid body', + autoCalculatePivotB: 'Automatically derivate the pivotB from the pivotA and the relative transform of the two rigid bodies', + linearLimit: { + xMotion: 'The constraint mode along the x axis', + yMotion: 'The constraint mode along the y axis', + zMotion: 'The constraint mode along the z axis', + upper: 'The upper limit of the constraint', + lower: 'The lower limit of the constraint', + enableSoftConstraint: 'Whether to enable soft constraint', + stiffness: 'The stiffness factor of the constraint', + damping: 'The damping factor of the constraint', + restitution: 'The restitution factor of the constraint', }, + angularLimit: { + twistMotion: 'The constraint mode of the twist angle', + swingMotion1: 'The constraint mode of the swing y angle', + swingMotion2: 'The constraint mode of the swing z angle', + twistExtent: 'The twist angle limit', + swingExtent1: 'The swing y angle limit', + swingExtent2: 'The swing z angle limit', + enableSoftConstraintSwing: 'Whether to enable soft constraint for the swing constraint', + swingStiffness: 'The stiffness factor of the swing constraint', + swingDamping: 'The damping factor of the swing constraint', + swingRestitution: 'The restitution factor of the swing constraint', + enableSoftConstraintTwist: 'Whether to enable soft constraint for the twist constraint', + twistStiffness: 'The stiffness factor of the twist constraint', + twistDamping: 'The damping factor of the twist constraint', + twistRestitution: 'The restitution factor of the twist constraint', + }, + linearDriver: { + xMode: 'The driver mode along the x axis', + yMode: 'The driver mode along the y axis', + zMode: 'The driver mode along the z axis', + targetPosition: 'The target position of the driver', + targetVelocity: 'The target velocity of the driver', + strength: 'The strength of the driver', + }, + angularDriver: { + twistMode: 'The driver mode along the twist axis', + swingMode1: 'The driver mode along the swing y axis', + swingMode2: 'The driver mode along the swing z axis', + targetOrientation: 'The target orientation of the driver', + targetAngularVelocity: 'The target angular velocity of the driver', + strength: 'The strength of the driver', + }, + }, + material: { + friction: 'The friction coefficient of the material', + rollingFriction: 'The rolling friction coefficient of the material', + spinningFriction: 'The spinning friction coefficient of the material', + restitution: 'The coefficient of restitution of the material', }, character_controller: { group: 'Collision Group of the character controller.', diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index c09bbbef81..11d7291b01 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -58,11 +58,20 @@ module.exports = { RigidBody2D: `${url}/${version}/manual/zh/physics-2d/physics-2d-rigid-body.html`, Joint2D: `${url}/${version}/manual/zh/physics-2d/physics-2d-joint.html`, BoxCollider: `${url}/${version}/manual/zh/physics/physics-collider.html`, - SphereCollider: `${url}/${version}/manual/zh/physics/physics-component.html`, - CapsuleCollider: `${url}/${version}/manual/zh/physics/physics-component.html`, - CylinderCollider: `${url}/${version}/manual/zh/physics/physics-component.html`, - MeshCollider: `${url}/${version}/manual/zh/physics/physics-component.html`, + CapsuleCollider: `${url}/${version}/manual/zh/physics/physics-collider.html`, + ConeCollider: `${url}/${version}/manual/zh/physics/physics-collider.html`, + CylinderCollider: `${url}/${version}/manual/zh/physics/physics-collider.html`, + MeshCollider: `${url}/${version}/manual/zh/physics/physics-collider.html`, + PlaneCollider: `${url}/${version}/manual/zh/physics/physics-collider.html`, + SphereCollider: `${url}/${version}/manual/zh/physics/physics-collider.html`, + SimplexCollider: `${url}/${version}/manual/zh/physics/physics-collider.html`, + TerrainCollider: `${url}/${version}/manual/zh/physics/physics-collider.html`, + ConfigurableConstraint: `${url}/${version}/manual/zh/physics/physics-constraint.html`, + FixedConstraint: `${url}/${version}/manual/zh/physics/physics-constraint.html`, + HingeConstraint: `${url}/${version}/manual/zh/physics/physics-constraint.html`, + PointToPointConstraint: `${url}/${version}/manual/zh/physics/physics-constraint.html`, RigidBody: `${url}/${version}/manual/zh/physics/physics-rigidbody.html`, + PhysicsMaterial: `${url}/${version}/manual/zh/physics/physics-material.html`, ConstantForce: `${url}/${version}/manual/zh/physics/physics-component.html`, VideoPlayer: `${url}/${version}/manual/zh/ui-system/components/editor/videoplayer.html`, WebView: `${url}/${version}/manual/zh/ui-system/components/editor/webview.html`, @@ -1088,11 +1097,65 @@ module.exports = { localTorque: '在本地坐标系中,对刚体施加的扭转力', }, constraint: { - hinge: { - pivotA: '在自身刚体的本地坐标系中,旋转轴的锚点位置', - pivotB: '在连接刚体的本地坐标系中,旋转轴的锚点位置', - axis: '在自身刚体的本地坐标系中,旋转轴的方向', + attachedBody: '约束附着的刚体', + connectedBody: '约束连接的刚体, 未指定时为连接世界刚体', + enableCollision: '是否开启两个刚体之间的碰撞', + pivotA: '约束在附着刚体的本地坐标系中的锚点', + pivotB: '约束在连接刚体的本地坐标系中的锚点', + breakForce: '约束在破坏之前可以施加的最大力', + breakTorque: '约束在破坏之前可以施加的最大扭转力', + axis: '约束在附着刚体的本地坐标系中的轴', + secondaryAxis: '附加刚体的本地坐标系中约束的次要轴', + autoCalculatePivotB: '从pivotA和两个刚体的相对变换自动推导出pivotB', + linearLimit: { + xMotion: '沿x轴的约束模式', + yMotion: '沿y轴的约束模式', + zMotion: '沿z轴的约束模式', + upper: '约束的上限', + lower: '约束的下限', + enableSoftConstraint: '是否启用软约束', + stiffness: '约束的刚度系数', + damping: '约束的阻尼系数', + restitution: '约束的恢复系数', }, + angularLimit: { + twistMotion: '扭转角度的约束模式', + swingMotion1: '摆动y角度的约束模式', + swingMotion2: '摆动z角度的约束模式', + twistExtent: '扭转角度限制', + swingExtent1: '摆动y角度限制', + swingExtent2: '摆动z角度限制', + enableSoftConstraintSwing: '是否启用摆动角度的软约束', + swingStiffness: '摆动约束的刚度系数', + swingDamping: '摆动约束的阻尼系数', + swingRestitution: '摆动约束的恢复系数', + enableSoftConstraintTwist: '是否启用扭转角度的软约束', + twistStiffness: '扭转约束的刚度系数', + twistDamping: '扭转约束的阻尼系数', + twistRestitution: '扭转约束的恢复系数', + }, + linearDriver: { + xMode: '沿x轴的驱动器模式', + yMode: '沿y轴的驱动器模式', + zMode: '沿z轴的驱动器模式', + targetPosition: '驱动器的目标位置', + targetVelocity: '驱动器的目标速度', + strength: '驱动器的强度', + }, + angularDriver: { + twistMode: '扭转角度的驱动器模式', + swingMode1: '摆动y角度的驱动器模式', + swingMode2: '摆动z角度的驱动器模式', + targetOrientation: '驱动器的目标方向', + targetAngularVelocity: '驱动器的目标角速度', + strength: '驱动器的强度', + }, + }, + material: { + friction: '材质的摩擦系数', + rollingFriction: '材质的滚动摩擦系数', + spinningFriction: '材质的旋转摩擦系数', + restitution: '材质的弹性系数', }, character_controller: { group: '碰撞分组', diff --git a/exports/physics-framework.ts b/exports/physics-framework.ts index 15940ccea4..3d5704b908 100644 --- a/exports/physics-framework.ts +++ b/exports/physics-framework.ts @@ -55,6 +55,8 @@ export { Constraint, HingeConstraint, + ConfigurableConstraint, + FixedConstraint, PointToPointConstraint, CapsuleCharacterController, diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 75bd8c7d41..34ece89e92 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -1902,6 +1902,8 @@ if(USE_PHYSICS_PHYSX) cocos/physics/physx/joints/PhysXFixedJoint.cpp cocos/physics/physx/joints/PhysXSpherical.h cocos/physics/physx/joints/PhysXSpherical.cpp + cocos/physics/physx/joints/PhysXGenericJoint.h + cocos/physics/physx/joints/PhysXGenericJoint.cpp cocos/physics/physx/character-controllers/PhysXCharacterController.h cocos/physics/physx/character-controllers/PhysXCharacterController.cpp cocos/physics/physx/character-controllers/PhysXCapsuleCharacterController.h diff --git a/native/cocos/physics/PhysicsSelector.h b/native/cocos/physics/PhysicsSelector.h index 1c1a3e7d88..572096f58d 100644 --- a/native/cocos/physics/PhysicsSelector.h +++ b/native/cocos/physics/PhysicsSelector.h @@ -28,19 +28,20 @@ #include "physics/bullet/Bullet.h" #else #include "physics/physx/PhysX.h" - #define WrappedWorld PhysXWorld - #define WrappedRigidBody PhysXRigidBody - #define WrappedSphereShape PhysXSphere - #define WrappedBoxShape PhysXBox - #define WrappedPlaneShape PhysXPlane - #define WrappedCapsuleShape PhysXCapsule - #define WrappedTrimeshShape PhysXTrimesh - #define WrappedTerrainShape PhysXTerrain - #define WrappedConeShape PhysXCone - #define WrappedCylinderShape PhysXCylinder - #define WrappedRevoluteJoint PhysXRevolute - #define WrappedFixedJoint PhysXFixedJoint - #define WrappedDistanceJoint PhysXSpherical - #define WrappedCapsuleCharacterController PhysXCapsuleCharacterController - #define WrappedBoxCharacterController PhysXBoxCharacterController + #define WrappedWorld PhysXWorld + #define WrappedRigidBody PhysXRigidBody + #define WrappedSphereShape PhysXSphere + #define WrappedBoxShape PhysXBox + #define WrappedPlaneShape PhysXPlane + #define WrappedCapsuleShape PhysXCapsule + #define WrappedTrimeshShape PhysXTrimesh + #define WrappedTerrainShape PhysXTerrain + #define WrappedConeShape PhysXCone + #define WrappedCylinderShape PhysXCylinder + #define WrappedRevoluteJoint PhysXRevolute + #define WrappedFixedJoint PhysXFixedJoint + #define WrappedSphericalJoint PhysXSpherical + #define WrappedGenericJoint PhysXGenericJoint + #define WrappedCapsuleCharacterController PhysXCapsuleCharacterController + #define WrappedBoxCharacterController PhysXBoxCharacterController #endif diff --git a/native/cocos/physics/physx/PhysX.h b/native/cocos/physics/physx/PhysX.h index 8549677380..718b70a33d 100644 --- a/native/cocos/physics/physx/PhysX.h +++ b/native/cocos/physics/physx/PhysX.h @@ -38,6 +38,7 @@ #include "physics/physx/shapes/PhysXTrimesh.h" #include "physics/physx/joints/PhysXFixedJoint.h" +#include "physics/physx/joints/PhysXGenericJoint.h" #include "physics/physx/joints/PhysXRevolute.h" #include "physics/physx/joints/PhysXSpherical.h" diff --git a/native/cocos/physics/physx/joints/PhysXGenericJoint.cpp b/native/cocos/physics/physx/joints/PhysXGenericJoint.cpp new file mode 100644 index 0000000000..578e638209 --- /dev/null +++ b/native/cocos/physics/physx/joints/PhysXGenericJoint.cpp @@ -0,0 +1,506 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated 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. +****************************************************************************/ + +#include "physics/physx/joints/PhysXGenericJoint.h" +#include +#include "math/Mat4.h" +#include "math/Quaternion.h" +#include "math/Utils.h" +#include "math/Vec3.h" +#include "physics/physx/PhysXSharedBody.h" +#include "physics/physx/PhysXUtils.h" + +namespace cc { +namespace physics { + +void PhysXGenericJoint::onComponentSet() { + _mJoint = PxD6JointCreate(PxGetPhysics(), &getTempRigidActor(), physx::PxTransform{physx::PxIdentity}, nullptr, physx::PxTransform{physx::PxIdentity}); +} + +inline auto mapAxis(uint32_t index) -> physx::PxD6Axis::Enum { + switch (index) { + case 0: + return physx::PxD6Axis::Enum::eX; + case 1: + return physx::PxD6Axis::Enum::eY; + case 2: + return physx::PxD6Axis::Enum::eZ; + case 3: + return physx::PxD6Axis::Enum::eTWIST; + case 4: + return physx::PxD6Axis::Enum::eSWING1; + case 5: + return physx::PxD6Axis::Enum::eSWING2; + default: + assert(false && "unsupported axis"); + return physx::PxD6Axis::Enum::eX; + } +} + +void PhysXGenericJoint::setConstraintMode(uint32_t index, uint32_t mode) { + physx::PxD6Axis::Enum axis{mapAxis(index)}; + physx::PxD6Motion::Enum motion{}; + switch (mode) { + case 0: + motion = physx::PxD6Motion::Enum::eFREE; + break; + case 1: + motion = physx::PxD6Motion::Enum::eLIMITED; + break; + case 2: + motion = physx::PxD6Motion::Enum::eLOCKED; + break; + default: + motion = physx::PxD6Motion::Enum::eFREE; + break; + } + switch (index) { + case 0: + _linearLimit.x = motion; + break; + case 1: + _linearLimit.y = motion; + break; + case 2: + _linearLimit.z = motion; + break; + case 3: + _angularLimit.eTwist = motion; + break; + case 4: + case 5: + _angularLimit.eSwing = motion; + break; + default: + break; + } + auto* _joint{static_cast(_mJoint)}; + _joint->setMotion(axis, motion); +} + +void PhysXGenericJoint::setLinearLimit(uint32_t index, float lower, float upper) { + assert(index < 3); // linear index should be 1, 2, or 3 + _linearLimit.lower[index] = lower; + _linearLimit.upper[index] = upper; + updateLinearLimit(); +} + +void PhysXGenericJoint::setAngularExtent(float twist, float swing1, float swing2) { + _angularLimit.twistExtent = mathutils::toRadian(twist); + _angularLimit.swing1Extent = mathutils::toRadian(swing1); + _angularLimit.swing2Extent = mathutils::toRadian(swing2); + updateTwistLimit(); + updateSwingLimit(); +} + +void PhysXGenericJoint::setLinearSoftConstraint(bool enable) { + _linearLimit.soft = enable; + updateLinearLimit(); +} + +void PhysXGenericJoint::setLinearStiffness(float stiffness) { + _linearLimit.stiffness = stiffness; + updateLinearLimit(); +} + +void PhysXGenericJoint::setLinearDamping(float damping) { + _linearLimit.damping = damping; + updateLinearLimit(); +} + +void PhysXGenericJoint::setLinearRestitution(float restitution) { + _linearLimit.restitution = restitution; + updateLinearLimit(); +} + +void PhysXGenericJoint::setSwingSoftConstraint(bool enable) { + _angularLimit.swingSoft = enable; + updateSwingLimit(); +} + +void PhysXGenericJoint::setSwingStiffness(float stiffness) { + _angularLimit.swingStiffness = stiffness; + updateSwingLimit(); +} + +void PhysXGenericJoint::setSwingDamping(float damping) { + _angularLimit.swingDamping = damping; + updateSwingLimit(); +} + +void PhysXGenericJoint::setSwingRestitution(float restitution) { + _angularLimit.swingRestitution = restitution; + updateSwingLimit(); +} + +void PhysXGenericJoint::setTwistSoftConstraint(bool enable) { + _angularLimit.twistSoft = enable; + updateTwistLimit(); +} + +void PhysXGenericJoint::setTwistStiffness(float stiffness) { + _angularLimit.twistStiffness = stiffness; + updateTwistLimit(); +} + +void PhysXGenericJoint::setTwistDamping(float damping) { + _angularLimit.twistDamping = damping; + updateTwistLimit(); +} + +void PhysXGenericJoint::setTwistRestitution(float restitution) { + _angularLimit.twistRestitution = restitution; + updateTwistLimit(); +} + +void PhysXGenericJoint::setDriverMode(uint32_t index, uint32_t mode) { + switch (index) { + case 0: + _linearMotor.xDrive = mode; + break; + case 1: + _linearMotor.yDrive = mode; + break; + case 2: + _linearMotor.zDrive = mode; + break; + case 3: + _angularMotor.twistDrive = mode; + break; + case 4: + _angularMotor.swingDrive1 = mode; + break; + case 5: + _angularMotor.swingDrive2 = mode; + break; + default: + break; + } + this->updateDrive(index); +} + +void PhysXGenericJoint::setLinearMotorTarget(float x, float y, float z) { + auto& p = _linearMotor.target; + p.x = x; + p.y = y; + p.z = z; + this->updateDrivePosition(); +} + +void PhysXGenericJoint::setLinearMotorVelocity(float x, float y, float z) { + auto& v = _linearMotor.velocity; + v.x = x; + v.y = y; + v.z = z; + this->updateDriveVelocity(); +} + +void PhysXGenericJoint::setLinearMotorForceLimit(float limit) { + _linearMotor.forceLimit = limit; + updateDrive(0); + updateDrive(1); + updateDrive(2); +} + +void PhysXGenericJoint::setAngularMotorTarget(float x, float y, float z) { + auto& p = _angularMotor.target; + p.x = x; + p.y = y; + p.z = z; + this->updateDrivePosition(); +} + +void PhysXGenericJoint::setAngularMotorVelocity(float x, float y, float z) { + auto& v = _angularMotor.velocity; + v.x = -mathutils::toRadian(x); + v.y = -mathutils::toRadian(y); + v.z = -mathutils::toRadian(z); + this->updateDriveVelocity(); +} + +void PhysXGenericJoint::setAngularMotorForceLimit(float limit) { + _angularMotor.forceLimit = limit; + this->updateDrive(3); + this->updateDrive(4); + this->updateDrive(5); +} + +void PhysXGenericJoint::setPivotA(float x, float y, float z) { + _mPivotA.x = x; + _mPivotA.y = y; + _mPivotA.z = z; + updatePose(); +} +void PhysXGenericJoint::setPivotB(float x, float y, float z) { + _mPivotB.x = x; + _mPivotB.y = y; + _mPivotB.z = z; + updatePose(); +} +void PhysXGenericJoint::setAutoPivotB(bool autoPivot) { + _mAutoPivotB = autoPivot; + updatePose(); +} +void PhysXGenericJoint::setAxis(float x, float y, float z) { + _mAxis.x = x; + _mAxis.y = y; + _mAxis.z = z; + updatePose(); +} +void PhysXGenericJoint::setSecondaryAxis(float x, float y, float z) { + _mSecondary.x = x; + _mSecondary.y = y; + _mSecondary.z = z; + updatePose(); +} + +void PhysXGenericJoint::setBreakForce(float force) { + _breakForce = force; + physx::PxD6Joint* joint{static_cast(_mJoint)}; + joint->getBreakForce(_breakForce, _breakTorque); +} +void PhysXGenericJoint::setBreakTorque(float torque) { + _breakTorque = torque; + physx::PxD6Joint* joint{static_cast(_mJoint)}; + joint->getBreakForce(_breakForce, _breakTorque); +} +void PhysXGenericJoint::updateScale0() { + this->updatePose(); +} +void PhysXGenericJoint::updateScale1() { + this->updatePose(); +} + +void PhysXGenericJoint::updateLinearLimit() { + physx::PxD6Joint* joint{static_cast(_mJoint)}; + const auto lower = _linearLimit.lower; + const auto upper = _linearLimit.upper; + auto limitx = joint->getLinearLimit(physx::PxD6Axis::Enum::eX); + auto limity = joint->getLinearLimit(physx::PxD6Axis::Enum::eY); + auto limitz = joint->getLinearLimit(physx::PxD6Axis::Enum::eZ); + if (_linearLimit.soft) { + limitx.stiffness = _linearLimit.stiffness; + limitx.damping = _linearLimit.damping; + } else { + limitx.stiffness = 0.0; + limitx.damping = 0.0; + } + limitx.contactDistance = 0.1; + limitx.bounceThreshold = 0.1; + limitx.restitution = _linearLimit.restitution; + + limity = limitx; + limitz = limitx; + if (_linearLimit.x == physx::PxD6Motion::Enum::eLIMITED) { + limitx.upper = upper[0]; + limitx.lower = lower[0]; + joint->setLinearLimit(physx::PxD6Axis::Enum::eX, limitx); + } + if (_linearLimit.y == physx::PxD6Motion::Enum::eLIMITED) { + limity.upper = upper[1]; + limity.lower = lower[1]; + joint->setLinearLimit(physx::PxD6Axis::Enum::eY, limity); + } + if (_linearLimit.z == physx::PxD6Motion::Enum::eLIMITED) { + limitz.upper = upper[2]; + limitz.lower = lower[2]; + joint->setLinearLimit(physx::PxD6Axis::Enum::eZ, limity); + } +} + +void PhysXGenericJoint::updateSwingLimit() { + if (_angularLimit.eSwing != physx::PxD6Motion::Enum::eLIMITED) { + return; + } + + physx::PxD6Joint* joint{static_cast(_mJoint)}; + auto coneLimit = joint->getSwingLimit(); + if (_angularLimit.swingSoft) { + coneLimit.stiffness = _angularLimit.swingStiffness; + coneLimit.damping = _angularLimit.swingDamping; + } else { + coneLimit.stiffness = 0; + coneLimit.damping = 0; + } + coneLimit.bounceThreshold = 0.1; + coneLimit.contactDistance = 0.1; + coneLimit.restitution = _angularLimit.swingRestitution; + coneLimit.yAngle = math::PI; + coneLimit.zAngle = math::PI; + if (_angularLimit.eSwing == 1) { + coneLimit.yAngle = _angularLimit.swing1Extent * 0.5; + coneLimit.zAngle = _angularLimit.swing2Extent * 0.5; + joint->setSwingLimit(coneLimit); + } +} + +void PhysXGenericJoint::updateTwistLimit() { + if (_angularLimit.eTwist != physx::PxD6Motion::Enum::eLIMITED) { + return; + } + physx::PxD6Joint* joint{static_cast(_mJoint)}; + auto twistLimit = joint->getTwistLimit(); + twistLimit.bounceThreshold = 0.1; + twistLimit.contactDistance = 0.1; + twistLimit.restitution = _angularLimit.twistRestitution; + if (_angularLimit.twistSoft) { + twistLimit.stiffness = _angularLimit.twistStiffness; + twistLimit.damping = _angularLimit.twistDamping; + } else { + twistLimit.damping = 0; + twistLimit.stiffness = _angularLimit.twistStiffness; + } + if (_angularLimit.eTwist == 1) { + twistLimit.lower = _angularLimit.twistExtent * -0.5; + twistLimit.upper = _angularLimit.twistExtent * 0.5; + joint->setTwistLimit(twistLimit); + } +} + +void PhysXGenericJoint::updateDrive(uint32_t axis) { + assert(axis < 6 && "axis should be in [0, 5]"); + physx::PxD6Joint* joint{static_cast(_mJoint)}; + auto drive = joint->getDrive(static_cast(axis)); + + uint32_t mode = 0; + physx::PxD6Drive::Enum driveAxis = physx::PxD6Drive::Enum::eX; + switch (axis) { + case 0: + mode = _linearMotor.xDrive; + driveAxis = physx::PxD6Drive::Enum::eX; + break; + case 1: + mode = _linearMotor.yDrive; + driveAxis = physx::PxD6Drive::Enum::eY; + break; + case 2: + mode = _linearMotor.zDrive; + driveAxis = physx::PxD6Drive::Enum::eZ; + break; + case 3: + mode = _angularMotor.twistDrive; + driveAxis = physx::PxD6Drive::Enum::eTWIST; + break; + case 4: + case 5: + if (_angularMotor.swingDrive1 == 2 || _angularMotor.swingDrive2 == 2) { + mode = 2; + } else if (_angularMotor.swingDrive1 == 1 || _angularMotor.swingDrive2 == 1) { + mode = 1; + } else { + mode = 0; + } + driveAxis = physx::PxD6Drive::Enum::eSWING; + break; + default: + break; + }; + + if (axis < 3) { + drive.forceLimit = _linearMotor.forceLimit; + } else if (axis == 3) { + drive.forceLimit = _angularMotor.forceLimit; + } else if (axis < 6) { + drive.forceLimit = _angularMotor.forceLimit; + } + + if (mode == 0) { // disabled + drive.forceLimit = 0; + } else if (mode == 1) { // servo + drive.damping = 0.0; + drive.stiffness = 1000.0; + } else if (mode == 2) { // induction + drive.damping = 1000.0; + drive.stiffness = 0.0; + } + joint->setDrive(driveAxis, drive); +} + +void PhysXGenericJoint::updateDrivePosition() { + physx::PxD6Joint* joint{static_cast(_mJoint)}; + physx::PxTransform trans{}; + + const auto& ld = _linearMotor.target; + const auto& ad = _angularMotor.target; + + Quaternion quat; + Quaternion::fromEuler(ad.x, ad.y, ad.z, &quat); + pxSetVec3Ext(trans.p, Vec3(ld.x, ld.y, ld.z)); + pxSetQuatExt(trans.q, quat); + + joint->setDrivePosition(trans, true); +} + +void PhysXGenericJoint::updateDriveVelocity() { + physx::PxD6Joint* joint{static_cast(_mJoint)}; + joint->setDriveVelocity(_linearMotor.velocity, _angularMotor.velocity, true); +} + +void PhysXGenericJoint::updatePose() { + physx::PxTransform pose0{physx::PxIdentity}; + physx::PxTransform pose1{physx::PxIdentity}; + auto* node0 = _mSharedBody->getNode(); + node0->updateWorldTransform(); + _mTertiary = _mAxis.cross(_mSecondary); + + Mat4 transform( + _mAxis.x, _mAxis.y, _mAxis.z, 0.F, + _mSecondary.x, _mSecondary.y, _mSecondary.z, 0.F, + _mTertiary.x, _mTertiary.y, _mTertiary.z, 0.F, + 0.F, 0.F, 0.F, 1.F); + + Quaternion quat{transform}; + pose0.q = physx::PxQuat{quat.x, quat.y, quat.z, quat.w}; + Vec3 pos = Vec3(_mPivotA.x, _mPivotA.y, _mPivotA.z) * node0->getWorldScale(); + pose0.p = physx::PxVec3{pos.x, pos.y, pos.z}; + _mJoint->setLocalPose(physx::PxJointActorIndex::eACTOR0, pose0); + + if (_mConnectedBody) { + auto* node1 = _mConnectedBody->getNode(); + node1->updateWorldTransform(); + const auto& rot_1_i = node1->getWorldRotation().getInversed(); + if (_mAutoPivotB) { + pos.transformQuat(node0->getWorldRotation()); + pos += node0->getWorldPosition(); + pos -= node1->getWorldPosition(); + pos.transformQuat(rot_1_i); + pxSetVec3Ext(pose1.p, pos); + } else { + pose1.p = _mPivotB * node1->getWorldScale(); + } + Quaternion::multiply(node0->getWorldRotation(), quat, &quat); + Quaternion::multiply(rot_1_i, quat, &quat); + pxSetQuatExt(pose1.q, quat); + } else { + pos.transformQuat(node0->getWorldRotation()); + pos += node0->getWorldPosition(); + Quaternion::multiply(node0->getWorldRotation(), quat, &quat); + pose1.p = physx::PxVec3{pos.x, pos.y, pos.z}; + pose1.q = physx::PxQuat{quat.x, quat.y, quat.z, quat.w}; + } + _mJoint->setLocalPose(physx::PxJointActorIndex::eACTOR1, pose1); +} + +} // namespace physics +} // namespace cc diff --git a/native/cocos/physics/physx/joints/PhysXGenericJoint.h b/native/cocos/physics/physx/joints/PhysXGenericJoint.h new file mode 100644 index 0000000000..3958aeb159 --- /dev/null +++ b/native/cocos/physics/physx/joints/PhysXGenericJoint.h @@ -0,0 +1,143 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated 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. +****************************************************************************/ + +#pragma once + +#include "physics/physx/joints/PhysXJoint.h" + +namespace cc { +namespace physics { + +class PhysXGenericJoint final : public PhysXJoint, public IGenericJoint { +public: + PhysXGenericJoint() = default; + ~PhysXGenericJoint() = default; + + void setConstraintMode(uint32_t index, uint32_t mode) override; + void setLinearLimit(uint32_t index, float lower, float upper) override; // linear only, angular use extent is better + void setAngularExtent(float twist, float swing1, float swing2) override; + void setLinearSoftConstraint(bool enable) override; + void setLinearStiffness(float stiffness) override; + void setLinearDamping(float damping) override; + void setLinearRestitution(float restitution) override; + + // TODO (yiwenxue): add new function to set angular limit + void setSwingSoftConstraint(bool enable) override; + void setTwistSoftConstraint(bool enable) override; + void setSwingStiffness(float stiffness) override; + void setSwingDamping(float damping) override; + void setSwingRestitution(float restitution) override; + void setTwistStiffness(float stiffness) override; + void setTwistDamping(float damping) override; + void setTwistRestitution(float restitution) override; + + void setDriverMode(uint32_t index, uint32_t mode) override; + void setLinearMotorTarget(float x, float y, float z) override; + void setLinearMotorVelocity(float x, float y, float z) override; + void setLinearMotorForceLimit(float limit) override; + + void setAngularMotorTarget(float x, float y, float z) override; + void setAngularMotorVelocity(float x, float y, float z) override; + void setAngularMotorForceLimit(float limit) override; + + void setPivotA(float x, float y, float z) override; + void setPivotB(float x, float y, float z) override; + void setAutoPivotB(bool autoPivot) override; + void setAxis(float x, float y, float z) override; + void setSecondaryAxis(float x, float y, float z) override; + + void setBreakForce(float force) override; + void setBreakTorque(float torque) override; + + void updateScale0() override; + void updateScale1() override; + +private: + void onComponentSet() override; + void updatePose(); + void updateLinearLimit(); + + void updateSwingLimit(); + void updateTwistLimit(); + + void updateDrive(uint32_t axis); + void updateDrivePosition(); + void updateDriveVelocity(); + + physx::PxVec3 _mPivotA{physx::PxZero}; + physx::PxVec3 _mPivotB{physx::PxZero}; + bool _mAutoPivotB{false}; + physx::PxVec3 _mAxis{physx::PxZero}; + physx::PxVec3 _mSecondary{physx::PxZero}; + physx::PxVec3 _mTertiary{physx::PxZero}; + + float _breakForce{0.F}; + float _breakTorque{0.F}; + + struct { + physx::PxD6Motion::Enum x, y, z; + float lower[3]; + float upper[3]; + + bool soft; + float stiffness; + float damping; + float restitution; + float forceLimit; + } _linearLimit; + + struct { + physx::PxD6Motion::Enum eTwist, eSwing, eSlerp; + float swing1Extent, swing2Extent, twistExtent; + + bool swingSoft, twistSoft; + float swingStiffness; + float swingDamping; + float swingRestitution; + float twistStiffness; + float twistDamping; + float twistRestitution; + } _angularLimit; + + struct { + uint32_t xDrive; + uint32_t yDrive; + uint32_t zDrive; + float forceLimit; + physx::PxVec3 target; + physx::PxVec3 velocity; + } _linearMotor; + + struct { + uint32_t twistDrive; + uint32_t swingDrive1; + uint32_t swingDrive2; + float forceLimit; + physx::PxVec3 target; + physx::PxVec3 velocity; + } _angularMotor; +}; + +} // namespace physics +} // namespace cc diff --git a/native/cocos/physics/physx/joints/PhysXSpherical.h b/native/cocos/physics/physx/joints/PhysXSpherical.h index 67a9b0aaf2..e31e59b6bc 100644 --- a/native/cocos/physics/physx/joints/PhysXSpherical.h +++ b/native/cocos/physics/physx/joints/PhysXSpherical.h @@ -29,7 +29,7 @@ namespace cc { namespace physics { -class PhysXSpherical final : public PhysXJoint, public IDistanceJoint { +class PhysXSpherical final : public PhysXJoint, public ISphericalJoint { public: PhysXSpherical() : _mPivotA(physx::PxZero), _mPivotB(physx::PxZero){}; diff --git a/native/cocos/physics/sdk/Joint.cpp b/native/cocos/physics/sdk/Joint.cpp index dd8d6bb191..373ed40de9 100644 --- a/native/cocos/physics/sdk/Joint.cpp +++ b/native/cocos/physics/sdk/Joint.cpp @@ -68,17 +68,18 @@ namespace physics { /// COMMON /// -CC_PHYSICS_JOINT_DEFINITION(DistanceJoint, WrappedDistanceJoint) +CC_PHYSICS_JOINT_DEFINITION(SphericalJoint, WrappedSphericalJoint) CC_PHYSICS_JOINT_DEFINITION(RevoluteJoint, WrappedRevoluteJoint) CC_PHYSICS_JOINT_DEFINITION(FixedJoint, WrappedFixedJoint) +CC_PHYSICS_JOINT_DEFINITION(GenericJoint, WrappedGenericJoint) /// EXTRAS /// -void DistanceJoint::setPivotA(float x, float y, float z) { +void SphericalJoint::setPivotA(float x, float y, float z) { _impl->setPivotA(x, y, z); } -void DistanceJoint::setPivotB(float x, float y, float z) { +void SphericalJoint::setPivotB(float x, float y, float z) { _impl->setPivotB(x, y, z); } @@ -126,5 +127,97 @@ void FixedJoint::setBreakTorque(float torque) { _impl->setBreakTorque(torque); } +void GenericJoint::setConstraintMode(uint32_t index, uint32_t mode) { + _impl->setConstraintMode(index, mode); +} +void GenericJoint::setLinearLimit(uint32_t index, float lower, float upper) { + _impl->setLinearLimit(index, lower, upper); +} + +void GenericJoint::setAngularExtent(float twist, float swing1, float swing2) { + _impl->setAngularExtent(twist, swing1, swing2); +} +void GenericJoint::setLinearSoftConstraint(bool enable) { + _impl->setLinearSoftConstraint(enable); +} +void GenericJoint::setLinearStiffness(float stiffness) { + _impl->setLinearStiffness(stiffness); +} +void GenericJoint::setLinearDamping(float damping) { + _impl->setLinearDamping(damping); +} +void GenericJoint::setLinearRestitution(float restitution) { + _impl->setLinearRestitution(restitution); +} + +void GenericJoint::setSwingSoftConstraint(bool enable) { + _impl->setSwingSoftConstraint(enable); +} +void GenericJoint::setTwistSoftConstraint(bool enable) { + _impl->setTwistSoftConstraint(enable); +} +void GenericJoint::setSwingStiffness(float stiffness) { + _impl->setSwingStiffness(stiffness); +} +void GenericJoint::setSwingDamping(float damping) { + _impl->setSwingDamping(damping); +} +void GenericJoint::setSwingRestitution(float restitution) { + _impl->setSwingRestitution(restitution); +} +void GenericJoint::setTwistStiffness(float stiffness) { + _impl->setTwistStiffness(stiffness); +} +void GenericJoint::setTwistDamping(float damping) { + _impl->setTwistDamping(damping); +} +void GenericJoint::setTwistRestitution(float restitution) { + _impl->setTwistRestitution(restitution); +} + +void GenericJoint::setDriverMode(uint32_t index, uint32_t mode) { + _impl->setDriverMode(index, mode); +} +void GenericJoint::setLinearMotorTarget(float x, float y, float z) { + _impl->setLinearMotorTarget(x, y, z); +} +void GenericJoint::setLinearMotorVelocity(float x, float y, float z) { + _impl->setLinearMotorVelocity(x, y, z); +} +void GenericJoint::setLinearMotorForceLimit(float limit) { + _impl->setLinearMotorForceLimit(limit); +} +void GenericJoint::setAngularMotorTarget(float x, float y, float z) { + _impl->setAngularMotorTarget(x, y, z); +} +void GenericJoint::setAngularMotorVelocity(float x, float y, float z) { + _impl->setAngularMotorVelocity(x, y, z); +} +void GenericJoint::setAngularMotorForceLimit(float limit) { + _impl->setAngularMotorForceLimit(limit); +} +void GenericJoint::setPivotA(float x, float y, float z) { + _impl->setPivotA(x, y, z); +} +void GenericJoint::setPivotB(float x, float y, float z) { + _impl->setPivotB(x, y, z); +} +void GenericJoint::setAutoPivotB(bool enable) { + _impl->setAutoPivotB(enable); +} +void GenericJoint::setAxis(float x, float y, float z) { + _impl->setAxis(x, y, z); +} +void GenericJoint::setSecondaryAxis(float x, float y, float z) { + _impl->setSecondaryAxis(x, y, z); +} + +void GenericJoint::setBreakForce(float force) { + _impl->setBreakForce(force); +} +void GenericJoint::setBreakTorque(float torque) { + _impl->setBreakTorque(torque); +} + } // namespace physics } // namespace cc diff --git a/native/cocos/physics/sdk/Joint.h b/native/cocos/physics/sdk/Joint.h index 0ce041317e..ade1e9eea1 100644 --- a/native/cocos/physics/sdk/Joint.h +++ b/native/cocos/physics/sdk/Joint.h @@ -60,10 +60,10 @@ void setMotorVelocity(float v) override; void setMotorForceLimit(float v) override; }; // RevoluteJoint -CC_PHYSICS_JOINT_CLASS(DistanceJoint) +CC_PHYSICS_JOINT_CLASS(SphericalJoint) void setPivotA(float x, float y, float z) override; void setPivotB(float x, float y, float z) override; -}; // DistanceJoint +}; // SphericalJoint CC_PHYSICS_JOINT_CLASS(FixedJoint) void setBreakForce(float force) override; @@ -71,5 +71,44 @@ void setBreakTorque(float torque) override; } ; // FixedJoint +CC_PHYSICS_JOINT_CLASS(GenericJoint) +void setConstraintMode(uint32_t index, uint32_t mode) override; +void setLinearLimit(uint32_t index, float lower, float upper) override; +void setAngularExtent(float twist, float swing1, float swing2) override; +void setLinearSoftConstraint(bool enable) override; +void setLinearStiffness(float stiffness) override; +void setLinearDamping(float damping) override; +void setLinearRestitution(float restitution) override; + +void setSwingSoftConstraint(bool enable) override; +void setTwistSoftConstraint(bool enable) override; +void setSwingStiffness(float stiffness) override; +void setSwingDamping(float damping) override; +void setSwingRestitution(float restitution) override; +void setTwistStiffness(float stiffness) override; +void setTwistDamping(float damping) override; +void setTwistRestitution(float restitution) override; + +virtual void setDriverMode(uint32_t index, uint32_t mode) override; + +void setLinearMotorTarget(float x, float y, float z) override; +void setLinearMotorVelocity(float x, float y, float z) override; +void setLinearMotorForceLimit(float limit) override; + +void setAngularMotorTarget(float x, float y, float z) override; +void setAngularMotorVelocity(float x, float y, float z) override; +void setAngularMotorForceLimit(float limit) override; + +void setPivotA(float x, float y, float z) override; +void setPivotB(float x, float y, float z) override; +void setAutoPivotB(bool enable) override; +void setAxis(float x, float y, float z) override; +void setSecondaryAxis(float x, float y, float z) override; + +void setBreakForce(float force) override; +void setBreakTorque(float torque) override; +} +; + } // namespace physics } // namespace cc diff --git a/native/cocos/physics/spec/IJoint.h b/native/cocos/physics/spec/IJoint.h index 7cf99d7c45..9e25a2d241 100644 --- a/native/cocos/physics/spec/IJoint.h +++ b/native/cocos/physics/spec/IJoint.h @@ -40,9 +40,9 @@ public: virtual uint32_t getObjectID() const = 0; }; -class IDistanceJoint : virtual public IBaseJoint { +class ISphericalJoint : virtual public IBaseJoint { public: - ~IDistanceJoint() override = default; + ~ISphericalJoint() override = default; virtual void setPivotA(float x, float y, float z) = 0; virtual void setPivotB(float x, float y, float z) = 0; }; @@ -68,5 +68,46 @@ public: virtual void setBreakTorque(float torque) = 0; }; +class IGenericJoint : virtual public IBaseJoint { +public: + ~IGenericJoint() override = default; + + virtual void setConstraintMode(uint32_t index, uint32_t mode) = 0; + virtual void setLinearLimit(uint32_t index, float lower, float upper) = 0; + virtual void setAngularExtent(float twist, float swing1, float swing2) = 0; + virtual void setLinearSoftConstraint(bool enable) = 0; + virtual void setLinearStiffness(float stiffness) = 0; + virtual void setLinearDamping(float damping) = 0; + virtual void setLinearRestitution(float restitution) = 0; + + virtual void setSwingSoftConstraint(bool enable) = 0; + virtual void setTwistSoftConstraint(bool enable) = 0; + virtual void setSwingStiffness(float stiffness) = 0; + virtual void setSwingDamping(float damping) = 0; + virtual void setSwingRestitution(float restitution) = 0; + virtual void setTwistStiffness(float stiffness) = 0; + virtual void setTwistDamping(float damping) = 0; + virtual void setTwistRestitution(float restitution) = 0; + + // motor + virtual void setDriverMode(uint32_t index, uint32_t mode) = 0; + virtual void setLinearMotorTarget(float x, float y, float z) = 0; + virtual void setLinearMotorVelocity(float x, float y, float z) = 0; + virtual void setLinearMotorForceLimit(float limit) = 0; + + virtual void setAngularMotorTarget(float x, float y, float z) = 0; + virtual void setAngularMotorVelocity(float x, float y, float z) = 0; + virtual void setAngularMotorForceLimit(float limit) = 0; + + virtual void setPivotA(float x, float y, float z) = 0; + virtual void setPivotB(float x, float y, float z) = 0; + virtual void setAutoPivotB(bool enable) = 0; + virtual void setAxis(float x, float y, float z) = 0; + virtual void setSecondaryAxis(float x, float y, float z) = 0; + + virtual void setBreakForce(float force) = 0; + virtual void setBreakTorque(float torque) = 0; +}; + } // namespace physics } // namespace cc diff --git a/platforms/native/engine/jsb-physics.js b/platforms/native/engine/jsb-physics.js index f5bcf3aa64..afc09c4fca 100644 --- a/platforms/native/engine/jsb-physics.js +++ b/platforms/native/engine/jsb-physics.js @@ -751,7 +751,7 @@ class Joint { } class SphericalJoint extends Joint { - constructor () { super(); this._impl = new jsbPhy.DistanceJoint(); } + constructor () { super(); this._impl = new jsbPhy.SphericalJoint(); } setPivotA (v) { this._impl.setPivotA(v.x, v.y, v.z); } setPivotB (v) { this._impl.setPivotB(v.x, v.y, v.z); } onLoad () { @@ -797,6 +797,105 @@ class FixedJoint extends Joint { } } +class ConfigurableJoint extends Joint { + constructor () { super(); this._impl = new jsbPhy.GenericJoint(); } + + setConstraintMode (idx, v) { this._impl.setConstraintMode(idx, v); } + setLinearLimit (idx, upper, lower) { this._impl.setLinearLimit(idx, upper, lower); } + setAngularExtent (twist, swing1, swing2) { this._impl.setAngularExtent(twist, swing1, swing2); } + setLinearSoftConstraint (v) { this._impl.setLinearSoftConstraint(v); } + setLinearStiffness (v) { this._impl.setLinearStiffness(v); } + setLinearDamping (v) { this._impl.setLinearDamping(v); } + setLinearRestitution (v) { this._impl.setLinearRestitution(v); } + + setSwingSoftConstraint (v) { this._impl.setSwingSoftConstraint(v); } + setTwistSoftConstraint (v) { this._impl.setTwistSoftConstraint(v); } + setSwingStiffness (v) { this._impl.setSwingStiffness(v); } + setSwingDamping (v) { this._impl.setSwingDamping(v); } + setSwingRestitution (v) { this._impl.setSwingRestitution(v); } + setTwistStiffness (v) { this._impl.setTwistStiffness(v); } + setTwistDamping (v) { this._impl.setTwistDamping(v); } + setTwistRestitution (v) { this._impl.setTwistRestitution(v); } + + // motor + setDriverMode (idx, v) { this._impl.setDriverMode(idx, v); } + setLinearMotorTarget (v) { this._impl.setLinearMotorTarget(v.x, v.y, v.z); } + setLinearMotorVelocity (v) { this._impl.setLinearMotorVelocity(v.x, v.y, v.z); } + setLinearMotorForceLimit (v) { this._impl.setLinearMotorForceLimit(v); } + + setAngularMotorTarget (v) { this._impl.setAngularMotorTarget(v.x, v.y, v.z); } + setAngularMotorVelocity (v) { this._impl.setAngularMotorVelocity(v.x, v.y, v.z); } + setAngularMotorForceLimit (v) { this._impl.setAngularMotorForceLimit(v); } + + setPivotA (v) { this._impl.setPivotA(v.x, v.y, v.z); } + setPivotB (v) { this._impl.setPivotB(v.x, v.y, v.z); } + setAutoPivotB (v) { this._impl.setAutoPivotB(v); } + setAxis (v) { this._impl.setAxis(v.x, v.y, v.z); } + setSecondaryAxis (v) { this._impl.setSecondaryAxis(v.x, v.y, v.z); } + + setBreakForce (v) { this._impl.setBreakForce(v); } + setBreakTorque (v) { this._impl.setBreakTorque(v); } + + onLoad () { + super.onLoad(); + this.setBreakForce(this._com.breakForce); + this.setBreakTorque(this._com.breakTorque); + + const com = this._com; + const linearLimit = com.linearLimitSettings; + const angularLimit = com.angularLimitSettings; + this.setConstraintMode(0, linearLimit.xMotion); + this.setConstraintMode(1, linearLimit.yMotion); + this.setConstraintMode(2, linearLimit.zMotion); + this.setConstraintMode(3, angularLimit.twistMotion); + this.setConstraintMode(4, angularLimit.swingMotion1); + this.setConstraintMode(5, angularLimit.swingMotion2); + + this.setLinearLimit(0, linearLimit.lower.x, linearLimit.upper.x); + this.setLinearLimit(1, linearLimit.lower.y, linearLimit.upper.y); + this.setLinearLimit(2, linearLimit.lower.z, linearLimit.upper.z); + this.setAngularExtent(angularLimit.twistExtent, angularLimit.swingExtent1, angularLimit.swingExtent2); + + this.setLinearSoftConstraint(linearLimit.enableSoftConstraint); + this.setLinearStiffness(linearLimit.stiffness); + this.setLinearDamping(linearLimit.damping); + this.setLinearRestitution(linearLimit.restitution); + + this.setSwingSoftConstraint(angularLimit.enableSoftConstraintSwing); + this.setTwistSoftConstraint(angularLimit.enableSoftConstraintTwist); + this.setSwingStiffness(angularLimit.swingStiffness); + this.setSwingDamping(angularLimit.swingDamping); + this.setSwingRestitution(angularLimit.swingRestitution); + this.setTwistStiffness(angularLimit.twistStiffness); + this.setTwistDamping(angularLimit.twistDamping); + this.setTwistRestitution(angularLimit.twistRestitution); + + const linearMotor = com.linearDriverSettings; + const angularMotor = com.angularDriverSettings; + this.setDriverMode(0, linearMotor.xDrive); + this.setDriverMode(1, linearMotor.yDrive); + this.setDriverMode(2, linearMotor.zDrive); + this.setDriverMode(3, angularMotor.twistDrive); + this.setDriverMode(4, angularMotor.swingDrive1); + this.setDriverMode(5, angularMotor.swingDrive2); + + this.setLinearMotorTarget(linearMotor.targetPosition); + this.setLinearMotorVelocity(linearMotor.targetVelocity); + this.setLinearMotorForceLimit(linearMotor.strength); + + this.setAngularMotorTarget(angularMotor.targetOrientation); + this.setAngularMotorVelocity(angularMotor.targetVelocity); + this.setAngularMotorForceLimit(angularMotor.strength); + + this.setPivotA(com.pivotA); + this.setPivotB(com.pivotB); + this.setAutoPivotB(com.autoPivotB); + this.setAxis(com.axis); + this.setSecondaryAxis(com.secondaryAxis); + this.setBreakForce(com.breakForce); + this.setBreakTorque(com.breakTorque); + } +} class CharacterController { get impl () { return this._impl; } get characterController () { return this._com; } @@ -896,6 +995,7 @@ cc.physics.selector.register('physx', { PointToPointConstraint: SphericalJoint, HingeConstraint: RevoluteJoint, FixedConstraint: FixedJoint, + ConfigurableConstraint: ConfigurableJoint, CapsuleCharacterController, BoxCharacterController, }); diff --git a/tests/physics/constraint.ts b/tests/physics/constraint.ts new file mode 100644 index 0000000000..aa48f018e6 --- /dev/null +++ b/tests/physics/constraint.ts @@ -0,0 +1,131 @@ +import { Quat, Vec3 } from "../../cocos/core"; +import { director } from "../../cocos/game"; +import { Node } from "../../cocos/scene-graph"; +import { ICollisionEvent, physics } from "../../exports/physics-framework"; + +function testConfigurableConstraintAPIs(child: Node) { + if (physics.selector.id === 'builtin' || physics.selector.id === 'cannon.js') { + return; + } + + const cs = child.addComponent(physics.ConfigurableConstraint) as physics.ConfigurableConstraint; + + { + const pivotA = new Vec3(1, 0, 0); + const pivotB = new Vec3(0, 1, 0); + + cs.pivotA = pivotA; + cs.pivotB = pivotB; + expect(cs.pivotA).toEqual(pivotA); + expect(cs.pivotB).toEqual(pivotB); + + const axis = new Vec3(1, 0, 0); + const secondaryAxis = new Vec3(0, 1, 0); + + cs.axis = axis; + cs.secondaryAxis = secondaryAxis; + expect(cs.axis).toEqual(axis); + expect(cs.secondaryAxis).toEqual(secondaryAxis); + + const maxForce = 1; + const maxTorque = 2; + + cs.breakForce = maxForce; + cs.breakTorque = maxTorque; + + expect(cs.breakForce).toBe(maxForce); + expect(cs.breakTorque).toBe(maxTorque); + + const ll = cs.linearLimitSettings; + const al = cs.angularLimitSettings; + const ld = cs.linearDriverSettings; + const ad = cs.angularDriverSettings; + + // linear limits + const linearLower = new Vec3(-1, -1, -1); + const linearUpper = new Vec3(1, 1, 1); + + ll.upper = linearUpper; + ll.lower = linearLower; + expect(cs.linearLimitSettings.lower).toEqual(linearLower); + expect(cs.linearLimitSettings.upper).toEqual(linearUpper); + + const linearSoft = false; + const linearStiffness = 1; + const linearDamping = 2; + const linearRestitution = 4; + + ll.enableSoftConstraint = linearSoft; + ll.damping = linearDamping; + ll.stiffness = linearStiffness; + ll.restitution = linearRestitution; + expect(ll.enableSoftConstraint).toBe(linearSoft); + expect(ll.damping).toBe(linearDamping); + expect(ll.stiffness).toBe(linearStiffness); + expect(ll.restitution).toBe(linearRestitution); + + // angular limits + const swingExtent1 = 1; + const swingExtent2 = 2; + const twistExtent = 0.8; + + al.swingExtent1 = swingExtent1; + al.swingExtent2 = swingExtent2; + al.twistExtent = twistExtent; + expect(al.swingExtent1).toBe(swingExtent1); + expect(al.swingExtent2).toBe(swingExtent2); + expect(al.twistExtent).toBe(twistExtent); + + const swingSoft = false; + const swingStiffness = 1; + const swingDamping = 2; + const swingRestitution = 4; + al.enableSoftConstraintSwing = swingSoft; + al.swingDamping = swingDamping; + al.swingStiffness = swingStiffness; + al.swingRestitution = swingRestitution; + expect(al.enableSoftConstraintSwing).toBe(swingSoft); + expect(al.swingDamping).toBe(swingDamping); + expect(al.swingStiffness).toBe(swingStiffness); + expect(al.swingRestitution).toBe(swingRestitution); + + const twistSoft = true; + const twistStiffness = 1; + const twistDamping = 2; + const twistRestitution = 4; + al.enableSoftConstraintTwist = twistSoft; + al.twistDamping = twistDamping; + al.twistStiffness = twistStiffness; + al.twistRestitution = twistRestitution; + expect(al.enableSoftConstraintSwing).toBe(swingSoft); + expect(al.swingDamping).toBe(swingDamping); + expect(al.swingStiffness).toBe(swingStiffness); + expect(al.swingRestitution).toBe(swingRestitution); + + // driver + const linearTargetPosition = new Vec3(1, 1, 1); + const linearTargetVelocity = new Vec3(2, 2, 2); + const linearForceLimit = 4; + ld.targetPosition = linearTargetPosition; + ld.targetVelocity = linearTargetVelocity; + ld.strength = linearForceLimit; + expect(ld.targetPosition).toEqual(linearTargetPosition); + expect(ld.targetVelocity).toEqual(linearTargetVelocity); + expect(ld.strength).toBe(linearForceLimit); + + const angularTargetPosition = new Vec3(1, 1, 1); + const angularTargetVelocity = new Vec3(2, 2, 2); + const angularForceLimit = 4; + ad.targetOrientation = angularTargetPosition; + ad.targetVelocity = angularTargetVelocity; + ad.strength = angularForceLimit; + expect(ad.targetOrientation).toEqual(angularTargetPosition); + expect(ad.targetVelocity).toEqual(angularTargetVelocity); + expect(ad.strength).toBe(angularForceLimit); + } + child.removeComponent(cs); +} + +export default function (temp0: Node) { + testConfigurableConstraintAPIs(temp0); +} \ No newline at end of file diff --git a/tests/physics/physics.test.ts b/tests/physics/physics.test.ts index f376c6bbc8..6c64dde998 100644 --- a/tests/physics/physics.test.ts +++ b/tests/physics/physics.test.ts @@ -17,6 +17,7 @@ import StableTest from "./stability"; import VolumeTest from "./volume"; import FilterTest from "./filtering"; import DynamicTest from "./dynamic"; +import ConstraintTest from "./constraint"; import CharacterController from "./characterController"; import { Node, Scene } from "../../cocos/scene-graph"; import { builtinResMgr } from "../../exports/base"; @@ -81,6 +82,9 @@ for (const id in physics.selector.backend) { // test rigid body DynamicTest(temp0); + // test constraint + ConstraintTest(temp0); + // test character controller CharacterController(temp0); From 31c0e880f19ce62feaebb1248adf7efbcf83b0b2 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Fri, 19 May 2023 14:30:04 +0800 Subject: [PATCH 2/8] fix ao map should affected by ao intensity (#15112) --- editor/assets/effects/advanced/common-functions.chunk | 2 +- editor/assets/effects/builtin-standard.effect | 2 +- editor/assets/effects/legacy/standard.effect | 2 +- editor/assets/effects/util/dcc/vat/houdini-rigidbody-v2.effect | 2 +- editor/assets/effects/util/dcc/vat/houdini-softbody-v3.effect | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/editor/assets/effects/advanced/common-functions.chunk b/editor/assets/effects/advanced/common-functions.chunk index 3209f0ebc0..15be29c81a 100644 --- a/editor/assets/effects/advanced/common-functions.chunk +++ b/editor/assets/effects/advanced/common-functions.chunk @@ -79,7 +79,7 @@ pbr.x = 1.0; #if USE_PBR_MAP vec4 res = texture(pbrMap, DEFAULT_UV); - pbr.x *= res.OCCLUSION_CHANNEL; + pbr.x = mix(1.0, res.OCCLUSION_CHANNEL, pbrParams.x); pbr.y *= res.ROUGHNESS_CHANNEL; pbr.z *= res.METALLIC_CHANNEL; pbr.w *= res.SPECULAR_INTENSITY_CHANNEL; diff --git a/editor/assets/effects/builtin-standard.effect b/editor/assets/effects/builtin-standard.effect index aa8b65e7d3..9bca925d41 100644 --- a/editor/assets/effects/builtin-standard.effect +++ b/editor/assets/effects/builtin-standard.effect @@ -320,7 +320,7 @@ CCProgram surface-fragment %{ pbr.x = 1.0; #if USE_PBR_MAP vec4 res = texture(pbrMap, DEFAULT_UV); - pbr.x *= res.OCCLUSION_CHANNEL; + pbr.x = mix(1.0, res.OCCLUSION_CHANNEL, pbrParams.x); pbr.y *= res.ROUGHNESS_CHANNEL; pbr.z *= res.METALLIC_CHANNEL; pbr.w *= res.SPECULAR_INTENSITY_CHANNEL; diff --git a/editor/assets/effects/legacy/standard.effect b/editor/assets/effects/legacy/standard.effect index ac5fdcdf0c..774af1b268 100644 --- a/editor/assets/effects/legacy/standard.effect +++ b/editor/assets/effects/legacy/standard.effect @@ -329,7 +329,7 @@ CCProgram standard-fs %{ pbr.x = 1.0; #if USE_PBR_MAP vec4 res = texture(pbrMap, PBR_UV); - pbr.x *= res.OCCLUSION_CHANNEL; + pbr.x = mix(1.0, res.OCCLUSION_CHANNEL, pbrParams.x); pbr.y *= res.ROUGHNESS_CHANNEL; pbr.z *= res.METALLIC_CHANNEL; pbr.w *= res.SPECULAR_INTENSITY_CHANNEL; diff --git a/editor/assets/effects/util/dcc/vat/houdini-rigidbody-v2.effect b/editor/assets/effects/util/dcc/vat/houdini-rigidbody-v2.effect index a999a40600..34bc0b6d82 100644 --- a/editor/assets/effects/util/dcc/vat/houdini-rigidbody-v2.effect +++ b/editor/assets/effects/util/dcc/vat/houdini-rigidbody-v2.effect @@ -294,7 +294,7 @@ CCProgram surface-fragment %{ pbr.x = 1.0; #if USE_PBR_MAP vec4 res = texture(pbrMap, DEFAULT_UV); - pbr.x *= res.OCCLUSION_CHANNEL; + pbr.x = mix(1.0, res.OCCLUSION_CHANNEL, pbrParams.x); pbr.y *= res.ROUGHNESS_CHANNEL; pbr.z *= res.METALLIC_CHANNEL; pbr.w *= res.SPECULAR_INTENSITY_CHANNEL; diff --git a/editor/assets/effects/util/dcc/vat/houdini-softbody-v3.effect b/editor/assets/effects/util/dcc/vat/houdini-softbody-v3.effect index 4ef8bebadc..0a09914bc0 100644 --- a/editor/assets/effects/util/dcc/vat/houdini-softbody-v3.effect +++ b/editor/assets/effects/util/dcc/vat/houdini-softbody-v3.effect @@ -306,7 +306,7 @@ CCProgram surface-fragment %{ pbr.x = 1.0; #if USE_PBR_MAP vec4 res = texture(pbrMap, DEFAULT_UV); - pbr.x *= res.OCCLUSION_CHANNEL; + pbr.x = mix(1.0, res.OCCLUSION_CHANNEL, pbrParams.x); pbr.y *= res.ROUGHNESS_CHANNEL; pbr.z *= res.METALLIC_CHANNEL; pbr.w *= res.SPECULAR_INTENSITY_CHANNEL; From 22ea407cc776ed9bc3b5ac0ca04856688aa74609 Mon Sep 17 00:00:00 2001 From: dogeFu <609075410@qq.com> Date: Fri, 19 May 2023 15:56:26 +0800 Subject: [PATCH 3/8] fix: restore downloader limited value (#15107) --- cocos/asset/asset-manager/downloader.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/asset/asset-manager/downloader.ts b/cocos/asset/asset-manager/downloader.ts index 9862dbc800..005dac1f08 100644 --- a/cocos/asset/asset-manager/downloader.ts +++ b/cocos/asset/asset-manager/downloader.ts @@ -219,7 +219,7 @@ export class Downloader { /** * @engineInternal */ - public limited = !(EDITOR && !legacyCC.GAME_VIEW); + public limited = !EDITOR; /** * @en From adc0a95ae7c3bf84588acb82b5c93d20de96d139 Mon Sep 17 00:00:00 2001 From: AFeiYA <386665678@qq.com> Date: Fri, 19 May 2023 17:12:26 +0800 Subject: [PATCH 4/8] Add default vertex color (#15021) --- editor/i18n/en/assets.js | 4 ++++ editor/i18n/zh/assets.js | 4 ++++ editor/inspector/assets/fbx/model.js | 27 +++++++++++++++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/editor/i18n/en/assets.js b/editor/i18n/en/assets.js index e8a0287391..fa50b60a62 100644 --- a/editor/i18n/en/assets.js +++ b/editor/i18n/en/assets.js @@ -319,6 +319,10 @@ module.exports = { 'Indicate whether the mesh data in this model could be read or write.
' + 'If it is unchecked, the mesh data will be released after it is uploaded to GPU', }, + addVertexColor: { + name: 'Add Vertex Color', + title: 'Fill vertex color with white if the model file does not contain vertex color attribute.', + }, meshOptimizer: { name: 'Mesh Optimizer', title: 'Mesh Optimizer is used to simplify imported mesh.
Use it when you need to reduce model face count.
In some cases, face reduction could lead to various model defect.
Tweak properties and try again in those cases.', diff --git a/editor/i18n/zh/assets.js b/editor/i18n/zh/assets.js index 4e1ba01a54..67ee31df8f 100644 --- a/editor/i18n/zh/assets.js +++ b/editor/i18n/zh/assets.js @@ -317,6 +317,10 @@ module.exports = { '标识此模型中的所有网格的数据是否可被读写,此接口只对静态网格资源生效,
' + '若不勾选,网格数据被提交到 GPU 后会被自动释放。
', }, + addVertexColor: { + name: '填充顶点色', + title: '如果模型没有顶点颜色属性,添加颜色属性,填充为白色。', + }, meshOptimizer: { name: 'Mesh 优化', title: 'Mesh 优化可以被用来简化导入的模型,可以在需要模型减面时使用。
在一些少数情况下减面后的模型可能会出现显示异常,如发生这种情况请尝试调整参数并重试。', diff --git a/editor/inspector/assets/fbx/model.js b/editor/inspector/assets/fbx/model.js index c889b8708f..e48269da2d 100644 --- a/editor/inspector/assets/fbx/model.js +++ b/editor/inspector/assets/fbx/model.js @@ -28,6 +28,10 @@ exports.template = /* html */` + + + + @@ -268,6 +272,7 @@ exports.$ = { skipValidationCheckbox: '.skipValidation-checkbox', disableMeshSplitCheckbox: '.disableMeshSplit-checkbox', allowMeshDataAccessCheckbox: '.allowMeshDataAccess-checkbox', + addVertexColorCheckbox: '.addVertexColor-checkbox', promoteSingleRootNodeCheckbox: '.promoteSingleRootNode-checkbox', generateLightmapUVNodeCheckbox: '.generateLightmapUVNode-checkbox', meshOptimizerCheckbox: '.meshOptimizer-checkbox', @@ -432,6 +437,28 @@ const Elements = { updateElementReadonly.call(panel, panel.$.allowMeshDataAccessCheckbox); }, }, + addVertexColorCheckbox: { + ready() { + const panel = this; + + panel.$.addVertexColorCheckbox.addEventListener('change', panel.setProp.bind(panel, 'addVertexColor', 'boolean')); + panel.$.addVertexColorCheckbox.addEventListener('confirm', () => { + panel.dispatch('snapshot'); + }); + }, + update() { + const panel = this; + + let defaultValue = false; + if (panel.meta.userData) { + defaultValue = getPropValue.call(panel, panel.meta.userData.addVertexColor, defaultValue); + } + panel.$.addVertexColorCheckbox.value = defaultValue; + + updateElementInvalid.call(panel, panel.$.addVertexColorCheckbox, 'addVertexColor'); + updateElementReadonly.call(panel, panel.$.addVertexColorCheckbox); + }, + }, // move this from ./fbx.js in v3.6.0 promoteSingleRootNode: { ready() { From 51c41ead2023f838b1c1397c0f9e265716a998a9 Mon Sep 17 00:00:00 2001 From: AFeiYA <386665678@qq.com> Date: Fri, 19 May 2023 17:15:20 +0800 Subject: [PATCH 5/8] Use uuid for remap (#15001) --- editor/assets/primitives.fbx.meta | 2 +- editor/inspector/assets/fbx/material.js | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/editor/assets/primitives.fbx.meta b/editor/assets/primitives.fbx.meta index 84e672fdc5..abc533a3bb 100644 --- a/editor/assets/primitives.fbx.meta +++ b/editor/assets/primitives.fbx.meta @@ -1,5 +1,5 @@ { - "ver": "2.3.4", + "ver": "2.3.5", "importer": "fbx", "imported": true, "uuid": "1263d74c-8167-4928-91a6-4e2672411f47", diff --git a/editor/inspector/assets/fbx/material.js b/editor/inspector/assets/fbx/material.js index 4bbebfd4e4..68556f61f3 100644 --- a/editor/inspector/assets/fbx/material.js +++ b/editor/inspector/assets/fbx/material.js @@ -276,10 +276,9 @@ const Elements = { } url = asset.source; } - image.remapUuid = uuid; image.remap = url; - panel.meta.userData.imageMetas[index].remap = url; + panel.meta.userData.imageMetas[index].remap = uuid; const remapAsPropContentImg = remapAsPropContent.querySelector('.image'); From 4a17955046616830f71edb672284e8adbcba3b57 Mon Sep 17 00:00:00 2001 From: Myway Date: Fri, 19 May 2023 18:10:26 +0800 Subject: [PATCH 6/8] Support enable/disable light map in editor (#15123) --- cocos/3d/framework/mesh-renderer.ts | 18 +++++++++++++----- cocos/render-scene/scene/model.ts | 18 ++++++++---------- cocos/rendering/scene-culling.ts | 4 ++-- cocos/scene-graph/scene-globals.ts | 6 ++++++ 4 files changed, 29 insertions(+), 17 deletions(-) diff --git a/cocos/3d/framework/mesh-renderer.ts b/cocos/3d/framework/mesh-renderer.ts index adcc3ab25f..cf2f620da1 100644 --- a/cocos/3d/framework/mesh-renderer.ts +++ b/cocos/3d/framework/mesh-renderer.ts @@ -855,11 +855,19 @@ export class MeshRenderer extends ModelRenderer { if (!mainLight) { return; } const visibility = mainLight.visibility; if (!mainLight.node) { return; } - if (mainLight.node.mobility === MobilityMode.Static - && (this.bakeSettings.texture || (this.node.scene.globals.lightProbeInfo.data - && this.node.scene.globals.lightProbeInfo.data.hasCoefficients() - && this._model.useLightProbe))) { - this.onUpdateReceiveDirLight(visibility, true); + + if (mainLight.node.mobility === MobilityMode.Static) { + let forceClose = false; + if (this.bakeSettings.texture && !this.node.scene.globals.disableLightmap) { + forceClose = true; + } + if (this.node.scene.globals.lightProbeInfo.data + && this.node.scene.globals.lightProbeInfo.data.hasCoefficients() + && this._model.useLightProbe) { + forceClose = true; + } + + this.onUpdateReceiveDirLight(visibility, forceClose); } else { this.onUpdateReceiveDirLight(visibility); } diff --git a/cocos/render-scene/scene/model.ts b/cocos/render-scene/scene/model.ts index 5b6151e9ff..41209baf06 100644 --- a/cocos/render-scene/scene/model.ts +++ b/cocos/render-scene/scene/model.ts @@ -1153,17 +1153,15 @@ export class Model { public getMacroPatches (subModelIndex: number): IMacroPatch[] | null { let patches = this.receiveShadow ? shadowMapPatches : null; if (this._lightmap != null) { - let stationary = false; - if (this.node && this.node.scene) { - stationary = this.node.scene.globals.bakedWithStationaryMainLight; - } + if (this.node && this.node.scene && !this.node.scene.globals.disableLightmap) { + const mainLightIsStationary = this.node.scene.globals.bakedWithStationaryMainLight; + const lightmapPathes = mainLightIsStationary ? stationaryLightMapPatches : staticLightMapPatches; - const lightmapPathes = stationary ? stationaryLightMapPatches : staticLightMapPatches; - patches = patches ? patches.concat(lightmapPathes) : lightmapPathes; - - // use highp lightmap - if (this.node.scene.globals.bakedWithHighpLightmap) { - patches = patches.concat(highpLightMapPatches); + patches = patches ? patches.concat(lightmapPathes) : lightmapPathes; + // use highp lightmap + if (this.node.scene.globals.bakedWithHighpLightmap) { + patches = patches.concat(highpLightMapPatches); + } } } if (this._useLightProbe) { diff --git a/cocos/rendering/scene-culling.ts b/cocos/rendering/scene-culling.ts index 6d3ba30e53..968f90a5bd 100644 --- a/cocos/rendering/scene-culling.ts +++ b/cocos/rendering/scene-culling.ts @@ -59,7 +59,7 @@ export function validPunctualLightsCulling (pipeline: RenderPipeline, camera: Ca const { spotLights } = camera.scene!; for (let i = 0; i < spotLights.length; i++) { const light = spotLights[i]; - if (light.baked) { + if (light.baked && !camera.node.scene.globals.disableLightmap) { continue; } @@ -72,7 +72,7 @@ export function validPunctualLightsCulling (pipeline: RenderPipeline, camera: Ca const { sphereLights } = camera.scene!; for (let i = 0; i < sphereLights.length; i++) { const light = sphereLights[i]; - if (light.baked) { + if (light.baked && !camera.node.scene.globals.disableLightmap) { continue; } geometry.Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); diff --git a/cocos/scene-graph/scene-globals.ts b/cocos/scene-graph/scene-globals.ts index fe49776a15..e492eac3fc 100644 --- a/cocos/scene-graph/scene-globals.ts +++ b/cocos/scene-graph/scene-globals.ts @@ -1617,6 +1617,12 @@ export class SceneGlobals { @serializable public bakedWithHighpLightmap = false; + /** + * @en disable light map + * @zh 关闭光照图效果 + */ + public disableLightmap = false; + /** * @en Activate and initialize the global configurations of the scene, no need to invoke manually. * @zh 启用和初始化场景全局配置,不需要手动调用 From 998869fbb4a6395d86473f7591d1aa76584fc68e Mon Sep 17 00:00:00 2001 From: troublemaker52025 Date: Fri, 19 May 2023 18:10:48 +0800 Subject: [PATCH 7/8] add tone mapping for post-process pipeline (#15122) --- cocos/rendering/post-process/passes/index.ts | 1 + .../post-process/passes/tone-mapping-pass.ts | 68 +++++++++++++++++++ .../post-process/post-process-builder.ts | 11 ++- 3 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 cocos/rendering/post-process/passes/tone-mapping-pass.ts diff --git a/cocos/rendering/post-process/passes/index.ts b/cocos/rendering/post-process/passes/index.ts index e403288cd5..d8e08a3389 100644 --- a/cocos/rendering/post-process/passes/index.ts +++ b/cocos/rendering/post-process/passes/index.ts @@ -8,3 +8,4 @@ export * from './color-grading-pass'; export * from './bloom-pass'; export * from './fxaa-pass'; export * from './forward-final-pass'; +export * from './tone-mapping-pass'; diff --git a/cocos/rendering/post-process/passes/tone-mapping-pass.ts b/cocos/rendering/post-process/passes/tone-mapping-pass.ts new file mode 100644 index 0000000000..d82caa414d --- /dev/null +++ b/cocos/rendering/post-process/passes/tone-mapping-pass.ts @@ -0,0 +1,68 @@ +/* + Copyright (c) 2023 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 { cclegacy, Vec4 } from '../../../core'; +import { ClearFlagBit, Format } from '../../../gfx'; +import { Camera } from '../../../render-scene/scene'; +import { Root } from '../../../root'; +import { Pipeline } from '../../custom'; +import { getCameraUniqueID } from '../../custom/define'; +import { passContext } from '../utils/pass-context'; + +import { SettingPass } from './setting-pass'; + +export class ToneMappingPass extends SettingPass { + name = 'ToneMappingPass' + effectName = 'pipeline/tone-mapping'; + outputNames = ['ToneMapping'] + + checkEnable (camera: Camera) { + let enable = true; + const ppl = (cclegacy.director.root as Root).pipeline; + if (!ppl.pipelineSceneData.isHDR || !ppl.getMacroBool('CC_USE_FLOAT_OUTPUT')) { + enable = false; + } + return enable; + } + + public render (camera: Camera, ppl: Pipeline): void { + const cameraID = getCameraUniqueID(camera); + passContext.material = this.material; + + const input = this.lastPass!.slotName(camera, 0); + const output = this.slotName(camera, 0); + const layoutName = 'tone-mapping'; + const passName = `tone-mapping${cameraID}`; + const passIndx = 0; + + passContext.clearFlag = ClearFlagBit.COLOR; + Vec4.set(passContext.clearColor, camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w); + passContext.updatePassViewPort() + .addRenderPass(layoutName, passName) + .setPassInput(input, 'u_texSampler') + .addRasterView(output, Format.RGBA8) + .blitScreen(passIndx) + .version(); + } +} diff --git a/cocos/rendering/post-process/post-process-builder.ts b/cocos/rendering/post-process/post-process-builder.ts index 79299ac8c1..8ce3b9c1d4 100644 --- a/cocos/rendering/post-process/post-process-builder.ts +++ b/cocos/rendering/post-process/post-process-builder.ts @@ -22,7 +22,7 @@ import { CCObject } from '../../core'; import { setCustomPipeline } from '../custom'; import { CameraComponent } from '../../misc'; -import { BloomPass, ColorGradingPass, FxaaPass } from './passes'; +import { BloomPass, ColorGradingPass, FxaaPass, ToneMappingPass } from './passes'; export class PostProcessBuilder implements PipelineBuilder { pipelines: Map = new Map(); @@ -38,17 +38,24 @@ export class PostProcessBuilder implements PipelineBuilder { this.addPass(forward, 'default'); this.addPass(forwardFinal, 'default'); - // forward pipeline + // rendering dependent data generation this.addPass(new ShadowPass()); + + // forward pipeline this.addPass(forward); + // pipeline related this.addPass(new HBAOPass()); + this.addPass(new ToneMappingPass()); + + // user post-processing this.addPass(new TAAPass()); this.addPass(new FxaaPass()); this.addPass(new ColorGradingPass()); this.addPass(new BlitScreenPass()); this.addPass(new BloomPass()); + // final output this.addPass(new FSRPass()); // fsr should be final this.addPass(forwardFinal); } From 6b2a2d1859b184f4b9c71afc287942b0f42f6b2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Fri, 19 May 2023 19:48:44 +0800 Subject: [PATCH 8/8] Enhance i18n configuration (#15119) * Enhance i18n configuration * Fix --- editor/i18n-utils.js | 131 +++++++++++++++++++++++++++++++++ editor/i18n/en/animation.js | 11 +++ editor/i18n/en/localization.js | 15 +++- editor/i18n/zh/animation.js | 11 +++ editor/i18n/zh/localization.js | 15 +++- 5 files changed, 179 insertions(+), 4 deletions(-) create mode 100644 editor/i18n-utils.js create mode 100644 editor/i18n/en/animation.js create mode 100644 editor/i18n/zh/animation.js diff --git a/editor/i18n-utils.js b/editor/i18n-utils.js new file mode 100644 index 0000000000..3cc7af6067 --- /dev/null +++ b/editor/i18n-utils.js @@ -0,0 +1,131 @@ +module.exports.mixin = function(result, ...args) { + for (const arg of args) { + mixinObject(result, arg); + } + return result; +}; + +module.exports.link = function(root) { + const visited = new Set(); + + link(root); + + return root; + + function link(o) { + if (visited.has(o)) { + return; + } + visited.add(o); + + const __extends__ = o.__extends__; + const extended = {}; + if (typeof __extends__ === 'string') { + const base = find(__extends__); + if (!base) { + console.error(`Can not find the __extends__ ${__extends__}`); + } else { + link(base); + mixinObject(extended, base); + } + } + + for (const [k, v] of Object.entries(o)) { + if (typeof v === 'object' && v) { + link(v); + } + } + + mixinObject(o, extended); + } + + function find(path) { + const items = path.split('.'); + if (items.length === 0) { + return undefined; + } + let result = root; + for (const item of items) { + if (!item) { + return undefined; + } + if (!(item in result)) { + return undefined; + } + const r = result[item]; + if (typeof r !== 'object' || !r) { + return undefined; + } + result = r; + } + return result; + } +}; + +function mixinObject(o1, o2, o1FullPath, o2FullPath) { + for (const [k, v2] of Object.entries(o2)) { + if (typeof v2 !== 'object' || !v2) { + if (k in o1) { + reportMixinFailure(k); + } else { + o1[k] = v2; + } + continue; + } + + if (Array.isArray(v2)) { + let v1; + if (!(k in o1)) { + v1 = o1[k] = []; + } else if (Array.isArray(o1[k])) { + v1 = o1[k]; + } else { + reportMixinFailure(k); + continue; + } + v1.push(...v2); + continue; + } + + // v2 is object + { + let v1; + if (!(k in o1)) { + v1 = o1[k] = {}; + } else { + v1 = o1[k]; + if (typeof v1 !== 'object' || !v1) { + reportMixinFailure(k); + continue; + } + } + mixinObject(v1, v2, getFullPath(o1FullPath, k), getFullPath(o2FullPath, k)); + continue; + } + } + + function reportMixinFailure(k) { + console.error( + `Can not mix ` + + `${getFullPath(o2FullPath, k)}(type: ${getLogType(o2[k])}) ` + + `into ` + + `${getFullPath(o1FullPath, k)}(type: ${getLogType(o1[k])})` + ); + } + + function getFullPath(prefix, k) { + return `${prefix}['${k}']`; + } + + function getLogType(v) { + if (typeof v !== 'object') { + return typeof v; + } else if (!v) { + return 'null'; + } else if (Array.isArray(v)) { + return 'array'; + } else { + return 'object'; + } + } +} diff --git a/editor/i18n/en/animation.js b/editor/i18n/en/animation.js new file mode 100644 index 0000000000..a79de0df6d --- /dev/null +++ b/editor/i18n/en/animation.js @@ -0,0 +1,11 @@ +/* eslint-disable quote-props */ + +module.exports = { + classes: { + 'cc': { + 'animation': { + + }, + }, + }, +}; diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 6a3984edde..70b6715b8f 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -1,11 +1,18 @@ +/* eslint-disable quote-props */ const pkg = require('../../../package.json'); +const { mixin, link } = require('../../i18n-utils'); const version = pkg.version.replace(/(^\d+\.\d+)\..*$/, (str, a) => { return a; }); const url = 'https://docs.cocos.com/creator'; -module.exports = { +module.exports = link(mixin({ + + classes: { + 'cc': { }, + }, + help: { cc: { Node: `${url}/${version}/manual/en/concepts/scene/node-component.html`, @@ -1227,4 +1234,8 @@ module.exports = { color_grading: { originalMap: 'The builtin lut texture path is internal/dependencies/textures/lut/.', }, -}; +}, + +require('./animation'), + +)); diff --git a/editor/i18n/zh/animation.js b/editor/i18n/zh/animation.js new file mode 100644 index 0000000000..a79de0df6d --- /dev/null +++ b/editor/i18n/zh/animation.js @@ -0,0 +1,11 @@ +/* eslint-disable quote-props */ + +module.exports = { + classes: { + 'cc': { + 'animation': { + + }, + }, + }, +}; diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index 11d7291b01..d8f3665405 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -1,11 +1,18 @@ +/* eslint-disable quote-props */ const pkg = require('../../../package.json'); +const { mixin, link } = require('../../i18n-utils'); const version = pkg.version.replace(/(^\d+\.\d+)\..*$/, (str, a) => { return a; }); const url = 'https://docs.cocos.com/creator'; -module.exports = { +module.exports = link(mixin({ + + classes: { + 'cc': { }, + }, + help: { cc: { Node: `${url}/${version}/manual/zh/concepts/scene/node-component.html`, @@ -1208,4 +1215,8 @@ module.exports = { color_grading: { originalMap: '内置lut贴图路径internal/dependencies/textures/lut/。', }, -}; +}, + +require('./animation'), + +));