Support box2d JS binding which improves the performance of 2D physical system for native platforms . (#18152)

This commit is contained in:
tangkai
2025-02-24 19:22:06 +08:00
committed by GitHub
parent f19bdb1290
commit b08a406d07
43 changed files with 4963 additions and 3 deletions
@@ -190,6 +190,7 @@ jobs:
echo "set(CC_USE_GLES3 ON)" >> build-android/proj/cfg.cmake
echo "set(CC_USE_VULKAN ON)" >> build-android/proj/cfg.cmake
echo "set(CC_USE_GLES2 ON)" >> build-android/proj/cfg.cmake
echo "set(USE_BOX2D_JSB ON)" >> build-android/proj/cfg.cmake
echo "set(USE_WEBSOCKET_SERVER ON)" >> build-android/proj/cfg.cmake
echo "set(CMAKE_CXX_STANDARD_REQUIRED ON)" >> build-android/proj/cfg.cmake
echo "set(COCOS_X_PATH $NATIVE_ROOT)" >> build-android/proj/cfg.cmake
+789
View File
@@ -0,0 +1,789 @@
declare namespace b2jsb {
const maxPolygonVertices: number;
export interface XY {
x: number;
y: number;
}
class Vec2 implements XY {
x: number;
y: number;
constructor();
constructor(data: Float32Array);
constructor(x: number, y: number);
constructor(...args: any[]);
Clone(): Vec2;
SetZero(): Vec2;
Set(): Vec2;
Copy(): Vec2;
SelfAdd(): Vec2;
SelfAddXY(): Vec2;
SelfSub(): Vec2;
SelfSubXY(): Vec2;
SelfMul(): Vec2;
SelfMulAdd(): Vec2;
SelfMulSub(): Vec2;
Dot(): any;
Cross(): any;
Length(): any;
LengthSquared(): any;
Normalize(): any;
SelfNormalize(): Vec2;
SelfRotate(): Vec2;
IsValid(): any;
SelfCrossVS(): Vec2;
SelfCrossSV(): Vec2;
SelfMinV(): Vec2;
SelfMaxV(): Vec2;
SelfAbs(): Vec2;
SelfNeg(): Vec2;
SelfSkew(): Vec2;
MakeArray(): any;
AbsV(): any;
MinV(): any;
MaxV(): any;
ClampV(): any;
RotateV(): any;
DotVV(): any;
CrossVV(): any;
CrossVS(): any;
CrossVOne(): any;
CrossSV(): any;
CrossOneV(): any;
AddVV(a, b, out): any;
SubVV(a, b, out): any;
MulSV(s, v, out): any;
MulVS(v, s, out): any;
AddVMulSV(a, s, b, out): any;
SubVMulSV(a, s, b, out): any;
AddVCrossSV(a, s, v, out): any;
MidVV(a, b, out): any;
ExtVV(a, b, out): any;
IsEqualToV(a, b): any;
DistanceVV(a, b): any;
DistanceSquaredVV(a, b): any;
NegV(v, out): any;
}
export enum b2ManifoldType {
e_unknown = -1,
e_circles = 0,
e_faceA = 1,
e_faceB = 2,
}
class Manifold {
readonly points: b2ManifoldPoint[];
readonly localNormal: Vec2;
readonly localPoint: Vec2;
type: b2ManifoldType;
pointCount: number;
Reset (): void;
Copy (o: Manifold): Manifold;
Clone(): Manifold;
}
class ContactID {
readonly cf: any;
Copy(o: ContactID): ContactID ;
Clone(): ContactID;
get key(): number;
set key(value: number);
}
class b2ManifoldPoint {
readonly localPoint: Vec2; ///< usage depends on manifold type
normalImpulse: number; ///< the non-penetration impulse
tangentImpulse: number; ///< the friction impulse
readonly id: ContactID; ///< uniquely identifies a contact point between two shapes
static MakeArray (length: number): b2ManifoldPoint[];
Reset (): void;
Copy (o: b2ManifoldPoint): b2ManifoldPoint;
}
export interface Vec2Vector {
push_back(v: Vec2): void;
get(i: number): Vec2;
size(): number;
}
export interface Int32Vector {
push_back(v: number): void;
get(i: number): number;
size(): number;
}
export interface MassData {
mass: number;
center: Vec2;
I: number;
}
class b2Rot {
s: number;
c: number;
constructor(angle) ;
Clone(): b2Rot;
Copy(angle: b2Rot): b2Rot;
SetAngle(angle);
SetIdentity(): b2Rot;
GetAngle(): number;
GetXAxis(out): b2Rot;
GetYAxis(out): b2Rot;
MulRR(q, r, out): any;
MulTRR(q, r, out): any;
MulRV(q, v, out): any;
MulTRV(q, v, out): any;
IDENTITY: b2Rot;
}
export class Transform {
static MulXV(_xf: any, center: any, _tmp_vec2: any): any;
constructor();
p: Vec2;
q: b2Rot;
}
const _tempFloatArray: Float32Array; // For other ts file in box2d-jsb module to access this arraybuffer.
function _setTempFloatArray(_array: any);
class AABB {
constructor();
lowerBound: any;
upperBound: any;
IsValid(): boolean;
GetCenter(): Vec2;
GetExtents(): Vec2;
GetPerimeter(): number;
Combine(aabb: AABB): void;
CombineTwo(aabb1: AABB, aabb2: AABB): void;
Contains(aabb: AABB): boolean;
RayCast(output: RayCastOutput, input: RayCastInput): boolean;
TestOverlap(other: AABB): boolean;
}
class RayCastCallback {
initWithThis(thisObj: RayCastCallback);
constructor();
ReportFixture(fixture, point, normal, fraction): number;
// #if B2_ENABLE_PARTICLE
ReportParticle(system, index, point, normal, fraction): number;
ShouldQueryParticleSystem(system): boolean;
}
class QueryCallback {
initWithThis(thisObj: QueryCallback);
constructor();
ReportFixture(fixture: Fixture): boolean;
}
export interface RayCastInput {
p1: Vec2;
p2: Vec2;
maxFraction: number;
}
export interface RayCastOutput {
normal: Vec2;
fraction: number;
}
export class Filter {
constructor();
categoryBits: number;
maskBits: number;
groupIndex: number;
}
class ContactListener {
initWithThis(param: any);
constructor();
BeginContact(contact: Contact): void;
EndContact(contact: Contact): void;
PreSolve(contact: Contact, oldManifold: Manifold): void;
PostSolve(contact: Contact, impulse: ContactImpulse): void;
registerContactFixture(fixture: Fixture): void;
unregisterContactFixture(fixture: Fixture): void;
isIndexOf(fixture: Fixture): void;
}
/// Friction mixing law. The idea is to allow either fixture to drive the friction to zero.
/// For example, anything slides on ice.
function b2MixFriction(friction1: number, friction2: number): number;
/// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface.
/// For example, a superball bounces on anything.
function b2MixRestitution(restitution1: number, restitution2: number): number;
class ContactEdge {
_other: Body | null; ///< provides quick access to the other body attached.
get other(): Body;
set other(value: Body);
readonly contact: Contact; ///< the contact
prev: ContactEdge | null; ///< the previous contact edge in the body's contact list
next: ContactEdge | null; ///< the next contact edge in the body's contact list
constructor(contact: Contact);
Reset(): void;
}
class WorldManifold {
readonly normal: Vec2;
readonly points: Vec2[];
readonly separations: number[];
static Initialize_s_pointA;
static Initialize_s_pointB;
static Initialize_s_cA;
static Initialize_s_cB;
static Initialize_s_planePoint;
static Initialize_s_clipPoint;
Initialize(manifold: Manifold, xfA: Transform, radiusA: number, xfB: Transform, radiusB: number): void ;
}
class Color {
constructor (rIn?: number, gIn?: number, bIn?: number, aIn?: number);
Set (rIn?: number, gIn?: number, bIn?: number, aIn?: number): void;
declare r: number;
declare g: number;
declare b: number;
declare a: number;
}
export abstract class Contact<A extends Shape = Shape, B extends Shape = Shape> {
m_islandFlag: boolean; /// Used when crawling contact graph when forming islands.
m_touchingFlag: boolean; /// Set when the shapes are touching.
m_enabledFlag: boolean; /// This contact can be disabled (by user)
m_filterFlag: boolean; /// This contact needs filtering because a fixture filter was changed.
m_bulletHitFlag: boolean; /// This bullet contact had a TOI event
m_toiFlag: boolean; /// This contact has a valid TOI in m_toi
m_prev: Contact | null;
m_next: Contact | null;
readonly m_nodeA: ContactEdge;
readonly m_nodeB: ContactEdge;
m_fixtureA: Fixture;
m_fixtureB: Fixture;
m_indexA: number;
m_indexB: number;
m_manifold: Manifold; // TODO: readonly
m_toiCount: number;
m_toi: number;
m_friction: number;
m_restitution: number;
m_tangentSpeed: number;
m_oldManifold: Manifold; // TODO: readonly
GetManifold() ;
GetWorldManifold(worldManifold: any): void;
IsTouching(): boolean ;
SetEnabled(flag: any);
IsEnabled();
GetNext(): Contact | null;
GetFixtureA(): Fixture ;
GetChildIndexA(): number ;
GetShapeA(): A ;
GetFixtureB(): Fixture ;
GetChildIndexB(): number;
GetShapeB(): B;
abstract Evaluate(manifold: Manifold, xfA: Transform, xfB: Transform): void;
FlagForFiltering(): void;
SetFriction(friction: any): void;
GetFriction(): number;
ResetFriction(): void;
SetRestitution(restitution: any): void;
GetRestitution(): number;
ResetRestitution(): void;
SetTangentSpeed(speed: any): void;
GetTangentSpeed(): number;
Reset(fixtureA: Fixture, indexA: number, fixtureB: Fixture, indexB: number): void ;
}
class Draw {
initWithThis(param: any);
constructor();
SetFlags(flags: number): void;
GetFlags(): number;
AppendFlags(flags: number): void;
ClearFlags(flags: number): void;
DrawPolygon(vertices: Vec2[], vertexCount: number, color: Color): void;
DrawSolidPolygon(vertices: Vec2[], vertexCount: number, color: Color): void;
DrawCircle(center: Vec2, radius: number, color: Color): void;
DrawSolidCircle(center: Vec2, radius: number, axis: Vec2, color: Color): void;
}
export interface ContactImpulse {
count: number;
normalImpulses: number[];
/**
* @en
* Tangent impulses.
* @zh
* 切线方向的冲量。
* @property tangentImpulses
*/
tangentImpulses: number[];
}
class World {
constructor(gravity: Vec2);
DrawDebugData(): void;
SetContactListener(listener: any): void;
SetDebugDraw(debugDraw: Draw): void;
CreateBody(def: BodyDef): Body;
DestroyBody(body: Body): void;
CreateJoint(def: JointDef): Joint;
DestroyJoint(joint: Joint|null): void;
Step(timeStep: number, velocityIterations: number, positionIterations: number): void;
DebugDraw(): void;
QueryAABB(callback: QueryCallback, aabb: AABB): void;
RayCast(callback: RayCastCallback, point1: any, point2: any): void;
SetAllowSleeping(flag: boolean): void;
GetAllowSleeping(): boolean;
SetGravity(gravity: Vec2): void;
GetGravity(): Vec2;
Dump(): void;
}
class Shape {
m_type: number;
m_radius: number;
GetType(): number;
GetChildCount(): number;
TestPoint(xf: Transform, p: Vec2): boolean;
RayCast(output: RayCastOutput, input: RayCastInput, transform: Transform, childIndex: number): boolean;
ComputeAABB(aabb: AABB, xf: Transform, childIndex: number): void;
ComputeMass(massData: MassData, density: number): void;
SetRadius(radius: number): void;
GetRadius(): number;
}
class CircleShape extends Shape {
constructor();
m_p: any;
Clone(): CircleShape;
GetChildCount(): number;
TestPoint(transform: Transform, p: Vec2): boolean;
RayCast(output: RayCastOutput, input: RayCastInput, transform: Transform, childIndex: number): boolean;
ComputeAABB(aabb: AABB, transform: Transform, childIndex: number): void;
ComputeMass(massData: MassData, density: number): void;
}
class EdgeShape extends Shape {
constructor();
Set(v1: Vec2, v2: Vec2): void;
Clone(): EdgeShape;
GetChildCount(): number;
TestPoint(transform: Transform, p: Vec2): boolean;
RayCast(output: RayCastOutput, input: RayCastInput, transform: Transform, childIndex: number): boolean;
ComputeAABB(aabb: AABB, transform: Transform, childIndex: number): void;
ComputeMass(massData: MassData, density: number): void;
}
class PolygonShape extends Shape {
constructor();
Clone(): PolygonShape;
Set(vertices: any, count: number): void;
SetAsBox(hx: number, hy: number): void;
SetAsBox(hx: number, hy: number, p: Vec2, px: number): void;
SetAsBoxWithCenterAndAngle(hx: number, hy: number, center: Vec2, angle: number): void;
GetChildCount(): number;
TestPoint(transform: Transform, p: Vec2): boolean;
RayCast(output: RayCastOutput, input: RayCastInput, transform: Transform, childIndex: number): boolean;
ComputeAABB(aabb: AABB, transform: Transform, childIndex: number): void;
ComputeMass(massData: MassData, density: number): void;
Validate(): boolean;
}
class FixtureDef {
shape: Shape;
userData: any;
friction: number;
restitution: number;
density: number;
isSensor: boolean;
filter: Filter;
SetShape(shape: Shape): void;
GetShape(): Shape;
}
class Fixture {
m_userData: any;
GetType(): number;
GetShape(): Shape;
SetSensor(sensor: boolean): void;
IsSensor(): boolean;
SetFilterData(filter: any): void;
GetFilterData(): Filter;
Refilter(): void;
GetBody(): Body;
GetNext(): Fixture;
TestPoint(p: Vec2): boolean;
RayCast(output: RayCastOutput, input: RayCastInput, childIndex: number): boolean;
GetMassData(massData: MassData): void;
SetDensity(density: number): void;
GetDensity(): number;
GetFriction(): number;
SetFriction(friction: number): void;
GetRestitution(): number;
SetRestitution(restitution: number): void;
GetAABB(childIndex: number): AABB;
Dump(bodyIndex: number): void;
}
enum BodyType{
b2_staticBody = 0,
b2_kinematicBody,
b2_dynamicBody,
cc_animatedBody,
}
class BodyDef {
constructor();
type: BodyType;
position: Vec2;
angle: number;
linearVelocity: Vec2;
angularVelocity: number;
linearDamping: number;
angularDamping: number;
allowSleep: boolean;
awake: boolean;
fixedRotation: boolean;
bullet: boolean;
gravityScale: number;
}
class Body {
m_userData: any;
_SetTransformJSB();
_SetPositionJSB();
_SetAngleJSB();
_GetTransformJSB(): any;
CreateFixture (fixtureDef: FixtureDef): Fixture;
CreateFixtureWithShape (shape: Shape, density: number): Fixture;
DestroyFixture(fixture: Fixture): void;
SetTransform(position: Vec2, angle: number): void;
GetTransform(): Transform;
GetPosition(): Vec2;
SetPosition(pos: Vec2): void;
GetAngle(): number;
SetAngle(angle: number): void;
GetWorldCenter(): Vec2;
GetLocalCenter(): Vec2;
SetLinearVelocity(v: Vec2): void;
GetLinearVelocity(): Vec2;
SetAngularVelocity(omega: number): void;
GetAngularVelocity(): number;
ApplyForce(force: Vec2, point: Vec2, wake: boolean): void;
ApplyForceToCenter(force: Vec2, wake: boolean): void;
ApplyTorque(torque: number, wake: boolean): void;
ApplyLinearImpulse(impulse: Vec2, point: Vec2, wake: boolean): void;
ApplyLinearImpulseToCenter(impulse: Vec2, wake: boolean): void;
ApplyAngularImpulse(impulse: number, wake: boolean): void;
GetMass(): number;
GetInertia(): number;
GetMassData(data: MassData): void;
SetMassData(data: MassData): void;
ResetMassData(): void;
GetWorldPoint(localPoint: Vec2): Vec2;
GetWorldVector(localVector: Vec2): Vec2;
GetLocalPoint(worldPoint: Vec2): Vec2;
GetLocalVector(worldVector: Vec2): Vec2;
GetLinearVelocityFromWorldPoint(worldPoint: Vec2): Vec2;
GetLinearVelocityFromLocalPoint(localPoint: Vec2): Vec2;
GetLinearDamping(): number;
SetLinearDamping(linearDamping: number): void;
GetAngularDamping(): number;
SetAngularDamping(angularDamping: number): void;
GetGravityScale(): number;
SetGravityScale(scale: number): void;
SetType(type: BodyType): void;
GetType(): BodyType;
SetBullet(flag: boolean): void;
IsBullet(): boolean;
SetSleepingAllowed(flag: boolean): void;
IsSleepingAllowed(): boolean;
SetAwake(flag: boolean): void;
IsAwake(): boolean;
SetEnabled(flag: boolean): void;
IsEnabled(): boolean;
SetFixedRotation(flag: boolean): void;
IsFixedRotation(): boolean;
GetFixtureList(): number;
GetJointList(): number;
GetWorld(): World;
Dump(): void;
}
enum JointType {
e_unknownJoint,
e_revoluteJoint,
e_prismaticJoint,
e_distanceJoint,
e_pulleyJoint,
e_mouseJoint,
e_gearJoint,
e_wheelJoint,
e_weldJoint,
e_frictionJoint,
e_ropeJoint,
e_motorJoint
}
class JointDef {
constructor(type: JointType);
type: JointType;
collideConnected: boolean;
bodyA: any;
bodyB: any;
SetBodyA(bodyA: Body): void;
SetBodyB(bodyB: Body): void;
GetBodyA(): Body;
GetBodyB(): Body;
SetCollideConnected(flag: boolean): void;
}
class Joint {
GetType(): JointType;
GetBodyA(): Body;
GetBodyB(): Body;
GetAnchorA(): Vec2;
GetAnchorB(): Vec2;
GetReactionForce(inv_dt: number): Vec2;
GetReactionTorque(inv_dt: number): number;
IsActive(): boolean;
GetCollideConnected(): boolean;
Dump(): void;
}
class DistanceJointDef extends JointDef {
constructor();
localAnchorA: any;
localAnchorB: any;
length: number;
frequencyHz: number;
dampingRatio: number;
}
class DistanceJoint extends Joint {
GetLocalAnchorA(): Vec2;
GetLocalAnchorB(): Vec2;
SetLength(length: number): void;
GetLength(): number;
SetFrequency(hz: number): void;
GetFrequency(): number;
SetDampingRatio(ratio: number): void;
GetDampingRatio(): number;
Dump(): void;
}
class MotorJointDef extends JointDef {
constructor();
linearOffset: any;
angularOffset: number;
maxForce: number;
maxTorque: number;
correctionFactor: number;
}
class MotorJoint extends Joint {
m_correctionFactor: any;
SetLinearOffset(linearOffset: Vec2): void;
GetLinearOffset(): Vec2;
SetAngularOffset(angularOffset: number): void;
GetAngularOffset(): number;
SetMaxForce(force: number): void;
GetMaxForce(): number;
SetMaxTorque(torque: number): void;
GetMaxTorque(): number;
SetCorrectionFactor(factor: number): void;
GetCorrectionFactor(): number;
Dump(): void;
}
class MouseJointDef extends JointDef {
constructor();
target: Vec2;
maxForce: number;
frequencyHz: number;
dampingRatio: number;
}
class MouseJoint extends Joint {
SetTarget(target: Vec2): void;
GetTarget(): Vec2;
SetMaxForce(force: number): void;
GetMaxForce(): number;
SetFrequency(hz: number): void;
GetFrequency(): number;
SetDampingRatio(ratio: number): void;
GetDampingRatio(): number;
Dump(): void;
}
class PrismaticJointDef extends JointDef {
constructor();
localAnchorA: any;
localAnchorB: any;
localAxisA: any;
referenceAngle: number;
enableLimit: boolean;
lowerTranslation: number;
upperTranslation: number;
enableMotor: boolean;
maxMotorForce: number;
motorSpeed: number;
}
class PrismaticJoint extends Joint {
GetLocalAnchorA(): Vec2;
GetLocalAnchorB(): Vec2;
GetLocalAxisA(): Vec2;
GetReferenceAngle(): number;
GetJointTranslation(): number;
GetJointSpeed(): number;
IsLimitEnabled(): boolean;
EnableLimit(flag: boolean): void;
GetLowerLimit(): number;
GetUpperLimit(): number;
SetLimits(lower: number, upper: number): void;
IsMotorEnabled(): boolean;
EnableMotor(flag: boolean): void;
SetMotorSpeed(speed: number): void;
GetMotorSpeed(): number;
SetMaxMotorForce(force: number): void;
GetMaxMotorForce(): number;
GetMotorForce(inv_dt: number): number;
Dump(): void;
}
class RevoluteJointDef extends JointDef {
constructor();
localAnchorA: any;
localAnchorB: any;
referenceAngle: number;
enableLimit: boolean;
lowerAngle: number;
upperAngle: number;
enableMotor: boolean;
motorSpeed: number;
maxMotorTorque: number;
}
class RevoluteJoint extends Joint {
GetLocalAnchorA(): Vec2;
GetLocalAnchorB(): Vec2;
GetReferenceAngle(): number;
GetJointAngle(): number;
GetJointSpeed(): number;
IsLimitEnabled(): boolean;
EnableLimit(flag: boolean): void;
GetLowerLimit(): number;
GetUpperLimit(): number;
SetLimits(lower: number, upper: number): void;
IsMotorEnabled(): boolean;
EnableMotor(flag: boolean): void;
SetMotorSpeed(speed: number): void;
GetMotorSpeed(): number;
SetMaxMotorTorque(torque: number): void;
GetMaxMotorTorque(): number;
GetMotorTorque(inv_dt: number): number;
Dump(): void;
}
class RopeJointDef extends JointDef {
constructor();
localAnchorA: any;
localAnchorB: any;
maxLength: number;
}
class RopeJoint extends Joint {
GetLocalAnchorA(): Vec2;
GetLocalAnchorB(): Vec2;
GetReactionForce(inv_dt: number): Vec2;
GetReactionTorque(inv_dt: number): number;
SetMaxLength(length: number): void;
GetMaxLength(): number;
Dump(): void;
}
class WeldJointDef extends JointDef {
constructor();
localAnchorA: any;
localAnchorB: any;
referenceAngle: number;
frequencyHz: number;
dampingRatio: number;
}
class WeldJoint extends Joint {
GetLocalAnchorA(): Vec2;
GetLocalAnchorB(): Vec2;
GetReferenceAngle(): number;
SetFrequency(hz: number): void;
GetFrequency(): number;
SetDampingRatio(ratio: number): void;
GetDampingRatio(): number;
Dump(): void;
}
class WheelJointDef extends JointDef {
constructor();
localAnchorA: any;
localAnchorB: any;
localAxisA: any;
enableMotor: boolean;
maxMotorTorque: number;
motorSpeed: number;
frequencyHz: number;
dampingRatio: number;
}
class WheelJoint extends Joint {
GetLocalAnchorA(): Vec2;
GetLocalAnchorB(): Vec2;
GetLocalAxisA(): Vec2;
GetJointTranslation(): number;
IsMotorEnabled(): boolean;
EnableMotor(flag: boolean): void;
SetMotorSpeed(speed: number): void;
GetMotorSpeed(): number;
SetMaxMotorTorque(torque: number): void;
GetMaxMotorTorque(): number;
GetMotorTorque(inv_dt: number): number;
SetSpringFrequencyHz(hz: number): void;
GetSpringFrequencyHz(): number;
SetSpringDampingRatio(ratio: number): void;
GetSpringDampingRatio(): number;
Dump(): void;
}
}
+3
View File
@@ -121,6 +121,9 @@
"physics-2d-framework": {
"modules": ["physics-2d-framework"]
},
"physics-2d-box2d-jsb": {
"modules": ["physics-2d-box2d-jsb", "physics-2d-framework"]
},
"physics-2d-box2d": {
"modules": ["physics-2d-box2d", "physics-2d-framework"]
},
@@ -0,0 +1,36 @@
/*
Copyright (c) 2025 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.
*/
export const b2EmptyInstance = {
ContactListener: class {},
QueryCallback: class {},
Draw: class {},
Vec2: class {},
RayCastCallback: class {},
BodyDef: class {},
AABB: class {},
Filter: class {},
Transform: class {},
Color: class {},
};
+60
View File
@@ -0,0 +1,60 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { selector } from '../framework/physics-selector';
import { b2PhysicsWorld } from './physics-world';
import { b2RigidBody2D } from './rigid-body';
import { b2BoxShape } from './shapes/box-shape-2d';
import { b2CircleShape } from './shapes/circle-shape-2d';
import { b2PolygonShape } from './shapes/polygon-shape-2d';
import { b2MouseJoint } from './joints/mouse-joint';
import { b2DistanceJoint } from './joints/distance-joint';
import { b2SpringJoint } from './joints/spring-joint';
import { b2RelativeJoint } from './joints/relative-joint';
import { b2SliderJoint } from './joints/slider-joint';
import { b2FixedJoint } from './joints/fixed-joint';
import { b2WheelJoint } from './joints/wheel-joint';
import { b2HingeJoint } from './joints/hinge-joint';
import { Game, game } from '../../game';
game.once(Game.EVENT_PRE_SUBSYSTEM_INIT, () => {
selector.register('box2d-jsb', {
PhysicsWorld: b2PhysicsWorld,
RigidBody: b2RigidBody2D,
BoxShape: b2BoxShape,
CircleShape: b2CircleShape,
PolygonShape: b2PolygonShape,
MouseJoint: b2MouseJoint,
DistanceJoint: b2DistanceJoint,
SpringJoint: b2SpringJoint,
RelativeJoint: b2RelativeJoint,
SliderJoint: b2SliderJoint,
FixedJoint: b2FixedJoint,
WheelJoint: b2WheelJoint,
HingeJoint: b2HingeJoint,
});
});
@@ -0,0 +1,44 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { IDistanceJoint } from '../../spec/i-physics-joint';
import { b2Joint } from './joint-2d';
import { DistanceJoint2D } from '../../framework';
import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types';
export class b2DistanceJoint extends b2Joint implements IDistanceJoint {
setMaxLength (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.RopeJoint).SetMaxLength(v);
}
}
_createJointDef (): any {
const comp = this._jointComp as DistanceJoint2D;
const def = new b2jsb.RopeJointDef();
def.localAnchorA = { x: comp.anchor.x / PHYSICS_2D_PTM_RATIO, y: comp.anchor.y / PHYSICS_2D_PTM_RATIO };
def.localAnchorB = { x: comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, y: comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO };
def.maxLength = comp.maxLength / PHYSICS_2D_PTM_RATIO;
return def;
}
}
@@ -0,0 +1,51 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { IFixedJoint } from '../../spec/i-physics-joint';
import { b2Joint } from './joint-2d';
import { FixedJoint2D } from '../../framework';
import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types';
export class b2FixedJoint extends b2Joint implements IFixedJoint {
setFrequency (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.WeldJoint).SetFrequency(v);
}
}
setDampingRatio (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.WeldJoint).SetDampingRatio(v);
}
}
_createJointDef (): any {
const comp = this._jointComp as FixedJoint2D;
const def = new b2jsb.WeldJointDef();
def.localAnchorA = { x: comp.anchor.x / PHYSICS_2D_PTM_RATIO, y: comp.anchor.y / PHYSICS_2D_PTM_RATIO };
def.localAnchorB = { x: comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, y: comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO };
def.referenceAngle = 0;
def.frequencyHz = comp.frequency;
def.dampingRatio = comp.dampingRatio;
return def;
}
}
@@ -0,0 +1,82 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { IHingeJoint } from '../../spec/i-physics-joint';
import { HingeJoint2D } from '../../framework';
import { b2Joint } from './joint-2d';
import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types';
import { toRadian } from '../../../core';
export class b2HingeJoint extends b2Joint implements IHingeJoint {
enableLimit (v: boolean): void {
if (this._b2joint) {
(this._b2joint as b2jsb.RevoluteJoint).EnableLimit(v);
}
}
setLowerAngle (v: number): void {
this.updateLimits();
}
setUpperAngle (v: number): void {
this.updateLimits();
}
updateLimits (): void {
if (this._b2joint) {
const comp = this._jointComp as HingeJoint2D;
(this._b2joint as b2jsb.RevoluteJoint).SetLimits(toRadian(comp.lowerAngle), toRadian(comp.upperAngle));
}
}
// motor
enableMotor (v: boolean): void {
if (this._b2joint) {
(this._b2joint as b2jsb.RevoluteJoint).EnableMotor(v);
}
}
setMaxMotorTorque (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.RevoluteJoint).SetMaxMotorTorque(v);
}
}
setMotorSpeed (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.RevoluteJoint).SetMotorSpeed(v);
}
}
_createJointDef (): any {
const comp = this._jointComp as HingeJoint2D;
const def = new b2jsb.RevoluteJointDef();
def.localAnchorA = { x: comp.anchor.x / PHYSICS_2D_PTM_RATIO, y: comp.anchor.y / PHYSICS_2D_PTM_RATIO };
def.localAnchorB = { x: comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, y: comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO };
def.enableMotor = comp.enableMotor;
def.maxMotorTorque = comp.maxMotorTorque;
def.motorSpeed = toRadian(comp.motorSpeed);
def.enableLimit = comp.enableLimit;
def.lowerAngle = toRadian(comp.lowerAngle);
def.upperAngle = toRadian(comp.upperAngle);
return def;
}
}
@@ -0,0 +1,123 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { IJoint2D } from '../../spec/i-physics-joint';
import { Joint2D, PhysicsSystem2D, RigidBody2D } from '../../framework';
import { b2PhysicsWorld } from '../physics-world';
export class b2Joint implements IJoint2D {
get impl (): b2jsb.Joint | null {
return this._b2joint;
}
get comp (): Joint2D | null {
return this._jointComp;
}
get body (): RigidBody2D | null {
return this._body;
}
protected _b2joint: b2jsb.Joint | null = null;
protected _jointComp: Joint2D | null = null;
protected _body: RigidBody2D | null = null;
private _inited = false;
initialize (comp: Joint2D): void {
this._jointComp = comp;
}
onEnable (): void {
PhysicsSystem2D.instance._callAfterStep(this, this._init);
}
onDisable (): void {
PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
}
// need init after body and connected body init
start (): void {
PhysicsSystem2D.instance._callAfterStep(this, this._init);
}
apply (): void {
PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
if (this.comp!.enabledInHierarchy) {
PhysicsSystem2D.instance._callAfterStep(this, this._init);
}
}
_init (): void {
if (this._inited) return;
const comp = this._jointComp!;
if (!comp.isValid) {
return;
}
this._body = comp.getComponent(RigidBody2D);
const def = this._createJointDef();
if (!def) {
return;
}
def.bodyA = this._body!.impl!.impl;
const connectedBody = comp.connectedBody;
//if connected body is set but not active, return
if (connectedBody && !connectedBody.enabledInHierarchy) {
return;
}
//if connected body is not set, use scene origin as connected body
if (!connectedBody) {
def.bodyB = (PhysicsSystem2D.instance.physicsWorld as b2PhysicsWorld).groundBodyImpl;
} else {
def.bodyB = connectedBody.impl!.impl;
}
def.collideConnected = comp.collideConnected;
this._b2joint = (PhysicsSystem2D.instance.physicsWorld as b2PhysicsWorld).impl.CreateJoint(def);
this._inited = true;
}
_destroy (): void {
if (!this._inited) return;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
(PhysicsSystem2D.instance.physicsWorld as b2PhysicsWorld).impl.DestroyJoint(this._b2joint);
this._b2joint = null;
this._inited = false;
}
_createJointDef (): b2jsb.JointDef | null {
return null;
}
isValid (): Joint2D | null {
return this._b2joint && this._body && this._body.impl && this._jointComp;
}
}
@@ -0,0 +1,131 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { IMouseJoint } from '../../spec/i-physics-joint';
import { b2Joint } from './joint-2d';
import { MouseJoint2D, PhysicsSystem2D, Joint2D } from '../../framework';
import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types';
import { IVec2Like, Vec2 } from '../../../core';
import { Touch } from '../../../input/types';
import { b2PhysicsWorld } from '../physics-world';
import { NodeEventType } from '../../../scene-graph/node-event';
import { find } from '../../../scene-graph';
const tempB2Vec2 = new b2jsb.Vec2();
export class b2MouseJoint extends b2Joint implements IMouseJoint {
_touchPoint = new Vec2();
_isTouched = false;
setTarget (v: IVec2Like): void {
if (this._b2joint) {
tempB2Vec2.x = v.x / PHYSICS_2D_PTM_RATIO;
tempB2Vec2.y = v.y / PHYSICS_2D_PTM_RATIO;
(this._b2joint as b2jsb.MouseJoint).SetTarget(tempB2Vec2);
}
}
setDampingRatio (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.MouseJoint).SetDampingRatio(v);
}
}
setFrequency (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.MouseJoint).SetFrequency(v);
}
}
setMaxForce (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.MouseJoint).SetMaxForce(v);
}
}
_createJointDef (): any {
const def = new b2jsb.MouseJointDef();
const comp = this._jointComp as MouseJoint2D;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
def.target = { x: this._touchPoint.x / PHYSICS_2D_PTM_RATIO, y: this._touchPoint.y / PHYSICS_2D_PTM_RATIO };
def.maxForce = comp.maxForce;
def.dampingRatio = comp.dampingRatio;
def.frequencyHz = comp.frequency;
return def;
}
initialize (comp: Joint2D): void {
super.initialize(comp);
const canvas = find('Canvas');
if (canvas) {
canvas.on(NodeEventType.TOUCH_START, this.onTouchBegan, this);
canvas.on(NodeEventType.TOUCH_MOVE, this.onTouchMove, this);
canvas.on(NodeEventType.TOUCH_END, this.onTouchEnd, this);
canvas.on(NodeEventType.TOUCH_CANCEL, this.onTouchEnd, this);
}
}
onEnable (): void {
}
start (): void {
}
onTouchBegan (event: Touch): void {
this._isTouched = true;
const target = this._touchPoint.set(event.getUILocation());
const world = (PhysicsSystem2D.instance.physicsWorld as b2PhysicsWorld);
const colliders = world.testPoint(target);
if (colliders.length <= 0) return;
const body = colliders[0].body;
body!.wakeUp();
const comp = this._jointComp as MouseJoint2D;
comp.connectedBody = body;
this._init();
this.setMaxForce(comp.maxForce * body!.getMass());
this.setTarget(target);
}
onTouchMove (event: Touch): void {
this._touchPoint = event.getUILocation();
}
onTouchEnd (event: Touch): void {
this._destroy();
this._isTouched = false;
}
update (): void {
if (!this._isTouched || !this.isValid()) {
return;
}
this.setTarget(this._touchPoint);
}
}
@@ -0,0 +1,67 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { IRelativeJoint } from '../../spec/i-physics-joint';
import { b2Joint } from './joint-2d';
import { RelativeJoint2D } from '../../framework';
import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types';
import { toRadian, Vec2 } from '../../../core';
export class b2RelativeJoint extends b2Joint implements IRelativeJoint {
setMaxForce (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.MotorJoint).SetMaxForce(v);
}
}
setAngularOffset (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.MotorJoint).SetAngularOffset(toRadian(v));
}
}
setLinearOffset (v: Vec2): void {
if (this._b2joint) {
(this._b2joint as b2jsb.MotorJoint).SetLinearOffset(new b2jsb.Vec2(v.x / PHYSICS_2D_PTM_RATIO, v.y / PHYSICS_2D_PTM_RATIO));
}
}
setCorrectionFactor (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.MotorJoint).m_correctionFactor = v;
}
}
setMaxTorque (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.MotorJoint).SetMaxTorque(v);
}
}
_createJointDef (): any {
const comp = this._jointComp as RelativeJoint2D;
const def = new b2jsb.MotorJointDef();
def.linearOffset = { x: comp.linearOffset.x / PHYSICS_2D_PTM_RATIO, y: comp.linearOffset.y / PHYSICS_2D_PTM_RATIO };
def.angularOffset = toRadian(comp.angularOffset);
def.maxForce = comp.maxForce;
def.maxTorque = comp.maxTorque;
def.correctionFactor = comp.correctionFactor;
return def;
}
}
@@ -0,0 +1,83 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { ISliderJoint } from '../../spec/i-physics-joint';
import { b2Joint } from './joint-2d';
import { SliderJoint2D } from '../../framework';
import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types';
import { toRadian } from '../../../core';
export class b2SliderJoint extends b2Joint implements ISliderJoint {
// limit
enableLimit (v: boolean): void {
if (this._b2joint) {
(this._b2joint as b2jsb.PrismaticJoint).EnableLimit(v);
}
}
setLowerLimit (v: number): void {
this.updateLimits();
}
setUpperLimit (v: number): void {
this.updateLimits();
}
updateLimits (): void {
if (this._b2joint) {
const comp = this._jointComp as SliderJoint2D;
(this._b2joint as b2jsb.PrismaticJoint).SetLimits(comp.lowerLimit / PHYSICS_2D_PTM_RATIO, comp.upperLimit / PHYSICS_2D_PTM_RATIO);
}
}
// motor
enableMotor (v: boolean): void {
if (this._b2joint) {
(this._b2joint as b2jsb.PrismaticJoint).EnableMotor(v);
}
}
setMaxMotorForce (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.PrismaticJoint).SetMaxMotorForce(v);
}
}
setMotorSpeed (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.PrismaticJoint).SetMotorSpeed(v);
}
}
_createJointDef (): any {
const comp = this._jointComp as SliderJoint2D;
const def = new b2jsb.PrismaticJointDef();
def.localAnchorA = { x: comp.anchor.x / PHYSICS_2D_PTM_RATIO, y: comp.anchor.y / PHYSICS_2D_PTM_RATIO };
def.localAnchorB = { x: comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, y: comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO };
const angle = toRadian(comp.angle);
def.localAxisA = { x: Math.cos(angle), y: Math.sin(angle) };
def.referenceAngle = 0;
def.enableLimit = comp.enableLimit;
def.lowerTranslation = comp.lowerLimit / PHYSICS_2D_PTM_RATIO;
def.upperTranslation = comp.upperLimit / PHYSICS_2D_PTM_RATIO;
def.enableMotor = comp.enableMotor;
def.maxMotorForce = comp.maxMotorForce;
def.motorSpeed = comp.motorSpeed;
return def;
}
}
@@ -0,0 +1,56 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { ISpringJoint } from '../../spec/i-physics-joint';
import { b2Joint } from './joint-2d';
import { SpringJoint2D } from '../../framework';
import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types';
export class b2SpringJoint extends b2Joint implements ISpringJoint {
setDampingRatio (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.DistanceJoint).SetDampingRatio(v);
}
}
setFrequency (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.DistanceJoint).SetFrequency(v);
}
}
setDistance (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.DistanceJoint).SetLength(v);
}
}
_createJointDef (): any {
const comp = this._jointComp as SpringJoint2D;
const def = new b2jsb.DistanceJointDef();
def.localAnchorA = { x: comp.anchor.x / PHYSICS_2D_PTM_RATIO, y: comp.anchor.y / PHYSICS_2D_PTM_RATIO };
def.localAnchorB = { x: comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, y: comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO };
def.length = comp.distance / PHYSICS_2D_PTM_RATIO;
def.dampingRatio = comp.dampingRatio;
def.frequencyHz = comp.frequency;
return def;
}
}
@@ -0,0 +1,73 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { IWheelJoint } from '../../spec/i-physics-joint';
import { WheelJoint2D } from '../../framework';
import { b2Joint } from './joint-2d';
import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types';
import { toRadian } from '../../../core';
export class b2WheelJoint extends b2Joint implements IWheelJoint {
setDampingRatio (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.WheelJoint).SetSpringDampingRatio(v);
}
}
setFrequency (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.WheelJoint).SetSpringFrequencyHz(v);
}
}
// motor
enableMotor (v: boolean): void {
if (this._b2joint) {
(this._b2joint as b2jsb.WheelJoint).EnableMotor(v);
}
}
setMaxMotorTorque (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.WheelJoint).SetMaxMotorTorque(v);
}
}
setMotorSpeed (v: number): void {
if (this._b2joint) {
(this._b2joint as b2jsb.WheelJoint).SetMotorSpeed(v);
}
}
_createJointDef (): any {
const comp = this._jointComp as WheelJoint2D;
const def = new b2jsb.WheelJointDef();
def.localAnchorA = { x: comp.anchor.x / PHYSICS_2D_PTM_RATIO, y: comp.anchor.y / PHYSICS_2D_PTM_RATIO };
def.localAnchorB = { x: comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, y: comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO };
const angle = toRadian(comp.angle);
def.localAxisA = { x: Math.cos(angle), y: Math.sin(angle) };
def.maxMotorTorque = comp.maxMotorTorque;
def.motorSpeed = toRadian(comp.motorSpeed);
def.enableMotor = comp.enableMotor;
def.dampingRatio = comp.dampingRatio;
def.frequencyHz = comp.frequency;
return def;
}
}
@@ -0,0 +1,302 @@
/*
Copyright (c) 2017-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 { Vec2 } from '../../core';
import { PHYSICS_2D_PTM_RATIO } from '../framework/physics-types';
import { Collider2D, Contact2DType, PhysicsSystem2D } from '../framework';
import { b2Shape2D } from './shapes/shape-2d';
import { IPhysics2DContact, IPhysics2DImpulse, IPhysics2DManifoldPoint, IPhysics2DWorldManifold } from '../spec/i-physics-contact';
export type b2ContactExtends = b2jsb.Contact & {
m_userData: any
}
const pools: PhysicsContact[] = [];
// temp world manifold
const pointCache = [new Vec2(), new Vec2()];
// const b2worldmanifold = new b2jsb.WorldManifold();
const b2worldmanifold = {
///< world vector pointing from A to B
normal: { x: 0, y: 0 },
points: [{ x: 0, y: 0 }, { x: 0, y: 0 }],
//b2_maxManifoldPoints];///< world contact point (point of intersection)
separations: [0, 0],
//[b2_maxManifoldPoints];///< a negative value indicates overlap, in meters
};
const worldmanifold: IPhysics2DWorldManifold = {
points: [] as Vec2[],
separations: [] as number[],
normal: new Vec2(),
};
class ManifoldPoint implements IPhysics2DManifoldPoint {
localPoint = new Vec2();
normalImpulse = 0;
tangentImpulse = 0;
}
const manifoldPointCache = [new ManifoldPoint(), new ManifoldPoint()];
const manifold = {
type: 0,
localPoint: new Vec2(),
localNormal: new Vec2(),
points: [] as ManifoldPoint[],
};
const impulse: IPhysics2DImpulse = {
normalImpulses: [] as number[],
tangentImpulses: [] as number[],
};
export class PhysicsContact implements IPhysics2DContact {
static get (b2contact: b2ContactExtends): PhysicsContact {
let c = pools.pop();
if (!c) {
c = new PhysicsContact();
}
c.init(b2contact);
return c;
}
static put (b2contact: b2ContactExtends): void {
const c: PhysicsContact = b2contact.m_userData as PhysicsContact;
if (!c) return;
pools.push(c);
c.reset();
}
colliderA: Collider2D | null = null;
colliderB: Collider2D | null = null;
disabled = false;
disabledOnce = false;
private _impulse: b2jsb.ContactImpulse = null!;
private _inverted = false;
private _b2contact: b2ContactExtends = null!;
_setImpulse (impulse: b2jsb.ContactImpulse | null): void {
this._impulse = impulse!;
}
init (b2contact: b2ContactExtends): void {
this.colliderA = (b2contact.GetFixtureA().m_userData as b2Shape2D).collider;
this.colliderB = (b2contact.GetFixtureB().m_userData as b2Shape2D).collider;
this.disabled = false;
this.disabledOnce = false;
this._impulse = null!;
this._inverted = false;
this._b2contact = b2contact;
b2contact.m_userData = this;
}
reset (): void {
this.setTangentSpeed(0);
this.resetFriction();
this.resetRestitution();
this.colliderA = null;
this.colliderB = null;
this.disabled = false;
this._impulse = null!;
this._b2contact.m_userData = null;
this._b2contact = null!;
}
getWorldManifold (): IPhysics2DWorldManifold {
const points = worldmanifold.points;
const separations = worldmanifold.separations;
const normal = worldmanifold.normal;
this._b2contact.GetWorldManifold(b2worldmanifold);
const b2points = b2worldmanifold.points;
const b2separations = b2worldmanifold.separations;
const count = this._b2contact.GetManifold().pointCount;
points.length = separations.length = count;
for (let i = 0; i < count; i++) {
const p = pointCache[i];
p.x = b2points[i].x * PHYSICS_2D_PTM_RATIO;
p.y = b2points[i].y * PHYSICS_2D_PTM_RATIO;
points[i] = p;
separations[i] = b2separations[i] * PHYSICS_2D_PTM_RATIO;
}
normal.x = b2worldmanifold.normal.x;
normal.y = b2worldmanifold.normal.y;
if (this._inverted) {
normal.x *= -1;
normal.y *= -1;
}
return worldmanifold;
}
getManifold (): { type: number; localPoint: Vec2; localNormal: Vec2; points: ManifoldPoint[]; } {
const points = manifold.points;
const localNormal = manifold.localNormal;
const localPoint = manifold.localPoint;
const b2manifold = this._b2contact.GetManifold();
const b2points = b2manifold.points;
const count = points.length = b2manifold.pointCount;
for (let i = 0; i < count; i++) {
const p = manifoldPointCache[i];
const b2p = b2points[i];
p.localPoint.x = b2p.localPoint.x * PHYSICS_2D_PTM_RATIO;
p.localPoint.y = b2p.localPoint.y * PHYSICS_2D_PTM_RATIO;
p.normalImpulse = b2p.normalImpulse * PHYSICS_2D_PTM_RATIO;
p.tangentImpulse = b2p.tangentImpulse;
points[i] = p;
}
localPoint.x = b2manifold.localPoint.x * PHYSICS_2D_PTM_RATIO;
localPoint.y = b2manifold.localPoint.y * PHYSICS_2D_PTM_RATIO;
localNormal.x = b2manifold.localNormal.x;
localNormal.y = b2manifold.localNormal.y;
manifold.type = b2manifold.type;
if (this._inverted) {
localNormal.x *= -1;
localNormal.y *= -1;
}
return manifold;
}
getImpulse (): IPhysics2DImpulse | null {
const b2impulse = this._impulse;
if (!b2impulse) return null;
const normalImpulses = impulse.normalImpulses;
const tangentImpulses = impulse.tangentImpulses;
const count = b2impulse.count;
for (let i = 0; i < count; i++) {
normalImpulses[i] = b2impulse.normalImpulses[i] * PHYSICS_2D_PTM_RATIO;
tangentImpulses[i] = b2impulse.tangentImpulses[i];
}
tangentImpulses.length = normalImpulses.length = count;
return impulse;
}
emit (contactType: string): void {
let func = '';
switch (contactType) {
case Contact2DType.BEGIN_CONTACT:
func = 'onBeginContact';
break;
case Contact2DType.END_CONTACT:
func = 'onEndContact';
break;
case Contact2DType.PRE_SOLVE:
func = 'onPreSolve';
break;
case Contact2DType.POST_SOLVE:
func = 'onPostSolve';
break;
default:
break;
}
const colliderA = this.colliderA;
const colliderB = this.colliderB;
const bodyA = colliderA!.body;
const bodyB = colliderB!.body;
if (bodyA!.enabledContactListener) {
colliderA?.emit(contactType, colliderA, colliderB, this);
}
if (bodyB!.enabledContactListener) {
colliderB?.emit(contactType, colliderB, colliderA, this);
}
if (bodyA!.enabledContactListener || bodyB!.enabledContactListener) {
PhysicsSystem2D.instance.emit(contactType, colliderA, colliderB, this);
}
if (this.disabled || this.disabledOnce) {
this.setEnabled(false);
this.disabledOnce = false;
}
}
setEnabled (value): void {
this._b2contact.SetEnabled(value);
}
isTouching (): boolean {
return this._b2contact.IsTouching();
}
setTangentSpeed (value): void {
this._b2contact.SetTangentSpeed(value);
}
getTangentSpeed (): number {
return this._b2contact.GetTangentSpeed();
}
setFriction (value): void {
this._b2contact.SetFriction(value);
}
getFriction (): number {
return this._b2contact.GetFriction();
}
resetFriction (): void {
return this._b2contact.ResetFriction();
}
setRestitution (value): void {
this._b2contact.SetRestitution(value);
}
getRestitution (): number {
return this._b2contact.GetRestitution();
}
resetRestitution (): void {
return this._b2contact.ResetRestitution();
}
}
+481
View File
@@ -0,0 +1,481 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-unsafe-argument */
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { EDITOR_NOT_IN_PREVIEW, JSB, TEST } from 'internal:constants';
import { IPhysicsWorld } from '../spec/i-physics-world';
import { IVec2Like, Vec3, Quat, Vec2, toDegree, Rect, CCObject, js, errorID } from '../../core';
import { PHYSICS_2D_PTM_RATIO, ERaycast2DType, ERigidBody2DType } from '../framework/physics-types';
// import { Canvas } from '../../2d/framework';
import type { Graphics } from '../../2d/components/graphics';
import { b2RigidBody2D } from './rigid-body';
import { PhysicsContactListener } from './platform/physics-contact-listener';
import { PhysicsAABBQueryCallback } from './platform/physics-aabb-query-callback';
import { PhysicsRayCastCallback } from './platform/physics-ray-cast-callback';
import { PhysicsContact, b2ContactExtends } from './physics-contact';
import { Contact2DType, Collider2D, RaycastResult2D } from '../framework';
import { b2Shape2D } from './shapes/shape-2d';
import { PhysicsDebugDraw } from './platform/physics-debug-draw';
import { Node, find, Layers } from '../../scene-graph';
import { director } from '../../game';
import { b2EmptyInstance } from './empty-for-editor';
let _tempFloatArray: Float32Array;
if (!JSB) {
(globalThis as any).b2jsb = b2EmptyInstance;
} else {
//@ts-ignore
_tempFloatArray = new Float32Array(jsb.createExternalArrayBuffer(5 * 4)); // 5 floats is enough for box2d jsb.
//@ts-ignore
b2jsb._tempFloatArray = _tempFloatArray; // For other ts file in box2d-jsb module to access this arraybuffer.
b2jsb._setTempFloatArray(_tempFloatArray.buffer);
}
const tempVec3 = new Vec3();
const tempVec2_1 = new Vec2();
const tempVec2_2 = new Vec2();
const temoBodyDef = new b2jsb.BodyDef();
const tempB2AABB = new b2jsb.AABB();
const testResults: Collider2D[] = [];
// namespace b2 {
/// Color for debug drawing. Each value has the range [0,1].
class Color {
constructor (rIn?: number, gIn?: number, bIn?: number, aIn?: number) {
this.r = rIn ?? 0;
this.g = gIn ?? 0;
this.b = bIn ?? 0;
this.a = aIn ?? 1.0;
}
Set (rIn?: number, gIn?: number, bIn?: number, aIn?: number): void {
this.r = rIn ?? 0;
this.g = gIn ?? 0;
this.b = bIn ?? 0;
this.a = aIn ?? 1.0;
}
declare r: number;
declare g: number;
declare b: number;
declare a: number;
}
// }
b2jsb.Color = Color;
export class b2PhysicsWorld implements IPhysicsWorld {
protected _world: b2jsb.World;
protected _bodies: b2RigidBody2D[] = [];
protected _animatedBodies: b2RigidBody2D[] = [];
protected _rotationAxis: Vec3 = new Vec3();
protected _physicsGroundBody: b2jsb.Body;
protected _contactListener: PhysicsContactListener;
protected _aabbQueryCallback: PhysicsAABBQueryCallback;
protected _raycastQueryCallback: PhysicsRayCastCallback;
get impl (): b2jsb.World {
return this._world;
}
get groundBodyImpl (): b2jsb.Body {
return this._physicsGroundBody;
}
constructor () {
this._world = new b2jsb.World(new b2jsb.Vec2(0, -10));
const tempBodyDef = new b2jsb.BodyDef();
//tempBodyDef.position.Set(480 / PHYSICS_2D_PTM_RATIO, 320 / PHYSICS_2D_PTM_RATIO);//temporary
this._physicsGroundBody = this._world.CreateBody(tempBodyDef);
const listener = new PhysicsContactListener();
listener.initWithThis(listener);
listener.setBeginContact(this._onBeginContact);
listener.setEndContact(this._onEndContact);
listener.setPreSolve(this._onPreSolve);
listener.setPostSolve(this._onPostSolve);
this._world.SetContactListener(listener);
this._contactListener = listener;
this._aabbQueryCallback = new PhysicsAABBQueryCallback();
this._raycastQueryCallback = new PhysicsRayCastCallback();
}
_debugGraphics: Graphics | null = null;
_b2DebugDrawer: b2jsb.Draw | null = null;
_debugDrawFlags = 0;
get debugDrawFlags (): number {
return this._debugDrawFlags;
}
set debugDrawFlags (v) {
if (EDITOR_NOT_IN_PREVIEW) return;
if (!v) {
if (this._debugGraphics) {
this._debugGraphics.node.parent = null;
}
}
this._debugDrawFlags = v;
}
_checkDebugDrawValid (): void {
if (EDITOR_NOT_IN_PREVIEW) return;
if (!this._debugGraphics || !this._debugGraphics.isValid) {
let canvas = find('Canvas');
if (!canvas) {
const scene = director.getScene();
if (!scene) {
return;
}
canvas = new Node('Canvas');
canvas.addComponent('cc.Canvas');
canvas.parent = scene;
}
let node: Node | null = new Node('PHYSICS_2D_DEBUG_DRAW');
// node.zIndex = cc.macro.MAX_ZINDEX;
node.hideFlags |= CCObject.Flags.DontSave;
node.parent = canvas;
node.worldPosition = Vec3.ZERO;
node.layer = Layers.Enum.UI_2D;
try {
this._debugGraphics = node.addComponent<Graphics>('cc.Graphics');
this._debugGraphics.lineWidth = 3;
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const debugDraw = new PhysicsDebugDraw(this._debugGraphics);
debugDraw.initWithThis(debugDraw);
this._b2DebugDrawer = debugDraw;
this._world.SetDebugDraw(debugDraw);
const parent = this._debugGraphics.node.parent!;
this._debugGraphics.node.setSiblingIndex(parent.children.length - 1);
} catch (e: any) {
errorID(4501, e.message as string);
node.destroy();
node = null;
}
}
if (this._b2DebugDrawer) {
this._b2DebugDrawer.SetFlags(this.debugDrawFlags);
}
}
setGravity (v: IVec2Like): void {
this._world.SetGravity(v as b2jsb.Vec2);
}
setAllowSleep (v: boolean): void {
this._world.SetAllowSleeping(true);
}
step (deltaTime: number, velocityIterations = 10, positionIterations = 10): void {
const animatedBodies = this._animatedBodies;
for (let i = 0, l = animatedBodies.length; i < l; i++) {
animatedBodies[i].animate(deltaTime);
}
this._world.Step(deltaTime, velocityIterations, positionIterations);
}
raycast (p1: Vec2, p2: Vec2, type: ERaycast2DType, mask: number): RaycastResult2D[] {
if (p1.equals(p2)) {
return [];
}
type = type || ERaycast2DType.Closest;
tempVec2_1.x = p1.x / PHYSICS_2D_PTM_RATIO;
tempVec2_1.y = p1.y / PHYSICS_2D_PTM_RATIO;
tempVec2_2.x = p2.x / PHYSICS_2D_PTM_RATIO;
tempVec2_2.y = p2.y / PHYSICS_2D_PTM_RATIO;
const callback = this._raycastQueryCallback;
callback.init(type, mask);
this._world.RayCast(callback, tempVec2_1, tempVec2_2);
const fixtures = callback.getFixtures() as b2jsb.Fixture[];
if (fixtures.length > 0) {
const points = callback.getPoints();
const normals = callback.getNormals();
const fractions = callback.getFractions();
const results: RaycastResult2D[] = [];
for (let i = 0, l = fixtures.length; i < l; i++) {
const fixture = fixtures[i];
const shape = fixture.m_userData as b2Shape2D;
const collider = shape.collider;
if (type === ERaycast2DType.AllClosest) {
let result;
for (let j = 0; j < results.length; j++) {
if (results[j].collider === collider) {
result = results[j];
}
}
if (result) {
if (fractions[i] < result.fraction) {
result.fixtureIndex = shape.getFixtureIndex(fixture);
result.point.x = points[i].x * PHYSICS_2D_PTM_RATIO;
result.point.y = points[i].y * PHYSICS_2D_PTM_RATIO;
result.normal.x = normals[i].x;
result.normal.y = normals[i].y;
result.fraction = fractions[i];
}
continue;
}
}
results.push({
collider,
fixtureIndex: shape.getFixtureIndex(fixture),
point: new Vec2(points[i].x * PHYSICS_2D_PTM_RATIO, points[i].y * PHYSICS_2D_PTM_RATIO),
normal: new Vec2(normals[i].x, normals[i].y),
fraction: fractions[i],
});
}
return results;
}
return [];
}
syncPhysicsToScene (): void {
const bodies = this._bodies;
for (let i = 0, l = bodies.length; i < l; i++) {
const body = bodies[i];
const bodyComp = body.rigidBody;
if (bodyComp.type === ERigidBody2DType.Animated) {
body.resetVelocity();
continue;
}
const node = bodyComp.node;
const b2body = body.impl;
// position
b2body!._GetTransformJSB();
// The _GetTransformJSB which we bind it manually is for optimizing the communication between JS and CPP.
// It will fill the _tempFloatArray with the first three elements.
// _tempFloatArray[0]: position's x
// _tempFloatArray[1]: position's y
// _tempFloatArray[2]: angle
tempVec3.x = _tempFloatArray[0] * PHYSICS_2D_PTM_RATIO;
tempVec3.y = _tempFloatArray[1] * PHYSICS_2D_PTM_RATIO;
tempVec3.z = 0;
// rotation
const angle = toDegree(_tempFloatArray[2]);
//@ts-ignore
node.set2DTransform(tempVec3.x, tempVec3.y, angle);
}
}
syncSceneToPhysics (): void {
const bodies = this._bodies;
for (let i = 0; i < bodies.length; i++) {
bodies[i].syncSceneToPhysics();
}
}
addBody (body: b2RigidBody2D): void {
const bodies = this._bodies;
if (bodies.includes(body)) {
return;
}
const bodyDef = temoBodyDef;
const comp = body.rigidBody;
bodyDef.allowSleep = comp.allowSleep;
bodyDef.gravityScale = comp.gravityScale;
bodyDef.linearDamping = comp.linearDamping;
bodyDef.angularDamping = comp.angularDamping;
bodyDef.fixedRotation = comp.fixedRotation;
bodyDef.bullet = comp.bullet;
const node = comp.node;
const pos = node.worldPosition;
//@ts-ignore
bodyDef.position = { x: pos.x / PHYSICS_2D_PTM_RATIO, y: pos.y / PHYSICS_2D_PTM_RATIO };
tempVec3.z = Quat.getAxisAngle(this._rotationAxis, node.worldRotation);
if (this._rotationAxis.z < 0.0) {
tempVec3.z = Math.PI * 2 - tempVec3.z;
}
bodyDef.angle = tempVec3.z;
bodyDef.awake = comp.awakeOnLoad;
if (comp.type === ERigidBody2DType.Animated) {
bodyDef.type = ERigidBody2DType.Kinematic as number;
this._animatedBodies.push(body);
const bodyPos = bodyDef.position;
body._animatedPos.set(bodyPos.x, bodyPos.y);
body._animatedAngle = bodyDef.angle;
} else {
bodyDef.type = comp.type as number;
}
// read private property
const compPrivate = comp as any;
const linearVelocity = compPrivate._linearVelocity as Vec2;
//@ts-ignore
bodyDef.linearVelocity = { x: linearVelocity.x, y: linearVelocity.y };
bodyDef.angularVelocity = compPrivate._angularVelocity;
const b2Body = this._world.CreateBody(bodyDef);
b2Body.m_userData = body;
body._imp = b2Body;
this._bodies.push(body);
}
removeBody (body: b2RigidBody2D): void {
if (!this._bodies.includes(body)) {
return;
}
if (body.impl) {
body.impl.m_userData = null;
this._world.DestroyBody(body.impl);
body._imp = null;
}
js.array.remove(this._bodies, body);
const comp = body.rigidBody;
if (comp.type === ERigidBody2DType.Animated) {
js.array.remove(this._animatedBodies, body);
}
}
registerContactFixture (fixture: b2jsb.Fixture): void {
this._contactListener.registerContactFixture(fixture);
}
unregisterContactFixture (fixture: b2jsb.Fixture): void {
this._contactListener.unregisterContactFixture(fixture);
}
testPoint (point: Vec2): readonly Collider2D[] {
const x = tempVec2_1.x = point.x / PHYSICS_2D_PTM_RATIO;
const y = tempVec2_1.y = point.y / PHYSICS_2D_PTM_RATIO;
const d = 0.2 / PHYSICS_2D_PTM_RATIO;
tempB2AABB.lowerBound = { x: x - d, y: y - d };
tempB2AABB.upperBound = { x: x + d, y: y + d };
const callback = this._aabbQueryCallback;
callback.init(tempVec2_1);
this._world.QueryAABB(callback, tempB2AABB);
const fixtures = callback.getFixtures();
testResults.length = 0;
for (let i = 0; i < fixtures.length; i++) {
const collider = (fixtures[i].m_userData as b2Shape2D).collider;
if (!testResults.includes(collider)) {
testResults.push(collider);
}
}
return testResults;
}
testAABB (rect: Rect): readonly Collider2D[] {
tempB2AABB.lowerBound = { x: rect.xMin / PHYSICS_2D_PTM_RATIO, y: rect.yMin / PHYSICS_2D_PTM_RATIO };
tempB2AABB.upperBound = { x: rect.xMax / PHYSICS_2D_PTM_RATIO, y: rect.yMax / PHYSICS_2D_PTM_RATIO };
const callback = this._aabbQueryCallback;
callback.init();
this._world.QueryAABB(callback, tempB2AABB);
const fixtures = callback.getFixtures();
testResults.length = 0;
for (let i = 0; i < fixtures.length; i++) {
const collider = (fixtures[i].m_userData as b2Shape2D).collider;
if (!testResults.includes(collider)) {
testResults.push(collider);
}
}
return testResults;
}
drawDebug (): void {
if (TEST) return;
this._checkDebugDrawValid();
if (!this._debugGraphics) {
return;
}
this._debugGraphics.clear();
this._world.DrawDebugData();
}
_onBeginContact (b2contact: b2ContactExtends): void {
const c = PhysicsContact.get(b2contact);
c.emit(Contact2DType.BEGIN_CONTACT);
}
_onEndContact (b2contact: b2ContactExtends): void {
const c = b2contact.m_userData as PhysicsContact;
if (!c) {
return;
}
c.emit(Contact2DType.END_CONTACT);
PhysicsContact.put(b2contact);
}
_onPreSolve (b2contact: b2ContactExtends): void {
const c = b2contact.m_userData as PhysicsContact;
if (!c) {
return;
}
c.emit(Contact2DType.PRE_SOLVE);
}
_onPostSolve (b2contact: b2ContactExtends, impulse: b2jsb.ContactImpulse): void {
const c: PhysicsContact = b2contact.m_userData as PhysicsContact;
if (!c) {
return;
}
// impulse only survive during post sole callback
c._setImpulse(impulse);
c.emit(Contact2DType.POST_SOLVE);
c._setImpulse(null);
}
}
@@ -0,0 +1,70 @@
/*
Copyright (c) 2017-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 { JSB } from 'internal:constants';
import { Vec2 } from '../../../core';
import { b2EmptyInstance } from '../empty-for-editor';
if (!JSB) {
(globalThis as any).b2jsb = b2EmptyInstance;
}
export class PhysicsAABBQueryCallback extends b2jsb.QueryCallback {
private _point = new b2jsb.Vec2();
private _isPoint = false;
private _fixtures: b2jsb.Fixture[] = [];
init (point?: Vec2): void {
this.initWithThis(this);
if (point) {
this._isPoint = true;
this._point.x = point.x;
this._point.y = point.y;
} else {
this._isPoint = false;
}
this._fixtures.length = 0;
}
ReportFixture (fixture: b2jsb.Fixture): boolean {
if (this._isPoint) {
if (fixture.TestPoint(this._point)) {
this._fixtures.push(fixture);
}
} else {
this._fixtures.push(fixture);
}
// True to continue the query, false to terminate the query.
return true;
}
getFixture (): any {
return this._fixtures[0];
}
getFixtures (): any[] {
return this._fixtures;
}
}
@@ -0,0 +1,99 @@
/*
Copyright (c) 2017-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 { JSB } from 'internal:constants';
import { js } from '../../../core';
import { b2EmptyInstance } from '../empty-for-editor';
if (!JSB) {
(globalThis as any).b2jsb = b2EmptyInstance;
}
export class PhysicsContactListener extends b2jsb.ContactListener {
_contactFixtures: b2jsb.Fixture[] = [];
_BeginContact: any = null;
_EndContact: any = null;
_PreSolve: any = null;
_PostSolve: any = null;
setBeginContact (cb): void {
this._BeginContact = cb;
}
setEndContact (cb): void {
this._EndContact = cb;
}
setPreSolve (cb): void {
this._PreSolve = cb;
}
setPostSolve (cb): void {
this._PostSolve = cb;
}
BeginContact (contact: b2jsb.Contact): void {
if (!this._BeginContact) return;
const fixtureA = contact.GetFixtureA();
const fixtureB = contact.GetFixtureB();
const fixtures = this._contactFixtures;
(contact as any)._shouldReport = false;
if (fixtures.indexOf(fixtureA) !== -1 || fixtures.indexOf(fixtureB) !== -1) {
(contact as any)._shouldReport = true; // for quick check whether this contact should report
this._BeginContact(contact);
}
}
EndContact (contact: b2jsb.Contact): void {
if (this._EndContact && (contact as any)._shouldReport) {
(contact as any)._shouldReport = false;
this._EndContact(contact);
}
}
PreSolve (contact: b2jsb.Contact, oldManifold: b2jsb.Manifold): void {
if (this._PreSolve && (contact as any)._shouldReport) {
this._PreSolve(contact, oldManifold);
}
}
PostSolve (contact: b2jsb.Contact, impulse: b2jsb.ContactImpulse): void {
if (this._PostSolve && (contact as any)._shouldReport) {
this._PostSolve(contact, impulse);
}
}
registerContactFixture (fixture): void {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
this._contactFixtures.push(fixture);
}
unregisterContactFixture (fixture): void {
js.array.remove(this._contactFixtures, fixture);
}
}
@@ -0,0 +1,185 @@
/*
Copyright (c) 2017-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 { JSB } from 'internal:constants';
import { Color, Vec2 } from '../../../core';
import { PHYSICS_2D_PTM_RATIO } from '../../framework';
import type { Graphics } from '../../../2d/components/graphics';
import { b2EmptyInstance } from '../empty-for-editor';
if (!JSB) {
(globalThis as any).b2jsb = b2EmptyInstance;
}
const _tmp_vec2 = new b2jsb.Vec2();
const _tmp_color = new Color();
const GREEN_COLOR = Color.GREEN;
const RED_COLOR = Color.RED;
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
b2jsb.Transform.MulXV = function (T, v, out): any {
const T_q_c = T.q.c; const T_q_s = T.q.s;
const v_x = v.x; const v_y = v.y;
out.x = (T_q_c * v_x - T_q_s * v_y) + T.p.x;
out.y = (T_q_s * v_x + T_q_c * v_y) + T.p.y;
return out;
};
export class PhysicsDebugDraw extends b2jsb.Draw {
_drawer: Graphics | null = null;
_xf = new b2jsb.Transform();
_dxf = new b2jsb.Transform();
constructor (drawer: Graphics) {
super();
this._drawer = drawer;
}
_DrawPolygon (vertices, vertexCount): void {
const drawer = this._drawer!;
for (let i = 0; i < vertexCount; i++) {
b2jsb.Transform.MulXV(this._xf, vertices[i] as Vec2, _tmp_vec2);
const x = _tmp_vec2.x * PHYSICS_2D_PTM_RATIO;
const y = _tmp_vec2.y * PHYSICS_2D_PTM_RATIO;
if (i === 0) drawer.moveTo(x, y);
else {
drawer.lineTo(x, y);
}
}
drawer.close();
}
DrawPolygon (vertices, vertexCount, color): void {
this._applyStrokeColor(color);
this._DrawPolygon(vertices, vertexCount);
this._drawer!.stroke();
}
DrawSolidPolygon (vertices, vertexCount, color): void {
this._applyFillColor(color);
this._DrawPolygon(vertices, vertexCount);
this._drawer!.fill();
this._drawer!.stroke();
}
_DrawCircle (center: b2jsb.Vec2, radius: number): void {
b2jsb.Transform.MulXV(this._xf, center, _tmp_vec2);
//scale?
this._drawer!.circle((_tmp_vec2.x) * PHYSICS_2D_PTM_RATIO, (_tmp_vec2.y) * PHYSICS_2D_PTM_RATIO, radius * PHYSICS_2D_PTM_RATIO);
}
DrawCircle (center: b2jsb.Vec2, radius: number, color): void {
this._applyStrokeColor(color);
this._DrawCircle(center, radius);
this._drawer!.stroke();
}
DrawSolidCircle (center: b2jsb.Vec2, radius: number, axis, color): void {
this._applyFillColor(color);
this._DrawCircle(center, radius);
this._drawer!.fill();
}
DrawSegment (p1: b2jsb.Vec2, p2: b2jsb.Vec2, color): void {
const drawer = this._drawer!;
if (p1.x === p2.x && p1.y === p2.y) {
this._applyFillColor(color);
this._DrawCircle(p1, 2 / PHYSICS_2D_PTM_RATIO);
drawer.fill();
return;
}
this._applyStrokeColor(color);
b2jsb.Transform.MulXV(this._xf, p1, _tmp_vec2);
drawer.moveTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
b2jsb.Transform.MulXV(this._xf, p2, _tmp_vec2);
drawer.lineTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
drawer.stroke();
}
DrawTransform (xf: b2jsb.Transform): void {
const drawer = this._drawer!;
drawer.strokeColor = RED_COLOR;
_tmp_vec2.x = _tmp_vec2.y = 0;
b2jsb.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
drawer.moveTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
_tmp_vec2.x = 1; _tmp_vec2.y = 0;
b2jsb.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
drawer.lineTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
drawer.stroke();
drawer.strokeColor = GREEN_COLOR;
_tmp_vec2.x = _tmp_vec2.y = 0;
b2jsb.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
drawer.moveTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
_tmp_vec2.x = 0; _tmp_vec2.y = 1;
b2jsb.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
drawer.lineTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
drawer.stroke();
}
DrawPoint (center, radius, color): void {
//empty
}
DrawParticles (): void {
//empty
}
_applyStrokeColor (color): void {
this._drawer!.strokeColor = _tmp_color.set(
color.r * 255,
color.g * 255,
color.b * 255,
150,
);
}
_applyFillColor (color): void {
this._drawer!.fillColor = _tmp_color.set(
color.r * 255,
color.g * 255,
color.b * 255,
150,
);
}
PushTransform (xf): void {
this._xf = xf;
}
PopTransform (): void {
this._xf = this._dxf;
}
}
@@ -0,0 +1,94 @@
/* eslint-disable @typescript-eslint/no-unsafe-argument */
/*
Copyright (c) 2017-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 { JSB } from 'internal:constants';
import { Vec2 } from '../../../core';
import { ERaycast2DType } from '../../framework';
import { b2EmptyInstance } from '../empty-for-editor';
if (!JSB) {
(globalThis as any).b2jsb = b2EmptyInstance;
}
export class PhysicsRayCastCallback extends b2jsb.RayCastCallback {
_type = ERaycast2DType.Closest;
_fixtures: b2jsb.Fixture[] = [];
_points: Vec2[] = [];
_normals: Vec2[] = [];
_fractions: number[] = [];
_mask = 0xffffffff;
init (type: ERaycast2DType, mask: number): void {
super.initWithThis(this);
this._type = type;
this._mask = mask;
this._fixtures.length = 0;
this._points.length = 0;
this._normals.length = 0;
this._fractions.length = 0;
}
ReportFixture (fixture: b2jsb.Fixture, point, normal, fraction): any {
if ((fixture.GetFilterData().categoryBits & this._mask) === 0) {
return 0;
}
if (this._type === ERaycast2DType.Closest) {
this._fixtures[0] = fixture;
this._points[0] = new Vec2(point.x, point.y);
this._normals[0] = new Vec2(normal.x, normal.y);
this._fractions[0] = fraction;
return fraction;
}
this._fixtures.push(fixture);
this._points.push(new Vec2(point.x, point.y));
this._normals.push(new Vec2(normal.x, normal.y));
this._fractions.push(fraction);
if (this._type === ERaycast2DType.Any) {
return 0;
} else if (this._type >= ERaycast2DType.All) {
return 1;
}
return fraction;
}
getFixtures (): any[] {
return this._fixtures;
}
getPoints (): Vec2[] {
return this._points;
}
getNormals (): Vec2[] {
return this._normals;
}
getFractions (): number[] {
return this._fractions;
}
}
+420
View File
@@ -0,0 +1,420 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { IRigidBody2D } from '../spec/i-rigid-body';
import { RigidBody2D } from '../framework/components/rigid-body-2d';
import { PhysicsSystem2D } from '../framework/physics-system';
import { b2PhysicsWorld } from './physics-world';
import { Vec2, toRadian, Vec3, Quat, IVec2Like, TWO_PI, HALF_PI } from '../../core';
import { PHYSICS_2D_PTM_RATIO, ERigidBody2DType } from '../framework/physics-types';
import { Node } from '../../scene-graph/node';
import { Collider2D } from '../framework';
const tempVec3 = new Vec3();
const tempVec2_1 = { x: 0, y: 0 };
export class b2RigidBody2D implements IRigidBody2D {
get impl (): b2jsb.Body | null {
return this._body;
}
set _imp (v: b2jsb.Body | null) {
this._body = v;
}
get rigidBody (): RigidBody2D {
return this._rigidBody;
}
get isAwake (): boolean {
return this._body!.IsAwake();
}
get isSleeping (): boolean {
return !(this._body!.IsAwake());
}
_animatedPos = new Vec2();
_animatedAngle = 0;
private _body: b2jsb.Body | null = null;
private _rigidBody!: RigidBody2D;
private _inited = false;
initialize (com: RigidBody2D): void {
this._rigidBody = com;
PhysicsSystem2D.instance._callAfterStep(this, this._init);
}
onDestroy (): void {
PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
}
onEnable (): void {
this.setActive(true);
}
onDisable (): void {
this.setActive(false);
}
nodeTransformChanged (type): void {
if (PhysicsSystem2D.instance.stepping) {
return;
}
if (type & Node.TransformBit.SCALE) {
const colliders = this.rigidBody.getComponents(Collider2D);
for (let i = 0; i < colliders.length; i++) {
colliders[i].apply();
}
}
const bodyType = this._rigidBody.type;
const b2body = this._body;
if (!b2body) return;
let rotation = 0;
let isPosDirty = false;
let isRotDirty = false;
if (type & Node.TransformBit.POSITION) {
isPosDirty = true;
const pos = this._rigidBody.node.worldPosition;
tempVec2_1.x = pos.x / PHYSICS_2D_PTM_RATIO;
tempVec2_1.y = pos.y / PHYSICS_2D_PTM_RATIO;
}
if (type & Node.TransformBit.ROTATION) {
isRotDirty = true;
const rot = this._rigidBody.node.worldRotation;
const euler = tempVec3;
Quat.toEulerInYXZOrder(euler, rot);
rotation = toRadian(euler.z);
}
if (isPosDirty || isRotDirty) {
if (bodyType === ERigidBody2DType.Animated) {
if (isPosDirty) {
this._animatedPos.set(tempVec2_1.x, tempVec2_1.y);
}
if (isRotDirty) {
this._animatedAngle = rotation;
}
} else {
const tempFloatArray = b2jsb._tempFloatArray;
if (isPosDirty && isRotDirty) {
tempFloatArray[0] = tempVec2_1.x;
tempFloatArray[1] = tempVec2_1.y;
tempFloatArray[2] = rotation;
b2body._SetTransformJSB();
} else if (isPosDirty) {
tempFloatArray[0] = tempVec2_1.x;
tempFloatArray[1] = tempVec2_1.y;
b2body._SetPositionJSB();
} else {
tempFloatArray[0] = rotation;
b2body._SetAngleJSB();
}
}
}
}
_init (): void {
if (this._inited) {
return;
}
(PhysicsSystem2D.instance.physicsWorld as b2PhysicsWorld).addBody(this);
this.setActive(false);
this._inited = true;
}
_destroy (): void {
if (!this._inited) return;
(PhysicsSystem2D.instance.physicsWorld as b2PhysicsWorld).removeBody(this);
this._inited = false;
}
animate (dt: number): void {
const b2body = this._body;
if (!b2body) return;
const b2Pos = b2body.GetPosition();
b2body.SetAwake(true);
const timeStep = 1 / dt;
tempVec2_1.x = (this._animatedPos.x - b2Pos.x) * timeStep;
tempVec2_1.y = (this._animatedPos.y - b2Pos.y) * timeStep;
// @ts-ignore
b2body.SetLinearVelocity(tempVec2_1);
//convert b2Rotation to [-PI~PI], which is the same as this._animatedAngle
let b2Rotation = b2body.GetAngle() % (TWO_PI);
if (b2Rotation > Math.PI) {
b2Rotation -= TWO_PI;
}
//calculate angular velocity
let angularVelocity = (this._animatedAngle - b2Rotation) * timeStep;
if (this._animatedAngle < -HALF_PI && b2Rotation > HALF_PI) { //ccw, crossing PI
angularVelocity = (this._animatedAngle + TWO_PI - b2Rotation) * timeStep;
} if (this._animatedAngle > HALF_PI && b2Rotation < -HALF_PI) { //cw, crossing PI
angularVelocity = (this._animatedAngle - TWO_PI - b2Rotation) * timeStep;
}
b2body.SetAngularVelocity(angularVelocity);
}
syncSceneToPhysics (): void {
const dirty = this._rigidBody.node.hasChangedFlags;
if (dirty) { this.nodeTransformChanged(dirty); }
}
syncPositionToPhysics (enableAnimated = false): void {
const b2body = this._body;
if (!b2body) return;
const pos = this._rigidBody.node.worldPosition;
const bodyType = this._rigidBody.type;
const temp = tempVec2_1;
temp.x = pos.x / PHYSICS_2D_PTM_RATIO;
temp.y = pos.y / PHYSICS_2D_PTM_RATIO;
if (bodyType === ERigidBody2DType.Animated && enableAnimated) {
this._animatedPos.set(temp.x, temp.y);
} else {
// @ts-ignore
b2body.SetTransform(temp, b2body.GetAngle());
}
}
syncRotationToPhysics (enableAnimated = false): void {
const b2body = this._body;
if (!b2body) return;
const rot = this._rigidBody.node.worldRotation;
const euler = tempVec3;
Quat.toEulerInYXZOrder(euler, rot);
const rotation = toRadian(euler.z);
const bodyType = this._rigidBody.type;
if (bodyType === ERigidBody2DType.Animated && enableAnimated) {
this._animatedAngle = rotation;
} else {
b2body.SetTransform(b2body.GetPosition(), rotation);
}
}
resetVelocity (): void {
const b2body = this._body;
if (!b2body) return;
tempVec2_1.x = 0;
tempVec2_1.y = 0;
// @ts-ignore
b2body.SetLinearVelocity(tempVec2_1);
b2body.SetAngularVelocity(0);
}
setType (v: ERigidBody2DType): void {
this._body!.SetType(v as number);
}
setLinearDamping (v: number): void {
this._body!.SetLinearDamping(v);
}
setAngularDamping (v: number): void {
this._body!.SetAngularDamping(v);
}
setGravityScale (v: number): void {
this._body!.SetGravityScale(v);
}
setFixedRotation (v: boolean): void {
this._body!.SetFixedRotation(v);
}
setAllowSleep (v: boolean): void {
this._body!.SetSleepingAllowed(v);
}
isActive (): any {
return this._body!.IsEnabled();
}
setActive (v: boolean): void {
this._body!.SetEnabled(v);
}
wakeUp (): void {
this._body!.SetAwake(true);
}
sleep (): void {
this._body!.SetAwake(false);
}
getMass (): any {
return this._body!.GetMass();
}
setLinearVelocity (v: IVec2Like): void {
this._body!.SetLinearVelocity(v as b2jsb.Vec2);
}
getLinearVelocity<Out extends IVec2Like> (out: Out): Out {
const velocity = this._body!.GetLinearVelocity();
out.x = velocity.x;
out.y = velocity.y;
return out;
}
getLinearVelocityFromWorldPoint<Out extends IVec2Like> (worldPoint: IVec2Like, out: Out): Out {
tempVec2_1.x = worldPoint.x / PHYSICS_2D_PTM_RATIO;
tempVec2_1.y = worldPoint.y / PHYSICS_2D_PTM_RATIO;
// @ts-ignore
const p = this._body!.GetLinearVelocityFromWorldPoint(tempVec2_1);//FIXME(cjh):, out as any);
out.x = p.x;
out.y = p.y;
out.x *= PHYSICS_2D_PTM_RATIO;
out.y *= PHYSICS_2D_PTM_RATIO;
return out;
}
setAngularVelocity (v: number): void {
this._body!.SetAngularVelocity(v);
}
getAngularVelocity (): number {
return this._body!.GetAngularVelocity();
}
getLocalVector<Out extends IVec2Like> (worldVector: IVec2Like, out: Out): Out {
out = out || new Vec2();
tempVec2_1.x = worldVector.x / PHYSICS_2D_PTM_RATIO;
tempVec2_1.y = worldVector.y / PHYSICS_2D_PTM_RATIO;
// @ts-ignore
const p = this._body!.GetLocalVector(tempVec2_1);//FIXME(cjh), out as any);
out.x = p.x;
out.y = p.y;
out.x *= PHYSICS_2D_PTM_RATIO;
out.y *= PHYSICS_2D_PTM_RATIO;
return out;
}
getWorldVector<Out extends IVec2Like> (localVector: IVec2Like, out: Out): Out {
tempVec2_1.x = localVector.x / PHYSICS_2D_PTM_RATIO;
tempVec2_1.y = localVector.y / PHYSICS_2D_PTM_RATIO;
// @ts-ignore
const p = this._body!.GetWorldVector(tempVec2_1);//FIXME(cjh):, out as any);
out.x = p.x;
out.y = p.y;
out.x *= PHYSICS_2D_PTM_RATIO;
out.y *= PHYSICS_2D_PTM_RATIO;
return out;
}
getLocalPoint<Out extends IVec2Like> (worldPoint: IVec2Like, out: Out): Out {
out = out || new Vec2();
tempVec2_1.x = worldPoint.x / PHYSICS_2D_PTM_RATIO;
tempVec2_1.y = worldPoint.y / PHYSICS_2D_PTM_RATIO;
// @ts-ignore
const p = this._body!.GetLocalPoint(tempVec2_1);//FIXME(cjh):, out as any);
out.x = p.x;
out.y = p.y;
out.x *= PHYSICS_2D_PTM_RATIO;
out.y *= PHYSICS_2D_PTM_RATIO;
return out;
}
getWorldPoint<Out extends IVec2Like> (localPoint: IVec2Like, out: Out): Out {
out = out || new Vec2();
tempVec2_1.x = localPoint.x / PHYSICS_2D_PTM_RATIO;
tempVec2_1.y = localPoint.y / PHYSICS_2D_PTM_RATIO;
// @ts-ignore
const p = this._body!.GetWorldPoint(tempVec2_1);//FIXME(cjh):, out as any);
out.x = p.x;
out.y = p.y;
out.x *= PHYSICS_2D_PTM_RATIO;
out.y *= PHYSICS_2D_PTM_RATIO;
return out;
}
getLocalCenter<Out extends IVec2Like> (out: Out): Out {
out = out || new Vec2();
const pos = this._body!.GetLocalCenter();
out.x = pos.x * PHYSICS_2D_PTM_RATIO;
out.y = pos.y * PHYSICS_2D_PTM_RATIO;
return out;
}
getWorldCenter<Out extends IVec2Like> (out: Out): Out {
out = out || new Vec2();
const pos = this._body!.GetWorldCenter();
out.x = pos.x * PHYSICS_2D_PTM_RATIO;
out.y = pos.y * PHYSICS_2D_PTM_RATIO;
return out;
}
getInertia (): any {
return this._body!.GetInertia();
}
applyForce (force: IVec2Like, point: IVec2Like, wake: boolean): void {
if (this._body) {
tempVec2_1.x = point.x / PHYSICS_2D_PTM_RATIO;
tempVec2_1.y = point.y / PHYSICS_2D_PTM_RATIO;
// @ts-ignore
this._body.ApplyForce(force as b2jsb.Vec2, tempVec2_1, wake);
}
}
applyForceToCenter (force: IVec2Like, wake: boolean): void {
if (this._body) {
this._body.ApplyForceToCenter(force as b2jsb.Vec2, wake);
}
}
applyTorque (torque: number, wake: boolean): void {
if (this._body) {
this._body.ApplyTorque(torque, wake);
}
}
applyLinearImpulse (impulse: IVec2Like, point: IVec2Like, wake: boolean): void {
if (this._body) {
tempVec2_1.x = point.x / PHYSICS_2D_PTM_RATIO;
tempVec2_1.y = point.y / PHYSICS_2D_PTM_RATIO;
// @ts-ignore
this._body.ApplyLinearImpulse(impulse as b2jsb.Vec2, tempVec2_1, wake);
}
}
applyLinearImpulseToCenter (impulse: IVec2Like, wake: boolean): void {
if (this._body) {
this._body.ApplyLinearImpulse(impulse as b2jsb.Vec2, this._body.GetPosition(), wake);
}
}
applyAngularImpulse (impulse: number, wake: boolean): void {
if (this._body) {
this._body.ApplyAngularImpulse(impulse, wake);
}
}
}
@@ -0,0 +1,71 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { b2Shape2D } from './shape-2d';
import { BoxCollider2D } from '../../framework';
import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types';
import { IBoxShape } from '../../spec/i-physics-shape';
import { Vec2, Rect } from '../../../core';
const tempAabb = new Rect();
export class b2BoxShape extends b2Shape2D implements IBoxShape {
_worldPoints: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
get worldPoints (): Readonly<Vec2>[] {
const aabb = tempAabb;
const collider = this.collider as BoxCollider2D;
const size = collider.size;
const offset = collider.offset;
aabb.x = offset.x - size.width / 2;
aabb.y = offset.y - size.height / 2;
aabb.width = size.width;
aabb.height = size.height;
const wps = this._worldPoints;
const wp0 = wps[0]; const wp1 = wps[1];
const wp2 = wps[2]; const wp3 = wps[3];
aabb.transformMat4ToPoints(collider.node.worldMatrix, wp0, wp1, wp2, wp3);
return wps;
}
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): any[] {
scaleX = Math.abs(scaleX);
scaleY = Math.abs(scaleY);
const comp = this.collider as BoxCollider2D;
const width = comp.size.width / 2 / PHYSICS_2D_PTM_RATIO * scaleX;
const height = comp.size.height / 2 / PHYSICS_2D_PTM_RATIO * scaleY;
const offsetX = (relativePositionX + comp.offset.x * scaleX) / PHYSICS_2D_PTM_RATIO;
const offsetY = (relativePositionY + comp.offset.y * scaleY) / PHYSICS_2D_PTM_RATIO;
const shape = new b2jsb.PolygonShape();
shape.SetAsBox(width, height, new b2jsb.Vec2(offsetX, offsetY), 0);
return [shape];
}
}
@@ -0,0 +1,56 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { b2Shape2D } from './shape-2d';
import { CircleCollider2D } from '../../framework';
import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types';
import { ICircleShape } from '../../spec/i-physics-shape';
import { Vec2 } from '../../../core';
export class b2CircleShape extends b2Shape2D implements ICircleShape {
get worldRadius (): number {
return (this._shapes[0] as b2jsb.CircleShape).m_radius * PHYSICS_2D_PTM_RATIO;
}
_worldPosition = new Vec2();
get worldPosition (): Vec2 {
const p = (this._shapes[0] as b2jsb.CircleShape).m_p;
return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO);
}
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): any[] {
scaleX = Math.abs(scaleX);
scaleY = Math.abs(scaleY);
const comp = this.collider as CircleCollider2D;
const offsetX = (relativePositionX + comp.offset.x * scaleX) / PHYSICS_2D_PTM_RATIO;
const offsetY = (relativePositionY + comp.offset.y * scaleY) / PHYSICS_2D_PTM_RATIO;
const shape = new b2jsb.CircleShape();
shape.m_radius = comp.radius / PHYSICS_2D_PTM_RATIO * scaleX;
shape.m_p = { x: offsetX, y: offsetY };
return [shape];
}
}
@@ -0,0 +1,109 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { b2Shape2D } from './shape-2d';
import * as PolygonPartition from '../../framework/utils/polygon-partition';
import { PolygonCollider2D } from '../../framework';
import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types';
import { IPolygonShape } from '../../spec/i-physics-shape';
import { Vec2, logID } from '../../../core';
export class b2PolygonShape extends b2Shape2D implements IPolygonShape {
_worldPoints: Vec2[] = [];
get worldPoints (): Readonly<Vec2>[] {
const comp = this.collider as PolygonCollider2D;
const points = comp.points;
const worldPoints = this._worldPoints;
const m = comp.node.worldMatrix;
for (let i = 0; i < points.length; i++) {
if (!worldPoints[i]) {
worldPoints[i] = new Vec2();
}
Vec2.transformMat4(worldPoints[i], points[i], m);
}
worldPoints.length = points.length;
return this._worldPoints;
}
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): any[] {
const shapes: b2jsb.PolygonShape[] = [];
const comp = this.collider as PolygonCollider2D;
const points = comp.points;
// check if last point equal to first point
if (points.length > 0 && points[0].equals(points[points.length - 1])) {
points.length -= 1;
}
const polys = PolygonPartition.ConvexPartition(points);
if (!polys) {
logID(16408, comp.node.name);
return shapes;
}
const offset = comp.offset;
for (let i = 0; i < polys.length; i++) {
const poly = polys[i];
let shape: b2jsb.PolygonShape | null = null; let vertices: b2jsb.Vec2[] = [];
let firstVertice: b2jsb.Vec2 | null = null;
for (let j = 0, l = poly.length; j < l; j++) {
if (!shape) {
shape = new b2jsb.PolygonShape();
}
const p = poly[j];
const x = (relativePositionX + (p.x + offset.x) * scaleX) / PHYSICS_2D_PTM_RATIO;
const y = (relativePositionY + (p.y + offset.y) * scaleY) / PHYSICS_2D_PTM_RATIO;
const v = new b2jsb.Vec2(x, y);
vertices.push(v);
if (!firstVertice) {
firstVertice = v;
}
if (vertices.length === b2jsb.maxPolygonVertices) {
shape.Set(vertices, vertices.length);
shapes.push(shape);
shape = null;
if (j < l - 1) {
vertices = [firstVertice, vertices[vertices.length - 1]];
}
}
}
if (shape) {
shape.Set(vertices, vertices.length);
shapes.push(shape);
}
}
return shapes;
}
}
@@ -0,0 +1,224 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { IBaseShape } from '../../spec/i-physics-shape';
import { Collider2D, PhysicsSystem2D, RigidBody2D, PHYSICS_2D_PTM_RATIO } from '../../../../exports/physics-2d-framework';
import { Rect, Vec3 } from '../../../core';
import { b2PhysicsWorld } from '../physics-world';
import { PhysicsGroup } from '../../../physics/framework/physics-enum';
const tempFilter = new b2jsb.Filter();
const lowerBound = { x: 0, y: 0 };
const upperBound = { x: 0, y: 0 };
function getFilter (shape: b2Shape2D): any {
const comp = shape.collider;
if (comp.body) {
tempFilter.categoryBits = comp.group === PhysicsGroup.DEFAULT ? comp.body.group : comp.group;
} else {
tempFilter.categoryBits = comp.group;
}
tempFilter.maskBits = PhysicsSystem2D.instance.collisionMatrix[tempFilter.categoryBits];
return tempFilter;
}
export class b2Shape2D implements IBaseShape {
protected _shapes: b2jsb.Shape[] = [];
protected _fixtures: b2jsb.Fixture[] = [];
protected _collider: Collider2D | null = null;
protected _body: b2jsb.Body | null = null;
private _inited = false;
private _rect = new Rect();
get impl (): b2jsb.Shape[] {
return this._shapes;
}
get collider (): Collider2D {
return this._collider!;
}
initialize (comp: Collider2D): void {
this._collider = comp;
}
onLoad (): void {
}
onEnable (): void {
PhysicsSystem2D.instance._callAfterStep(this, this._init);
}
onDisable (): void {
PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
}
start (): void {
}
onGroupChanged (): void {
const filter = getFilter(this);
this._fixtures.forEach((f): void => {
f.SetFilterData(filter);
});
}
apply (): void {
this._destroy();
if (this.collider.enabledInHierarchy) {
this._init();
}
}
get worldAABB (): Readonly<Rect> {
const MAX = 10e6;
let minX = MAX; let minY = MAX;
let maxX = -MAX; let maxY = -MAX;
const fixtures = this._fixtures;
for (let i = 0; i < fixtures.length; i++) {
const fixture = fixtures[i];
const count = fixture.GetShape().GetChildCount();
for (let j = 0; j < count; j++) {
const lower = fixture.GetAABB(j).lowerBound;
lowerBound.x = lower.x;
lowerBound.y = lower.y;
const upper = fixture.GetAABB(j).upperBound;
upperBound.x = upper.x;
upperBound.y = upper.y;
if (fixture.GetShape().m_type === 2) { //b2ShapeType.e_polygonShape
const skinWidth = fixture.GetShape().m_radius;
lowerBound.x += skinWidth;
lowerBound.y += skinWidth;
upperBound.x -= skinWidth;
upperBound.y -= skinWidth;
}
if (lowerBound.x < minX) minX = lowerBound.x;
if (lowerBound.y < minY) minY = lowerBound.y;
if (upperBound.x > maxX) maxX = upperBound.x;
if (upperBound.y > maxY) maxY = upperBound.y;
}
}
minX *= PHYSICS_2D_PTM_RATIO;
minY *= PHYSICS_2D_PTM_RATIO;
maxX *= PHYSICS_2D_PTM_RATIO;
maxY *= PHYSICS_2D_PTM_RATIO;
const r = this._rect;
r.x = minX;
r.y = minY;
r.width = maxX - minX;
r.height = maxY - minY;
return r;
}
getFixtureIndex (fixture: b2jsb.Fixture): number {
return this._fixtures.indexOf(fixture);
}
//relativePositionX/Y : relative Position from shape to rigid body
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): b2jsb.Shape[] {
return [];
}
_init (): void {
if (this._inited) return;
const comp = this.collider;
const scale = comp.node.worldScale;
// relative Position from shape to rigid body
let relativePosition = Vec3.ZERO;
const body = comp.getComponent(RigidBody2D);
//if rigid body is not attached to the same node of collider, this b2jsb.shape is attached
// to the groundRigidBody(pos zero, rot zero)
if (body && body.impl && body.impl.impl) {
this._body = body.impl.impl as b2jsb.Body;
} else {
this._body = (PhysicsSystem2D.instance.physicsWorld as b2PhysicsWorld).groundBodyImpl;
relativePosition = comp.node.worldPosition;
}
const shapes = scale.x === 0 && scale.y === 0 ? [] : this._createShapes(scale.x, scale.y, relativePosition.x, relativePosition.y);
const filter = getFilter(this);
for (let i = 0; i < shapes.length; i++) {
const shape = shapes[i];
const fixDef = new b2jsb.FixtureDef();
fixDef.density = comp.density;
fixDef.isSensor = comp.sensor;
fixDef.friction = comp.friction;
fixDef.restitution = comp.restitution;
fixDef.shape = shape;
fixDef.filter = filter;
const fixture = this._body.CreateFixture(fixDef);
fixture.m_userData = this;
if (body?.enabledContactListener) {
(PhysicsSystem2D.instance.physicsWorld as b2PhysicsWorld).registerContactFixture(fixture);
}
this._shapes.push(shape);
this._fixtures.push(fixture);
}
this._inited = true;
}
_destroy (): void {
if (!this._inited) return;
const fixtures = this._fixtures;
const body = this._body;
for (let i = fixtures.length - 1; i >= 0; i--) {
const fixture = fixtures[i];
fixture.m_userData = null;
(PhysicsSystem2D.instance.physicsWorld as b2PhysicsWorld).unregisterContactFixture(fixture);
if (body) {
body.DestroyFixture(fixture);
}
}
this._body = null;
this._fixtures.length = 0;
this._shapes.length = 0;
this._inited = false;
}
}
+7
View File
@@ -741,6 +741,13 @@ nodeProto.getScale = function getScale(out?: Vec3): Vec3 {
return Vec3.copy(new Vec3(), this._lscale);
};
nodeProto.set2DTransform = function set2DTransform(x: number, y: number, angle: number) {
_tempFloatArray[0] = x;
_tempFloatArray[1] = y;
_tempFloatArray[2] = angle;
this._set2DTransform();
}
nodeProto.setScale = function setScale(val: Readonly<Vec3> | number, y?: number, z?: number) {
if (y === undefined && z === undefined) {
_tempFloatArray[0] = 3;
@@ -214,6 +214,12 @@
"physics-2d-builtin": {
"label": "i18n:ENGINE.features.physics_2d_builtin.label",
"description": "i18n:ENGINE.features.physics_2d_builtin.description"
},
"physics-2d-box2d-jsb": {
"isNativeModule": true,
"cmakeConfig": "USE_BOX2D_JSB",
"label": "i18n:ENGINE.features.physics_2d_box2d_jsb.label",
"description": "i18n:ENGINE.features.physics_2d_box2d_jsb.description"
}
}
},
+4
View File
@@ -1011,6 +1011,10 @@ module.exports = link(mixin({
label: "Box2D-wasm Based 2D Physics System",
description: "2D Physics system that based on Box2D-wasm.",
},
physics_2d_box2d_jsb: {
label: "Box2D-JSB Based 2D Physics System",
description: "2D Physics system that based on Box2D-JSB.",
},
intersection_2d: {
label: "2D Intersection Algorithms",
description: "Include 2D intersection algorithms.",
+4
View File
@@ -989,6 +989,10 @@ module.exports = link(mixin({
label: "基于 Box2D-wasm 的 2D 物理系统",
description: "基于 Box2D-wasm 的 2D 物理系统支持。",
},
physics_2d_box2d_jsb: {
label: "基于 Box2D JSB 的 2D 物理系统",
description: "基于 Box2D JSB 的 2D 物理系统支持。",
},
intersection_2d: {
label: "2D 相交检测算法",
description: "包含用于二维相交检测的算法。",
+26
View File
@@ -0,0 +1,26 @@
/*
Copyright (c) 2020 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 engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import '../cocos/physics-2d/box2d-jsb/instantiate';
+17
View File
@@ -33,6 +33,7 @@ cc_set_if_undefined(USE_WEBSOCKET_SERVER OFF)
cc_set_if_undefined(USE_JOB_SYSTEM_TASKFLOW OFF)
cc_set_if_undefined(USE_JOB_SYSTEM_TBB OFF)
cc_set_if_undefined(USE_PHYSICS_PHYSX OFF)
cc_set_if_undefined(USE_BOX2D_JSB OFF)
cc_set_if_undefined(USE_MODULES OFF)
cc_set_if_undefined(USE_XR OFF)
cc_set_if_undefined(USE_SERVER_MODE OFF)
@@ -181,6 +182,7 @@ if(CI_FORCE_MINIMAL_FEATURES)
set(USE_DEBUG_RENDERER OFF)
set(USE_GEOMETRY_RENDERER OFF)
set(USE_WEBP OFF)
set(USE_BOX2D_JSB OFF)
endif()
################################# external source code ################################
@@ -236,6 +238,7 @@ cc_inspect_values(
NODE_EXECUTABLE
NET_MODE
USE_REMOTE_LOG
USE_BOX2D_JSB
)
if(USE_XR)
@@ -2038,6 +2041,19 @@ cocos_source_files(
cocos/2d/renderer/StencilManager.cpp
)
##### box2d
if(USE_BOX2D_JSB)
cocos_source_files(
NO_WERROR NO_UBUILD ${SWIG_OUTPUT}/jsb_box2d_auto.cpp
${SWIG_OUTPUT}/jsb_box2d_auto.h
NO_WERROR cocos/bindings/manual/jsb_box2d_manual.cpp
cocos/bindings/manual/jsb_box2d_manual.h
cocos/bindings/manual/Box2dCallbacks.cpp
cocos/bindings/manual/Box2dCallbacks.h
)
endif()
##### 3d
cocos_source_files(
cocos/3d/assets/Types.h
@@ -3175,6 +3191,7 @@ function(cc_apply_definations target)
$<$<OR:$<CONFIG:Debug>,$<BOOL:${CC_DEBUG_FORCE}>>:CC_DEBUG=1>
$<IF:$<BOOL:${USE_ADPF}>,CC_USE_ADPF=1,CC_USE_ADPF=0>
$<IF:$<BOOL:${USE_GOOGLE_BILLING}>,CC_USE_GOOGLE_BILLING=1,CC_USE_GOOGLE_BILLING=0>
$<IF:$<BOOL:${USE_BOX2D_JSB}>,CC_USE_BOX2D_JSB=1,CC_USE_BOX2D_JSB=0>
)
endfunction()
@@ -0,0 +1,343 @@
#include "Box2dCallbacks.h"
#include "bindings/auto/jsb_box2d_auto.h"
#include "bindings/manual/jsb_global.h"
#define GET_THIS(name) \
do {\
if (_thisObject != nullptr) { \
_thisObject->decRef(); \
} \
_thisObject = thisObject; \
_thisObject->incRef(); \
} while(0)
#define GET_JS_PROPERTY(name) \
do {\
if (_cb##name != nullptr) { \
_cb##name->decRef(); \
_cb##name = nullptr; \
} \
se::Value callbackVal; \
bool ok = thisObject->getProperty(#name, &callbackVal); \
CC_ASSERT(ok && callbackVal.isObject() && callbackVal.toObject()->isFunction()); \
se::Object* callbackObj = callbackVal.toObject(); \
callbackObj->incRef(); \
_cb##name = callbackObj; \
} while(0)
#define SAFE_RELEASE_CALLBACK(name) \
do {\
if (_cb##name != nullptr) { \
_cb##name->decRef(); \
_cb##name = nullptr; \
} \
} while(0)
#define SAFE_RELEASE_THIS() \
do { \
if (_thisObject != nullptr) { \
_thisObject->decRef(); \
_thisObject = nullptr; \
} \
} while(0)
JSBQueryCallback::JSBQueryCallback() {
_args.resize(1);
}
JSBQueryCallback::~JSBQueryCallback() {
SAFE_RELEASE_THIS();
SAFE_RELEASE_CALLBACK(ReportFixture);
}
void JSBQueryCallback::initWithThis(se::Object *thisObject) {
GET_THIS();
GET_JS_PROPERTY(ReportFixture);
}
bool JSBQueryCallback::ReportFixture(b2Fixture* fixture) {
se::AutoHandleScope hs;
if (_cbReportFixture == nullptr) {
return false;
}
bool ok = nativevalue_to_se(fixture, _args[0]);
SE_PRECONDITION2(ok, false, "Error processing arguments");
se::Value rval;
ok = _cbReportFixture->call(_args, _thisObject, &rval);
if (rval.isBoolean()) {
return rval.toBoolean();
}
return false;
}
JSBRayCastCallback::JSBRayCastCallback() {
_args.resize(4);
}
void JSBRayCastCallback::initWithThis(se::Object *thisObject) {
GET_THIS();
GET_JS_PROPERTY(ReportFixture);
}
JSBRayCastCallback::~JSBRayCastCallback() {
SAFE_RELEASE_THIS();
SAFE_RELEASE_CALLBACK(ReportFixture);
}
float JSBRayCastCallback::ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float fraction) {
se::AutoHandleScope hs;
if (_cbReportFixture == nullptr) {
return 0.F;
}
bool ok = nativevalue_to_se(fixture, _args[0]);
SE_PRECONDITION2(ok, 0.F, "Error processing arguments");
ok = nativevalue_to_se(point, _args[1]);
SE_PRECONDITION2(ok, 0.F, "Error processing arguments");
ok = nativevalue_to_se(normal, _args[2]);
SE_PRECONDITION2(ok, 0.F, "Error processing arguments");
ok = nativevalue_to_se(fraction, _args[3]);
SE_PRECONDITION2(ok, 0.F, "Error processing arguments");
se::Value rval;
ok = _cbReportFixture->call(_args, _thisObject, &rval);
if (rval.isNumber()) {
return rval.toFloat();
}
return 0.F;
}
JSBB2Draw::JSBB2Draw() {
_args1.resize(1);
_args3.resize(3);
_args4.resize(4);
}
JSBB2Draw::~JSBB2Draw() {
SAFE_RELEASE_THIS();
SAFE_RELEASE_CALLBACK(DrawPolygon);
SAFE_RELEASE_CALLBACK(DrawSolidPolygon);
SAFE_RELEASE_CALLBACK(DrawCircle);
SAFE_RELEASE_CALLBACK(DrawSolidCircle);
SAFE_RELEASE_CALLBACK(DrawSegment);
SAFE_RELEASE_CALLBACK(DrawTransform);
SAFE_RELEASE_CALLBACK(DrawPoint);
}
void JSBB2Draw::initWithThis(se::Object *thisObject) {
GET_THIS();
GET_JS_PROPERTY(DrawPolygon);
GET_JS_PROPERTY(DrawSolidPolygon);
GET_JS_PROPERTY(DrawCircle);
GET_JS_PROPERTY(DrawSolidCircle);
GET_JS_PROPERTY(DrawSegment);
GET_JS_PROPERTY(DrawTransform);
GET_JS_PROPERTY(DrawPoint);
}
void JSBB2Draw::DrawPolygonWithCallback(se::Object *cbObj, const b2Vec2* vertices, int32 vertexCount, const b2Color& color) {
if (cbObj == nullptr || vertexCount <= 0 || vertices == nullptr) {
return;
}
se::AutoHandleScope hs;
ccstd::vector<b2Vec2> verticeArray;
verticeArray.resize(vertexCount);
memcpy(verticeArray.data(), vertices, sizeof(b2Vec2) * vertexCount);
bool ok = nativevalue_to_se(verticeArray, _args3[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = nativevalue_to_se(vertexCount, _args3[1]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = nativevalue_to_se(color, _args3[2]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
cbObj->call(_args3, _thisObject);
}
/// Draw a closed polygon provided in CCW order.
void JSBB2Draw::DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) {
DrawPolygonWithCallback(_cbDrawPolygon, vertices, vertexCount, color);
}
/// Draw a solid closed polygon provided in CCW order.
void JSBB2Draw::DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) {
DrawPolygonWithCallback(_cbDrawSolidPolygon, vertices, vertexCount, color);
}
/// Draw a circle.
void JSBB2Draw::DrawCircle(const b2Vec2& center, float radius, const b2Color& color) {
if (_cbDrawCircle == nullptr) {
return;
}
se::AutoHandleScope hs;
bool ok = nativevalue_to_se(center, _args3[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = nativevalue_to_se(radius, _args3[1]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = nativevalue_to_se(color, _args3[2]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
_cbDrawCircle->call(_args3, _thisObject);
}
/// Draw a solid circle.
void JSBB2Draw::DrawSolidCircle(const b2Vec2& center, float radius, const b2Vec2& axis, const b2Color& color) {
if (_cbDrawSolidCircle == nullptr) {
return;
}
se::AutoHandleScope hs;
bool ok = nativevalue_to_se(center, _args4[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = nativevalue_to_se(radius, _args4[1]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = nativevalue_to_se(axis, _args4[2]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = nativevalue_to_se(color, _args4[3]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
_cbDrawSolidCircle->call(_args4, _thisObject);
}
/// Draw a line segment.
void JSBB2Draw::DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) {
if (_cbDrawSegment == nullptr) {
return;
}
se::AutoHandleScope hs;
bool ok = nativevalue_to_se(p1, _args3[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = nativevalue_to_se(p2, _args3[1]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = nativevalue_to_se(color, _args3[2]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
_cbDrawSegment->call(_args3, _thisObject);
}
/// Draw a transform. Choose your own length scale.
/// @param xf a transform.
void JSBB2Draw::DrawTransform(const b2Transform& xf) {
if (_cbDrawTransform== nullptr) {
return;
}
se::AutoHandleScope hs;
bool ok = nativevalue_to_se(xf, _args1[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
_cbDrawTransform->call(_args1, _thisObject);
}
/// Draw a point.
void JSBB2Draw::DrawPoint(const b2Vec2& p, float size, const b2Color& color) {
if (_cbDrawPoint == nullptr) {
return;
}
se::AutoHandleScope hs;
bool ok = nativevalue_to_se(p, _args3[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = nativevalue_to_se(size, _args3[1]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = nativevalue_to_se(color, _args3[2]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
_cbDrawPoint->call(_args3, _thisObject);
}
// b2ContactListener
JSB_b2ContactListener::JSB_b2ContactListener() {
_args1.resize(1);
_args2.resize(2);
}
JSB_b2ContactListener::~JSB_b2ContactListener() {
SAFE_RELEASE_THIS();
SAFE_RELEASE_CALLBACK(BeginContact);
SAFE_RELEASE_CALLBACK(EndContact);
SAFE_RELEASE_CALLBACK(PreSolve);
SAFE_RELEASE_CALLBACK(PostSolve);
}
void JSB_b2ContactListener::initWithThis(se::Object *thisObject) {
GET_THIS();
GET_JS_PROPERTY(BeginContact);
GET_JS_PROPERTY(EndContact);
GET_JS_PROPERTY(PreSolve);
GET_JS_PROPERTY(PostSolve);
}
void JSB_b2ContactListener::BeginContact(b2Contact* contact) {
se::AutoHandleScope hs;
if (_cbBeginContact == nullptr) {
return;
}
bool ok = nativevalue_to_se(contact, _args1[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = _cbBeginContact->call(_args1, _thisObject);
}
void JSB_b2ContactListener::EndContact(b2Contact* contact) {
se::AutoHandleScope hs;
if (_cbEndContact == nullptr) {
return;
}
bool ok = nativevalue_to_se(contact, _args1[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = _cbEndContact->call(_args1, _thisObject);
}
void JSB_b2ContactListener::PreSolve(b2Contact* contact, const b2Manifold* oldManifold) {
se::AutoHandleScope hs;
if (_cbPreSolve == nullptr) {
return;
}
bool ok = nativevalue_to_se(contact, _args2[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
static b2Manifold gManifold;
gManifold = *oldManifold;
ok = nativevalue_to_se(gManifold, _args2[1]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = _cbPreSolve->call(_args2, _thisObject);
}
void JSB_b2ContactListener::PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) {
se::AutoHandleScope hs;
if (_cbPostSolve == nullptr) {
return;
}
bool ok = nativevalue_to_se(contact, _args2[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
static b2ContactImpulse gImpulse;
gImpulse = *impulse;
ok = nativevalue_to_se(gImpulse, _args2[1]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = _cbPostSolve->call(_args2, _thisObject);
}
@@ -0,0 +1,117 @@
#pragma once
#include "box2d/box2d.h"
#include "bindings/jswrapper/SeApi.h"
class JSBQueryCallback : public b2QueryCallback {
public:
JSBQueryCallback();
~JSBQueryCallback();
void initWithThis(se::Object *thisObject);
bool ReportFixture(b2Fixture* fixture) override;
private:
se::Object *_cbReportFixture{};
se::Object *_thisObject{};
se::ValueArray _args;
};
class JSBRayCastCallback : public b2RayCastCallback {
public:
JSBRayCastCallback();
~JSBRayCastCallback();
void initWithThis(se::Object *thisObject);
float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float fraction) override;
private:
se::Object *_cbReportFixture{};
se::Object *_thisObject{};
se::ValueArray _args;
};
class JSBB2Draw : public b2Draw {
public:
JSBB2Draw();
~JSBB2Draw();
void initWithThis(se::Object *thisObject);
private:
void DrawPolygonWithCallback(se::Object *cbObj, const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
public:
/// Draw a closed polygon provided in CCW order.
void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override;
/// Draw a solid closed polygon provided in CCW order.
void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override;
/// Draw a circle.
void DrawCircle(const b2Vec2& center, float radius, const b2Color& color) override;
/// Draw a solid circle.
void DrawSolidCircle(const b2Vec2& center, float radius, const b2Vec2& axis, const b2Color& color) override;
/// Draw a line segment.
void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) override;
/// Draw a transform. Choose your own length scale.
/// @param xf a transform.
void DrawTransform(const b2Transform& xf) override;
/// Draw a point.
void DrawPoint(const b2Vec2& p, float size, const b2Color& color) override;
/// Set the drawing flags.
inline void SetFlags(uint32 flags) { b2Draw::SetFlags(flags); }
/// Get the drawing flags.
inline uint32 GetFlags() const { return b2Draw::GetFlags(); };
/// Append flags to the current flags.
inline void AppendFlags(uint32 flags) { b2Draw::AppendFlags(flags); }
/// Clear flags from the current flags.
inline void ClearFlags(uint32 flags) { b2Draw::ClearFlags(flags); }
private:
se::Object *_cbDrawPolygon{};
se::Object *_cbDrawSolidPolygon{};
se::Object *_cbDrawCircle{};
se::Object *_cbDrawSolidCircle{};
se::Object *_cbDrawSegment{};
se::Object *_cbDrawTransform{};
se::Object *_cbDrawPoint{};
se::Object *_thisObject{};
se::ValueArray _args1;
se::ValueArray _args3;
se::ValueArray _args4;
};
// b2ContactListener
class JSB_b2ContactListener : public b2ContactListener {
public:
JSB_b2ContactListener();
~JSB_b2ContactListener();
void initWithThis(se::Object *thisObject);
void BeginContact(b2Contact* contact) override;
void EndContact(b2Contact* contact) override;
void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override;
void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) override;
private:
se::Object *_thisObject{};
se::Object *_cbBeginContact{};
se::Object *_cbEndContact{};
se::Object *_cbPreSolve{};
se::Object *_cbPostSolve{};
se::ValueArray _args1;
se::ValueArray _args2;
};
@@ -0,0 +1,337 @@
#include "jsb_box2d_manual.h"
#include "bindings/auto/jsb_box2d_auto.h"
#include "bindings/manual/jsb_global.h"
namespace {
class TempFloatArray final {
public:
TempFloatArray() = default;
~TempFloatArray() = default;
inline void setData(float *data) { _data = data; }
inline const float &operator[](size_t index) const { return _data[index]; }
inline float &operator[](size_t index) { return _data[index]; }
private:
float *_data{nullptr};
CC_DISALLOW_ASSIGN(TempFloatArray)
};
TempFloatArray tempFloatArray;
bool js_b2World_SetContactListener(se::State& s)
{
CC_UNUSED bool ok = true;
const auto& args = s.args();
size_t argc = args.size();
b2World *arg1 = (b2World *) NULL ;
JSB_b2ContactListener *arg2 = (JSB_b2ContactListener *) NULL ;
if(argc != 1) {
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
return false;
}
arg1 = SE_THIS_OBJECT<b2World>(s);
if (nullptr == arg1) return true;
ok &= sevalue_to_native(args[0], &arg2, s.thisObject());
SE_PRECONDITION2(ok, false, "Error processing arguments");
(arg1)->SetContactListener(arg2);
return true;
}
SE_BIND_FUNC(js_b2World_SetContactListener)
bool js_b2World_SetDebugDraw(se::State& s)
{
CC_UNUSED bool ok = true;
const auto& args = s.args();
size_t argc = args.size();
b2World *arg1 = (b2World *) NULL ;
JSBB2Draw *arg2 = (JSBB2Draw *) NULL ;
if(argc != 1) {
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
return false;
}
arg1 = SE_THIS_OBJECT<b2World>(s);
if (nullptr == arg1) return true;
ok &= sevalue_to_native(args[0], &arg2, s.thisObject());
SE_PRECONDITION2(ok, false, "Error processing arguments");
(arg1)->SetDebugDraw(arg2);
return true;
}
SE_BIND_FUNC(js_b2World_SetDebugDraw)
bool js_b2World_QueryAABB(se::State& s)
{
CC_UNUSED bool ok = true;
const auto& args = s.args();
size_t argc = args.size();
b2World *arg1 = (b2World *) NULL ;
JSBQueryCallback *arg2 = (JSBQueryCallback *) NULL ;
b2AABB *arg3 = 0 ;
b2AABB temp3 ;
if(argc != 2) {
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2);
return false;
}
arg1 = SE_THIS_OBJECT<b2World>(s);
if (nullptr == arg1) return true;
ok &= sevalue_to_native(args[0], &arg2, s.thisObject());
SE_PRECONDITION2(ok, false, "Error processing arguments");
ok &= sevalue_to_native(args[1], &temp3, s.thisObject());
SE_PRECONDITION2(ok, false, "Error processing arguments");
arg3 = &temp3;
((b2World const *)arg1)->QueryAABB(arg2,(b2AABB const &)*arg3);
return true;
}
SE_BIND_FUNC(js_b2World_QueryAABB)
bool js_b2World_RayCast(se::State& s)
{
CC_UNUSED bool ok = true;
const auto& args = s.args();
size_t argc = args.size();
b2World *arg1 = (b2World *) NULL ;
JSBRayCastCallback *arg2 = (JSBRayCastCallback *) NULL ;
b2Vec2 *arg3 = 0 ;
b2Vec2 *arg4 = 0 ;
b2Vec2 temp3 ;
b2Vec2 temp4 ;
if(argc != 3) {
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3);
return false;
}
arg1 = SE_THIS_OBJECT<b2World>(s);
if (nullptr == arg1) return true;
ok &= sevalue_to_native(args[0], &arg2, s.thisObject());
SE_PRECONDITION2(ok, false, "Error processing arguments");
ok &= sevalue_to_native(args[1], &temp3, s.thisObject());
SE_PRECONDITION2(ok, false, "Error processing arguments");
arg3 = &temp3;
ok &= sevalue_to_native(args[2], &temp4, s.thisObject());
SE_PRECONDITION2(ok, false, "Error processing arguments");
arg4 = &temp4;
((b2World const *)arg1)->RayCast(arg2,(b2Vec2 const &)*arg3,(b2Vec2 const &)*arg4);
return true;
}
SE_BIND_FUNC(js_b2World_RayCast)
bool js_Contact_GetWorldManifold(se::State& s)
{
CC_UNUSED bool ok = true;
const auto& args = s.args();
size_t argc = args.size();
b2Contact *arg1 = (b2Contact *) NULL ;
if(argc != 1) {
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
return false;
}
arg1 = SE_THIS_OBJECT<b2Contact>(s);
if (nullptr == arg1) return true;
b2WorldManifold worldManifold;
((b2Contact const *)arg1)->GetWorldManifold(&worldManifold);
se::Object *worldManifoldObj = args[0].toObject();
{
se::Value normal;
worldManifoldObj->getProperty("normal", &normal);
if (normal.isObject()) {
normal.toObject()->setProperty("x", se::Value(worldManifold.normal.x));
normal.toObject()->setProperty("y", se::Value(worldManifold.normal.y));
}
}
{
se::Value points;
worldManifoldObj->getProperty("points", &points);
if (points.isObject() && points.toObject()->isArray()) {
auto* pointsObj = points.toObject();
for (uint32_t i = 0; i < b2_maxManifoldPoints; ++i) {
se::Value e;
if (pointsObj->getArrayElement(i, &e) && e.isObject()) {
e.toObject()->setProperty("x", se::Value(worldManifold.points[i].x));
e.toObject()->setProperty("y", se::Value(worldManifold.points[i].y));
}
}
}
}
{
se::Value separations;
worldManifoldObj->getProperty("separations", &separations);
if (separations.isObject() && separations.toObject()->isArray()) {
auto* separationsObj = separations.toObject();
for (uint32_t i = 0; i < b2_maxManifoldPoints; ++i) {
separationsObj->setArrayElement(i, se::Value(worldManifold.separations[i]));
}
}
}
return true;
}
SE_BIND_FUNC(js_Contact_GetWorldManifold)
bool js_b2PolygonShape_Set(se::State& s) {
CC_UNUSED bool ok = true;
const auto& args = s.args();
size_t argc = args.size();
if (argc != 2) {
return false;
}
b2PolygonShape *arg1 = SE_THIS_OBJECT<b2PolygonShape>(s);
if (nullptr == arg1) return true;
int32 count = 0;
ok = sevalue_to_native(args[1], &count, s.thisObject());
SE_PRECONDITION2(ok, false, "Error processing arguments");
if (count <= 0) {
return true;
}
ccstd::vector<b2Vec2> vertex;
vertex.resize(count);
ok = sevalue_to_native(args[0], &vertex, s.thisObject());
SE_PRECONDITION2(ok, false, "Error processing arguments");
arg1->Set(vertex.data(), count);
return true;
}
SE_BIND_FUNC(js_b2PolygonShape_Set)
bool js_b2_setTempFloatArray(se::State &s) // NOLINT(readability-identifier-naming)
{
const auto &args = s.args();
size_t argc = args.size();
CC_UNUSED bool ok = true;
if (argc == 1) {
uint8_t *buffer = nullptr;
args[0].toObject()->getArrayBufferData(&buffer, nullptr);
tempFloatArray.setData(reinterpret_cast<float *>(buffer));
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
return false;
}
SE_BIND_FUNC(js_b2_setTempFloatArray)
bool js_Body_GetTransformJSB(void *s) // NOLINT(readability-identifier-naming)
{
auto *cobj = reinterpret_cast<b2Body *>(s);
const auto &pos = cobj->GetPosition();
float angle = cobj->GetAngle();
tempFloatArray[0] = pos.x;
tempFloatArray[1] = pos.y;
tempFloatArray[2] = angle;
return true;
}
SE_BIND_FUNC_FAST(js_Body_GetTransformJSB)
bool js_Body_SetTransformJSB(void *s) // NOLINT(readability-identifier-naming)
{
auto *cobj = reinterpret_cast<b2Body *>(s);
cobj->SetTransform(b2Vec2{tempFloatArray[0], tempFloatArray[1]}, tempFloatArray[2]);
return true;
}
SE_BIND_FUNC_FAST(js_Body_SetTransformJSB)
bool js_Body_SetPositionJSB(void *s) // NOLINT(readability-identifier-naming)
{
auto *cobj = reinterpret_cast<b2Body *>(s);
cobj->SetTransform(b2Vec2{tempFloatArray[0], tempFloatArray[1]}, cobj->GetAngle());
return true;
}
SE_BIND_FUNC_FAST(js_Body_SetPositionJSB)
bool js_Body_SetAngleJSB(void *s) // NOLINT(readability-identifier-naming)
{
auto *cobj = reinterpret_cast<b2Body *>(s);
cobj->SetTransform(cobj->GetPosition(), tempFloatArray[0]);
return true;
}
SE_BIND_FUNC_FAST(js_Body_SetAngleJSB)
} // namespace {
bool register_all_box2d_manual(se::Object *obj) { // NOLINT
// Get the ns
se::Value nsVal;
if (!obj->getProperty("b2jsb", &nsVal)) {
se::HandleObject jsobj(se::Object::createPlainObject());
nsVal.setObject(jsobj);
obj->setProperty("b2jsb", nsVal);
}
se::Object *nsObj = nsVal.toObject();
__jsb_b2PolygonShape_proto->defineFunction("Set", _SE(js_b2PolygonShape_Set));
__jsb_b2World_proto->defineFunction("SetDebugDraw", _SE(js_b2World_SetDebugDraw));
__jsb_b2World_proto->defineFunction("SetContactListener", _SE(js_b2World_SetContactListener));
__jsb_b2World_proto->defineFunction("QueryAABB", _SE(js_b2World_QueryAABB));
__jsb_b2World_proto->defineFunction("RayCast", _SE(js_b2World_RayCast));
__jsb_b2Contact_proto->defineFunction("GetWorldManifold", _SE(js_Contact_GetWorldManifold));
nsVal.toObject()->defineFunction("_setTempFloatArray", _SE(js_b2_setTempFloatArray));
__jsb_b2Body_proto->defineFunction("_GetTransformJSB", _SE(js_Body_GetTransformJSB));
__jsb_b2Body_proto->defineFunction("_SetTransformJSB", _SE(js_Body_SetTransformJSB));
__jsb_b2Body_proto->defineFunction("_SetPositionJSB", _SE(js_Body_SetPositionJSB));
__jsb_b2Body_proto->defineFunction("_SetAngleJSB", _SE(js_Body_SetAngleJSB));
nsObj->setProperty("maxFloat", se::Value(b2_maxFloat));
nsObj->setProperty("epsilon", se::Value(b2_epsilon));
nsObj->setProperty("pi", se::Value(b2_pi));
nsObj->setProperty("maxManifoldPoints", se::Value(b2_maxManifoldPoints));
nsObj->setProperty("maxPolygonVertices", se::Value(b2_maxPolygonVertices));
nsObj->setProperty("aabbExtension", se::Value(b2_aabbExtension));
nsObj->setProperty("aabbMultiplier", se::Value(b2_aabbMultiplier));
nsObj->setProperty("linearSlop", se::Value(b2_linearSlop));
nsObj->setProperty("angularSlop", se::Value(b2_angularSlop));
nsObj->setProperty("polygonRadius", se::Value(b2_polygonRadius));
nsObj->setProperty("maxSubSteps", se::Value(b2_maxSubSteps));
nsObj->setProperty("maxTOIContacts", se::Value(b2_maxTOIContacts));
nsObj->setProperty("velocityThreshold", se::Value(b2_velocityThreshold));
nsObj->setProperty("maxLinearCorrection", se::Value(b2_maxLinearCorrection));
nsObj->setProperty("maxAngularCorrection", se::Value(b2_maxAngularCorrection));
nsObj->setProperty("maxTranslation", se::Value(b2_maxTranslation));
nsObj->setProperty("maxTranslationSquared", se::Value(b2_maxTranslationSquared));
nsObj->setProperty("maxRotation", se::Value(b2_maxRotation));
nsObj->setProperty("maxRotationSquared", se::Value(b2_maxRotationSquared));
nsObj->setProperty("baumgarte", se::Value(b2_baumgarte));
nsObj->setProperty("toiBaumgarte", se::Value(b2_toiBaumgarte));
nsObj->setProperty("timeToSleep", se::Value(b2_timeToSleep));
nsObj->setProperty("linearSleepTolerance", se::Value(b2_linearSleepTolerance));
nsObj->setProperty("angularSleepTolerance", se::Value(b2_angularSleepTolerance));
return true;
}
@@ -0,0 +1,34 @@
/****************************************************************************
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// clang-format off
#pragma once
#include <type_traits>
#include "cocos/bindings/jswrapper/SeApi.h"
#include "cocos/bindings/manual/jsb_conversions.h"
bool register_all_box2d_manual(se::Object *obj); // NOLINT
@@ -54,6 +54,11 @@
#include "cocos/editor-support/spine-creator-support/Vector2.h"
#endif
#if CC_USE_BOX2D_JSB
#include "bindings/auto/jsb_box2d_auto.h"
#include "box2d/box2d.h"
#endif
///////////////////////// utils /////////////////////////
#define CHECK_ASSIGN_PRVOBJ_RET(jsObj, nativeObj) \
@@ -1780,3 +1785,65 @@ bool sevalue_to_native(const se::Value &from, cc::physics::RaycastOptions *to, s
}
#endif // CC_USE_PHYSICS_PHYSX
#if CC_USE_BOX2D_JSB
bool sevalue_to_native(const se::Value &from, b2Vec2 *to, se::Object * /*unused*/) {
SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Vec2 failed!");
se::Object *obj = from.toObject();
CHECK_ASSIGN_PRVOBJ_RET(obj, to)
se::Value tmp;
set_member_field(obj, to, "x", &b2Vec2::x, tmp);
set_member_field(obj, to, "y", &b2Vec2::y, tmp);
return true;
}
bool sevalue_to_native(const se::Value &from, b2Vec3 *to, se::Object * /*unused*/) {
SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Vec3 failed!");
se::Object *obj = from.toObject();
CHECK_ASSIGN_PRVOBJ_RET(obj, to)
se::Value tmp;
set_member_field(obj, to, "x", &b2Vec3::x, tmp);
set_member_field(obj, to, "y", &b2Vec3::y, tmp);
set_member_field(obj, to, "z", &b2Vec3::z, tmp);
return true;
}
bool sevalue_to_native(const se::Value &from, b2Color *to, se::Object * /*unused*/) {
SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Color failed!");
se::Object *obj = from.toObject();
CHECK_ASSIGN_PRVOBJ_RET(obj, to)
se::Value t;
set_member_field(obj, to, "r", &b2Color::r, t);
set_member_field(obj, to, "g", &b2Color::g, t);
set_member_field(obj, to, "b", &b2Color::b, t);
set_member_field(obj, to, "a", &b2Color::a, t);
return true;
}
bool nativevalue_to_se(const b2Vec2 &from, se::Value &to, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming)
auto *obj = se::Object::createObjectWithClass(__jsb_b2Vec2_class);
to.setObject(obj, true);
obj->setPrivateData(ccnew b2Vec2(from));
obj->getPrivateObject()->tryAllowDestroyInGC();
return true;
}
//
bool nativevalue_to_se(const b2Vec3 &from, se::Value &to, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming)
auto *obj = se::Object::createObjectWithClass(__jsb_b2Vec3_class);
to.setObject(obj, true);
obj->setPrivateData(ccnew b2Vec3(from));
obj->getPrivateObject()->tryAllowDestroyInGC();
return true;
}
bool nativevalue_to_se(const b2Color &from, se::Value &to, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming)
se::HandleObject obj(se::Object::createPlainObject());
obj->setProperty("r", se::Value(from.r));
obj->setProperty("g", se::Value(from.g));
obj->setProperty("b", se::Value(from.b));
obj->setProperty("a", se::Value(from.a));
to.setObject(obj);
return true;
}
#endif // CC_USE_BOX2D_JSB
@@ -38,6 +38,12 @@
#include "physics/spec/IWorld.h"
#endif
#if CC_USE_BOX2D_JSB
class b2Vec2;
class b2Vec3;
class b2Color;
#endif
namespace cc {
class Data;
class Vec4;
@@ -636,3 +642,14 @@ bool sevalue_to_native(const se::Value &from, cc::physics::HeightFieldDesc *to,
bool sevalue_to_native(const se::Value &from, cc::physics::RaycastOptions *to, se::Object *ctx);
#endif // USE_PHYSICS_PHYSX
#if CC_USE_BOX2D_JSB
bool sevalue_to_native(const se::Value &from, b2Vec2 *to, se::Object * /*unused*/);
bool sevalue_to_native(const se::Value &from, b2Vec3 *to, se::Object * /*unused*/);
bool sevalue_to_native(const se::Value &from, b2Color *to, se::Object * /*unused*/);
bool nativevalue_to_se(const b2Vec2 &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming)
bool nativevalue_to_se(const b2Vec3 &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming)
bool nativevalue_to_se(const b2Color &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming)
#endif //CC_USE_BOX2D_JSB
@@ -48,6 +48,10 @@
#include "cocos/bindings/manual/jsb_platform.h"
#include "cocos/bindings/manual/jsb_scene_manual.h"
#include "cocos/bindings/manual/jsb_xmlhttprequest.h"
#if CC_USE_BOX2D_JSB
#include "cocos/bindings/manual/jsb_box2d_manual.h"
#include "cocos/bindings/auto/jsb_box2d_auto.h"
#endif
#if USE_GFX_RENDERER
#endif
@@ -164,6 +168,10 @@ bool jsb_register_all_modules() {
se->addRegisterCallback(register_all_scene_manual);
se->addRegisterCallback(register_all_render);
se->addRegisterCallback(register_all_native2d);
#if CC_USE_BOX2D_JSB
se->addRegisterCallback(register_all_box2d);
se->addRegisterCallback(register_all_box2d_manual);
#endif
#if (CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_MACOS)
se->addRegisterCallback(register_javascript_objc_bridge);
@@ -622,6 +622,18 @@ static bool js_scene_Node_inverseTransformPoint(void *nativeObject) // NOLINT(re
}
SE_BIND_FUNC_FAST(js_scene_Node_inverseTransformPoint)
static bool js_scene_Node_set2DTransform(void *nativeObject) // NOLINT(readability-identifier-naming)
{
auto *cobj = reinterpret_cast<cc::Node *>(nativeObject);
float x = tempFloatArray[0];
float y = tempFloatArray[1];
float angle = tempFloatArray[2];
cobj->setWorldPosition(x, y, 0);
cobj->setWorldRotationFromEuler(0, 0, angle);
return true;
}
SE_BIND_FUNC_FAST(js_scene_Node_set2DTransform)
static bool js_scene_Pass_blocks_getter(se::State &s) { // NOLINT(readability-identifier-naming)
auto *cobj = SE_THIS_OBJECT<cc::scene::Pass>(s);
SE_PRECONDITION2(cobj, false, "Invalid Native Object");
@@ -868,6 +880,7 @@ bool register_all_scene_manual(se::Object *obj) // NOLINT(readability-identifier
__jsb_cc_Node_proto->defineFunction("_setRTS", _SE(js_scene_Node_setRTS));
__jsb_cc_Node_proto->defineFunction("_inverseTransformPoint", _SE(js_scene_Node_inverseTransformPoint));
__jsb_cc_Node_proto->defineFunction("_set2DTransform", _SE(js_scene_Node_set2DTransform));
__jsb_cc_scene_Pass_proto->defineProperty("blocks", _SE(js_scene_Pass_blocks_getter), nullptr);
@@ -719,7 +719,6 @@ EMSCRIPTEN_BINDINGS(spine) {
.property("height", &RegionAttachment::_height)
.property("color", GETTER_RVAL_TO_PTR(RegionAttachment, getColor, Color*))
.property("path", &RegionAttachment::_path)
//FIXME(cjh): .function("getRendererObject", &RegionAttachment::getRendererObject, allow_raw_pointers())
.function("getOffset", optional_override([](RegionAttachment &obj) {
return &obj.getOffset(); }), allow_raw_pointer<SPVectorFloat>())
.function("setUVs", &RegionAttachment::setUVs)
+1 -1
View File
@@ -3,6 +3,6 @@
"type": "github",
"owner": "cocos-creator",
"name": "engine-native-external",
"checkout": "v3.8.6-1"
"checkout": "v3.8.6-4"
}
}
+250
View File
@@ -0,0 +1,250 @@
// Define module
// target_namespace means the name exported to JS, could be same as which in other modules
// box2d at the last means the suffix of binding function name, different modules should use unique name
// Note: doesn't support number prefix
%module(target_namespace="b2jsb") box2d
// Disable some swig warnings, find warning number reference here ( https://www.swig.org/Doc4.1/Warnings.html )
#pragma SWIG nowarn=503,302,401,317,402
// Insert code at the beginning of generated header file (.h)
%insert(header_file) %{
#pragma once
#include "bindings/jswrapper/SeApi.h"
#include "bindings/manual/jsb_conversions.h"
#include "bindings/manual/Box2dCallbacks.h"
%}
// Insert code at the beginning of generated source file (.cpp)
%{
#include "bindings/auto/jsb_box2d_auto.h"
#define SWIGINTERN static
%}
// ----- Ignore Section ------
// Brief: Classes, methods or attributes need to be ignored
//
// Usage:
//
// %ignore your_namespace::your_class_name;
// %ignore your_namespace::your_class_name::your_method_name;
// %ignore your_namespace::your_class_name::your_attribute_name;
//
// Note:
// 1. 'Ignore Section' should be placed before attribute definition and %import/%include
// 2. namespace is needed
//
%ignore b2ContactRegister;
%ignore b2BlockAllocator;
%ignore b2GetPointStates;
%ignore b2JointUserData;
// Callbacks need to be ignored.
%ignore b2ContactListener;
%ignore b2QueryCallback;
%ignore b2RayCastCallback;
%ignore b2Draw;
//
%ignore b2Manifold::points;
%ignore b2WorldManifold::points;
%ignore b2WorldManifold::separations;
%ignore b2Hull::points;
%ignore b2PolygonShape::m_vertices;
%ignore b2PolygonShape::m_normals;
%ignore b2ContactImpulse::normalImpulses;
%ignore b2ContactImpulse::tangentImpulses;
%ignore b2ChainShape::CreateLoop;
%ignore b2ChainShape::CreateChain;
%ignore b2DistanceProxy::Set;
%ignore b2PolygonShape::Set;
%ignore b2Joint::Draw;
%ignore b2World::SetContactListener;
%ignore b2World::SetDebugDraw;
%ignore b2World::QueryAABB;
%ignore b2World::RayCast;
%ignore b2Contact::GetWorldManifold;
%rename("$ignore", regextarget=1, fullname=1) ".*Clone$";
%rename("$ignore", regextarget=1, fullname=1) "b2.*Def::userData$";
// %rename("$ignore", regextarget=1, fullname=1) "b2.*Def::userData$";
// ----- Rename Section ------
// Brief: Classes, methods or attributes needs to be renamed
//
// Usage:
//
// %rename(rename_to_name) your_namespace::original_class_name;
// %rename(rename_to_name) your_namespace::original_class_name::method_name;
// %rename(rename_to_name) your_namespace::original_class_name::attribute_name;
//
// Note:
// 1. 'Rename Section' should be placed before attribute definition and %import/%include
// 2. namespace is needed
%rename(Vec2) b2Vec2;
%rename(Vec3) b2Vec3;
%rename(Mat22) b2Mat22;
%rename(Mat33) b2Mat33;
%rename(Rot) b2Rot;
%rename(Transform) b2Transform;
%rename(Sweep) b2Sweep;
%rename(MassData) b2MassData;
%rename(Shape) b2Shape;
%rename(Color) b2Color;
// %rename(Draw) b2Draw;
%rename(ContactFeature) b2ContactFeature;
%rename(ContactID) b2ContactID;
%rename(ManifoldPoint) b2ManifoldPoint;
%rename(Manifold) b2Manifold;
%rename(WorldManifold) b2WorldManifold;
%rename(ClipVertex) b2ClipVertex;
%rename(RayCastInput) b2RayCastInput;
%rename(RayCastOutput) b2RayCastOutput;
%rename(AABB) b2AABB;
%rename(Jacobian) b2Jacobian;
%rename(JointEdge) b2JointEdge;
%rename(JointDef) b2JointDef;
%rename(Joint) b2Joint;
%rename(ChainShape) b2ChainShape;
%rename(CircleShape) b2CircleShape;
%rename(EdgeShape) b2EdgeShape;
%rename(PolygonShape) b2PolygonShape;
%rename(Pair) b2Pair;
%rename(BroadPhase) b2BroadPhase;
%rename(TreeNode) b2TreeNode;
%rename(DynamicTree) b2DynamicTree;
%rename(BodyDef) b2BodyDef;
%rename(Body) b2Body;
%rename(ContactEdge) b2ContactEdge;
%rename(Contact) b2Contact;
%rename(Filter) b2Filter;
%rename(FixtureDef) b2FixtureDef;
%rename(FixtureProxy) b2FixtureProxy;
%rename(Fixture) b2Fixture;
%rename(Profile) b2Profile;
%rename(TimeStep) b2TimeStep;
%rename(Position) b2Position;
%rename(Velocity) b2Velocity;
%rename(SolverData) b2SolverData;
%rename(World) b2World;
%rename(DestructionListener) b2DestructionListener;
%rename(ContactFilter) b2ContactFilter;
%rename(ContactImpulse) b2ContactImpulse;
// %rename(ContactListener) b2ContactListener;
// %rename(QueryCallback) b2QueryCallback;
// %rename(RayCastCallback) b2RayCastCallback;
%rename(RopeJointDef) b2RopeJointDef;
%rename(RopeJoint) b2RopeJoint;
%rename(FrictionJointDef) b2FrictionJointDef;
%rename(FrictionJoint) b2FrictionJoint;
%rename(GearJointDef) b2GearJointDef;
%rename(GearJoint) b2GearJoint;
%rename(DistanceJointDef) b2DistanceJointDef;
%rename(DistanceJoint) b2DistanceJoint;
%rename(MotorJointDef) b2MotorJointDef;
%rename(MotorJoint) b2MotorJoint;
%rename(MouseJointDef) b2MouseJointDef;
%rename(MouseJoint) b2MouseJoint;
%rename(PrismaticJointDef) b2PrismaticJointDef;
%rename(PrismaticJoint) b2PrismaticJoint;
%rename(PulleyJointDef) b2PulleyJointDef;
%rename(PulleyJoint) b2PulleyJoint;
%rename(RevoluteJointDef) b2RevoluteJointDef;
%rename(RevoluteJoint) b2RevoluteJoint;
%rename(WeldJointDef) b2WeldJointDef;
%rename(WeldJoint) b2WeldJoint;
%rename(WheelJointDef) b2WheelJointDef;
%rename(WheelJoint) b2WheelJoint;
%rename(DrawDebugData) b2World::DebugDraw;
%rename(QueryCallback) JSBQueryCallback;
%rename(RayCastCallback) JSBRayCastCallback;
%rename(Draw) JSBB2Draw;
%rename(ContactListener) JSB_b2ContactListener;
// ----- Module Macro Section ------
// Brief: Generated code should be wrapped inside a macro
// Usage:
// 1. Configure for class
// %module_macro(CC_USE_GEOMETRY_RENDERER) cc::pipeline::GeometryRenderer;
// 2. Configure for member function or attribute
// %module_macro(CC_USE_GEOMETRY_RENDERER) cc::pipeline::RenderPipeline::geometryRenderer;
// Note: Should be placed before 'Attribute Section'
// Write your code bellow
// ----- Attribute Section ------
// Brief: Define attributes ( JS properties with getter and setter )
// Usage:
// 1. Define an attribute without setter
// %attribute(your_namespace::your_class_name, cpp_member_variable_type, js_property_name, cpp_getter_name)
// 2. Define an attribute with getter and setter
// %attribute(your_namespace::your_class_name, cpp_member_variable_type, js_property_name, cpp_getter_name, cpp_setter_name)
// 3. Define an attribute without getter
// %attribute_writeonly(your_namespace::your_class_name, cpp_member_variable_type, js_property_name, cpp_setter_name)
//
// Note:
// 1. Don't need to add 'const' prefix for cpp_member_variable_type
// 2. The return type of getter should keep the same as the type of setter's parameter
// 3. If using reference, add '&' suffix for cpp_member_variable_type to avoid generated code using value assignment
// 4. 'Attribute Section' should be placed before 'Import Section' and 'Include Section'
//
// ----- Import Section ------
// Brief: Import header files which are depended by 'Include Section'
// Note:
// %import "your_header_file.h" will not generate code for that header file
//
// ----- Include Section ------
// Brief: Include header files in which classes and methods will be bound
%include "../external/sources/box2d/include/box2d/b2_math.h"
%include "../external/sources/box2d/include/box2d/b2_shape.h"
%include "../external/sources/box2d/include/box2d/b2_draw.h"
%include "../external/sources/box2d/include/box2d/b2_collision.h"
%include "../external/sources/box2d/include/box2d/b2_joint.h"
%include "../external/sources/box2d/include/box2d/b2_chain_shape.h"
%include "../external/sources/box2d/include/box2d/b2_circle_shape.h"
%include "../external/sources/box2d/include/box2d/b2_edge_shape.h"
%include "../external/sources/box2d/include/box2d/b2_polygon_shape.h"
%include "../external/sources/box2d/include/box2d/b2_broad_phase.h"
%include "../external/sources/box2d/include/box2d/b2_dynamic_tree.h"
%include "../external/sources/box2d/include/box2d/b2_body.h"
%include "../external/sources/box2d/include/box2d/b2_contact.h"
%include "../external/sources/box2d/include/box2d/b2_fixture.h"
%include "../external/sources/box2d/include/box2d/b2_time_step.h"
%include "../external/sources/box2d/include/box2d/b2_world.h"
%include "../external/sources/box2d/include/box2d/b2_world_callbacks.h"
%include "../external/sources/box2d/include/box2d/b2_rope_joint.h"
%include "../external/sources/box2d/include/box2d/b2_friction_joint.h"
%include "../external/sources/box2d/include/box2d/b2_distance_joint.h"
%include "../external/sources/box2d/include/box2d/b2_gear_joint.h"
%include "../external/sources/box2d/include/box2d/b2_motor_joint.h"
%include "../external/sources/box2d/include/box2d/b2_mouse_joint.h"
%include "../external/sources/box2d/include/box2d/b2_prismatic_joint.h"
%include "../external/sources/box2d/include/box2d/b2_pulley_joint.h"
%include "../external/sources/box2d/include/box2d/b2_revolute_joint.h"
%include "../external/sources/box2d/include/box2d/b2_weld_joint.h"
%include "../external/sources/box2d/include/box2d/b2_wheel_joint.h"
%include "bindings/manual/Box2dCallbacks.h"
+2 -1
View File
@@ -24,6 +24,7 @@
"./@types/globals",
"./@types/consts",
"./@types/jsb",
"./@types/box2d-jsb",
"./@types/editor-extends",
"./@types/webGL.extras",
"./@types/webGL2.extras",
@@ -48,7 +49,7 @@
"./@types/pal/input",
"./@types/pal/env",
"./@types/pal/pacer",
"./@types/pal/wasm",
"./@types/pal/wasm"
]
},
"include": [