diff options
Diffstat (limited to 'modules/bullet')
35 files changed, 584 insertions, 704 deletions
diff --git a/modules/bullet/SCsub b/modules/bullet/SCsub index 692c749886..b853ebfc63 100644 --- a/modules/bullet/SCsub +++ b/modules/bullet/SCsub @@ -175,6 +175,7 @@ if env["builtin_bullet"]: "BulletSoftBody/btDeformableContactProjection.cpp", "BulletSoftBody/btDeformableMultiBodyDynamicsWorld.cpp", "BulletSoftBody/btDeformableContactConstraint.cpp", + "BulletSoftBody/poly34.cpp", # clew "clew/clew.c", # LinearMath @@ -203,6 +204,8 @@ if env["builtin_bullet"]: # if env['target'] == "debug" or env['target'] == "release_debug": # env_bullet.Append(CPPDEFINES=['BT_DEBUG']) + env_bullet.Append(CPPDEFINES=["BT_USE_OLD_DAMPING_METHOD"]) + env_thirdparty = env_bullet.Clone() env_thirdparty.disable_warnings() env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources) diff --git a/modules/bullet/area_bullet.cpp b/modules/bullet/area_bullet.cpp index 4d727529ef..79d8e252f0 100644 --- a/modules/bullet/area_bullet.cpp +++ b/modules/bullet/area_bullet.cpp @@ -44,19 +44,7 @@ */ AreaBullet::AreaBullet() : - RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_AREA), - monitorable(true), - spOv_mode(PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED), - spOv_gravityPoint(false), - spOv_gravityPointDistanceScale(0), - spOv_gravityPointAttenuation(1), - spOv_gravityVec(0, -1, 0), - spOv_gravityMag(10), - spOv_linearDump(0.1), - spOv_angularDump(1), - spOv_priority(0), - isScratched(false) { - + RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_AREA) { btGhost = bulletnew(btGhostObject); reload_shapes(); setupBulletCollisionObject(btGhost); @@ -64,19 +52,22 @@ AreaBullet::AreaBullet() : /// In order to use collision objects as trigger, you have to disable the collision response. set_collision_enabled(false); - for (int i = 0; i < 5; ++i) + for (int i = 0; i < 5; ++i) { call_event_res_ptr[i] = &call_event_res[i]; + } } AreaBullet::~AreaBullet() { // signal are handled by godot, so just clear without notify - for (int i = overlappingObjects.size() - 1; 0 <= i; --i) + for (int i = overlappingObjects.size() - 1; 0 <= i; --i) { overlappingObjects[i].object->on_exit_area(this); + } } void AreaBullet::dispatch_callbacks() { - if (!isScratched) + if (!isScratched) { return; + } isScratched = false; // Reverse order because I've to remove EXIT objects @@ -102,7 +93,6 @@ void AreaBullet::dispatch_callbacks() { } void AreaBullet::call_event(CollisionObjectBullet *p_otherObject, PhysicsServer3D::AreaBodyStatus p_status) { - InOutEventCallback &event = eventsCallbacks[static_cast<int>(p_otherObject->getType())]; Object *areaGodoObject = ObjectDB::get_instance(event.event_callback_id); @@ -122,15 +112,17 @@ void AreaBullet::call_event(CollisionObjectBullet *p_otherObject, PhysicsServer3 } void AreaBullet::scratch() { - if (isScratched) + if (isScratched) { return; + } isScratched = true; } void AreaBullet::clear_overlaps(bool p_notify) { for (int i = overlappingObjects.size() - 1; 0 <= i; --i) { - if (p_notify) + if (p_notify) { call_event(overlappingObjects[i].object, PhysicsServer3D::AREA_BODY_REMOVED); + } overlappingObjects[i].object->on_exit_area(this); } overlappingObjects.clear(); @@ -139,8 +131,9 @@ void AreaBullet::clear_overlaps(bool p_notify) { void AreaBullet::remove_overlap(CollisionObjectBullet *p_object, bool p_notify) { for (int i = overlappingObjects.size() - 1; 0 <= i; --i) { if (overlappingObjects[i].object == p_object) { - if (p_notify) + if (p_notify) { call_event(overlappingObjects[i].object, PhysicsServer3D::AREA_BODY_REMOVED); + } overlappingObjects[i].object->on_exit_area(this); overlappingObjects.remove(i); break; diff --git a/modules/bullet/area_bullet.h b/modules/bullet/area_bullet.h index 56977d4451..cde889c1ba 100644 --- a/modules/bullet/area_bullet.h +++ b/modules/bullet/area_bullet.h @@ -61,12 +61,10 @@ public: }; struct OverlappingObjectData { - CollisionObjectBullet *object; - OverlapState state; + CollisionObjectBullet *object = nullptr; + OverlapState state = OVERLAP_STATE_ENTER; - OverlappingObjectData() : - object(NULL), - state(OVERLAP_STATE_ENTER) {} + OverlappingObjectData() {} OverlappingObjectData(CollisionObjectBullet *p_object, OverlapState p_state) : object(p_object), state(p_state) {} @@ -86,19 +84,19 @@ private: btGhostObject *btGhost; Vector<OverlappingObjectData> overlappingObjects; - bool monitorable; - - PhysicsServer3D::AreaSpaceOverrideMode spOv_mode; - bool spOv_gravityPoint; - real_t spOv_gravityPointDistanceScale; - real_t spOv_gravityPointAttenuation; - Vector3 spOv_gravityVec; - real_t spOv_gravityMag; - real_t spOv_linearDump; - real_t spOv_angularDump; - int spOv_priority; - - bool isScratched; + bool monitorable = true; + + PhysicsServer3D::AreaSpaceOverrideMode spOv_mode = PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED; + bool spOv_gravityPoint = false; + real_t spOv_gravityPointDistanceScale = 0; + real_t spOv_gravityPointAttenuation = 1; + Vector3 spOv_gravityVec = Vector3(0, -1, 0); + real_t spOv_gravityMag = 10; + real_t spOv_linearDump = 0.1; + real_t spOv_angularDump = 1; + int spOv_priority = 0; + + bool isScratched = false; InOutEventCallback eventsCallbacks[2]; diff --git a/modules/bullet/btRayShape.cpp b/modules/bullet/btRayShape.cpp index 4071723a3e..a754ca6a89 100644 --- a/modules/bullet/btRayShape.cpp +++ b/modules/bullet/btRayShape.cpp @@ -43,13 +43,13 @@ btRayShape::btRayShape(btScalar length) : m_shapeAxis(0, 0, 1) { m_shapeType = CUSTOM_CONVEX_SHAPE_TYPE; setLength(length); + slipsOnSlope = false; } btRayShape::~btRayShape() { } void btRayShape::setLength(btScalar p_length) { - m_length = p_length; reload_cache(); } @@ -60,7 +60,6 @@ void btRayShape::setMargin(btScalar margin) { } void btRayShape::setSlipsOnSlope(bool p_slipsOnSlope) { - slipsOnSlope = p_slipsOnSlope; } @@ -69,10 +68,11 @@ btVector3 btRayShape::localGetSupportingVertex(const btVector3 &vec) const { } btVector3 btRayShape::localGetSupportingVertexWithoutMargin(const btVector3 &vec) const { - if (vec.z() > 0) + if (vec.z() > 0) { return m_shapeAxis * m_cacheScaledLength; - else + } else { return btVector3(0, 0, 0); + } } void btRayShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3 *vectors, btVector3 *supportVerticesOut, int numVectors) const { @@ -100,7 +100,6 @@ void btRayShape::getPreferredPenetrationDirection(int index, btVector3 &penetrat } void btRayShape::reload_cache() { - m_cacheScaledLength = m_length * m_localScaling[2]; m_cacheSupportPoint.setIdentity(); diff --git a/modules/bullet/btRayShape.h b/modules/bullet/btRayShape.h index df6dd93d57..d9ecde81e6 100644 --- a/modules/bullet/btRayShape.h +++ b/modules/bullet/btRayShape.h @@ -42,7 +42,6 @@ /// Ray shape around z axis ATTRIBUTE_ALIGNED16(class) btRayShape : public btConvexInternalShape { - btScalar m_length; bool slipsOnSlope; /// The default axis is the z diff --git a/modules/bullet/bullet_physics_server.cpp b/modules/bullet/bullet_physics_server.cpp index 5b3fe1bfac..55686543f3 100644 --- a/modules/bullet/bullet_physics_server.cpp +++ b/modules/bullet/bullet_physics_server.cpp @@ -79,46 +79,36 @@ void BulletPhysicsServer3D::_bind_methods() { } BulletPhysicsServer3D::BulletPhysicsServer3D() : - PhysicsServer3D(), - active(true), - active_spaces_count(0) {} + PhysicsServer3D() {} BulletPhysicsServer3D::~BulletPhysicsServer3D() {} RID BulletPhysicsServer3D::shape_create(ShapeType p_shape) { - ShapeBullet *shape = NULL; + ShapeBullet *shape = nullptr; switch (p_shape) { case SHAPE_PLANE: { - shape = bulletnew(PlaneShapeBullet); } break; case SHAPE_SPHERE: { - shape = bulletnew(SphereShapeBullet); } break; case SHAPE_BOX: { - shape = bulletnew(BoxShapeBullet); } break; case SHAPE_CAPSULE: { - shape = bulletnew(CapsuleShapeBullet); } break; case SHAPE_CYLINDER: { - shape = bulletnew(CylinderShapeBullet); } break; case SHAPE_CONVEX_POLYGON: { - shape = bulletnew(ConvexPolygonShapeBullet); } break; case SHAPE_CONCAVE_POLYGON: { - shape = bulletnew(ConcavePolygonShapeBullet); } break; case SHAPE_HEIGHTMAP: { - shape = bulletnew(HeightMapShapeBullet); } break; case SHAPE_RAY: { @@ -178,7 +168,6 @@ RID BulletPhysicsServer3D::space_create() { } void BulletPhysicsServer3D::space_set_active(RID p_space, bool p_active) { - SpaceBullet *space = space_owner.getornull(p_space); ERR_FAIL_COND(!space); @@ -216,7 +205,7 @@ real_t BulletPhysicsServer3D::space_get_param(RID p_space, SpaceParameter p_para PhysicsDirectSpaceState3D *BulletPhysicsServer3D::space_get_direct_state(RID p_space) { SpaceBullet *space = space_owner.getornull(p_space); - ERR_FAIL_COND_V(!space, NULL); + ERR_FAIL_COND_V(!space, nullptr); return space->get_direct_state(); } @@ -252,7 +241,7 @@ RID BulletPhysicsServer3D::area_create() { void BulletPhysicsServer3D::area_set_space(RID p_area, RID p_space) { AreaBullet *area = area_owner.getornull(p_area); ERR_FAIL_COND(!area); - SpaceBullet *space = NULL; + SpaceBullet *space = nullptr; if (p_space.is_valid()) { space = space_owner.getornull(p_space); ERR_FAIL_COND(!space); @@ -337,8 +326,9 @@ void BulletPhysicsServer3D::area_clear_shapes(RID p_area) { AreaBullet *area = area_owner.getornull(p_area); ERR_FAIL_COND(!area); - for (int i = area->get_shape_count(); 0 < i; --i) + for (int i = area->get_shape_count(); 0 < i; --i) { area->remove_shape_full(0); + } } void BulletPhysicsServer3D::area_set_shape_disabled(RID p_area, int p_shape_idx, bool p_disabled) { @@ -373,7 +363,6 @@ void BulletPhysicsServer3D::area_set_param(RID p_area, AreaParameter p_param, co space->set_param(p_param, p_value); } } else { - AreaBullet *area = area_owner.getornull(p_area); ERR_FAIL_COND(!area); @@ -455,23 +444,25 @@ RID BulletPhysicsServer3D::body_create(BodyMode p_mode, bool p_init_sleeping) { body->set_mode(p_mode); body->set_collision_layer(1); body->set_collision_mask(1); - if (p_init_sleeping) + if (p_init_sleeping) { body->set_state(BODY_STATE_SLEEPING, p_init_sleeping); + } CreateThenReturnRID(rigid_body_owner, body); } void BulletPhysicsServer3D::body_set_space(RID p_body, RID p_space) { RigidBodyBullet *body = rigid_body_owner.getornull(p_body); ERR_FAIL_COND(!body); - SpaceBullet *space = NULL; + SpaceBullet *space = nullptr; if (p_space.is_valid()) { space = space_owner.getornull(p_space); ERR_FAIL_COND(!space); } - if (body->get_space() == space) + if (body->get_space() == space) { return; //pointles + } body->set_space(space); } @@ -481,8 +472,9 @@ RID BulletPhysicsServer3D::body_get_space(RID p_body) const { ERR_FAIL_COND_V(!body, RID()); SpaceBullet *space = body->get_space(); - if (!space) + if (!space) { return RID(); + } return space->get_self(); } @@ -499,7 +491,6 @@ PhysicsServer3D::BodyMode BulletPhysicsServer3D::body_get_mode(RID p_body) const } void BulletPhysicsServer3D::body_add_shape(RID p_body, RID p_shape, const Transform &p_transform, bool p_disabled) { - RigidBodyBullet *body = rigid_body_owner.getornull(p_body); ERR_FAIL_COND(!body); @@ -653,7 +644,6 @@ void BulletPhysicsServer3D::body_set_kinematic_safe_margin(RID p_body, real_t p_ ERR_FAIL_COND(!body); if (body->get_kinematic_utilities()) { - body->get_kinematic_utilities()->setSafeMargin(p_margin); } } @@ -663,7 +653,6 @@ real_t BulletPhysicsServer3D::body_get_kinematic_safe_margin(RID p_body) const { ERR_FAIL_COND_V(!body, 0); if (body->get_kinematic_utilities()) { - return body->get_kinematic_utilities()->safe_margin; } @@ -861,8 +850,8 @@ bool BulletPhysicsServer3D::body_is_ray_pickable(RID p_body) const { PhysicsDirectBodyState3D *BulletPhysicsServer3D::body_get_direct_state(RID p_body) { RigidBodyBullet *body = rigid_body_owner.getornull(p_body); - ERR_FAIL_COND_V(!body, NULL); - return BulletPhysicsDirectBodyState::get_singleton(body); + ERR_FAIL_COND_V(!body, nullptr); + return BulletPhysicsDirectBodyState3D::get_singleton(body); } bool BulletPhysicsServer3D::body_test_motion(RID p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, MotionResult *r_result, bool p_exclude_raycast_shapes) { @@ -885,8 +874,9 @@ RID BulletPhysicsServer3D::soft_body_create(bool p_init_sleeping) { SoftBodyBullet *body = bulletnew(SoftBodyBullet); body->set_collision_layer(1); body->set_collision_mask(1); - if (p_init_sleeping) + if (p_init_sleeping) { body->set_activation_state(false); + } CreateThenReturnRID(soft_body_owner, body); } @@ -900,15 +890,16 @@ void BulletPhysicsServer3D::soft_body_update_rendering_server(RID p_body, class void BulletPhysicsServer3D::soft_body_set_space(RID p_body, RID p_space) { SoftBodyBullet *body = soft_body_owner.getornull(p_body); ERR_FAIL_COND(!body); - SpaceBullet *space = NULL; + SpaceBullet *space = nullptr; if (p_space.is_valid()) { space = space_owner.getornull(p_space); ERR_FAIL_COND(!space); } - if (body->get_space() == space) + if (body->get_space() == space) { return; //pointles + } body->set_space(space); } @@ -918,8 +909,9 @@ RID BulletPhysicsServer3D::soft_body_get_space(RID p_body) const { ERR_FAIL_COND_V(!body, RID()); SpaceBullet *space = body->get_space(); - if (!space) + if (!space) { return RID(); + } return space->get_self(); } @@ -1214,7 +1206,7 @@ RID BulletPhysicsServer3D::joint_create_pin(RID p_body_A, const Vector3 &p_local JointAssertSpace(body_A, "A", RID()); - RigidBodyBullet *body_B = NULL; + RigidBodyBullet *body_B = nullptr; if (p_body_B.is_valid()) { body_B = rigid_body_owner.getornull(p_body_B); JointAssertSpace(body_B, "B", RID()); @@ -1282,7 +1274,7 @@ RID BulletPhysicsServer3D::joint_create_hinge(RID p_body_A, const Transform &p_h ERR_FAIL_COND_V(!body_A, RID()); JointAssertSpace(body_A, "A", RID()); - RigidBodyBullet *body_B = NULL; + RigidBodyBullet *body_B = nullptr; if (p_body_B.is_valid()) { body_B = rigid_body_owner.getornull(p_body_B); JointAssertSpace(body_B, "B", RID()); @@ -1302,7 +1294,7 @@ RID BulletPhysicsServer3D::joint_create_hinge_simple(RID p_body_A, const Vector3 ERR_FAIL_COND_V(!body_A, RID()); JointAssertSpace(body_A, "A", RID()); - RigidBodyBullet *body_B = NULL; + RigidBodyBullet *body_B = nullptr; if (p_body_B.is_valid()) { body_B = rigid_body_owner.getornull(p_body_B); JointAssertSpace(body_B, "B", RID()); @@ -1354,7 +1346,7 @@ RID BulletPhysicsServer3D::joint_create_slider(RID p_body_A, const Transform &p_ ERR_FAIL_COND_V(!body_A, RID()); JointAssertSpace(body_A, "A", RID()); - RigidBodyBullet *body_B = NULL; + RigidBodyBullet *body_B = nullptr; if (p_body_B.is_valid()) { body_B = rigid_body_owner.getornull(p_body_B); JointAssertSpace(body_B, "B", RID()); @@ -1390,7 +1382,7 @@ RID BulletPhysicsServer3D::joint_create_cone_twist(RID p_body_A, const Transform ERR_FAIL_COND_V(!body_A, RID()); JointAssertSpace(body_A, "A", RID()); - RigidBodyBullet *body_B = NULL; + RigidBodyBullet *body_B = nullptr; if (p_body_B.is_valid()) { body_B = rigid_body_owner.getornull(p_body_B); JointAssertSpace(body_B, "B", RID()); @@ -1424,7 +1416,7 @@ RID BulletPhysicsServer3D::joint_create_generic_6dof(RID p_body_A, const Transfo ERR_FAIL_COND_V(!body_A, RID()); JointAssertSpace(body_A, "A", RID()); - RigidBodyBullet *body_B = NULL; + RigidBodyBullet *body_B = nullptr; if (p_body_B.is_valid()) { body_B = rigid_body_owner.getornull(p_body_B); JointAssertSpace(body_B, "B", RID()); @@ -1489,7 +1481,6 @@ int BulletPhysicsServer3D::generic_6dof_joint_get_precision(RID p_joint) { void BulletPhysicsServer3D::free(RID p_rid) { if (shape_owner.owns(p_rid)) { - ShapeBullet *shape = shape_owner.getornull(p_rid); // Notify the shape is configured @@ -1500,10 +1491,9 @@ void BulletPhysicsServer3D::free(RID p_rid) { shape_owner.free(p_rid); bulletdelete(shape); } else if (rigid_body_owner.owns(p_rid)) { - RigidBodyBullet *body = rigid_body_owner.getornull(p_rid); - body->set_space(NULL); + body->set_space(nullptr); body->remove_all_shapes(true, true); @@ -1511,19 +1501,17 @@ void BulletPhysicsServer3D::free(RID p_rid) { bulletdelete(body); } else if (soft_body_owner.owns(p_rid)) { - SoftBodyBullet *body = soft_body_owner.getornull(p_rid); - body->set_space(NULL); + body->set_space(nullptr); soft_body_owner.free(p_rid); bulletdelete(body); } else if (area_owner.owns(p_rid)) { - AreaBullet *area = area_owner.getornull(p_rid); - area->set_space(NULL); + area->set_space(nullptr); area->remove_all_shapes(true, true); @@ -1531,14 +1519,12 @@ void BulletPhysicsServer3D::free(RID p_rid) { bulletdelete(area); } else if (joint_owner.owns(p_rid)) { - JointBullet *joint = joint_owner.getornull(p_rid); joint->destroy_internal_constraint(); joint_owner.free(p_rid); bulletdelete(joint); } else if (space_owner.owns(p_rid)) { - SpaceBullet *space = space_owner.getornull(p_rid); space->remove_all_collision_objects(); @@ -1547,23 +1533,22 @@ void BulletPhysicsServer3D::free(RID p_rid) { space_owner.free(p_rid); bulletdelete(space); } else { - ERR_FAIL_MSG("Invalid ID."); } } void BulletPhysicsServer3D::init() { - BulletPhysicsDirectBodyState::initSingleton(); + BulletPhysicsDirectBodyState3D::initSingleton(); } void BulletPhysicsServer3D::step(float p_deltaTime) { - if (!active) + if (!active) { return; + } - BulletPhysicsDirectBodyState::singleton_setDeltaTime(p_deltaTime); + BulletPhysicsDirectBodyState3D::singleton_setDeltaTime(p_deltaTime); for (int i = 0; i < active_spaces_count; ++i) { - active_spaces[i]->step(p_deltaTime); } } @@ -1575,7 +1560,7 @@ void BulletPhysicsServer3D::flush_queries() { } void BulletPhysicsServer3D::finish() { - BulletPhysicsDirectBodyState::destroySingleton(); + BulletPhysicsDirectBodyState3D::destroySingleton(); } int BulletPhysicsServer3D::get_process_info(ProcessInfo p_info) { @@ -1592,7 +1577,7 @@ CollisionObjectBullet *BulletPhysicsServer3D::get_collisin_object(RID p_object) if (soft_body_owner.owns(p_object)) { return soft_body_owner.getornull(p_object); } - return NULL; + return nullptr; } RigidCollisionObjectBullet *BulletPhysicsServer3D::get_rigid_collisin_object(RID p_object) const { @@ -1602,5 +1587,5 @@ RigidCollisionObjectBullet *BulletPhysicsServer3D::get_rigid_collisin_object(RID if (area_owner.owns(p_object)) { return area_owner.getornull(p_object); } - return NULL; + return nullptr; } diff --git a/modules/bullet/bullet_physics_server.h b/modules/bullet/bullet_physics_server.h index 1269dac78b..558d1ce5f7 100644 --- a/modules/bullet/bullet_physics_server.h +++ b/modules/bullet/bullet_physics_server.h @@ -40,6 +40,7 @@ #include "shape_bullet.h" #include "soft_body_bullet.h" #include "space_bullet.h" + /** @author AndreaCatania */ @@ -49,8 +50,8 @@ class BulletPhysicsServer3D : public PhysicsServer3D { friend class BulletPhysicsDirectSpaceState; - bool active; - char active_spaces_count; + bool active = true; + char active_spaces_count = 0; Vector<SpaceBullet *> active_spaces; mutable RID_PtrOwner<SpaceBullet> space_owner; @@ -254,7 +255,7 @@ public: // this function only works on physics process, errors and returns null otherwise virtual PhysicsDirectBodyState3D *body_get_direct_state(RID p_body); - virtual bool body_test_motion(RID p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, MotionResult *r_result = NULL, bool p_exclude_raycast_shapes = true); + virtual bool body_test_motion(RID p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, MotionResult *r_result = nullptr, bool p_exclude_raycast_shapes = true); virtual int body_test_ray_separation(RID p_body, const Transform &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, SeparationResult *r_results, int p_result_max, float p_margin = 0.001); /* SOFT BODY API */ diff --git a/modules/bullet/bullet_utilities.h b/modules/bullet/bullet_utilities.h index 968cb38ba2..a5e33d9829 100644 --- a/modules/bullet/bullet_utilities.h +++ b/modules/bullet/bullet_utilities.h @@ -41,6 +41,6 @@ #define bulletdelete(cl) \ { \ delete cl; \ - cl = NULL; \ + cl = nullptr; \ } #endif diff --git a/modules/bullet/collision_object_bullet.cpp b/modules/bullet/collision_object_bullet.cpp index 0ce57811d7..a3158a15e5 100644 --- a/modules/bullet/collision_object_bullet.cpp +++ b/modules/bullet/collision_object_bullet.cpp @@ -80,27 +80,17 @@ btTransform CollisionObjectBullet::ShapeWrapper::get_adjusted_transform() const void CollisionObjectBullet::ShapeWrapper::claim_bt_shape(const btVector3 &body_scale) { if (!bt_shape) { - if (active) + if (active) { bt_shape = shape->create_bt_shape(scale * body_scale); - else + } else { bt_shape = ShapeBullet::create_shape_empty(); + } } } CollisionObjectBullet::CollisionObjectBullet(Type p_type) : RIDBullet(), - type(p_type), - instance_id(ObjectID()), - collisionLayer(0), - collisionMask(0), - collisionsEnabled(true), - m_isStatic(false), - ray_pickable(false), - bt_collision_object(NULL), - body_scale(1., 1., 1.), - force_shape_reset(false), - space(NULL), - isTransformChanged(false) {} + type(p_type) {} CollisionObjectBullet::~CollisionObjectBullet() { // Remove all overlapping, notify is not required since godot take care of it @@ -147,18 +137,21 @@ void CollisionObjectBullet::setupBulletCollisionObject(btCollisionObject *p_coll void CollisionObjectBullet::add_collision_exception(const CollisionObjectBullet *p_ignoreCollisionObject) { exceptions.insert(p_ignoreCollisionObject->get_self()); - if (!bt_collision_object) + if (!bt_collision_object) { return; + } bt_collision_object->setIgnoreCollisionCheck(p_ignoreCollisionObject->bt_collision_object, true); - if (space) + if (space) { space->get_broadphase()->getOverlappingPairCache()->cleanProxyFromPairs(bt_collision_object->getBroadphaseHandle(), space->get_dispatcher()); + } } void CollisionObjectBullet::remove_collision_exception(const CollisionObjectBullet *p_ignoreCollisionObject) { exceptions.erase(p_ignoreCollisionObject->get_self()); bt_collision_object->setIgnoreCollisionCheck(p_ignoreCollisionObject->bt_collision_object, false); - if (space) + if (space) { space->get_broadphase()->getOverlappingPairCache()->cleanProxyFromPairs(bt_collision_object->getBroadphaseHandle(), space->get_dispatcher()); + } } bool CollisionObjectBullet::has_collision_exception(const CollisionObjectBullet *p_otherCollisionObject) const { @@ -195,7 +188,6 @@ int CollisionObjectBullet::get_godot_object_flags() const { } void CollisionObjectBullet::set_transform(const Transform &p_global_transform) { - set_body_scale(p_global_transform.basis.get_scale_abs()); btTransform bt_transform; @@ -225,11 +217,6 @@ void CollisionObjectBullet::notify_transform_changed() { isTransformChanged = true; } -RigidCollisionObjectBullet::RigidCollisionObjectBullet(Type p_type) : - CollisionObjectBullet(p_type), - mainShape(NULL) { -} - RigidCollisionObjectBullet::~RigidCollisionObjectBullet() { remove_all_shapes(true, true); if (mainShape && mainShape->isCompound()) { @@ -266,8 +253,9 @@ btCollisionShape *RigidCollisionObjectBullet::get_bt_shape(int p_index) const { int RigidCollisionObjectBullet::find_shape(ShapeBullet *p_shape) const { const int size = shapes.size(); for (int i = 0; i < size; ++i) { - if (shapes[i].shape == p_shape) + if (shapes[i].shape == p_shape) { return i; + } } return -1; } @@ -297,8 +285,9 @@ void RigidCollisionObjectBullet::remove_all_shapes(bool p_permanentlyFromThisBod internal_shape_destroy(i, p_permanentlyFromThisBody); } shapes.clear(); - if (!p_force_not_reload) + if (!p_force_not_reload) { reload_shapes(); + } } void RigidCollisionObjectBullet::set_shape_transform(int p_index, const Transform &p_transform) { @@ -319,8 +308,9 @@ Transform RigidCollisionObjectBullet::get_shape_transform(int p_index) const { } void RigidCollisionObjectBullet::set_shape_disabled(int p_index, bool p_disabled) { - if (shapes[p_index].active != p_disabled) + if (shapes[p_index].active != p_disabled) { return; + } shapes.write[p_index].active = !p_disabled; shape_changed(p_index); } @@ -332,20 +322,19 @@ bool RigidCollisionObjectBullet::is_shape_disabled(int p_index) { void RigidCollisionObjectBullet::shape_changed(int p_shape_index) { ShapeWrapper &shp = shapes.write[p_shape_index]; if (shp.bt_shape == mainShape) { - mainShape = NULL; + mainShape = nullptr; } bulletdelete(shp.bt_shape); reload_shapes(); } void RigidCollisionObjectBullet::reload_shapes() { - if (mainShape && mainShape->isCompound()) { // Destroy compound bulletdelete(mainShape); } - mainShape = NULL; + mainShape = nullptr; ShapeWrapper *shpWrapper; const int shape_count = shapes.size(); @@ -398,7 +387,7 @@ void RigidCollisionObjectBullet::internal_shape_destroy(int p_index, bool p_perm ShapeWrapper &shp = shapes.write[p_index]; shp.shape->remove_owner(this, p_permanentlyFromThisBody); if (shp.bt_shape == mainShape) { - mainShape = NULL; + mainShape = nullptr; } bulletdelete(shp.bt_shape); } diff --git a/modules/bullet/collision_object_bullet.h b/modules/bullet/collision_object_bullet.h index 42ba4aa907..f1423a69e4 100644 --- a/modules/bullet/collision_object_bullet.h +++ b/modules/bullet/collision_object_bullet.h @@ -69,27 +69,22 @@ public: }; struct ShapeWrapper { - ShapeBullet *shape; - btCollisionShape *bt_shape; + ShapeBullet *shape = nullptr; + btCollisionShape *bt_shape = nullptr; btTransform transform; btVector3 scale; - bool active; + bool active = true; - ShapeWrapper() : - shape(NULL), - bt_shape(NULL), - active(true) {} + ShapeWrapper() {} ShapeWrapper(ShapeBullet *p_shape, const btTransform &p_transform, bool p_active) : shape(p_shape), - bt_shape(NULL), active(p_active) { set_transform(p_transform); } ShapeWrapper(ShapeBullet *p_shape, const Transform &p_transform, bool p_active) : shape(p_shape), - bt_shape(NULL), active(p_active) { set_transform(p_transform); } @@ -117,15 +112,15 @@ public: protected: Type type; ObjectID instance_id; - uint32_t collisionLayer; - uint32_t collisionMask; - bool collisionsEnabled; - bool m_isStatic; - bool ray_pickable; - btCollisionObject *bt_collision_object; - Vector3 body_scale; - bool force_shape_reset; - SpaceBullet *space; + uint32_t collisionLayer = 0; + uint32_t collisionMask = 0; + bool collisionsEnabled = true; + bool m_isStatic = false; + bool ray_pickable = false; + btCollisionObject *bt_collision_object = nullptr; + Vector3 body_scale = Vector3(1, 1, 1); + bool force_shape_reset = false; + SpaceBullet *space = nullptr; VSet<RID> exceptions; @@ -133,7 +128,7 @@ protected: /// New area is added when overlap with new area (AreaBullet::addOverlap), then is removed when it exit (CollisionObjectBullet::onExitArea) /// This array is used mainly to know which area hold the pointer of this object Vector<AreaBullet *> areasOverlapped; - bool isTransformChanged; + bool isTransformChanged = false; public: CollisionObjectBullet(Type p_type); @@ -218,11 +213,12 @@ public: class RigidCollisionObjectBullet : public CollisionObjectBullet, public ShapeOwnerBullet { protected: - btCollisionShape *mainShape; + btCollisionShape *mainShape = nullptr; Vector<ShapeWrapper> shapes; public: - RigidCollisionObjectBullet(Type p_type); + RigidCollisionObjectBullet(Type p_type) : + CollisionObjectBullet(p_type) {} ~RigidCollisionObjectBullet(); _FORCE_INLINE_ const Vector<ShapeWrapper> &get_shapes_wrappers() const { return shapes; } diff --git a/modules/bullet/cone_twist_joint_bullet.cpp b/modules/bullet/cone_twist_joint_bullet.cpp index aac51034b8..b4735fa9e9 100644 --- a/modules/bullet/cone_twist_joint_bullet.cpp +++ b/modules/bullet/cone_twist_joint_bullet.cpp @@ -42,7 +42,6 @@ ConeTwistJointBullet::ConeTwistJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &rbAFrame, const Transform &rbBFrame) : JointBullet() { - Transform scaled_AFrame(rbAFrame.scaled(rbA->get_body_scale())); scaled_AFrame.basis.rotref_posscale_decomposition(scaled_AFrame.basis); @@ -50,7 +49,6 @@ ConeTwistJointBullet::ConeTwistJointBullet(RigidBodyBullet *rbA, RigidBodyBullet G_TO_B(scaled_AFrame, btFrameA); if (rbB) { - Transform scaled_BFrame(rbBFrame.scaled(rbB->get_body_scale())); scaled_BFrame.basis.rotref_posscale_decomposition(scaled_BFrame.basis); diff --git a/modules/bullet/config.py b/modules/bullet/config.py index f6fd0be8ba..d22f9454ed 100644 --- a/modules/bullet/config.py +++ b/modules/bullet/config.py @@ -4,14 +4,3 @@ def can_build(env, platform): def configure(env): pass - - -def get_doc_classes(): - return [ - "BulletPhysicsDirectBodyState", - "BulletPhysicsServer", - ] - - -def get_doc_path(): - return "doc_classes" diff --git a/modules/bullet/constraint_bullet.cpp b/modules/bullet/constraint_bullet.cpp index 7e90e2b488..c47a23e75f 100644 --- a/modules/bullet/constraint_bullet.cpp +++ b/modules/bullet/constraint_bullet.cpp @@ -37,10 +37,7 @@ @author AndreaCatania */ -ConstraintBullet::ConstraintBullet() : - space(NULL), - constraint(NULL), - disabled_collisions_between_bodies(true) {} +ConstraintBullet::ConstraintBullet() {} void ConstraintBullet::setup(btTypedConstraint *p_constraint) { constraint = p_constraint; diff --git a/modules/bullet/constraint_bullet.h b/modules/bullet/constraint_bullet.h index 89ad150257..538808be51 100644 --- a/modules/bullet/constraint_bullet.h +++ b/modules/bullet/constraint_bullet.h @@ -45,11 +45,10 @@ class SpaceBullet; class btTypedConstraint; class ConstraintBullet : public RIDBullet { - protected: - SpaceBullet *space; - btTypedConstraint *constraint; - bool disabled_collisions_between_bodies; + SpaceBullet *space = nullptr; + btTypedConstraint *constraint = nullptr; + bool disabled_collisions_between_bodies = true; public: ConstraintBullet(); @@ -64,7 +63,7 @@ public: public: virtual ~ConstraintBullet() { bulletdelete(constraint); - constraint = NULL; + constraint = nullptr; } _FORCE_INLINE_ btTypedConstraint *get_bt_constraint() { return constraint; } diff --git a/modules/bullet/doc_classes/BulletPhysicsDirectBodyState.xml b/modules/bullet/doc_classes/BulletPhysicsDirectBodyState.xml deleted file mode 100644 index 5ea1b810a1..0000000000 --- a/modules/bullet/doc_classes/BulletPhysicsDirectBodyState.xml +++ /dev/null @@ -1,13 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="BulletPhysicsDirectBodyState" inherits="PhysicsDirectBodyState" version="4.0"> - <brief_description> - </brief_description> - <description> - </description> - <tutorials> - </tutorials> - <methods> - </methods> - <constants> - </constants> -</class> diff --git a/modules/bullet/doc_classes/BulletPhysicsServer.xml b/modules/bullet/doc_classes/BulletPhysicsServer.xml deleted file mode 100644 index af8fb3c02c..0000000000 --- a/modules/bullet/doc_classes/BulletPhysicsServer.xml +++ /dev/null @@ -1,13 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="BulletPhysicsServer" inherits="PhysicsServer" version="4.0"> - <brief_description> - </brief_description> - <description> - </description> - <tutorials> - </tutorials> - <methods> - </methods> - <constants> - </constants> -</class> diff --git a/modules/bullet/generic_6dof_joint_bullet.cpp b/modules/bullet/generic_6dof_joint_bullet.cpp index a6a01ebaa8..56a66dba45 100644 --- a/modules/bullet/generic_6dof_joint_bullet.cpp +++ b/modules/bullet/generic_6dof_joint_bullet.cpp @@ -42,6 +42,11 @@ Generic6DOFJointBullet::Generic6DOFJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &frameInA, const Transform &frameInB) : JointBullet() { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < PhysicsServer3D::G6DOF_JOINT_FLAG_MAX; j++) { + flags[i][j] = false; + } + } Transform scaled_AFrame(frameInA.scaled(rbA->get_body_scale())); diff --git a/modules/bullet/godot_collision_configuration.cpp b/modules/bullet/godot_collision_configuration.cpp index f3e3a01a52..ec7a1dbd9a 100644 --- a/modules/bullet/godot_collision_configuration.cpp +++ b/modules/bullet/godot_collision_configuration.cpp @@ -41,8 +41,7 @@ GodotCollisionConfiguration::GodotCollisionConfiguration(const btDiscreteDynamicsWorld *world, const btDefaultCollisionConstructionInfo &constructionInfo) : btDefaultCollisionConfiguration(constructionInfo) { - - void *mem = NULL; + void *mem = nullptr; mem = btAlignedAlloc(sizeof(GodotRayWorldAlgorithm::CreateFunc), 16); m_rayWorldCF = new (mem) GodotRayWorldAlgorithm::CreateFunc(world); @@ -60,45 +59,34 @@ GodotCollisionConfiguration::~GodotCollisionConfiguration() { } btCollisionAlgorithmCreateFunc *GodotCollisionConfiguration::getCollisionAlgorithmCreateFunc(int proxyType0, int proxyType1) { - if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0 && CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - // This collision is not supported return m_emptyCreateFunc; } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0) { - return m_rayWorldCF; } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - return m_swappedRayWorldCF; } else { - return btDefaultCollisionConfiguration::getCollisionAlgorithmCreateFunc(proxyType0, proxyType1); } } btCollisionAlgorithmCreateFunc *GodotCollisionConfiguration::getClosestPointsAlgorithmCreateFunc(int proxyType0, int proxyType1) { - if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0 && CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - // This collision is not supported return m_emptyCreateFunc; } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0) { - return m_rayWorldCF; } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - return m_swappedRayWorldCF; } else { - return btDefaultCollisionConfiguration::getClosestPointsAlgorithmCreateFunc(proxyType0, proxyType1); } } GodotSoftCollisionConfiguration::GodotSoftCollisionConfiguration(const btDiscreteDynamicsWorld *world, const btDefaultCollisionConstructionInfo &constructionInfo) : btSoftBodyRigidBodyCollisionConfiguration(constructionInfo) { - - void *mem = NULL; + void *mem = nullptr; mem = btAlignedAlloc(sizeof(GodotRayWorldAlgorithm::CreateFunc), 16); m_rayWorldCF = new (mem) GodotRayWorldAlgorithm::CreateFunc(world); @@ -116,37 +104,27 @@ GodotSoftCollisionConfiguration::~GodotSoftCollisionConfiguration() { } btCollisionAlgorithmCreateFunc *GodotSoftCollisionConfiguration::getCollisionAlgorithmCreateFunc(int proxyType0, int proxyType1) { - if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0 && CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - // This collision is not supported return m_emptyCreateFunc; } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0) { - return m_rayWorldCF; } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - return m_swappedRayWorldCF; } else { - return btSoftBodyRigidBodyCollisionConfiguration::getCollisionAlgorithmCreateFunc(proxyType0, proxyType1); } } btCollisionAlgorithmCreateFunc *GodotSoftCollisionConfiguration::getClosestPointsAlgorithmCreateFunc(int proxyType0, int proxyType1) { - if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0 && CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - // This collision is not supported return m_emptyCreateFunc; } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0) { - return m_rayWorldCF; } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - return m_swappedRayWorldCF; } else { - return btSoftBodyRigidBodyCollisionConfiguration::getClosestPointsAlgorithmCreateFunc(proxyType0, proxyType1); } } diff --git a/modules/bullet/godot_motion_state.h b/modules/bullet/godot_motion_state.h index e2c1b10e94..90d1614a77 100644 --- a/modules/bullet/godot_motion_state.h +++ b/modules/bullet/godot_motion_state.h @@ -46,7 +46,6 @@ class RigidBodyBullet; /// DOC: /// http://www.bulletphysics.org/mediawiki-1.5.8/index.php/MotionStates#What.27s_a_MotionState.3F class GodotMotionState : public btMotionState { - /// This data is used to store the new world position for kinematic body btTransform bodyKinematicWorldTransf; /// This data is used to store last world position diff --git a/modules/bullet/godot_ray_world_algorithm.cpp b/modules/bullet/godot_ray_world_algorithm.cpp index 2ef277cf5b..a84f3511ba 100644 --- a/modules/bullet/godot_ray_world_algorithm.cpp +++ b/modules/bullet/godot_ray_world_algorithm.cpp @@ -52,7 +52,6 @@ GodotRayWorldAlgorithm::GodotRayWorldAlgorithm(const btDiscreteDynamicsWorld *wo btActivatingCollisionAlgorithm(ci, body0Wrap, body1Wrap), m_world(world), m_manifoldPtr(mf), - m_ownManifold(false), m_isSwapped(isSwapped) {} GodotRayWorldAlgorithm::~GodotRayWorldAlgorithm() { @@ -62,7 +61,6 @@ GodotRayWorldAlgorithm::~GodotRayWorldAlgorithm() { } void GodotRayWorldAlgorithm::processCollision(const btCollisionObjectWrapper *body0Wrap, const btCollisionObjectWrapper *body1Wrap, const btDispatcherInfo &dispatchInfo, btManifoldResult *resultOut) { - if (!m_manifoldPtr) { if (m_isSwapped) { m_manifoldPtr = m_dispatcher->getNewManifold(body1Wrap->getCollisionObject(), body0Wrap->getCollisionObject()); @@ -80,13 +78,11 @@ void GodotRayWorldAlgorithm::processCollision(const btCollisionObjectWrapper *bo const btCollisionObjectWrapper *other_co_wrapper; if (m_isSwapped) { - ray_shape = static_cast<const btRayShape *>(body1Wrap->getCollisionShape()); ray_transform = body1Wrap->getWorldTransform(); other_co_wrapper = body0Wrap; } else { - ray_shape = static_cast<const btRayShape *>(body0Wrap->getCollisionShape()); ray_transform = body0Wrap->getWorldTransform(); @@ -100,15 +96,15 @@ void GodotRayWorldAlgorithm::processCollision(const btCollisionObjectWrapper *bo m_world->rayTestSingleInternal(ray_transform, to, other_co_wrapper, btResult); if (btResult.hasHit()) { - btScalar depth(ray_shape->getScaledLength() * (btResult.m_closestHitFraction - 1)); - if (depth > -RAY_PENETRATION_DEPTH_EPSILON) + if (depth > -RAY_PENETRATION_DEPTH_EPSILON) { depth = 0.0; + } - if (ray_shape->getSlipsOnSlope()) + if (ray_shape->getSlipsOnSlope()) { resultOut->addContactPoint(btResult.m_hitNormalWorld, btResult.m_hitPointWorld, depth); - else { + } else { resultOut->addContactPoint((ray_transform.getOrigin() - to.getOrigin()).normalize(), btResult.m_hitPointWorld, depth); } } diff --git a/modules/bullet/godot_ray_world_algorithm.h b/modules/bullet/godot_ray_world_algorithm.h index 2cdea6c133..9786732d40 100644 --- a/modules/bullet/godot_ray_world_algorithm.h +++ b/modules/bullet/godot_ray_world_algorithm.h @@ -42,10 +42,9 @@ class btDiscreteDynamicsWorld; class GodotRayWorldAlgorithm : public btActivatingCollisionAlgorithm { - const btDiscreteDynamicsWorld *m_world; btPersistentManifold *m_manifoldPtr; - bool m_ownManifold; + bool m_ownManifold = false; bool m_isSwapped; public: @@ -57,11 +56,11 @@ public: virtual void getAllContactManifolds(btManifoldArray &manifoldArray) { ///should we use m_ownManifold to avoid adding duplicates? - if (m_manifoldPtr && m_ownManifold) + if (m_manifoldPtr && m_ownManifold) { manifoldArray.push_back(m_manifoldPtr); + } } struct CreateFunc : public btCollisionAlgorithmCreateFunc { - const btDiscreteDynamicsWorld *m_world; CreateFunc(const btDiscreteDynamicsWorld *world); @@ -72,7 +71,6 @@ public: }; struct SwappedCreateFunc : public btCollisionAlgorithmCreateFunc { - const btDiscreteDynamicsWorld *m_world; SwappedCreateFunc(const btDiscreteDynamicsWorld *world); diff --git a/modules/bullet/godot_result_callbacks.cpp b/modules/bullet/godot_result_callbacks.cpp index ad054e3027..f82648d6ff 100644 --- a/modules/bullet/godot_result_callbacks.cpp +++ b/modules/bullet/godot_result_callbacks.cpp @@ -62,11 +62,13 @@ bool GodotClosestRayResultCallback::needsCollision(btBroadphaseProxy *proxy0) co CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) { - if (!collide_with_areas) + if (!collide_with_areas) { return false; + } } else { - if (!collide_with_bodies) + if (!collide_with_bodies) { return false; + } } if (m_pickRay && !gObj->is_ray_pickable()) { @@ -84,8 +86,9 @@ bool GodotClosestRayResultCallback::needsCollision(btBroadphaseProxy *proxy0) co } bool GodotAllConvexResultCallback::needsCollision(btBroadphaseProxy *proxy0) const { - if (count >= m_resultMax) + if (count >= m_resultMax) { return false; + } const bool needs = GodotFilterCallback::test_collision_filters(m_collisionFilterGroup, m_collisionFilterMask, proxy0->m_collisionFilterGroup, proxy0->m_collisionFilterMask); if (needs) { @@ -102,8 +105,9 @@ bool GodotAllConvexResultCallback::needsCollision(btBroadphaseProxy *proxy0) con } btScalar GodotAllConvexResultCallback::addSingleResult(btCollisionWorld::LocalConvexResult &convexResult, bool normalInWorldSpace) { - if (count >= m_resultMax) + if (count >= m_resultMax) { return 1; // not used by bullet + } CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(convexResult.m_hitCollisionObject->getUserPointer()); @@ -112,7 +116,7 @@ btScalar GodotAllConvexResultCallback::addSingleResult(btCollisionWorld::LocalCo result.shape = convexResult.m_localShapeInfo->m_triangleIndex; // "m_triangleIndex" Is a odd name but contains the compound shape ID result.rid = gObj->get_self(); result.collider_id = gObj->get_instance_id(); - result.collider = result.collider_id.is_null() ? NULL : ObjectDB::get_instance(result.collider_id); + result.collider = result.collider_id.is_null() ? nullptr : ObjectDB::get_instance(result.collider_id); ++count; return 1; // not used by bullet @@ -126,16 +130,18 @@ bool GodotKinClosestConvexResultCallback::needsCollision(btBroadphaseProxy *prox if (gObj == m_self_object) { return false; } else { - // A kinematic body can't be stopped by a rigid body since the mass of kinematic body is infinite - if (m_infinite_inertia && !btObj->isStaticOrKinematicObject()) + if (m_infinite_inertia && !btObj->isStaticOrKinematicObject()) { return false; + } - if (gObj->getType() == CollisionObjectBullet::TYPE_AREA) + if (gObj->getType() == CollisionObjectBullet::TYPE_AREA) { return false; + } - if (m_self_object->has_collision_exception(gObj) || gObj->has_collision_exception(m_self_object)) + if (m_self_object->has_collision_exception(gObj) || gObj->has_collision_exception(m_self_object)) { return false; + } } return true; } else { @@ -150,11 +156,13 @@ bool GodotClosestConvexResultCallback::needsCollision(btBroadphaseProxy *proxy0) CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) { - if (!collide_with_areas) + if (!collide_with_areas) { return false; + } } else { - if (!collide_with_bodies) + if (!collide_with_bodies) { return false; + } } if (m_exclude->has(gObj->get_self())) { @@ -167,16 +175,18 @@ bool GodotClosestConvexResultCallback::needsCollision(btBroadphaseProxy *proxy0) } btScalar GodotClosestConvexResultCallback::addSingleResult(btCollisionWorld::LocalConvexResult &convexResult, bool normalInWorldSpace) { - if (convexResult.m_localShapeInfo) + if (convexResult.m_localShapeInfo) { m_shapeId = convexResult.m_localShapeInfo->m_triangleIndex; // "m_triangleIndex" Is a odd name but contains the compound shape ID - else + } else { m_shapeId = 0; + } return btCollisionWorld::ClosestConvexResultCallback::addSingleResult(convexResult, normalInWorldSpace); } bool GodotAllContactResultCallback::needsCollision(btBroadphaseProxy *proxy0) const { - if (m_count >= m_resultMax) + if (m_count >= m_resultMax) { return false; + } const bool needs = GodotFilterCallback::test_collision_filters(m_collisionFilterGroup, m_collisionFilterMask, proxy0->m_collisionFilterGroup, proxy0->m_collisionFilterMask); if (needs) { @@ -184,11 +194,13 @@ bool GodotAllContactResultCallback::needsCollision(btBroadphaseProxy *proxy0) co CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) { - if (!collide_with_areas) + if (!collide_with_areas) { return false; + } } else { - if (!collide_with_bodies) + if (!collide_with_bodies) { return false; + } } if (m_exclude->has(gObj->get_self())) { @@ -201,12 +213,11 @@ bool GodotAllContactResultCallback::needsCollision(btBroadphaseProxy *proxy0) co } btScalar GodotAllContactResultCallback::addSingleResult(btManifoldPoint &cp, const btCollisionObjectWrapper *colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper *colObj1Wrap, int partId1, int index1) { - - if (m_count >= m_resultMax) + if (m_count >= m_resultMax) { return cp.getDistance(); + } if (cp.getDistance() <= 0) { - PhysicsDirectSpaceState3D::ShapeResult &result = m_results[m_count]; // Penetrated @@ -220,7 +231,7 @@ btScalar GodotAllContactResultCallback::addSingleResult(btManifoldPoint &cp, con } result.collider_id = colObj->get_instance_id(); - result.collider = result.collider_id.is_null() ? NULL : ObjectDB::get_instance(result.collider_id); + result.collider = result.collider_id.is_null() ? nullptr : ObjectDB::get_instance(result.collider_id); result.rid = colObj->get_self(); ++m_count; } @@ -229,8 +240,9 @@ btScalar GodotAllContactResultCallback::addSingleResult(btManifoldPoint &cp, con } bool GodotContactPairContactResultCallback::needsCollision(btBroadphaseProxy *proxy0) const { - if (m_count >= m_resultMax) + if (m_count >= m_resultMax) { return false; + } const bool needs = GodotFilterCallback::test_collision_filters(m_collisionFilterGroup, m_collisionFilterMask, proxy0->m_collisionFilterGroup, proxy0->m_collisionFilterMask); if (needs) { @@ -238,11 +250,13 @@ bool GodotContactPairContactResultCallback::needsCollision(btBroadphaseProxy *pr CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) { - if (!collide_with_areas) + if (!collide_with_areas) { return false; + } } else { - if (!collide_with_bodies) + if (!collide_with_bodies) { return false; + } } if (m_exclude->has(gObj->get_self())) { @@ -255,8 +269,9 @@ bool GodotContactPairContactResultCallback::needsCollision(btBroadphaseProxy *pr } btScalar GodotContactPairContactResultCallback::addSingleResult(btManifoldPoint &cp, const btCollisionObjectWrapper *colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper *colObj1Wrap, int partId1, int index1) { - if (m_count >= m_resultMax) + if (m_count >= m_resultMax) { return 1; // not used by bullet + } if (m_self_object == colObj0Wrap->getCollisionObject()) { B_TO_G(cp.m_localPointA, m_results[m_count * 2 + 0]); // Local contact @@ -278,11 +293,13 @@ bool GodotRestInfoContactResultCallback::needsCollision(btBroadphaseProxy *proxy CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) { - if (!collide_with_areas) + if (!collide_with_areas) { return false; + } } else { - if (!collide_with_bodies) + if (!collide_with_bodies) { return false; + } } if (m_exclude->has(gObj->get_self())) { @@ -295,7 +312,6 @@ bool GodotRestInfoContactResultCallback::needsCollision(btBroadphaseProxy *proxy } btScalar GodotRestInfoContactResultCallback::addSingleResult(btManifoldPoint &cp, const btCollisionObjectWrapper *colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper *colObj1Wrap, int partId1, int index1) { - if (cp.getDistance() <= m_min_distance) { m_min_distance = cp.getDistance(); @@ -325,7 +341,6 @@ btScalar GodotRestInfoContactResultCallback::addSingleResult(btManifoldPoint &cp } void GodotDeepPenetrationContactResultCallback::addContactPoint(const btVector3 &normalOnBInWorld, const btVector3 &pointInWorldOnB, btScalar depth) { - if (m_penetration_distance > depth) { // Has penetration? const bool isSwapped = m_manifoldPtr->getBody0() != m_body0Wrap->getCollisionObject(); diff --git a/modules/bullet/godot_result_callbacks.h b/modules/bullet/godot_result_callbacks.h index 7e74a2b22e..1325542973 100644 --- a/modules/bullet/godot_result_callbacks.h +++ b/modules/bullet/godot_result_callbacks.h @@ -56,8 +56,8 @@ struct GodotFilterCallback : public btOverlapFilterCallback { /// It performs an additional check allow exclusions. struct GodotClosestRayResultCallback : public btCollisionWorld::ClosestRayResultCallback { const Set<RID> *m_exclude; - bool m_pickRay; - int m_shapeId; + bool m_pickRay = false; + int m_shapeId = 0; bool collide_with_bodies; bool collide_with_areas; @@ -66,18 +66,17 @@ public: GodotClosestRayResultCallback(const btVector3 &rayFromWorld, const btVector3 &rayToWorld, const Set<RID> *p_exclude, bool p_collide_with_bodies, bool p_collide_with_areas) : btCollisionWorld::ClosestRayResultCallback(rayFromWorld, rayToWorld), m_exclude(p_exclude), - m_pickRay(false), - m_shapeId(0), collide_with_bodies(p_collide_with_bodies), collide_with_areas(p_collide_with_areas) {} virtual bool needsCollision(btBroadphaseProxy *proxy0) const; virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult &rayResult, bool normalInWorldSpace) { - if (rayResult.m_localShapeInfo) + if (rayResult.m_localShapeInfo) { m_shapeId = rayResult.m_localShapeInfo->m_triangleIndex; // "m_triangleIndex" Is a odd name but contains the compound shape ID - else + } else { m_shapeId = 0; + } return btCollisionWorld::ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace); } }; @@ -88,13 +87,12 @@ public: PhysicsDirectSpaceState3D::ShapeResult *m_results; int m_resultMax; const Set<RID> *m_exclude; - int count; + int count = 0; GodotAllConvexResultCallback(PhysicsDirectSpaceState3D::ShapeResult *p_results, int p_resultMax, const Set<RID> *p_exclude) : m_results(p_results), m_resultMax(p_resultMax), - m_exclude(p_exclude), - count(0) {} + m_exclude(p_exclude) {} virtual bool needsCollision(btBroadphaseProxy *proxy0) const; @@ -117,7 +115,7 @@ public: struct GodotClosestConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback { public: const Set<RID> *m_exclude; - int m_shapeId; + int m_shapeId = 0; bool collide_with_bodies; bool collide_with_areas; @@ -125,7 +123,6 @@ public: GodotClosestConvexResultCallback(const btVector3 &convexFromWorld, const btVector3 &convexToWorld, const Set<RID> *p_exclude, bool p_collide_with_bodies, bool p_collide_with_areas) : btCollisionWorld::ClosestConvexResultCallback(convexFromWorld, convexToWorld), m_exclude(p_exclude), - m_shapeId(0), collide_with_bodies(p_collide_with_bodies), collide_with_areas(p_collide_with_areas) {} @@ -140,7 +137,7 @@ public: PhysicsDirectSpaceState3D::ShapeResult *m_results; int m_resultMax; const Set<RID> *m_exclude; - int m_count; + int m_count = 0; bool collide_with_bodies; bool collide_with_areas; @@ -150,7 +147,6 @@ public: m_results(p_results), m_resultMax(p_resultMax), m_exclude(p_exclude), - m_count(0), collide_with_bodies(p_collide_with_bodies), collide_with_areas(p_collide_with_areas) {} @@ -166,7 +162,7 @@ public: Vector3 *m_results; int m_resultMax; const Set<RID> *m_exclude; - int m_count; + int m_count = 0; bool collide_with_bodies; bool collide_with_areas; @@ -176,7 +172,6 @@ public: m_results(p_results), m_resultMax(p_resultMax), m_exclude(p_exclude), - m_count(0), collide_with_bodies(p_collide_with_bodies), collide_with_areas(p_collide_with_areas) {} @@ -190,8 +185,8 @@ public: const btCollisionObject *m_self_object; PhysicsDirectSpaceState3D::ShapeRestInfo *m_result; const Set<RID> *m_exclude; - bool m_collided; - real_t m_min_distance; + bool m_collided = false; + real_t m_min_distance = 0; const btCollisionObject *m_rest_info_collision_object; btVector3 m_rest_info_bt_point; bool collide_with_bodies; @@ -201,8 +196,6 @@ public: m_self_object(p_self_object), m_result(p_result), m_exclude(p_exclude), - m_collided(false), - m_min_distance(0), collide_with_bodies(p_collide_with_bodies), collide_with_areas(p_collide_with_areas) {} @@ -214,13 +207,11 @@ public: struct GodotDeepPenetrationContactResultCallback : public btManifoldResult { btVector3 m_pointNormalWorld; btVector3 m_pointWorld; - btScalar m_penetration_distance; - int m_other_compound_shape_index; + btScalar m_penetration_distance = 0; + int m_other_compound_shape_index = 0; GodotDeepPenetrationContactResultCallback(const btCollisionObjectWrapper *body0Wrap, const btCollisionObjectWrapper *body1Wrap) : - btManifoldResult(body0Wrap, body1Wrap), - m_penetration_distance(0), - m_other_compound_shape_index(0) {} + btManifoldResult(body0Wrap, body1Wrap) {} void reset() { m_penetration_distance = 0; diff --git a/modules/bullet/hinge_joint_bullet.cpp b/modules/bullet/hinge_joint_bullet.cpp index eaac1d650d..2338277565 100644 --- a/modules/bullet/hinge_joint_bullet.cpp +++ b/modules/bullet/hinge_joint_bullet.cpp @@ -42,7 +42,6 @@ HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &frameA, const Transform &frameB) : JointBullet() { - Transform scaled_AFrame(frameA.scaled(rbA->get_body_scale())); scaled_AFrame.basis.rotref_posscale_decomposition(scaled_AFrame.basis); @@ -50,7 +49,6 @@ HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, c G_TO_B(scaled_AFrame, btFrameA); if (rbB) { - Transform scaled_BFrame(frameB.scaled(rbB->get_body_scale())); scaled_BFrame.basis.rotref_posscale_decomposition(scaled_BFrame.basis); @@ -59,7 +57,6 @@ HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, c hingeConstraint = bulletnew(btHingeConstraint(*rbA->get_bt_rigid_body(), *rbB->get_bt_rigid_body(), btFrameA, btFrameB)); } else { - hingeConstraint = bulletnew(btHingeConstraint(*rbA->get_bt_rigid_body(), btFrameA)); } @@ -68,7 +65,6 @@ HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, c HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Vector3 &pivotInA, const Vector3 &pivotInB, const Vector3 &axisInA, const Vector3 &axisInB) : JointBullet() { - btVector3 btPivotA; btVector3 btAxisA; G_TO_B(pivotInA * rbA->get_body_scale(), btPivotA); @@ -82,7 +78,6 @@ HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, c hingeConstraint = bulletnew(btHingeConstraint(*rbA->get_bt_rigid_body(), *rbB->get_bt_rigid_body(), btPivotA, btPivotB, btAxisA, btAxisB)); } else { - hingeConstraint = bulletnew(btHingeConstraint(*rbA->get_bt_rigid_body(), btPivotA, btAxisA)); } @@ -96,7 +91,7 @@ real_t HingeJointBullet::get_hinge_angle() { void HingeJointBullet::set_param(PhysicsServer3D::HingeJointParam p_param, real_t p_value) { switch (p_param) { case PhysicsServer3D::HINGE_JOINT_BIAS: - WARN_DEPRECATED_MSG("The HingeJoint parameter \"bias\" is deprecated."); + WARN_DEPRECATED_MSG("The HingeJoint3D parameter \"bias\" is deprecated."); break; case PhysicsServer3D::HINGE_JOINT_LIMIT_UPPER: hingeConstraint->setLimit(hingeConstraint->getLowerLimit(), p_value, hingeConstraint->getLimitSoftness(), hingeConstraint->getLimitBiasFactor(), hingeConstraint->getLimitRelaxationFactor()); @@ -128,7 +123,7 @@ void HingeJointBullet::set_param(PhysicsServer3D::HingeJointParam p_param, real_ real_t HingeJointBullet::get_param(PhysicsServer3D::HingeJointParam p_param) const { switch (p_param) { case PhysicsServer3D::HINGE_JOINT_BIAS: - WARN_DEPRECATED_MSG("The HingeJoint parameter \"bias\" is deprecated."); + WARN_DEPRECATED_MSG("The HingeJoint3D parameter \"bias\" is deprecated."); return 0; case PhysicsServer3D::HINGE_JOINT_LIMIT_UPPER: return hingeConstraint->getUpperLimit(); @@ -162,7 +157,8 @@ void HingeJointBullet::set_flag(PhysicsServer3D::HingeJointFlag p_flag, bool p_v case PhysicsServer3D::HINGE_JOINT_FLAG_ENABLE_MOTOR: hingeConstraint->enableMotor(p_value); break; - case PhysicsServer3D::HINGE_JOINT_FLAG_MAX: break; // Can't happen, but silences warning + case PhysicsServer3D::HINGE_JOINT_FLAG_MAX: + break; // Can't happen, but silences warning } } diff --git a/modules/bullet/joint_bullet.h b/modules/bullet/joint_bullet.h index 9cb8aab276..c70cea817e 100644 --- a/modules/bullet/joint_bullet.h +++ b/modules/bullet/joint_bullet.h @@ -42,7 +42,6 @@ class RigidBodyBullet; class btTypedConstraint; class JointBullet : public ConstraintBullet { - public: JointBullet(); virtual ~JointBullet(); diff --git a/modules/bullet/pin_joint_bullet.cpp b/modules/bullet/pin_joint_bullet.cpp index 68b40d7405..1cfbc65c78 100644 --- a/modules/bullet/pin_joint_bullet.cpp +++ b/modules/bullet/pin_joint_bullet.cpp @@ -42,7 +42,6 @@ PinJointBullet::PinJointBullet(RigidBodyBullet *p_body_a, const Vector3 &p_pos_a, RigidBodyBullet *p_body_b, const Vector3 &p_pos_b) : JointBullet() { if (p_body_b) { - btVector3 btPivotA; btVector3 btPivotB; G_TO_B(p_pos_a * p_body_a->get_body_scale(), btPivotA); diff --git a/modules/bullet/rigid_body_bullet.cpp b/modules/bullet/rigid_body_bullet.cpp index b92166e653..9aac7ba9e4 100644 --- a/modules/bullet/rigid_body_bullet.cpp +++ b/modules/bullet/rigid_body_bullet.cpp @@ -48,141 +48,141 @@ @author AndreaCatania */ -BulletPhysicsDirectBodyState *BulletPhysicsDirectBodyState::singleton = NULL; +BulletPhysicsDirectBodyState3D *BulletPhysicsDirectBodyState3D::singleton = nullptr; -Vector3 BulletPhysicsDirectBodyState::get_total_gravity() const { +Vector3 BulletPhysicsDirectBodyState3D::get_total_gravity() const { Vector3 gVec; B_TO_G(body->btBody->getGravity(), gVec); return gVec; } -float BulletPhysicsDirectBodyState::get_total_angular_damp() const { +float BulletPhysicsDirectBodyState3D::get_total_angular_damp() const { return body->btBody->getAngularDamping(); } -float BulletPhysicsDirectBodyState::get_total_linear_damp() const { +float BulletPhysicsDirectBodyState3D::get_total_linear_damp() const { return body->btBody->getLinearDamping(); } -Vector3 BulletPhysicsDirectBodyState::get_center_of_mass() const { +Vector3 BulletPhysicsDirectBodyState3D::get_center_of_mass() const { Vector3 gVec; B_TO_G(body->btBody->getCenterOfMassPosition(), gVec); return gVec; } -Basis BulletPhysicsDirectBodyState::get_principal_inertia_axes() const { +Basis BulletPhysicsDirectBodyState3D::get_principal_inertia_axes() const { return Basis(); } -float BulletPhysicsDirectBodyState::get_inverse_mass() const { +float BulletPhysicsDirectBodyState3D::get_inverse_mass() const { return body->btBody->getInvMass(); } -Vector3 BulletPhysicsDirectBodyState::get_inverse_inertia() const { +Vector3 BulletPhysicsDirectBodyState3D::get_inverse_inertia() const { Vector3 gVec; B_TO_G(body->btBody->getInvInertiaDiagLocal(), gVec); return gVec; } -Basis BulletPhysicsDirectBodyState::get_inverse_inertia_tensor() const { +Basis BulletPhysicsDirectBodyState3D::get_inverse_inertia_tensor() const { Basis gInertia; B_TO_G(body->btBody->getInvInertiaTensorWorld(), gInertia); return gInertia; } -void BulletPhysicsDirectBodyState::set_linear_velocity(const Vector3 &p_velocity) { +void BulletPhysicsDirectBodyState3D::set_linear_velocity(const Vector3 &p_velocity) { body->set_linear_velocity(p_velocity); } -Vector3 BulletPhysicsDirectBodyState::get_linear_velocity() const { +Vector3 BulletPhysicsDirectBodyState3D::get_linear_velocity() const { return body->get_linear_velocity(); } -void BulletPhysicsDirectBodyState::set_angular_velocity(const Vector3 &p_velocity) { +void BulletPhysicsDirectBodyState3D::set_angular_velocity(const Vector3 &p_velocity) { body->set_angular_velocity(p_velocity); } -Vector3 BulletPhysicsDirectBodyState::get_angular_velocity() const { +Vector3 BulletPhysicsDirectBodyState3D::get_angular_velocity() const { return body->get_angular_velocity(); } -void BulletPhysicsDirectBodyState::set_transform(const Transform &p_transform) { +void BulletPhysicsDirectBodyState3D::set_transform(const Transform &p_transform) { body->set_transform(p_transform); } -Transform BulletPhysicsDirectBodyState::get_transform() const { +Transform BulletPhysicsDirectBodyState3D::get_transform() const { return body->get_transform(); } -void BulletPhysicsDirectBodyState::add_central_force(const Vector3 &p_force) { +void BulletPhysicsDirectBodyState3D::add_central_force(const Vector3 &p_force) { body->apply_central_force(p_force); } -void BulletPhysicsDirectBodyState::add_force(const Vector3 &p_force, const Vector3 &p_pos) { +void BulletPhysicsDirectBodyState3D::add_force(const Vector3 &p_force, const Vector3 &p_pos) { body->apply_force(p_force, p_pos); } -void BulletPhysicsDirectBodyState::add_torque(const Vector3 &p_torque) { +void BulletPhysicsDirectBodyState3D::add_torque(const Vector3 &p_torque) { body->apply_torque(p_torque); } -void BulletPhysicsDirectBodyState::apply_central_impulse(const Vector3 &p_impulse) { +void BulletPhysicsDirectBodyState3D::apply_central_impulse(const Vector3 &p_impulse) { body->apply_central_impulse(p_impulse); } -void BulletPhysicsDirectBodyState::apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse) { +void BulletPhysicsDirectBodyState3D::apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse) { body->apply_impulse(p_pos, p_impulse); } -void BulletPhysicsDirectBodyState::apply_torque_impulse(const Vector3 &p_impulse) { +void BulletPhysicsDirectBodyState3D::apply_torque_impulse(const Vector3 &p_impulse) { body->apply_torque_impulse(p_impulse); } -void BulletPhysicsDirectBodyState::set_sleep_state(bool p_enable) { - body->set_activation_state(p_enable); +void BulletPhysicsDirectBodyState3D::set_sleep_state(bool p_sleep) { + body->set_activation_state(!p_sleep); } -bool BulletPhysicsDirectBodyState::is_sleeping() const { +bool BulletPhysicsDirectBodyState3D::is_sleeping() const { return !body->is_active(); } -int BulletPhysicsDirectBodyState::get_contact_count() const { +int BulletPhysicsDirectBodyState3D::get_contact_count() const { return body->collisionsCount; } -Vector3 BulletPhysicsDirectBodyState::get_contact_local_position(int p_contact_idx) const { +Vector3 BulletPhysicsDirectBodyState3D::get_contact_local_position(int p_contact_idx) const { return body->collisions[p_contact_idx].hitLocalLocation; } -Vector3 BulletPhysicsDirectBodyState::get_contact_local_normal(int p_contact_idx) const { +Vector3 BulletPhysicsDirectBodyState3D::get_contact_local_normal(int p_contact_idx) const { return body->collisions[p_contact_idx].hitNormal; } -float BulletPhysicsDirectBodyState::get_contact_impulse(int p_contact_idx) const { +float BulletPhysicsDirectBodyState3D::get_contact_impulse(int p_contact_idx) const { return body->collisions[p_contact_idx].appliedImpulse; } -int BulletPhysicsDirectBodyState::get_contact_local_shape(int p_contact_idx) const { +int BulletPhysicsDirectBodyState3D::get_contact_local_shape(int p_contact_idx) const { return body->collisions[p_contact_idx].local_shape; } -RID BulletPhysicsDirectBodyState::get_contact_collider(int p_contact_idx) const { +RID BulletPhysicsDirectBodyState3D::get_contact_collider(int p_contact_idx) const { return body->collisions[p_contact_idx].otherObject->get_self(); } -Vector3 BulletPhysicsDirectBodyState::get_contact_collider_position(int p_contact_idx) const { +Vector3 BulletPhysicsDirectBodyState3D::get_contact_collider_position(int p_contact_idx) const { return body->collisions[p_contact_idx].hitWorldLocation; } -ObjectID BulletPhysicsDirectBodyState::get_contact_collider_id(int p_contact_idx) const { +ObjectID BulletPhysicsDirectBodyState3D::get_contact_collider_id(int p_contact_idx) const { return body->collisions[p_contact_idx].otherObject->get_instance_id(); } -int BulletPhysicsDirectBodyState::get_contact_collider_shape(int p_contact_idx) const { +int BulletPhysicsDirectBodyState3D::get_contact_collider_shape(int p_contact_idx) const { return body->collisions[p_contact_idx].other_object_shape; } -Vector3 BulletPhysicsDirectBodyState::get_contact_collider_velocity_at_position(int p_contact_idx) const { +Vector3 BulletPhysicsDirectBodyState3D::get_contact_collider_velocity_at_position(int p_contact_idx) const { RigidBodyBullet::CollisionData &colDat = body->collisions.write[p_contact_idx]; btVector3 hitLocation; @@ -194,7 +194,7 @@ Vector3 BulletPhysicsDirectBodyState::get_contact_collider_velocity_at_position( return velocityAtPoint; } -PhysicsDirectSpaceState3D *BulletPhysicsDirectBodyState::get_space_state() { +PhysicsDirectSpaceState3D *BulletPhysicsDirectBodyState3D::get_space_state() { return body->get_space()->get_direct_state(); } @@ -241,7 +241,7 @@ void RigidBodyBullet::KinematicUtilities::copyAllOwnerShapes() { } break; default: WARN_PRINT("This shape is not supported for kinematic collision."); - shapes.write[i].shape = NULL; + shapes.write[i].shape = nullptr; } } } @@ -256,31 +256,12 @@ void RigidBodyBullet::KinematicUtilities::just_delete_shapes(int new_size) { } RigidBodyBullet::RigidBodyBullet() : - RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_RIGID_BODY), - kinematic_utilities(NULL), - locked_axis(0), - mass(1), - gravity_scale(1), - linearDamp(0), - angularDamp(0), - can_sleep(true), - omit_forces_integration(false), - can_integrate_forces(false), - maxCollisionsDetection(0), - collisionsCount(0), - prev_collision_count(0), - maxAreasWhereIam(10), - areaWhereIamCount(0), - countGravityPointSpaces(0), - isScratchedSpaceOverrideModificator(false), - previousActiveState(true), - force_integration_callback(NULL) { - + RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_RIGID_BODY) { godotMotionState = bulletnew(GodotMotionState(this)); // Initial properties const btVector3 localInertia(0, 0, 0); - btRigidBody::btRigidBodyConstructionInfo cInfo(mass, godotMotionState, NULL, localInertia); + btRigidBody::btRigidBodyConstructionInfo cInfo(mass, godotMotionState, nullptr, localInertia); btBody = bulletnew(btRigidBody(cInfo)); reload_shapes(); @@ -291,7 +272,7 @@ RigidBodyBullet::RigidBodyBullet() : areasWhereIam.resize(maxAreasWhereIam); for (int i = areasWhereIam.size() - 1; 0 <= i; --i) { - areasWhereIam.write[i] = NULL; + areasWhereIam.write[i] = nullptr; } btBody->setSleepingThresholds(0.2, 0.2); @@ -302,8 +283,9 @@ RigidBodyBullet::RigidBodyBullet() : RigidBodyBullet::~RigidBodyBullet() { bulletdelete(godotMotionState); - if (force_integration_callback) + if (force_integration_callback) { memdelete(force_integration_callback); + } destroy_kinematic_utilities(); } @@ -315,7 +297,7 @@ void RigidBodyBullet::init_kinematic_utilities() { void RigidBodyBullet::destroy_kinematic_utilities() { if (kinematic_utilities) { memdelete(kinematic_utilities); - kinematic_utilities = NULL; + kinematic_utilities = nullptr; } } @@ -328,8 +310,9 @@ void RigidBodyBullet::main_shape_changed() { void RigidBodyBullet::reload_body() { if (space) { space->remove_rigid_body(this); - if (get_main_shape()) + if (get_main_shape()) { space->add_rigid_body(this); + } } } @@ -355,11 +338,11 @@ void RigidBodyBullet::set_space(SpaceBullet *p_space) { void RigidBodyBullet::dispatch_callbacks() { /// The check isFirstTransformChanged is necessary in order to call integrated forces only when the first transform is sent if ((btBody->isKinematicObject() || btBody->isActive() || previousActiveState != btBody->isActive()) && force_integration_callback && can_integrate_forces) { - - if (omit_forces_integration) + if (omit_forces_integration) { btBody->clearForces(); + } - BulletPhysicsDirectBodyState *bodyDirect = BulletPhysicsDirectBodyState::get_singleton(this); + BulletPhysicsDirectBodyState3D *bodyDirect = BulletPhysicsDirectBodyState3D::get_singleton(this); Variant variantBodyDirect = bodyDirect; @@ -389,10 +372,9 @@ void RigidBodyBullet::dispatch_callbacks() { } void RigidBodyBullet::set_force_integration_callback(ObjectID p_id, const StringName &p_method, const Variant &p_udata) { - if (force_integration_callback) { memdelete(force_integration_callback); - force_integration_callback = NULL; + force_integration_callback = nullptr; } if (p_id.is_valid()) { @@ -416,7 +398,6 @@ void RigidBodyBullet::on_collision_filters_change() { } void RigidBodyBullet::on_collision_checker_start() { - prev_collision_count = collisionsCount; collisionsCount = 0; @@ -432,7 +413,6 @@ void RigidBodyBullet::on_collision_checker_end() { } bool RigidBodyBullet::add_collision_object(RigidBodyBullet *p_otherObject, const Vector3 &p_hitWorldLocation, const Vector3 &p_hitLocalLocation, const Vector3 &p_hitNormal, const float &p_appliedImpulse, int p_other_shape_index, int p_local_shape_index) { - if (collisionsCount >= maxCollisionsDetection) { return false; } @@ -454,8 +434,9 @@ bool RigidBodyBullet::add_collision_object(RigidBodyBullet *p_otherObject, const bool RigidBodyBullet::was_colliding(RigidBodyBullet *p_other_object) { for (int i = prev_collision_count - 1; 0 <= i; --i) { - if ((*prev_collision_traces)[i] == p_other_object) + if ((*prev_collision_traces)[i] == p_other_object) { return true; + } } return false; } @@ -464,11 +445,6 @@ void RigidBodyBullet::assert_no_constraints() { if (btBody->getNumConstraintRefs()) { WARN_PRINT("A body with a joints is destroyed. Please check the implementation in order to destroy the joint before the body."); } - /*for(int i = btBody->getNumConstraintRefs()-1; 0<=i; --i){ - btTypedConstraint* btConst = btBody->getConstraintRef(i); - JointBullet* joint = static_cast<JointBullet*>( btConst->getUserConstraintPtr() ); - space->removeConstraint(joint); - }*/ } void RigidBodyBullet::set_activation_state(bool p_active) { @@ -503,15 +479,18 @@ void RigidBodyBullet::set_param(PhysicsServer3D::BodyParameter p_param, real_t p } case PhysicsServer3D::BODY_PARAM_LINEAR_DAMP: linearDamp = p_value; - btBody->setDamping(linearDamp, angularDamp); + // Mark for updating total linear damping. + scratch_space_override_modificator(); break; case PhysicsServer3D::BODY_PARAM_ANGULAR_DAMP: angularDamp = p_value; - btBody->setDamping(linearDamp, angularDamp); + // Mark for updating total angular damping. + scratch_space_override_modificator(); break; case PhysicsServer3D::BODY_PARAM_GRAVITY_SCALE: gravity_scale = p_value; - /// The Bullet gravity will be is set by reload_space_override_modificator + // The Bullet gravity will be is set by reload_space_override_modificator. + // Mark for updating total gravity scale. scratch_space_override_modificator(); break; default: @@ -575,12 +554,12 @@ void RigidBodyBullet::set_mode(PhysicsServer3D::BodyMode p_mode) { btBody->setAngularVelocity(btVector3(0, 0, 0)); btBody->setLinearVelocity(btVector3(0, 0, 0)); } + PhysicsServer3D::BodyMode RigidBodyBullet::get_mode() const { return mode; } void RigidBodyBullet::set_state(PhysicsServer3D::BodyState p_state, const Variant &p_variant) { - switch (p_state) { case PhysicsServer3D::BODY_STATE_TRANSFORM: set_transform(p_variant); @@ -627,8 +606,9 @@ Variant RigidBodyBullet::get_state(PhysicsServer3D::BodyState p_state) const { void RigidBodyBullet::apply_central_impulse(const Vector3 &p_impulse) { btVector3 btImpu; G_TO_B(p_impulse, btImpu); - if (Vector3() != p_impulse) + if (Vector3() != p_impulse) { btBody->activate(); + } btBody->applyCentralImpulse(btImpu); } @@ -637,16 +617,18 @@ void RigidBodyBullet::apply_impulse(const Vector3 &p_pos, const Vector3 &p_impul btVector3 btPos; G_TO_B(p_impulse, btImpu); G_TO_B(p_pos, btPos); - if (Vector3() != p_impulse) + if (Vector3() != p_impulse) { btBody->activate(); + } btBody->applyImpulse(btImpu, btPos); } void RigidBodyBullet::apply_torque_impulse(const Vector3 &p_impulse) { btVector3 btImp; G_TO_B(p_impulse, btImp); - if (Vector3() != p_impulse) + if (Vector3() != p_impulse) { btBody->activate(); + } btBody->applyTorqueImpulse(btImp); } @@ -655,32 +637,36 @@ void RigidBodyBullet::apply_force(const Vector3 &p_force, const Vector3 &p_pos) btVector3 btPos; G_TO_B(p_force, btForce); G_TO_B(p_pos, btPos); - if (Vector3() != p_force) + if (Vector3() != p_force) { btBody->activate(); + } btBody->applyForce(btForce, btPos); } void RigidBodyBullet::apply_central_force(const Vector3 &p_force) { btVector3 btForce; G_TO_B(p_force, btForce); - if (Vector3() != p_force) + if (Vector3() != p_force) { btBody->activate(); + } btBody->applyCentralForce(btForce); } void RigidBodyBullet::apply_torque(const Vector3 &p_torque) { btVector3 btTorq; G_TO_B(p_torque, btTorq); - if (Vector3() != p_torque) + if (Vector3() != p_torque) { btBody->activate(); + } btBody->applyTorque(btTorq); } void RigidBodyBullet::set_applied_force(const Vector3 &p_force) { btVector3 btVec = btBody->getTotalTorque(); - if (Vector3() != p_force) + if (Vector3() != p_force) { btBody->activate(); + } btBody->clearForces(); btBody->applyTorque(btVec); @@ -698,8 +684,9 @@ Vector3 RigidBodyBullet::get_applied_force() const { void RigidBodyBullet::set_applied_torque(const Vector3 &p_torque) { btVector3 btVec = btBody->getTotalForce(); - if (Vector3() != p_torque) + if (Vector3() != p_torque) { btBody->activate(); + } btBody->clearForces(); btBody->applyCentralForce(btVec); @@ -729,7 +716,6 @@ bool RigidBodyBullet::is_axis_locked(PhysicsServer3D::BodyAxis p_axis) const { } void RigidBodyBullet::reload_axis_lock() { - btBody->setLinearFactor(btVector3(float(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_X)), float(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_Y)), float(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_Z)))); if (PhysicsServer3D::BODY_MODE_CHARACTER == mode) { /// When character angular is always locked @@ -768,8 +754,9 @@ bool RigidBodyBullet::is_continuous_collision_detection_enabled() const { void RigidBodyBullet::set_linear_velocity(const Vector3 &p_velocity) { btVector3 btVec; G_TO_B(p_velocity, btVec); - if (Vector3() != p_velocity) + if (Vector3() != p_velocity) { btBody->activate(); + } btBody->setLinearVelocity(btVec); } @@ -782,8 +769,9 @@ Vector3 RigidBodyBullet::get_linear_velocity() const { void RigidBodyBullet::set_angular_velocity(const Vector3 &p_velocity) { btVector3 btVec; G_TO_B(p_velocity, btVec); - if (Vector3() != p_velocity) + if (Vector3() != p_velocity) { btBody->activate(); + } btBody->setAngularVelocity(btVec); } @@ -795,8 +783,9 @@ Vector3 RigidBodyBullet::get_angular_velocity() const { void RigidBodyBullet::set_transform__bullet(const btTransform &p_global_transform) { if (mode == PhysicsServer3D::BODY_MODE_KINEMATIC) { - if (space && space->get_delta_time() != 0) + if (space && space->get_delta_time() != 0) { btBody->setLinearVelocity((p_global_transform.getOrigin() - btBody->getWorldTransform().getOrigin()) / space->get_delta_time()); + } // The kinematic use MotionState class godotMotionState->moveBody(p_global_transform); } else { @@ -808,10 +797,8 @@ void RigidBodyBullet::set_transform__bullet(const btTransform &p_global_transfor const btTransform &RigidBodyBullet::get_transform__bullet() const { if (is_static()) { - return RigidCollisionObjectBullet::get_transform__bullet(); } else { - return godotMotionState->getCurrentWorldTransform(); } } @@ -827,8 +814,9 @@ void RigidBodyBullet::reload_shapes() { // shapes incorrectly do not set the vector in calculateLocalIntertia. // Arbitrary zero is preferable to undefined behaviour. btVector3 inertia(0, 0, 0); - if (EMPTY_SHAPE_PROXYTYPE != mainShape->getShapeType()) // Necessary to avoid assertion of the empty shape + if (EMPTY_SHAPE_PROXYTYPE != mainShape->getShapeType()) { // Necessary to avoid assertion of the empty shape mainShape->calculateLocalInertia(mass, inertia); + } btBody->setMassProps(mass, inertia); } btBody->updateInertiaTensor(); @@ -846,8 +834,7 @@ void RigidBodyBullet::on_enter_area(AreaBullet *p_area) { return; } for (int i = 0; i < areaWhereIamCount; ++i) { - - if (NULL == areasWhereIam[i]) { + if (nullptr == areasWhereIam[i]) { // This area has the highest priority areasWhereIam.write[i] = p_area; break; @@ -894,7 +881,7 @@ void RigidBodyBullet::on_exit_area(AreaBullet *p_area) { } --areaWhereIamCount; - areasWhereIam.write[areaWhereIamCount] = NULL; // Even if this is not required, I clear the last element to be safe + areasWhereIam.write[areaWhereIamCount] = nullptr; // Even if this is not required, I clear the last element to be safe if (PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED != p_area->get_spOv_mode()) { scratch_space_override_modificator(); } @@ -902,22 +889,21 @@ void RigidBodyBullet::on_exit_area(AreaBullet *p_area) { } void RigidBodyBullet::reload_space_override_modificator() { - // Make sure that kinematic bodies have their total gravity calculated - if (!is_active() && PhysicsServer3D::BODY_MODE_KINEMATIC != mode) + if (!is_active() && PhysicsServer3D::BODY_MODE_KINEMATIC != mode) { return; + } - Vector3 newGravity(space->get_gravity_direction() * space->get_gravity_magnitude()); - real_t newLinearDamp(linearDamp); - real_t newAngularDamp(angularDamp); + Vector3 newGravity(0.0, 0.0, 0.0); + real_t newLinearDamp = MAX(0.0, linearDamp); + real_t newAngularDamp = MAX(0.0, angularDamp); AreaBullet *currentArea; // Variable used to calculate new gravity for gravity point areas, it is pointed by currentGravity pointer Vector3 support_gravity(0, 0, 0); - int countCombined(0); - for (int i = areaWhereIamCount - 1; 0 <= i; --i) { - + bool stopped = false; + for (int i = areaWhereIamCount - 1; (0 <= i) && !stopped; --i) { currentArea = areasWhereIam[i]; if (!currentArea || PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED == currentArea->get_spOv_mode()) { @@ -926,7 +912,6 @@ void RigidBodyBullet::reload_space_override_modificator() { /// Here is calculated the gravity if (currentArea->is_spOv_gravityPoint()) { - /// It calculates the direction of new gravity support_gravity = currentArea->get_transform().xform(currentArea->get_spOv_gravityVec()) - get_transform().get_origin(); real_t distanceMag = support_gravity.length(); @@ -965,7 +950,6 @@ void RigidBodyBullet::reload_space_override_modificator() { newGravity += support_gravity; newLinearDamp += currentArea->get_spOv_linearDamp(); newAngularDamp += currentArea->get_spOv_angularDamp(); - ++countCombined; break; case PhysicsServer3D::AREA_SPACE_OVERRIDE_COMBINE_REPLACE: /// This area adds its gravity/damp values to whatever has been calculated @@ -974,32 +958,31 @@ void RigidBodyBullet::reload_space_override_modificator() { newGravity += support_gravity; newLinearDamp += currentArea->get_spOv_linearDamp(); newAngularDamp += currentArea->get_spOv_angularDamp(); - ++countCombined; - goto endAreasCycle; + stopped = true; + break; case PhysicsServer3D::AREA_SPACE_OVERRIDE_REPLACE: /// This area replaces any gravity/damp, even the default one, and /// stops taking into account the rest of the areas. newGravity = support_gravity; newLinearDamp = currentArea->get_spOv_linearDamp(); newAngularDamp = currentArea->get_spOv_angularDamp(); - countCombined = 1; - goto endAreasCycle; + stopped = true; + break; case PhysicsServer3D::AREA_SPACE_OVERRIDE_REPLACE_COMBINE: /// This area replaces any gravity/damp calculated so far, but keeps /// calculating the rest of the areas, down to the default one. newGravity = support_gravity; newLinearDamp = currentArea->get_spOv_linearDamp(); newAngularDamp = currentArea->get_spOv_angularDamp(); - countCombined = 1; break; } } -endAreasCycle: - if (1 < countCombined) { - newGravity /= countCombined; - newLinearDamp /= countCombined; - newAngularDamp /= countCombined; + // Add default gravity and damping from space. + if (!stopped) { + newGravity += space->get_gravity_direction() * space->get_gravity_magnitude(); + newLinearDamp += space->get_linear_damp(); + newAngularDamp += space->get_angular_damp(); } btVector3 newBtGravity; @@ -1022,7 +1005,6 @@ void RigidBodyBullet::notify_transform_changed() { } void RigidBodyBullet::_internal_set_mass(real_t p_mass) { - btVector3 localInertia(0, 0, 0); int clearedCurrentFlags = btBody->getCollisionFlags(); @@ -1031,19 +1013,18 @@ void RigidBodyBullet::_internal_set_mass(real_t p_mass) { // Rigidbody is dynamic if and only if mass is non Zero, otherwise static const bool isDynamic = p_mass != 0.f; if (isDynamic) { - - if (PhysicsServer3D::BODY_MODE_RIGID != mode && PhysicsServer3D::BODY_MODE_CHARACTER != mode) + if (PhysicsServer3D::BODY_MODE_RIGID != mode && PhysicsServer3D::BODY_MODE_CHARACTER != mode) { return; + } m_isStatic = false; - if (mainShape) + if (mainShape) { mainShape->calculateLocalInertia(p_mass, localInertia); + } if (PhysicsServer3D::BODY_MODE_RIGID == mode) { - btBody->setCollisionFlags(clearedCurrentFlags); // Just set the flags without Kin and Static } else { - btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_CHARACTER_OBJECT); } @@ -1053,16 +1034,14 @@ void RigidBodyBullet::_internal_set_mass(real_t p_mass) { btBody->forceActivationState(DISABLE_DEACTIVATION); // DISABLE_DEACTIVATION 4 } } else { - - if (PhysicsServer3D::BODY_MODE_STATIC != mode && PhysicsServer3D::BODY_MODE_KINEMATIC != mode) + if (PhysicsServer3D::BODY_MODE_STATIC != mode && PhysicsServer3D::BODY_MODE_KINEMATIC != mode) { return; + } m_isStatic = true; if (PhysicsServer3D::BODY_MODE_STATIC == mode) { - btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_STATIC_OBJECT); } else { - btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_KINEMATIC_OBJECT); set_transform__bullet(btBody->getWorldTransform()); // Set current Transform using kinematic method } diff --git a/modules/bullet/rigid_body_bullet.h b/modules/bullet/rigid_body_bullet.h index bce3511282..6d159504b8 100644 --- a/modules/bullet/rigid_body_bullet.h +++ b/modules/bullet/rigid_body_bullet.h @@ -45,7 +45,7 @@ class AreaBullet; class SpaceBullet; class btRigidBody; class GodotMotionState; -class BulletPhysicsDirectBodyState; +class BulletPhysicsDirectBodyState3D; /// This class could be used in multi thread with few changes but currently /// is set to be only in one single thread. @@ -53,29 +53,29 @@ class BulletPhysicsDirectBodyState; /// In the system there is only one object at a time that manage all bodies and is /// created by BulletPhysicsServer3D and is held by the "singleton" variable of this class /// Each time something require it, the body must be set again. -class BulletPhysicsDirectBodyState : public PhysicsDirectBodyState3D { - GDCLASS(BulletPhysicsDirectBodyState, PhysicsDirectBodyState3D); +class BulletPhysicsDirectBodyState3D : public PhysicsDirectBodyState3D { + GDCLASS(BulletPhysicsDirectBodyState3D, PhysicsDirectBodyState3D); - static BulletPhysicsDirectBodyState *singleton; + static BulletPhysicsDirectBodyState3D *singleton; public: /// This class avoid the creation of more object of this class static void initSingleton() { if (!singleton) { - singleton = memnew(BulletPhysicsDirectBodyState); + singleton = memnew(BulletPhysicsDirectBodyState3D); } } static void destroySingleton() { memdelete(singleton); - singleton = NULL; + singleton = nullptr; } static void singleton_setDeltaTime(real_t p_deltaTime) { singleton->deltaTime = p_deltaTime; } - static BulletPhysicsDirectBodyState *get_singleton(RigidBodyBullet *p_body) { + static BulletPhysicsDirectBodyState3D *get_singleton(RigidBodyBullet *p_body) { singleton->body = p_body; return singleton; } @@ -85,7 +85,7 @@ public: real_t deltaTime; private: - BulletPhysicsDirectBodyState() {} + BulletPhysicsDirectBodyState3D() {} public: virtual Vector3 get_total_gravity() const; @@ -117,7 +117,7 @@ public: virtual void apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse); virtual void apply_torque_impulse(const Vector3 &p_impulse); - virtual void set_sleep_state(bool p_enable); + virtual void set_sleep_state(bool p_sleep); virtual bool is_sleeping() const; virtual int get_contact_count() const; @@ -142,7 +142,6 @@ public: }; class RigidBodyBullet : public RigidCollisionObjectBullet { - public: struct CollisionData { RigidBodyBullet *otherObject; @@ -162,11 +161,10 @@ public: /// Used to hold shapes struct KinematicShape { - class btConvexShape *shape; + class btConvexShape *shape = nullptr; btTransform transform; - KinematicShape() : - shape(NULL) {} + KinematicShape() {} bool is_active() const { return shape; } }; @@ -187,22 +185,22 @@ public: }; private: - friend class BulletPhysicsDirectBodyState; + friend class BulletPhysicsDirectBodyState3D; // This is required only for Kinematic movement - KinematicUtilities *kinematic_utilities; + KinematicUtilities *kinematic_utilities = nullptr; PhysicsServer3D::BodyMode mode; GodotMotionState *godotMotionState; btRigidBody *btBody; - uint16_t locked_axis; - real_t mass; - real_t gravity_scale; - real_t linearDamp; - real_t angularDamp; - bool can_sleep; - bool omit_forces_integration; - bool can_integrate_forces; + uint16_t locked_axis = 0; + real_t mass = 1; + real_t gravity_scale = 1; + real_t linearDamp = 0; + real_t angularDamp = 0; + bool can_sleep = true; + bool omit_forces_integration = false; + bool can_integrate_forces = false; Vector<CollisionData> collisions; Vector<RigidBodyBullet *> collision_traces_1; @@ -211,21 +209,21 @@ private: Vector<RigidBodyBullet *> *curr_collision_traces; // these parameters are used to avoid vector resize - int maxCollisionsDetection; - int collisionsCount; - int prev_collision_count; + int maxCollisionsDetection = 0; + int collisionsCount = 0; + int prev_collision_count = 0; Vector<AreaBullet *> areasWhereIam; // these parameters are used to avoid vector resize - int maxAreasWhereIam; - int areaWhereIamCount; + int maxAreasWhereIam = 10; + int areaWhereIamCount = 0; // Used to know if the area is used as gravity point - int countGravityPointSpaces; - bool isScratchedSpaceOverrideModificator; + int countGravityPointSpaces = 0; + bool isScratchedSpaceOverrideModificator = false; - bool previousActiveState; // Last check state + bool previousActiveState = true; // Last check state - ForceIntegrationCallback *force_integration_callback; + ForceIntegrationCallback *force_integration_callback = nullptr; public: RigidBodyBullet(); @@ -250,7 +248,6 @@ public: virtual void on_collision_checker_end(); void set_max_collisions_detection(int p_maxCollisionsDetection) { - ERR_FAIL_COND(0 > p_maxCollisionsDetection); maxCollisionsDetection = p_maxCollisionsDetection; diff --git a/modules/bullet/shape_bullet.cpp b/modules/bullet/shape_bullet.cpp index 6b73525d10..d53f1e7d17 100644 --- a/modules/bullet/shape_bullet.cpp +++ b/modules/bullet/shape_bullet.cpp @@ -46,8 +46,7 @@ @author AndreaCatania */ -ShapeBullet::ShapeBullet() : - margin(0.04) {} +ShapeBullet::ShapeBullet() {} ShapeBullet::~ShapeBullet() {} @@ -81,7 +80,9 @@ void ShapeBullet::add_owner(ShapeOwnerBullet *p_owner) { void ShapeBullet::remove_owner(ShapeOwnerBullet *p_owner, bool p_permanentlyFromThisBody) { Map<ShapeOwnerBullet *, int>::Element *E = owners.find(p_owner); - if (!E) return; + if (!E) { + return; + } E->get()--; if (p_permanentlyFromThisBody || 0 >= E->get()) { owners.erase(E); @@ -89,7 +90,6 @@ void ShapeBullet::remove_owner(ShapeOwnerBullet *p_owner, bool p_permanentlyFrom } bool ShapeBullet::is_owner(ShapeOwnerBullet *p_owner) const { - return owners.has(p_owner); } @@ -138,7 +138,7 @@ btScaledBvhTriangleMeshShape *ShapeBullet::create_shape_concave(btBvhTriangleMes if (p_mesh_shape) { return bulletnew(btScaledBvhTriangleMeshShape(p_mesh_shape, p_local_scaling)); } else { - return NULL; + return nullptr; } } @@ -151,8 +151,9 @@ btHeightfieldTerrainShape *ShapeBullet::create_shape_height_field(Vector<real_t> btHeightfieldTerrainShape *heightfield = bulletnew(btHeightfieldTerrainShape(p_width, p_depth, heightsPtr, ignoredHeightScale, p_min_height, p_max_height, YAxis, PHY_FLOAT, flipQuadEdges)); // The shape can be created without params when you do PhysicsServer3D.shape_create(PhysicsServer3D.SHAPE_HEIGHTMAP) - if (heightsPtr) + if (heightsPtr) { heightfield->buildAccelerator(16); + } return heightfield; } @@ -349,9 +350,10 @@ void ConvexPolygonShapeBullet::setup(const Vector<Vector3> &p_vertices) { } btCollisionShape *ConvexPolygonShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge) { - if (!vertices.size()) + if (!vertices.size()) { // This is necessary since 0 vertices return prepare(ShapeBullet::create_shape_empty()); + } btCollisionShape *cs(ShapeBullet::create_shape_convex(vertices)); cs->setLocalScaling(p_implicit_scale); prepare(cs); @@ -361,8 +363,7 @@ btCollisionShape *ConvexPolygonShapeBullet::create_bt_shape(const btVector3 &p_i /* Concave polygon */ ConcavePolygonShapeBullet::ConcavePolygonShapeBullet() : - ShapeBullet(), - meshShape(NULL) {} + ShapeBullet() {} ConcavePolygonShapeBullet::~ConcavePolygonShapeBullet() { if (meshShape) { @@ -395,7 +396,6 @@ void ConcavePolygonShapeBullet::setup(Vector<Vector3> p_faces) { } int src_face_count = faces.size(); if (0 < src_face_count) { - // It counts the faces and assert the array contains the correct number of vertices. ERR_FAIL_COND(src_face_count % 3); @@ -425,7 +425,7 @@ void ConcavePolygonShapeBullet::setup(Vector<Vector3> p_faces) { btGenerateInternalEdgeInfo(meshShape, triangleInfoMap); } } else { - meshShape = NULL; + meshShape = nullptr; ERR_PRINT("The faces count are 0, the mesh shape cannot be created"); } notifyShapeChanged(); @@ -433,9 +433,10 @@ void ConcavePolygonShapeBullet::setup(Vector<Vector3> p_faces) { btCollisionShape *ConcavePolygonShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge) { btCollisionShape *cs = ShapeBullet::create_shape_concave(meshShape); - if (!cs) - // This is necessary since if 0 faces the creation of concave return NULL + if (!cs) { + // This is necessary since if 0 faces the creation of concave return null cs = ShapeBullet::create_shape_empty(); + } cs->setLocalScaling(p_implicit_scale); prepare(cs); cs->setMargin(0); @@ -458,10 +459,12 @@ void HeightMapShapeBullet::set_data(const Variant &p_data) { real_t l_max_height = 0.0; // If specified, min and max height will be used as precomputed values - if (d.has("min_height")) + if (d.has("min_height")) { l_min_height = d["min_height"]; - if (d.has("max_height")) + } + if (d.has("max_height")) { l_max_height = d["max_height"]; + } ERR_FAIL_COND(l_min_height > l_max_height); @@ -514,7 +517,6 @@ void HeightMapShapeBullet::set_data(const Variant &p_data) { // Compute min and max heights if not specified. if (!d.has("min_height") && !d.has("max_height")) { - const real_t *r = l_heights.ptr(); int heights_size = l_heights.size(); @@ -562,18 +564,14 @@ btCollisionShape *HeightMapShapeBullet::create_bt_shape(const btVector3 &p_impli /* Ray shape */ RayShapeBullet::RayShapeBullet() : - ShapeBullet(), - length(1), - slips_on_slope(false) {} + ShapeBullet() {} void RayShapeBullet::set_data(const Variant &p_data) { - Dictionary d = p_data; setup(d["length"], d["slips_on_slope"]); } Variant RayShapeBullet::get_data() const { - Dictionary d; d["length"] = length; d["slips_on_slope"] = slips_on_slope; diff --git a/modules/bullet/shape_bullet.h b/modules/bullet/shape_bullet.h index 0dbc616fe5..b24ded574f 100644 --- a/modules/bullet/shape_bullet.h +++ b/modules/bullet/shape_bullet.h @@ -50,9 +50,8 @@ class ShapeOwnerBullet; class btBvhTriangleMeshShape; class ShapeBullet : public RIDBullet { - Map<ShapeOwnerBullet *, int> owners; - real_t margin; + real_t margin = 0.04; protected: /// return self @@ -95,7 +94,6 @@ public: }; class PlaneShapeBullet : public ShapeBullet { - Plane plane; public: @@ -111,7 +109,6 @@ private: }; class SphereShapeBullet : public ShapeBullet { - real_t radius; public: @@ -128,7 +125,6 @@ private: }; class BoxShapeBullet : public ShapeBullet { - btVector3 half_extents; public: @@ -145,7 +141,6 @@ private: }; class CapsuleShapeBullet : public ShapeBullet { - real_t height; real_t radius; @@ -164,7 +159,6 @@ private: }; class CylinderShapeBullet : public ShapeBullet { - real_t height; real_t radius; @@ -183,7 +177,6 @@ private: }; class ConvexPolygonShapeBullet : public ShapeBullet { - public: btAlignedObjectArray<btVector3> vertices; @@ -200,7 +193,7 @@ private: }; class ConcavePolygonShapeBullet : public ShapeBullet { - class btBvhTriangleMeshShape *meshShape; + class btBvhTriangleMeshShape *meshShape = nullptr; public: Vector<Vector3> faces; @@ -218,7 +211,6 @@ private: }; class HeightMapShapeBullet : public ShapeBullet { - public: Vector<real_t> heights; int width; @@ -238,10 +230,9 @@ private: }; class RayShapeBullet : public ShapeBullet { - public: - real_t length; - bool slips_on_slope; + real_t length = 1; + bool slips_on_slope = false; RayShapeBullet(); diff --git a/modules/bullet/slider_joint_bullet.cpp b/modules/bullet/slider_joint_bullet.cpp index f193daef39..6d5d95d07a 100644 --- a/modules/bullet/slider_joint_bullet.cpp +++ b/modules/bullet/slider_joint_bullet.cpp @@ -42,7 +42,6 @@ SliderJointBullet::SliderJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &frameInA, const Transform &frameInB) : JointBullet() { - Transform scaled_AFrame(frameInA.scaled(rbA->get_body_scale())); scaled_AFrame.basis.rotref_posscale_decomposition(scaled_AFrame.basis); @@ -50,7 +49,6 @@ SliderJointBullet::SliderJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, G_TO_B(scaled_AFrame, btFrameA); if (rbB) { - Transform scaled_BFrame(frameInB.scaled(rbB->get_body_scale())); scaled_BFrame.basis.rotref_posscale_decomposition(scaled_BFrame.basis); @@ -121,6 +119,7 @@ real_t SliderJointBullet::getLowerLinLimit() const { void SliderJointBullet::setLowerLinLimit(real_t lowerLimit) { sliderConstraint->setLowerLinLimit(lowerLimit); } + real_t SliderJointBullet::getUpperLinLimit() const { return sliderConstraint->getUpperLinLimit(); } @@ -344,56 +343,123 @@ real_t SliderJointBullet::getLinearPos() { void SliderJointBullet::set_param(PhysicsServer3D::SliderJointParam p_param, real_t p_value) { switch (p_param) { - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_UPPER: setUpperLinLimit(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_LOWER: setLowerLinLimit(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS: setSoftnessLimLin(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION: setRestitutionLimLin(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_DAMPING: setDampingLimLin(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS: setSoftnessDirLin(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION: setRestitutionDirLin(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_DAMPING: setDampingDirLin(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS: setSoftnessOrthoLin(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION: setRestitutionOrthoLin(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING: setDampingOrthoLin(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_UPPER: setUpperAngLimit(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_LOWER: setLowerAngLimit(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS: setSoftnessLimAng(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION: setRestitutionLimAng(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING: setDampingLimAng(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS: setSoftnessDirAng(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION: setRestitutionDirAng(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_DAMPING: setDampingDirAng(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS: setSoftnessOrthoAng(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION: setRestitutionOrthoAng(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING: setDampingOrthoAng(p_value); break; - case PhysicsServer3D::SLIDER_JOINT_MAX: break; // Can't happen, but silences warning + case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_UPPER: + setUpperLinLimit(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_LOWER: + setLowerLinLimit(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS: + setSoftnessLimLin(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION: + setRestitutionLimLin(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_DAMPING: + setDampingLimLin(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS: + setSoftnessDirLin(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION: + setRestitutionDirLin(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_DAMPING: + setDampingDirLin(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS: + setSoftnessOrthoLin(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION: + setRestitutionOrthoLin(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING: + setDampingOrthoLin(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_UPPER: + setUpperAngLimit(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_LOWER: + setLowerAngLimit(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS: + setSoftnessLimAng(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION: + setRestitutionLimAng(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING: + setDampingLimAng(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS: + setSoftnessDirAng(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION: + setRestitutionDirAng(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_DAMPING: + setDampingDirAng(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS: + setSoftnessOrthoAng(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION: + setRestitutionOrthoAng(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING: + setDampingOrthoAng(p_value); + break; + case PhysicsServer3D::SLIDER_JOINT_MAX: + break; // Can't happen, but silences warning } } real_t SliderJointBullet::get_param(PhysicsServer3D::SliderJointParam p_param) const { switch (p_param) { - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_UPPER: return getUpperLinLimit(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_LOWER: return getLowerLinLimit(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS: return getSoftnessLimLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION: return getRestitutionLimLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_DAMPING: return getDampingLimLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS: return getSoftnessDirLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION: return getRestitutionDirLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_DAMPING: return getDampingDirLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS: return getSoftnessOrthoLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION: return getRestitutionOrthoLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING: return getDampingOrthoLin(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_UPPER: return getUpperAngLimit(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_LOWER: return getLowerAngLimit(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS: return getSoftnessLimAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION: return getRestitutionLimAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING: return getDampingLimAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS: return getSoftnessDirAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION: return getRestitutionDirAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_DAMPING: return getDampingDirAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS: return getSoftnessOrthoAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION: return getRestitutionOrthoAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING: return getDampingOrthoAng(); + case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_UPPER: + return getUpperLinLimit(); + case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_LOWER: + return getLowerLinLimit(); + case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS: + return getSoftnessLimLin(); + case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION: + return getRestitutionLimLin(); + case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_DAMPING: + return getDampingLimLin(); + case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS: + return getSoftnessDirLin(); + case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION: + return getRestitutionDirLin(); + case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_DAMPING: + return getDampingDirLin(); + case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS: + return getSoftnessOrthoLin(); + case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION: + return getRestitutionOrthoLin(); + case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING: + return getDampingOrthoLin(); + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_UPPER: + return getUpperAngLimit(); + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_LOWER: + return getLowerAngLimit(); + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS: + return getSoftnessLimAng(); + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION: + return getRestitutionLimAng(); + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING: + return getDampingLimAng(); + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS: + return getSoftnessDirAng(); + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION: + return getRestitutionDirAng(); + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_DAMPING: + return getDampingDirAng(); + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS: + return getSoftnessOrthoAng(); + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION: + return getRestitutionOrthoAng(); + case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING: + return getDampingOrthoAng(); default: return 0; } diff --git a/modules/bullet/soft_body_bullet.cpp b/modules/bullet/soft_body_bullet.cpp index 2984bf9c2b..6794d6c313 100644 --- a/modules/bullet/soft_body_bullet.cpp +++ b/modules/bullet/soft_body_bullet.cpp @@ -36,18 +36,7 @@ #include "space_bullet.h" SoftBodyBullet::SoftBodyBullet() : - CollisionObjectBullet(CollisionObjectBullet::TYPE_SOFT_BODY), - bt_soft_body(NULL), - isScratched(false), - simulation_precision(5), - total_mass(1.), - linear_stiffness(0.5), - areaAngular_stiffness(0.5), - volume_stiffness(0.5), - pressure_coefficient(0.), - pose_matching_coefficient(0.), - damping_coefficient(0.01), - drag_coefficient(0.) {} + CollisionObjectBullet(CollisionObjectBullet::TYPE_SOFT_BODY) {} SoftBodyBullet::~SoftBodyBullet() { } @@ -77,8 +66,9 @@ void SoftBodyBullet::on_enter_area(AreaBullet *p_area) {} void SoftBodyBullet::on_exit_area(AreaBullet *p_area) {} void SoftBodyBullet::update_rendering_server(SoftBodyRenderingServerHandler *p_rendering_server_handler) { - if (!bt_soft_body) + if (!bt_soft_body) { return; + } /// Update visual server vertices const btSoftBody::tNodeArray &nodes(bt_soft_body->m_nodes); @@ -116,14 +106,13 @@ void SoftBodyBullet::update_rendering_server(SoftBodyRenderingServerHandler *p_r } void SoftBodyBullet::set_soft_mesh(const Ref<Mesh> &p_mesh) { - - if (p_mesh.is_null()) + if (p_mesh.is_null()) { soft_mesh.unref(); - else + } else { soft_mesh = p_mesh; + } if (soft_mesh.is_null()) { - destroy_soft_body(); return; } @@ -134,9 +123,9 @@ void SoftBodyBullet::set_soft_mesh(const Ref<Mesh> &p_mesh) { } void SoftBodyBullet::destroy_soft_body() { - - if (!bt_soft_body) + if (!bt_soft_body) { return; + } if (space) { /// Remove from world before deletion @@ -144,7 +133,7 @@ void SoftBodyBullet::destroy_soft_body() { } destroyBulletCollisionObject(); - bt_soft_body = NULL; + bt_soft_body = nullptr; } void SoftBodyBullet::set_soft_transform(const Transform &p_transform) { @@ -153,8 +142,9 @@ void SoftBodyBullet::set_soft_transform(const Transform &p_transform) { } void SoftBodyBullet::move_all_nodes(const Transform &p_transform) { - if (!bt_soft_body) + if (!bt_soft_body) { return; + } btTransform bt_transf; G_TO_B(p_transform, bt_transf); bt_soft_body->transform(bt_transf); @@ -180,8 +170,9 @@ void SoftBodyBullet::get_node_position(int p_node_index, Vector3 &r_position) co } void SoftBodyBullet::get_node_offset(int p_node_index, Vector3 &r_offset) const { - if (soft_mesh.is_null()) + if (soft_mesh.is_null()) { return; + } Array arrays = soft_mesh->surface_get_arrays(0); Vector<Vector3> vertices(arrays[RS::ARRAY_VERTEX]); @@ -226,15 +217,15 @@ void SoftBodyBullet::reset_all_node_mass() { } void SoftBodyBullet::reset_all_node_positions() { - if (soft_mesh.is_null()) + if (soft_mesh.is_null()) { return; + } Array arrays = soft_mesh->surface_get_arrays(0); Vector<Vector3> vs_vertices(arrays[RS::ARRAY_VERTEX]); const Vector3 *vs_vertices_read = vs_vertices.ptr(); for (int vertex_index = bt_soft_body->m_nodes.size() - 1; 0 <= vertex_index; --vertex_index) { - G_TO_B(vs_vertices_read[indices_table[vertex_index][0]], bt_soft_body->m_nodes[vertex_index].m_x); bt_soft_body->m_nodes[vertex_index].m_q = bt_soft_body->m_nodes[vertex_index].m_x; @@ -342,7 +333,6 @@ void SoftBodyBullet::set_trimesh_body_shape(Vector<int> p_indices, Vector<Vector const Vector3 *p_vertices_read = p_vertices.ptr(); for (int vs_vertex_index = 0; vs_vertex_index < vs_vertices_size; ++vs_vertex_index) { - Map<Vector3, int>::Element *e = unique_vertices.find(p_vertices_read[vs_vertex_index]); int vertex_id; if (e) { @@ -398,13 +388,13 @@ void SoftBodyBullet::set_trimesh_body_shape(Vector<int> p_indices, Vector<Vector } void SoftBodyBullet::setup_soft_body() { - - if (!bt_soft_body) + if (!bt_soft_body) { return; + } // Soft body setup setupBulletCollisionObject(bt_soft_body); - bt_soft_body->m_worldInfo = NULL; // Remove fake world info + bt_soft_body->m_worldInfo = nullptr; // Remove fake world info bt_soft_body->getCollisionShape()->setMargin(0.01); bt_soft_body->setCollisionFlags(bt_soft_body->getCollisionFlags() & (~(btCollisionObject::CF_KINEMATIC_OBJECT | btCollisionObject::CF_STATIC_OBJECT))); diff --git a/modules/bullet/soft_body_bullet.h b/modules/bullet/soft_body_bullet.h index 3c6871e0d6..da8a2412ed 100644 --- a/modules/bullet/soft_body_bullet.h +++ b/modules/bullet/soft_body_bullet.h @@ -56,24 +56,23 @@ */ class SoftBodyBullet : public CollisionObjectBullet { - private: - btSoftBody *bt_soft_body; + btSoftBody *bt_soft_body = nullptr; Vector<Vector<int>> indices_table; btSoftBody::Material *mat0; // This is just a copy of pointer managed by btSoftBody - bool isScratched; + bool isScratched = false; Ref<Mesh> soft_mesh; - int simulation_precision; - real_t total_mass; - real_t linear_stiffness; // [0,1] - real_t areaAngular_stiffness; // [0,1] - real_t volume_stiffness; // [0,1] - real_t pressure_coefficient; // [-inf,+inf] - real_t pose_matching_coefficient; // [0,1] - real_t damping_coefficient; // [0,1] - real_t drag_coefficient; // [0,1] + int simulation_precision = 5; + real_t total_mass = 1.; + real_t linear_stiffness = 0.5; // [0,1] + real_t areaAngular_stiffness = 0.5; // [0,1] + real_t volume_stiffness = 0.5; // [0,1] + real_t pressure_coefficient = 0.; // [-inf,+inf] + real_t pose_matching_coefficient = 0.; // [0,1] + real_t damping_coefficient = 0.01; // [0,1] + real_t drag_coefficient = 0.; // [0,1] Vector<int> pinned_nodes; // Other property to add diff --git a/modules/bullet/space_bullet.cpp b/modules/bullet/space_bullet.cpp index c40a1500f0..99f58e7059 100644 --- a/modules/bullet/space_bullet.cpp +++ b/modules/bullet/space_bullet.cpp @@ -63,9 +63,9 @@ BulletPhysicsDirectSpaceState::BulletPhysicsDirectSpaceState(SpaceBullet *p_spac space(p_space) {} int BulletPhysicsDirectSpaceState::intersect_point(const Vector3 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) { - - if (p_result_max <= 0) + if (p_result_max <= 0) { return 0; + } btVector3 bt_point; G_TO_B(p_point, bt_point); @@ -86,7 +86,6 @@ int BulletPhysicsDirectSpaceState::intersect_point(const Vector3 &p_point, Shape } bool BulletPhysicsDirectSpaceState::intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, bool p_pick_ray) { - btVector3 btVec_from; btVector3 btVec_to; @@ -108,7 +107,7 @@ bool BulletPhysicsDirectSpaceState::intersect_ray(const Vector3 &p_from, const V r_result.shape = btResult.m_shapeId; r_result.rid = gObj->get_self(); r_result.collider_id = gObj->get_instance_id(); - r_result.collider = r_result.collider_id.is_null() ? NULL : ObjectDB::get_instance(r_result.collider_id); + r_result.collider = r_result.collider_id.is_null() ? nullptr : ObjectDB::get_instance(r_result.collider_id); } else { WARN_PRINT("The raycast performed has hit a collision object that is not part of Godot scene, please check it."); } @@ -119,8 +118,9 @@ bool BulletPhysicsDirectSpaceState::intersect_ray(const Vector3 &p_from, const V } int BulletPhysicsDirectSpaceState::intersect_shape(const RID &p_shape, const Transform &p_xform, float p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) { - if (p_result_max <= 0) + if (p_result_max <= 0) { return 0; + } ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->getornull(p_shape); @@ -204,8 +204,9 @@ bool BulletPhysicsDirectSpaceState::cast_motion(const RID &p_shape, const Transf /// Returns the list of contacts pairs in this order: Local contact, other body contact bool BulletPhysicsDirectSpaceState::collide_shape(RID p_shape, const Transform &p_shape_xform, float p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) { - if (p_result_max <= 0) - return 0; + if (p_result_max <= 0) { + return false; + } ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->getornull(p_shape); @@ -213,7 +214,7 @@ bool BulletPhysicsDirectSpaceState::collide_shape(RID p_shape, const Transform & if (!btShape->isConvex()) { bulletdelete(btShape); ERR_PRINT("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type())); - return 0; + return false; } btConvexShape *btConvex = static_cast<btConvexShape *>(btShape); @@ -238,14 +239,13 @@ bool BulletPhysicsDirectSpaceState::collide_shape(RID p_shape, const Transform & } bool BulletPhysicsDirectSpaceState::rest_info(RID p_shape, const Transform &p_shape_xform, float p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) { - ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->getornull(p_shape); btCollisionShape *btShape = shape->create_bt_shape(p_shape_xform.basis.get_scale_abs(), p_margin); if (!btShape->isConvex()) { bulletdelete(btShape); ERR_PRINT("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type())); - return 0; + return false; } btConvexShape *btConvex = static_cast<btConvexShape *>(btShape); @@ -276,7 +276,6 @@ bool BulletPhysicsDirectSpaceState::rest_info(RID p_shape, const Transform &p_sh } Vector3 BulletPhysicsDirectSpaceState::get_closest_point_to_object_volume(RID p_object, const Vector3 p_point) const { - RigidCollisionObjectBullet *rigid_object = space->get_physics_server()->get_rigid_collisin_object(p_object); ERR_FAIL_COND_V(!rigid_object, Vector3()); @@ -309,7 +308,7 @@ Vector3 BulletPhysicsDirectSpaceState::get_closest_point_to_object_volume(RID p_ btPointCollector result; btGjkPairDetector gjk_pair_detector(&point_shape, convex_shape, space->gjk_simplex_solver, space->gjk_epa_pen_solver); - gjk_pair_detector.getClosestPoints(input, result, 0); + gjk_pair_detector.getClosestPoints(input, result, nullptr); if (out_distance > result.m_distance) { out_distance = result.m_distance; @@ -320,31 +319,16 @@ Vector3 BulletPhysicsDirectSpaceState::get_closest_point_to_object_volume(RID p_ } if (shapes_found) { - Vector3 out; B_TO_G(out_closest_point, out); return out; } else { - // no shapes found, use distance to origin. return rigid_object->get_transform().get_origin(); } } -SpaceBullet::SpaceBullet() : - broadphase(NULL), - collisionConfiguration(NULL), - dispatcher(NULL), - solver(NULL), - dynamicsWorld(NULL), - soft_body_world_info(NULL), - ghostPairCallback(NULL), - godotFilterCallback(NULL), - gravityDirection(0, -1, 0), - gravityMagnitude(10), - contactDebugCount(0), - delta_time(0.) { - +SpaceBullet::SpaceBullet() { create_empty_world(GLOBAL_DEF("physics/3d/active_soft_world", true)); direct_access = memnew(BulletPhysicsDirectSpaceState(this)); } @@ -379,8 +363,11 @@ void SpaceBullet::set_param(PhysicsServer3D::AreaParameter p_param, const Varian update_gravity(); break; case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP: + linear_damp = p_value; + break; case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP: - break; // No damp + angular_damp = p_value; + break; case PhysicsServer3D::AREA_PARAM_PRIORITY: // Priority is always 0, the lower break; @@ -401,8 +388,9 @@ Variant SpaceBullet::get_param(PhysicsServer3D::AreaParameter p_param) { case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR: return gravityDirection; case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP: + return linear_damp; case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP: - return 0; // No damp + return angular_damp; case PhysicsServer3D::AREA_PARAM_PRIORITY: return 0; // Priority is always 0, the lower case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT: @@ -511,7 +499,7 @@ void SpaceBullet::remove_soft_body(SoftBodyBullet *p_body) { if (is_using_soft_world()) { if (p_body->get_bt_soft_body()) { static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->removeSoftBody(p_body->get_bt_soft_body()); - p_body->get_bt_soft_body()->m_worldInfo = NULL; + p_body->get_bt_soft_body()->m_worldInfo = nullptr; } } } @@ -539,7 +527,7 @@ void SpaceBullet::remove_all_collision_objects() { for (int i = dynamicsWorld->getNumCollisionObjects() - 1; 0 <= i; --i) { btCollisionObject *btObj = dynamicsWorld->getCollisionObjectArray()[i]; CollisionObjectBullet *colObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); - colObj->set_space(NULL); + colObj->set_space(nullptr); } } @@ -548,7 +536,6 @@ void onBulletPreTickCallback(btDynamicsWorld *p_dynamicsWorld, btScalar timeStep } void onBulletTickCallback(btDynamicsWorld *p_dynamicsWorld, btScalar timeStep) { - const btCollisionObjectArray &colObjArray = p_dynamicsWorld->getCollisionObjectArray(); // Notify all Collision objects the collision checker is started @@ -570,17 +557,14 @@ BulletPhysicsDirectSpaceState *SpaceBullet::get_direct_state() { } btScalar calculateGodotCombinedRestitution(const btCollisionObject *body0, const btCollisionObject *body1) { - return CLAMP(body0->getRestitution() + body1->getRestitution(), 0, 1); } btScalar calculateGodotCombinedFriction(const btCollisionObject *body0, const btCollisionObject *body1) { - return ABS(MIN(body0->getFriction(), body1->getFriction())); } void SpaceBullet::create_empty_world(bool p_create_soft_world) { - gjk_epa_pen_solver = bulletnew(btGjkEpaPenetrationDepthSolver); gjk_simplex_solver = bulletnew(btVoronoiSimplexSolver); @@ -633,11 +617,10 @@ void SpaceBullet::create_empty_world(bool p_create_soft_world) { } void SpaceBullet::destroy_world() { - /// The world elements (like: Collision Objects, Constraints, Shapes) are managed by godot - dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(NULL); - dynamicsWorld->getPairCache()->setOverlapFilterCallback(NULL); + dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(nullptr); + dynamicsWorld->getPairCache()->setOverlapFilterCallback(nullptr); bulletdelete(ghostPairCallback); bulletdelete(godotFilterCallback); @@ -645,7 +628,7 @@ void SpaceBullet::destroy_world() { // Deallocate world dynamicsWorld->~btDiscreteDynamicsWorld(); free(dynamicsWorld); - dynamicsWorld = NULL; + dynamicsWorld = nullptr; bulletdelete(solver); bulletdelete(broadphase); @@ -657,7 +640,6 @@ void SpaceBullet::destroy_world() { } void SpaceBullet::check_ghost_overlaps() { - /// Algorithm support variables btCollisionShape *other_body_shape; btConvexShape *area_shape; @@ -671,8 +653,9 @@ void SpaceBullet::check_ghost_overlaps() { btVector3 area_scale(area->get_bt_body_scale()); - if (!area->is_monitoring()) + if (!area->is_monitoring()) { continue; + } /// 1. Reset all states for (i = area->overlappingObjects.size() - 1; 0 <= i; --i) { @@ -690,7 +673,6 @@ void SpaceBullet::check_ghost_overlaps() { // For each overlapping for (i = ghostOverlaps.size() - 1; 0 <= i; --i) { - bool hasOverlap = false; btCollisionObject *overlapped_bt_co = ghostOverlaps[i]; RigidCollisionObjectBullet *otherObject = static_cast<RigidCollisionObjectBullet *>(overlapped_bt_co->getUserPointer()); @@ -702,15 +684,18 @@ void SpaceBullet::check_ghost_overlaps() { } if (overlapped_bt_co->getUserIndex() == CollisionObjectBullet::TYPE_AREA) { - if (!static_cast<AreaBullet *>(overlapped_bt_co->getUserPointer())->is_monitorable()) + if (!static_cast<AreaBullet *>(overlapped_bt_co->getUserPointer())->is_monitorable()) { continue; - } else if (overlapped_bt_co->getUserIndex() != CollisionObjectBullet::TYPE_RIGID_BODY) + } + } else if (overlapped_bt_co->getUserIndex() != CollisionObjectBullet::TYPE_RIGID_BODY) { continue; + } // For each area shape for (y = area->get_shape_count() - 1; 0 <= y; --y) { - if (!area->get_bt_shape(y)->isConvex()) + if (!area->get_bt_shape(y)->isConvex()) { continue; + } btTransform area_shape_treansform(area->get_bt_shape_transform(y)); area_shape_treansform.getOrigin() *= area_scale; @@ -723,7 +708,6 @@ void SpaceBullet::check_ghost_overlaps() { // For each other object shape for (z = otherObject->get_shape_count() - 1; 0 <= z; --z) { - other_body_shape = static_cast<btCollisionShape *>(otherObject->get_bt_shape(z)); btTransform other_shape_transform(otherObject->get_bt_shape_transform(z)); @@ -734,14 +718,13 @@ void SpaceBullet::check_ghost_overlaps() { other_shape_transform; if (other_body_shape->isConvex()) { - btPointCollector result; btGjkPairDetector gjk_pair_detector( area_shape, static_cast<btConvexShape *>(other_body_shape), gjk_simplex_solver, gjk_epa_pen_solver); - gjk_pair_detector.getClosestPoints(gjk_input, result, 0); + gjk_pair_detector.getClosestPoints(gjk_input, result, nullptr); if (0 >= result.m_distance) { hasOverlap = true; @@ -749,14 +732,14 @@ void SpaceBullet::check_ghost_overlaps() { } } else { + btCollisionObjectWrapper obA(nullptr, area_shape, area->get_bt_ghost(), gjk_input.m_transformA, -1, y); + btCollisionObjectWrapper obB(nullptr, other_body_shape, otherObject->get_bt_collision_object(), gjk_input.m_transformB, -1, z); - btCollisionObjectWrapper obA(NULL, area_shape, area->get_bt_ghost(), gjk_input.m_transformA, -1, y); - btCollisionObjectWrapper obB(NULL, other_body_shape, otherObject->get_bt_collision_object(), gjk_input.m_transformB, -1, z); + btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, nullptr, BT_CONTACT_POINT_ALGORITHMS); - btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, NULL, BT_CONTACT_POINT_ALGORITHMS); - - if (!algorithm) + if (!algorithm) { continue; + } GodotDeepPenetrationContactResultCallback contactPointResult(&obA, &obB); algorithm->processCollision(&obA, &obB, dynamicsWorld->getDispatchInfo(), &contactPointResult); @@ -774,8 +757,9 @@ void SpaceBullet::check_ghost_overlaps() { } // ~For each area shape collision_found: - if (!hasOverlap) + if (!hasOverlap) { continue; + } indexOverlap = area->find_overlapping_object(otherObject); if (-1 == indexOverlap) { @@ -832,7 +816,6 @@ void SpaceBullet::check_body_collision() { pt.getDistance() <= 0.0 || bodyA->was_colliding(bodyB) || bodyB->was_colliding(bodyA)) { - Vector3 collisionWorldPosition; Vector3 collisionLocalPosition; Vector3 normalOnB; @@ -885,20 +868,19 @@ void SpaceBullet::update_gravity() { #include "scene/3d/immediate_geometry.h" -static ImmediateGeometry *motionVec(NULL); -static ImmediateGeometry *normalLine(NULL); +static ImmediateGeometry3D *motionVec(nullptr); +static ImmediateGeometry3D *normalLine(nullptr); static Ref<StandardMaterial3D> red_mat; static Ref<StandardMaterial3D> blue_mat; #endif bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, PhysicsServer3D::MotionResult *r_result, bool p_exclude_raycast_shapes) { - #if debug_test_motion /// Yes I know this is not good, but I've used it as fast debugging hack. /// I'm leaving it here just for speedup the other eventual debugs if (!normalLine) { - motionVec = memnew(ImmediateGeometry); - normalLine = memnew(ImmediateGeometry); + motionVec = memnew(ImmediateGeometry3D); + normalLine = memnew(ImmediateGeometry3D); SceneTree::get_singleton()->get_current_scene()->add_child(motionVec); SceneTree::get_singleton()->get_current_scene()->add_child(normalLine); @@ -951,7 +933,7 @@ bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_f Vector3 sup_line; B_TO_G(body_safe_position.getOrigin(), sup_line); motionVec->clear(); - motionVec->begin(Mesh::PRIMITIVE_LINES, NULL); + motionVec->begin(Mesh::PRIMITIVE_LINES, nullptr); motionVec->add_vertex(sup_line); motionVec->add_vertex(sup_line + p_motion * 10); motionVec->end(); @@ -1009,7 +991,6 @@ bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_f B_TO_G(motion + initial_recover_motion + __rec, r_result->motion); if (has_penetration) { - const btRigidBody *btRigid = static_cast<const btRigidBody *>(r_recover_result.other_collision_object); CollisionObjectBullet *collisionObject = static_cast<CollisionObjectBullet *>(btRigid->getUserPointer()); @@ -1028,7 +1009,7 @@ bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_f Vector3 sup_line2; B_TO_G(motion, sup_line2); normalLine->clear(); - normalLine->begin(Mesh::PRIMITIVE_LINES, NULL); + normalLine->begin(Mesh::PRIMITIVE_LINES, nullptr); normalLine->add_vertex(r_result->collision_point); normalLine->add_vertex(r_result->collision_point + r_result->collision_normal * 10); normalLine->end(); @@ -1043,7 +1024,6 @@ bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_f } int SpaceBullet::test_ray_separation(RigidBodyBullet *p_body, const Transform &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, PhysicsServer3D::SeparationResult *r_results, int p_result_max, float p_margin) { - btTransform body_transform; G_TO_B(p_transform, body_transform); UNSCALE_BT_BASIS(body_transform); @@ -1108,14 +1088,12 @@ public: self_collision_object(p_self_collision_object), collision_layer(p_collision_layer), collision_mask(p_collision_mask) { - bounds = btDbvtVolume::FromMM(p_aabb_min, p_aabb_max); } virtual ~RecoverPenetrationBroadPhaseCallback() {} virtual bool process(const btBroadphaseProxy *proxy) { - btCollisionObject *co = static_cast<btCollisionObject *>(proxy->m_clientObject); if (co->getInternalType() <= btCollisionObject::CO_RIGID_BODY) { if (self_collision_object != proxy->m_clientObject && GodotFilterCallback::test_collision_filters(collision_layer, collision_mask, proxy->m_collisionFilterGroup, proxy->m_collisionFilterMask)) { @@ -1124,7 +1102,7 @@ public: if (cs->getNumChildShapes() > 1) { const btDbvt *tree = cs->getDynamicAabbTree(); - ERR_FAIL_COND_V(tree == NULL, true); + ERR_FAIL_COND_V(tree == nullptr, true); // Transform bounds into compound shape local space const btTransform other_in_compound_space = co->getWorldTransform().inverse(); @@ -1159,13 +1137,11 @@ public: }; bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) { - // Calculate the cumulative AABB of all shapes of the kinematic body btVector3 aabb_min, aabb_max; bool shapes_found = false; for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) { - const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]); if (!kin_shape.is_active()) { continue; @@ -1210,7 +1186,6 @@ bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTran // Perform narrowphase per shape for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) { - const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]); if (!kin_shape.is_active()) { continue; @@ -1229,8 +1204,9 @@ bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTran if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) { otherObject->activate(); // Force activation of hitten rigid, soft body continue; - } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object())) + } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object())) { continue; + } if (otherObject->getCollisionShape()->isCompound()) { const btCompoundShape *cs = static_cast<const btCompoundShape *>(otherObject->getCollisionShape()); @@ -1239,23 +1215,19 @@ bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTran if (cs->getChildShape(shape_idx)->isConvex()) { if (RFP_convex_convex_test(kin_shape.shape, static_cast<const btConvexShape *>(cs->getChildShape(shape_idx)), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) { - penetration = true; } } else { if (RFP_convex_world_test(kin_shape.shape, cs->getChildShape(shape_idx), p_body->get_bt_collision_object(), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) { - penetration = true; } } } else if (otherObject->getCollisionShape()->isConvex()) { /// Execute GJK test against object shape if (RFP_convex_convex_test(kin_shape.shape, static_cast<const btConvexShape *>(otherObject->getCollisionShape()), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) { - penetration = true; } } else { if (RFP_convex_world_test(kin_shape.shape, otherObject->getCollisionShape(), p_body->get_bt_collision_object(), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) { - penetration = true; } } @@ -1266,7 +1238,6 @@ bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTran } bool SpaceBullet::RFP_convex_convex_test(const btConvexShape *p_shapeA, const btConvexShape *p_shapeB, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) { - // Initialize GJK input btGjkPairDetector::ClosestPointInput gjk_input; gjk_input.m_transformA = p_transformA; @@ -1275,7 +1246,7 @@ bool SpaceBullet::RFP_convex_convex_test(const btConvexShape *p_shapeA, const bt // Perform GJK test btPointCollector result; btGjkPairDetector gjk_pair_detector(p_shapeA, p_shapeB, gjk_simplex_solver, gjk_epa_pen_solver); - gjk_pair_detector.getClosestPoints(gjk_input, result, 0); + gjk_pair_detector.getClosestPoints(gjk_input, result, nullptr); if (0 > result.m_distance) { // Has penetration r_delta_recover_movement += result.m_normalOnBInWorld * (result.m_distance * -1 * p_recover_movement_scale); @@ -1297,15 +1268,14 @@ bool SpaceBullet::RFP_convex_convex_test(const btConvexShape *p_shapeA, const bt } bool SpaceBullet::RFP_convex_world_test(const btConvexShape *p_shapeA, const btCollisionShape *p_shapeB, btCollisionObject *p_objectA, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) { - /// Contact test btTransform tA(p_transformA); - btCollisionObjectWrapper obA(NULL, p_shapeA, p_objectA, tA, -1, p_shapeId_A); - btCollisionObjectWrapper obB(NULL, p_shapeB, p_objectB, p_transformB, -1, p_shapeId_B); + btCollisionObjectWrapper obA(nullptr, p_shapeA, p_objectA, tA, -1, p_shapeId_A); + btCollisionObjectWrapper obB(nullptr, p_shapeB, p_objectB, p_transformB, -1, p_shapeId_B); - btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, NULL, BT_CONTACT_POINT_ALGORITHMS); + btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, nullptr, BT_CONTACT_POINT_ALGORITHMS); if (algorithm) { GodotDeepPenetrationContactResultCallback contactPointResult(&obA, &obB); //discrete collision detection query @@ -1334,7 +1304,6 @@ bool SpaceBullet::RFP_convex_world_test(const btConvexShape *p_shapeA, const btC } int SpaceBullet::add_separation_result(PhysicsServer3D::SeparationResult *r_result, const SpaceBullet::RecoverResult &p_recover_result, int p_shape_id, const btCollisionObject *p_other_object) const { - // optimize results (ignore non-colliding) if (p_recover_result.penetration_distance < 0.0) { const btRigidBody *btRigid = static_cast<const btRigidBody *>(p_other_object); @@ -1356,13 +1325,11 @@ int SpaceBullet::add_separation_result(PhysicsServer3D::SeparationResult *r_resu } int SpaceBullet::recover_from_penetration_ray(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, int p_result_max, btVector3 &r_delta_recover_movement, PhysicsServer3D::SeparationResult *r_results) { - // Calculate the cumulative AABB of all shapes of the kinematic body btVector3 aabb_min, aabb_max; bool shapes_found = false; for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) { - const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]); if (!kin_shape.is_active()) { continue; @@ -1406,7 +1373,6 @@ int SpaceBullet::recover_from_penetration_ray(RigidBodyBullet *p_body, const btT // Perform narrowphase per shape for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) { - if (ray_count >= p_result_max) { break; } @@ -1428,8 +1394,9 @@ int SpaceBullet::recover_from_penetration_ray(RigidBodyBullet *p_body, const btT if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) { otherObject->activate(); // Force activation of hitten rigid, soft body continue; - } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object())) + } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object())) { continue; + } if (otherObject->getCollisionShape()->isCompound()) { const btCompoundShape *cs = static_cast<const btCompoundShape *>(otherObject->getCollisionShape()); @@ -1438,14 +1405,11 @@ int SpaceBullet::recover_from_penetration_ray(RigidBodyBullet *p_body, const btT RecoverResult recover_result; if (RFP_convex_world_test(kin_shape.shape, cs->getChildShape(shape_idx), p_body->get_bt_collision_object(), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, &recover_result)) { - ray_count = add_separation_result(&r_results[ray_count], recover_result, kinIndex, otherObject); } } else { - RecoverResult recover_result; if (RFP_convex_world_test(kin_shape.shape, otherObject->getCollisionShape(), p_body->get_bt_collision_object(), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, &recover_result)) { - ray_count = add_separation_result(&r_results[ray_count], recover_result, kinIndex, otherObject); } } diff --git a/modules/bullet/space_bullet.h b/modules/bullet/space_bullet.h index fce715b48d..5ff421ef52 100644 --- a/modules/bullet/space_bullet.h +++ b/modules/bullet/space_bullet.h @@ -79,7 +79,7 @@ public: virtual int intersect_point(const Vector3 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false); virtual bool intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false, bool p_pick_ray = false); virtual int intersect_shape(const RID &p_shape, const Transform &p_xform, float p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false); - virtual bool cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, float p_margin, float &r_closest_safe, float &r_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false, ShapeRestInfo *r_info = NULL); + virtual bool cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, float p_margin, float &r_closest_safe, float &r_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false, ShapeRestInfo *r_info = nullptr); /// Returns the list of contacts pairs in this order: Local contact, other body contact virtual bool collide_shape(RID p_shape, const Transform &p_shape_xform, float p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false); virtual bool rest_info(RID p_shape, const Transform &p_shape_xform, float p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false); @@ -87,32 +87,34 @@ public: }; class SpaceBullet : public RIDBullet { - friend class AreaBullet; friend void onBulletTickCallback(btDynamicsWorld *world, btScalar timeStep); friend class BulletPhysicsDirectSpaceState; - btBroadphaseInterface *broadphase; - btDefaultCollisionConfiguration *collisionConfiguration; - btCollisionDispatcher *dispatcher; - btConstraintSolver *solver; - btDiscreteDynamicsWorld *dynamicsWorld; - btSoftBodyWorldInfo *soft_body_world_info; - btGhostPairCallback *ghostPairCallback; - GodotFilterCallback *godotFilterCallback; + btBroadphaseInterface *broadphase = nullptr; + btDefaultCollisionConfiguration *collisionConfiguration = nullptr; + btCollisionDispatcher *dispatcher = nullptr; + btConstraintSolver *solver = nullptr; + btDiscreteDynamicsWorld *dynamicsWorld = nullptr; + btSoftBodyWorldInfo *soft_body_world_info = nullptr; + btGhostPairCallback *ghostPairCallback = nullptr; + GodotFilterCallback *godotFilterCallback = nullptr; btGjkEpaPenetrationDepthSolver *gjk_epa_pen_solver; btVoronoiSimplexSolver *gjk_simplex_solver; BulletPhysicsDirectSpaceState *direct_access; - Vector3 gravityDirection; - real_t gravityMagnitude; + Vector3 gravityDirection = Vector3(0, -1, 0); + real_t gravityMagnitude = 10; + + real_t linear_damp = 0.0; + real_t angular_damp = 0.0; Vector<AreaBullet *> areas; Vector<Vector3> contactDebug; - int contactDebugCount; - real_t delta_time; + int contactDebugCount = 0; + real_t delta_time = 0.; public: SpaceBullet(); @@ -167,7 +169,9 @@ public: contactDebugCount = 0; } _FORCE_INLINE_ void add_debug_contact(const Vector3 &p_contact) { - if (contactDebugCount < contactDebug.size()) contactDebug.write[contactDebugCount++] = p_contact; + if (contactDebugCount < contactDebug.size()) { + contactDebug.write[contactDebugCount++] = p_contact; + } } _FORCE_INLINE_ Vector<Vector3> get_debug_contacts() { return contactDebug; } _FORCE_INLINE_ int get_debug_contact_count() { return contactDebugCount; } @@ -177,6 +181,9 @@ public: void update_gravity(); + real_t get_linear_damp() const { return linear_damp; } + real_t get_angular_damp() const { return angular_damp; } + bool test_body_motion(RigidBodyBullet *p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, PhysicsServer3D::MotionResult *r_result, bool p_exclude_raycast_shapes); int test_ray_separation(RigidBodyBullet *p_body, const Transform &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, PhysicsServer3D::SeparationResult *r_results, int p_result_max, float p_margin); @@ -187,31 +194,24 @@ private: void check_body_collision(); struct RecoverResult { - bool hasPenetration; - btVector3 normal; - btVector3 pointWorld; - btScalar penetration_distance; // Negative mean penetration - int other_compound_shape_index; - const btCollisionObject *other_collision_object; - int local_shape_most_recovered; - - RecoverResult() : - hasPenetration(false), - normal(0, 0, 0), - pointWorld(0, 0, 0), - penetration_distance(1e20), - other_compound_shape_index(0), - other_collision_object(NULL), - local_shape_most_recovered(0) {} + bool hasPenetration = false; + btVector3 normal = btVector3(0, 0, 0); + btVector3 pointWorld = btVector3(0, 0, 0); + btScalar penetration_distance = 1e20; // Negative mean penetration + int other_compound_shape_index = 0; + const btCollisionObject *other_collision_object = nullptr; + int local_shape_most_recovered = 0; + + RecoverResult() {} }; - bool recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result = NULL); + bool recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result = nullptr); /// This is an API that recover a kinematic object from penetration /// This allow only Convex Convex test and it always use GJK algorithm, With this API we don't benefit of Bullet special accelerated functions - bool RFP_convex_convex_test(const btConvexShape *p_shapeA, const btConvexShape *p_shapeB, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result = NULL); + bool RFP_convex_convex_test(const btConvexShape *p_shapeA, const btConvexShape *p_shapeB, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result = nullptr); /// This is an API that recover a kinematic object from penetration /// Using this we leave Bullet to select the best algorithm, For example GJK in case we have Convex Convex, or a Bullet accelerated algorithm - bool RFP_convex_world_test(const btConvexShape *p_shapeA, const btCollisionShape *p_shapeB, btCollisionObject *p_objectA, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result = NULL); + bool RFP_convex_world_test(const btConvexShape *p_shapeA, const btCollisionShape *p_shapeB, btCollisionObject *p_objectA, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result = nullptr); int add_separation_result(PhysicsServer3D::SeparationResult *r_results, const SpaceBullet::RecoverResult &p_recover_result, int p_shape_id, const btCollisionObject *p_other_object) const; int recover_from_penetration_ray(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, int p_result_max, btVector3 &r_delta_recover_movement, PhysicsServer3D::SeparationResult *r_results); |