From aaa6afed76d442bf81a97f25c31e31fe4dc69433 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 13 Mar 2011 07:46:36 -0400 Subject: [PATCH 01/78] start box2d update branch --HG-- branch : box2d-update From 57e345e91e18fe1e469c71b1c464f5142bb5f215 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 13 Mar 2011 07:59:18 -0400 Subject: [PATCH 02/78] bring in new version of Box2D and update #include paths --HG-- branch : box2d-update --- .../macosx/love.xcodeproj/project.pbxproj | 529 ++++---- src/modules/physics/box2d/Body.h | 2 +- src/modules/physics/box2d/Box2D/Box2D.h | 62 + .../Box2D/Collision/Shapes/b2CircleShape.cpp | 89 ++ .../Box2D/Collision/Shapes/b2CircleShape.h | 87 ++ .../Box2D/Collision/Shapes/b2PolygonShape.cpp | 434 +++++++ .../Box2D/Collision/Shapes/b2PolygonShape.h | 131 ++ .../box2d/Box2D/Collision/Shapes/b2Shape.h | 95 ++ .../box2d/Box2D/Collision/b2BroadPhase.cpp | 116 ++ .../box2d/Box2D/Collision/b2BroadPhase.h | 229 ++++ .../box2d/Box2D/Collision/b2CollideCircle.cpp | 154 +++ .../Collision/b2CollidePolygon.cpp} | 190 ++- .../box2d/Box2D/Collision/b2Collision.cpp | 250 ++++ .../box2d/Box2D/Collision/b2Collision.h | 240 ++++ .../box2d/Box2D/Collision/b2Distance.cpp | 571 +++++++++ .../box2d/Box2D/Collision/b2Distance.h | 141 +++ .../box2d/Box2D/Collision/b2DynamicTree.cpp | 365 ++++++ .../box2d/Box2D/Collision/b2DynamicTree.h | 286 +++++ .../box2d/Box2D/Collision/b2TimeOfImpact.cpp | 483 ++++++++ .../box2d/Box2D/Collision/b2TimeOfImpact.h | 59 + .../Common/b2BlockAllocator.cpp | 11 +- .../Common/b2BlockAllocator.h | 4 +- .../physics/box2d/Box2D/Common/b2Math.cpp | 55 + .../box2d/{Source => Box2D}/Common/b2Math.h | 444 ++++--- .../Common/b2Settings.cpp} | 24 +- .../{Source => Box2D}/Common/b2Settings.h | 113 +- .../Common/b2StackAllocator.cpp | 6 +- .../Common/b2StackAllocator.h | 4 +- .../Dynamics/Contacts/b2CircleContact.cpp | 52 + .../Dynamics/Contacts/b2CircleContact.h | 22 +- .../Box2D/Dynamics/Contacts/b2Contact.cpp | 226 ++++ .../box2d/Box2D/Dynamics/Contacts/b2Contact.h | 242 ++++ .../Dynamics/Contacts/b2ContactSolver.cpp | 623 ++++++++++ .../Dynamics/Contacts/b2ContactSolver.h | 45 +- .../Contacts/b2PolygonAndCircleContact.cpp | 52 + .../Contacts/b2PolygonAndCircleContact.h} | 24 +- .../Dynamics/Contacts/b2PolygonContact.cpp | 52 + .../Dynamics/Contacts/b2PolygonContact.h} | 20 +- .../Box2D/Dynamics/Contacts/b2TOISolver.cpp | 231 ++++ .../Box2D/Dynamics/Contacts/b2TOISolver.h | 51 + .../Dynamics/Joints/b2DistanceJoint.cpp | 77 +- .../Dynamics/Joints/b2DistanceJoint.h | 76 +- .../Box2D/Dynamics/Joints/b2FrictionJoint.cpp | 229 ++++ .../Box2D/Dynamics/Joints/b2FrictionJoint.h | 99 ++ .../Dynamics/Joints/b2GearJoint.cpp | 132 +- .../Dynamics/Joints/b2GearJoint.h | 20 +- .../Dynamics/Joints/b2Joint.cpp | 78 +- .../Dynamics/Joints/b2Joint.h | 95 +- .../Box2D/Dynamics/Joints/b2LineJoint.cpp | 591 +++++++++ .../box2d/Box2D/Dynamics/Joints/b2LineJoint.h | 170 +++ .../Box2D/Dynamics/Joints/b2MouseJoint.cpp | 197 +++ .../Dynamics/Joints/b2MouseJoint.h | 44 +- .../Dynamics/Joints/b2PrismaticJoint.cpp | 586 +++++++++ .../Dynamics/Joints/b2PrismaticJoint.h | 45 +- .../Dynamics/Joints/b2PulleyJoint.cpp | 197 ++- .../Dynamics/Joints/b2PulleyJoint.h | 81 +- .../Box2D/Dynamics/Joints/b2RevoluteJoint.cpp | 478 ++++++++ .../Dynamics/Joints/b2RevoluteJoint.h | 42 +- .../Box2D/Dynamics/Joints/b2WeldJoint.cpp | 219 ++++ .../box2d/Box2D/Dynamics/Joints/b2WeldJoint.h | 82 ++ .../physics/box2d/Box2D/Dynamics/b2Body.cpp | 470 +++++++ .../physics/box2d/Box2D/Dynamics/b2Body.h | 802 ++++++++++++ .../box2d/Box2D/Dynamics/b2ContactManager.cpp | 266 ++++ .../Dynamics/b2ContactManager.h | 36 +- .../box2d/Box2D/Dynamics/b2Fixture.cpp | 163 +++ .../physics/box2d/Box2D/Dynamics/b2Fixture.h | 326 +++++ .../{Source => Box2D}/Dynamics/b2Island.cpp | 286 ++--- .../{Source => Box2D}/Dynamics/b2Island.h | 33 +- .../Dynamics/b2TimeStep.h} | 46 +- .../physics/box2d/Box2D/Dynamics/b2World.cpp | 1076 +++++++++++++++++ .../{Source => Box2D}/Dynamics/b2World.h | 538 +++++---- .../Dynamics/b2WorldCallbacks.cpp | 20 +- .../Dynamics/b2WorldCallbacks.h | 129 +- src/modules/physics/box2d/Contact.h | 2 +- src/modules/physics/box2d/Include/Box2D.h | 52 - src/modules/physics/box2d/Joint.h | 2 +- src/modules/physics/box2d/Shape.h | 2 +- .../Source/Collision/Shapes/b2CircleShape.cpp | 120 -- .../Source/Collision/Shapes/b2CircleShape.h | 92 -- .../Collision/Shapes/b2PolygonShape.cpp | 449 ------- .../Source/Collision/Shapes/b2PolygonShape.h | 163 --- .../box2d/Source/Collision/Shapes/b2Shape.cpp | 167 --- .../box2d/Source/Collision/Shapes/b2Shape.h | 286 ----- .../box2d/Source/Collision/b2BroadPhase.cpp | 668 ---------- .../box2d/Source/Collision/b2BroadPhase.h | 146 --- .../Source/Collision/b2CollideCircle.cpp | 168 --- .../box2d/Source/Collision/b2Collision.cpp | 72 -- .../box2d/Source/Collision/b2Collision.h | 154 --- .../box2d/Source/Collision/b2Distance.cpp | 364 ------ .../box2d/Source/Collision/b2PairManager.cpp | 396 ------ .../box2d/Source/Collision/b2PairManager.h | 121 -- .../box2d/Source/Collision/b2TimeOfImpact.cpp | 112 -- .../physics/box2d/Source/Common/Fixed.h | 477 -------- .../physics/box2d/Source/Common/b2Math.cpp | 54 - .../physics/box2d/Source/Common/jtypes.h | 139 --- .../Dynamics/Contacts/b2CircleContact.cpp | 122 -- .../Source/Dynamics/Contacts/b2Contact.cpp | 172 --- .../Source/Dynamics/Contacts/b2Contact.h | 183 --- .../Dynamics/Contacts/b2ContactSolver.cpp | 360 ------ .../Contacts/b2PolyAndCircleContact.cpp | 158 --- .../Dynamics/Contacts/b2PolyContact.cpp | 157 --- .../Source/Dynamics/Joints/b2MouseJoint.cpp | 146 --- .../Dynamics/Joints/b2PrismaticJoint.cpp | 478 -------- .../Dynamics/Joints/b2RevoluteJoint.cpp | 399 ------ .../physics/box2d/Source/Dynamics/b2Body.cpp | 394 ------ .../physics/box2d/Source/Dynamics/b2Body.h | 587 --------- .../Source/Dynamics/b2ContactManager.cpp | 240 ---- .../physics/box2d/Source/Dynamics/b2World.cpp | 1064 ---------------- src/modules/physics/box2d/World.h | 2 +- 109 files changed, 12874 insertions(+), 10337 deletions(-) create mode 100644 src/modules/physics/box2d/Box2D/Box2D.h create mode 100644 src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.cpp create mode 100644 src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.h create mode 100644 src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp create mode 100644 src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.h create mode 100644 src/modules/physics/box2d/Box2D/Collision/Shapes/b2Shape.h create mode 100644 src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.cpp create mode 100644 src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.h create mode 100644 src/modules/physics/box2d/Box2D/Collision/b2CollideCircle.cpp rename src/modules/physics/box2d/{Source/Collision/b2CollidePoly.cpp => Box2D/Collision/b2CollidePolygon.cpp} (53%) create mode 100644 src/modules/physics/box2d/Box2D/Collision/b2Collision.cpp create mode 100644 src/modules/physics/box2d/Box2D/Collision/b2Collision.h create mode 100644 src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp create mode 100644 src/modules/physics/box2d/Box2D/Collision/b2Distance.h create mode 100644 src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.cpp create mode 100644 src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.h create mode 100644 src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.cpp create mode 100644 src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.h rename src/modules/physics/box2d/{Source => Box2D}/Common/b2BlockAllocator.cpp (91%) rename src/modules/physics/box2d/{Source => Box2D}/Common/b2BlockAllocator.h (91%) create mode 100644 src/modules/physics/box2d/Box2D/Common/b2Math.cpp rename src/modules/physics/box2d/{Source => Box2D}/Common/b2Math.h (60%) rename src/modules/physics/box2d/{Source/Dynamics/Contacts/b2NullContact.h => Box2D/Common/b2Settings.cpp} (70%) rename src/modules/physics/box2d/{Source => Box2D}/Common/b2Settings.h (57%) rename src/modules/physics/box2d/{Source => Box2D}/Common/b2StackAllocator.cpp (89%) rename src/modules/physics/box2d/{Source => Box2D}/Common/b2StackAllocator.h (90%) create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.cpp rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/Contacts/b2CircleContact.h (66%) create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.h create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.cpp rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/Contacts/b2ContactSolver.h (67%) create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp rename src/modules/physics/box2d/{Source/Dynamics/Contacts/b2PolyAndCircleContact.h => Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h} (63%) create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.cpp rename src/modules/physics/box2d/{Source/Dynamics/Contacts/b2PolyContact.h => Box2D/Dynamics/Contacts/b2PolygonContact.h} (69%) create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.cpp create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.h rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/Joints/b2DistanceJoint.cpp (67%) rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/Joints/b2DistanceJoint.h (59%) create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/Joints/b2GearJoint.cpp (57%) rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/Joints/b2GearJoint.h (85%) rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/Joints/b2Joint.cpp (61%) rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/Joints/b2Joint.h (69%) create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.cpp create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.h create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.cpp rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/Joints/b2MouseJoint.h (70%) create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/Joints/b2PrismaticJoint.h (83%) rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/Joints/b2PulleyJoint.cpp (57%) rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/Joints/b2PulleyJoint.h (65%) create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/Joints/b2RevoluteJoint.h (82%) create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/b2Body.h create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/b2ContactManager.h (58%) create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/b2Island.cpp (62%) rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/b2Island.h (75%) rename src/modules/physics/box2d/{Source/Common/b2Settings.cpp => Box2D/Dynamics/b2TimeStep.h} (57%) create mode 100644 src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/b2World.h (57%) rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/b2WorldCallbacks.cpp (68%) rename src/modules/physics/box2d/{Source => Box2D}/Dynamics/b2WorldCallbacks.h (50%) delete mode 100644 src/modules/physics/box2d/Include/Box2D.h delete mode 100644 src/modules/physics/box2d/Source/Collision/Shapes/b2CircleShape.cpp delete mode 100644 src/modules/physics/box2d/Source/Collision/Shapes/b2CircleShape.h delete mode 100644 src/modules/physics/box2d/Source/Collision/Shapes/b2PolygonShape.cpp delete mode 100644 src/modules/physics/box2d/Source/Collision/Shapes/b2PolygonShape.h delete mode 100644 src/modules/physics/box2d/Source/Collision/Shapes/b2Shape.cpp delete mode 100644 src/modules/physics/box2d/Source/Collision/Shapes/b2Shape.h delete mode 100644 src/modules/physics/box2d/Source/Collision/b2BroadPhase.cpp delete mode 100644 src/modules/physics/box2d/Source/Collision/b2BroadPhase.h delete mode 100644 src/modules/physics/box2d/Source/Collision/b2CollideCircle.cpp delete mode 100644 src/modules/physics/box2d/Source/Collision/b2Collision.cpp delete mode 100644 src/modules/physics/box2d/Source/Collision/b2Collision.h delete mode 100644 src/modules/physics/box2d/Source/Collision/b2Distance.cpp delete mode 100644 src/modules/physics/box2d/Source/Collision/b2PairManager.cpp delete mode 100644 src/modules/physics/box2d/Source/Collision/b2PairManager.h delete mode 100644 src/modules/physics/box2d/Source/Collision/b2TimeOfImpact.cpp delete mode 100644 src/modules/physics/box2d/Source/Common/Fixed.h delete mode 100644 src/modules/physics/box2d/Source/Common/b2Math.cpp delete mode 100644 src/modules/physics/box2d/Source/Common/jtypes.h delete mode 100644 src/modules/physics/box2d/Source/Dynamics/Contacts/b2CircleContact.cpp delete mode 100644 src/modules/physics/box2d/Source/Dynamics/Contacts/b2Contact.cpp delete mode 100644 src/modules/physics/box2d/Source/Dynamics/Contacts/b2Contact.h delete mode 100644 src/modules/physics/box2d/Source/Dynamics/Contacts/b2ContactSolver.cpp delete mode 100644 src/modules/physics/box2d/Source/Dynamics/Contacts/b2PolyAndCircleContact.cpp delete mode 100644 src/modules/physics/box2d/Source/Dynamics/Contacts/b2PolyContact.cpp delete mode 100644 src/modules/physics/box2d/Source/Dynamics/Joints/b2MouseJoint.cpp delete mode 100644 src/modules/physics/box2d/Source/Dynamics/Joints/b2PrismaticJoint.cpp delete mode 100644 src/modules/physics/box2d/Source/Dynamics/Joints/b2RevoluteJoint.cpp delete mode 100644 src/modules/physics/box2d/Source/Dynamics/b2Body.cpp delete mode 100644 src/modules/physics/box2d/Source/Dynamics/b2Body.h delete mode 100644 src/modules/physics/box2d/Source/Dynamics/b2ContactManager.cpp delete mode 100644 src/modules/physics/box2d/Source/Dynamics/b2World.cpp diff --git a/platform/macosx/love.xcodeproj/project.pbxproj b/platform/macosx/love.xcodeproj/project.pbxproj index e0a8c6197..eee5e9af9 100644 --- a/platform/macosx/love.xcodeproj/project.pbxproj +++ b/platform/macosx/love.xcodeproj/project.pbxproj @@ -98,65 +98,34 @@ A946D73C10424AC7002BF36C /* Mouse.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6AC510420AC3007D418B /* Mouse.cpp */; }; A946D73D10424AC7002BF36C /* wrap_Mouse.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6AC710420AC3007D418B /* wrap_Mouse.cpp */; }; A946D7DA10424E57002BF36C /* wrap_GearJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B5810420ACA007D418B /* wrap_GearJoint.cpp */; }; - A946D7DB10424E57002BF36C /* b2CircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B3410420AC9007D418B /* b2CircleContact.cpp */; }; A946D7DC10424E57002BF36C /* wrap_Shape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B6810420ACA007D418B /* wrap_Shape.cpp */; }; A946D7DD10424E57002BF36C /* wrap_PolygonShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B6010420ACA007D418B /* wrap_PolygonShape.cpp */; }; A946D7DE10424E57002BF36C /* DistanceJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6AF110420AC7007D418B /* DistanceJoint.cpp */; }; - A946D7DF10424E57002BF36C /* b2PulleyJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B4A10420ACA007D418B /* b2PulleyJoint.cpp */; }; - A946D7E010424E57002BF36C /* b2Island.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B2D10420AC9007D418B /* b2Island.cpp */; }; - A946D7E110424E57002BF36C /* b2BlockAllocator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B1E10420AC9007D418B /* b2BlockAllocator.cpp */; }; A946D7E210424E57002BF36C /* Contact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6AEF10420AC7007D418B /* Contact.cpp */; }; - A946D7E310424E57002BF36C /* b2Distance.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B1210420AC8007D418B /* b2Distance.cpp */; }; A946D7E410424E57002BF36C /* Joint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6AFA10420AC8007D418B /* Joint.cpp */; }; - A946D7E510424E57002BF36C /* b2PolyContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B3D10420AC9007D418B /* b2PolyContact.cpp */; }; - A946D7E610424E57002BF36C /* b2Joint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B4410420AC9007D418B /* b2Joint.cpp */; }; - A946D7E710424E57002BF36C /* b2WorldCallbacks.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B3110420AC9007D418B /* b2WorldCallbacks.cpp */; }; A946D7E810424E57002BF36C /* wrap_PulleyJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B6410420ACA007D418B /* wrap_PulleyJoint.cpp */; }; - A946D7E910424E57002BF36C /* b2Body.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B2910420AC9007D418B /* b2Body.cpp */; }; - A946D7EA10424E57002BF36C /* b2TimeOfImpact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B1510420AC8007D418B /* b2TimeOfImpact.cpp */; }; A946D7EB10424E57002BF36C /* wrap_DistanceJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B5610420ACA007D418B /* wrap_DistanceJoint.cpp */; }; A946D7EC10424E57002BF36C /* CircleShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6AED10420AC7007D418B /* CircleShape.cpp */; }; - A946D7ED10424E57002BF36C /* b2ContactSolver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B3810420AC9007D418B /* b2ContactSolver.cpp */; }; A946D7EE10424E57002BF36C /* MouseJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6AFC10420AC8007D418B /* MouseJoint.cpp */; }; A946D7EF10424E57002BF36C /* wrap_CircleShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B5210420ACA007D418B /* wrap_CircleShape.cpp */; }; A946D7F010424E57002BF36C /* wrap_Contact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B5410420ACA007D418B /* wrap_Contact.cpp */; }; - A946D7F110424E57002BF36C /* b2PrismaticJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B4810420ACA007D418B /* b2PrismaticJoint.cpp */; }; A946D7F210424E57002BF36C /* RevoluteJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B0610420AC8007D418B /* RevoluteJoint.cpp */; }; - A946D7F310424E57002BF36C /* b2Shape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B1B10420AC9007D418B /* b2Shape.cpp */; }; - A946D7F410424E57002BF36C /* b2BroadPhase.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B0C10420AC8007D418B /* b2BroadPhase.cpp */; }; - A946D7F510424E57002BF36C /* b2PolygonShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B1910420AC8007D418B /* b2PolygonShape.cpp */; }; A946D7F610424E57002BF36C /* PulleyJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B0410420AC8007D418B /* PulleyJoint.cpp */; }; - A946D7F710424E57002BF36C /* b2CollidePoly.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B0F10420AC8007D418B /* b2CollidePoly.cpp */; }; A946D7F810424E57002BF36C /* Shape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B0810420AC8007D418B /* Shape.cpp */; }; A946D7F910424E57002BF36C /* wrap_World.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B6A10420ACA007D418B /* wrap_World.cpp */; }; A946D7FA10424E57002BF36C /* wrap_RevoluteJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B6610420ACA007D418B /* wrap_RevoluteJoint.cpp */; }; A946D7FB10424E57002BF36C /* wrap_PrismaticJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B6210420ACA007D418B /* wrap_PrismaticJoint.cpp */; }; A946D7FC10424E57002BF36C /* GrahamScanConvexHull.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6AF610420AC7007D418B /* GrahamScanConvexHull.cpp */; }; - A946D7FD10424E57002BF36C /* b2RevoluteJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B4C10420ACA007D418B /* b2RevoluteJoint.cpp */; }; A946D7FE10424E57002BF36C /* wrap_MouseJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B5C10420ACA007D418B /* wrap_MouseJoint.cpp */; }; A946D7FF10424E57002BF36C /* wrap_Physics.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B5E10420ACA007D418B /* wrap_Physics.cpp */; }; - A946D80010424E57002BF36C /* b2ContactManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B2B10420AC9007D418B /* b2ContactManager.cpp */; }; - A946D80110424E57002BF36C /* b2StackAllocator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B2410420AC9007D418B /* b2StackAllocator.cpp */; }; A946D80210424E57002BF36C /* PrismaticJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B0210420AC8007D418B /* PrismaticJoint.cpp */; }; - A946D80310424E57002BF36C /* b2PairManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B1310420AC8007D418B /* b2PairManager.cpp */; }; - A946D80410424E57002BF36C /* b2Contact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B3610420AC9007D418B /* b2Contact.cpp */; }; - A946D80510424E57002BF36C /* b2CollideCircle.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B0E10420AC8007D418B /* b2CollideCircle.cpp */; }; - A946D80610424E57002BF36C /* b2DistanceJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B4010420AC9007D418B /* b2DistanceJoint.cpp */; }; A946D80710424E57002BF36C /* Body.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6AEB10420AC7007D418B /* Body.cpp */; }; - A946D80810424E57002BF36C /* b2GearJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B4210420AC9007D418B /* b2GearJoint.cpp */; }; A946D80910424E57002BF36C /* PolygonShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B0010420AC8007D418B /* PolygonShape.cpp */; }; A946D80A10424E57002BF36C /* GearJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6AF310420AC7007D418B /* GearJoint.cpp */; }; A946D80B10424E57002BF36C /* World.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B4E10420ACA007D418B /* World.cpp */; }; - A946D80C10424E57002BF36C /* b2Math.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B2010420AC9007D418B /* b2Math.cpp */; }; - A946D80D10424E57002BF36C /* b2CircleShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B1710420AC8007D418B /* b2CircleShape.cpp */; }; - A946D80E10424E57002BF36C /* b2MouseJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B4610420AC9007D418B /* b2MouseJoint.cpp */; }; A946D80F10424E57002BF36C /* Physics.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6AFE10420AC8007D418B /* Physics.cpp */; }; - A946D81010424E57002BF36C /* b2World.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B2F10420AC9007D418B /* b2World.cpp */; }; - A946D81110424E57002BF36C /* b2Collision.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B1010420AC8007D418B /* b2Collision.cpp */; }; A946D81210424E57002BF36C /* wrap_Joint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B5A10420ACA007D418B /* wrap_Joint.cpp */; }; - A946D81310424E57002BF36C /* b2PolyAndCircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B3B10420AC9007D418B /* b2PolyAndCircleContact.cpp */; }; A946D81410424E57002BF36C /* wrap_Body.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B5010420ACA007D418B /* wrap_Body.cpp */; }; - A946D81510424E57002BF36C /* b2Settings.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B2210420AC9007D418B /* b2Settings.cpp */; }; A946D82A10424EE3002BF36C /* Sound.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B7F10420ACB007D418B /* Sound.cpp */; }; A946D82B10424EE3002BF36C /* Mpg123Decoder.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B7D10420ACB007D418B /* Mpg123Decoder.cpp */; }; A946D82C10424EE3002BF36C /* Decoder.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B7710420ACB007D418B /* Decoder.cpp */; }; @@ -178,9 +147,43 @@ A968F0D91083A9FC00A895AA /* Mouse.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0D81083A9FC00A895AA /* Mouse.cpp */; }; A968F0DD1083AA6600A895AA /* Shape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0DB1083AA6600A895AA /* Shape.cpp */; }; A968F0DE1083AA6600A895AA /* Joint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0DC1083AA6600A895AA /* Joint.cpp */; }; - A97E3843132A9EDE00198A2F /* love-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = A97E3842132A9EDE00198A2F /* love-Info.plist */; }; A986DEB5113249A800810279 /* Thread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986DEB1113249A800810279 /* Thread.cpp */; }; A986DEB6113249A800810279 /* wrap_Thread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986DEB3113249A800810279 /* wrap_Thread.cpp */; }; + A986EC64132CE6DB00F048C8 /* b2BroadPhase.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBC8132CE6D800F048C8 /* b2BroadPhase.cpp */; }; + A986EC65132CE6DB00F048C8 /* b2CollideCircle.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBCA132CE6D800F048C8 /* b2CollideCircle.cpp */; }; + A986EC66132CE6DB00F048C8 /* b2CollidePolygon.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBCB132CE6D800F048C8 /* b2CollidePolygon.cpp */; }; + A986EC67132CE6DB00F048C8 /* b2Collision.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBCC132CE6D800F048C8 /* b2Collision.cpp */; }; + A986EC68132CE6DB00F048C8 /* b2Distance.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBCE132CE6D800F048C8 /* b2Distance.cpp */; }; + A986EC69132CE6DB00F048C8 /* b2DynamicTree.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBD0132CE6D800F048C8 /* b2DynamicTree.cpp */; }; + A986EC6A132CE6DB00F048C8 /* b2TimeOfImpact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBD2132CE6D800F048C8 /* b2TimeOfImpact.cpp */; }; + A986EC6B132CE6DB00F048C8 /* b2CircleShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBD5132CE6D800F048C8 /* b2CircleShape.cpp */; }; + A986EC6C132CE6DB00F048C8 /* b2PolygonShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBD7132CE6D800F048C8 /* b2PolygonShape.cpp */; }; + A986EC6D132CE6DB00F048C8 /* b2BlockAllocator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBDB132CE6D800F048C8 /* b2BlockAllocator.cpp */; }; + A986EC6E132CE6DB00F048C8 /* b2Math.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBDD132CE6D800F048C8 /* b2Math.cpp */; }; + A986EC6F132CE6DB00F048C8 /* b2Settings.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBDF132CE6D800F048C8 /* b2Settings.cpp */; }; + A986EC70132CE6DB00F048C8 /* b2StackAllocator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBE1132CE6D800F048C8 /* b2StackAllocator.cpp */; }; + A986EC71132CE6DB00F048C8 /* b2Body.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBE4132CE6D800F048C8 /* b2Body.cpp */; }; + A986EC72132CE6DB00F048C8 /* b2ContactManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBE6132CE6D800F048C8 /* b2ContactManager.cpp */; }; + A986EC73132CE6DB00F048C8 /* b2Fixture.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBE8132CE6D800F048C8 /* b2Fixture.cpp */; }; + A986EC74132CE6DB00F048C8 /* b2Island.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBEA132CE6D800F048C8 /* b2Island.cpp */; }; + A986EC75132CE6DB00F048C8 /* b2World.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBED132CE6D800F048C8 /* b2World.cpp */; }; + A986EC76132CE6DB00F048C8 /* b2WorldCallbacks.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBEF132CE6D800F048C8 /* b2WorldCallbacks.cpp */; }; + A986EC77132CE6DB00F048C8 /* b2CircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBF2132CE6D800F048C8 /* b2CircleContact.cpp */; }; + A986EC78132CE6DB00F048C8 /* b2Contact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBF4132CE6D800F048C8 /* b2Contact.cpp */; }; + A986EC79132CE6DB00F048C8 /* b2ContactSolver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBF6132CE6D800F048C8 /* b2ContactSolver.cpp */; }; + A986EC7A132CE6DB00F048C8 /* b2PolygonAndCircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBF8132CE6D800F048C8 /* b2PolygonAndCircleContact.cpp */; }; + A986EC7B132CE6DB00F048C8 /* b2PolygonContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBFA132CE6D800F048C8 /* b2PolygonContact.cpp */; }; + A986EC7C132CE6DB00F048C8 /* b2TOISolver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBFC132CE6D800F048C8 /* b2TOISolver.cpp */; }; + A986EC7D132CE6DB00F048C8 /* b2DistanceJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBFF132CE6D800F048C8 /* b2DistanceJoint.cpp */; }; + A986EC7E132CE6DB00F048C8 /* b2FrictionJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC01132CE6D800F048C8 /* b2FrictionJoint.cpp */; }; + A986EC7F132CE6DB00F048C8 /* b2GearJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC03132CE6D800F048C8 /* b2GearJoint.cpp */; }; + A986EC80132CE6DB00F048C8 /* b2Joint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC05132CE6D800F048C8 /* b2Joint.cpp */; }; + A986EC81132CE6DB00F048C8 /* b2LineJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC07132CE6D800F048C8 /* b2LineJoint.cpp */; }; + A986EC82132CE6DB00F048C8 /* b2MouseJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC09132CE6D800F048C8 /* b2MouseJoint.cpp */; }; + A986EC83132CE6DB00F048C8 /* b2PrismaticJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC0B132CE6D800F048C8 /* b2PrismaticJoint.cpp */; }; + A986EC84132CE6DB00F048C8 /* b2PulleyJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC0D132CE6D800F048C8 /* b2PulleyJoint.cpp */; }; + A986EC85132CE6DB00F048C8 /* b2RevoluteJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC0F132CE6D800F048C8 /* b2RevoluteJoint.cpp */; }; + A986EC86132CE6DB00F048C8 /* b2WeldJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC11132CE6D800F048C8 /* b2WeldJoint.cpp */; }; A98D914410507C97008E03F2 /* EncodedImageData.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A98D914310507C97008E03F2 /* EncodedImageData.cpp */; }; A9B4BA9C1045937F001DBC80 /* ParticleSystem.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9B4BA9A1045937F001DBC80 /* ParticleSystem.cpp */; }; A9B4BA9D1045937F001DBC80 /* wrap_ParticleSystem.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9B4BA9B1045937F001DBC80 /* wrap_ParticleSystem.cpp */; }; @@ -416,7 +419,6 @@ A93E6AF410420AC7007D418B /* GearJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GearJoint.h; sourceTree = ""; }; A93E6AF610420AC7007D418B /* GrahamScanConvexHull.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GrahamScanConvexHull.cpp; sourceTree = ""; }; A93E6AF710420AC8007D418B /* GrahamScanConvexHull.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GrahamScanConvexHull.h; sourceTree = ""; }; - A93E6AF910420AC8007D418B /* Box2D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Box2D.h; sourceTree = ""; }; A93E6AFA10420AC8007D418B /* Joint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Joint.cpp; sourceTree = ""; }; A93E6AFB10420AC8007D418B /* Joint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Joint.h; sourceTree = ""; }; A93E6AFC10420AC8007D418B /* MouseJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MouseJoint.cpp; sourceTree = ""; }; @@ -433,67 +435,6 @@ A93E6B0710420AC8007D418B /* RevoluteJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RevoluteJoint.h; sourceTree = ""; }; A93E6B0810420AC8007D418B /* Shape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Shape.cpp; sourceTree = ""; }; A93E6B0910420AC8007D418B /* Shape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Shape.h; sourceTree = ""; }; - A93E6B0C10420AC8007D418B /* b2BroadPhase.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2BroadPhase.cpp; sourceTree = ""; }; - A93E6B0D10420AC8007D418B /* b2BroadPhase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2BroadPhase.h; sourceTree = ""; }; - A93E6B0E10420AC8007D418B /* b2CollideCircle.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CollideCircle.cpp; sourceTree = ""; }; - A93E6B0F10420AC8007D418B /* b2CollidePoly.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CollidePoly.cpp; sourceTree = ""; }; - A93E6B1010420AC8007D418B /* b2Collision.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Collision.cpp; sourceTree = ""; }; - A93E6B1110420AC8007D418B /* b2Collision.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Collision.h; sourceTree = ""; }; - A93E6B1210420AC8007D418B /* b2Distance.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Distance.cpp; sourceTree = ""; }; - A93E6B1310420AC8007D418B /* b2PairManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PairManager.cpp; sourceTree = ""; }; - A93E6B1410420AC8007D418B /* b2PairManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PairManager.h; sourceTree = ""; }; - A93E6B1510420AC8007D418B /* b2TimeOfImpact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2TimeOfImpact.cpp; sourceTree = ""; }; - A93E6B1710420AC8007D418B /* b2CircleShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CircleShape.cpp; sourceTree = ""; }; - A93E6B1810420AC8007D418B /* b2CircleShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2CircleShape.h; sourceTree = ""; }; - A93E6B1910420AC8007D418B /* b2PolygonShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PolygonShape.cpp; sourceTree = ""; }; - A93E6B1A10420AC8007D418B /* b2PolygonShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PolygonShape.h; sourceTree = ""; }; - A93E6B1B10420AC9007D418B /* b2Shape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Shape.cpp; sourceTree = ""; }; - A93E6B1C10420AC9007D418B /* b2Shape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Shape.h; sourceTree = ""; }; - A93E6B1E10420AC9007D418B /* b2BlockAllocator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2BlockAllocator.cpp; sourceTree = ""; }; - A93E6B1F10420AC9007D418B /* b2BlockAllocator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2BlockAllocator.h; sourceTree = ""; }; - A93E6B2010420AC9007D418B /* b2Math.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Math.cpp; sourceTree = ""; }; - A93E6B2110420AC9007D418B /* b2Math.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Math.h; sourceTree = ""; }; - A93E6B2210420AC9007D418B /* b2Settings.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Settings.cpp; sourceTree = ""; }; - A93E6B2310420AC9007D418B /* b2Settings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Settings.h; sourceTree = ""; }; - A93E6B2410420AC9007D418B /* b2StackAllocator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2StackAllocator.cpp; sourceTree = ""; }; - A93E6B2510420AC9007D418B /* b2StackAllocator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2StackAllocator.h; sourceTree = ""; }; - A93E6B2610420AC9007D418B /* Fixed.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Fixed.h; sourceTree = ""; }; - A93E6B2710420AC9007D418B /* jtypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jtypes.h; sourceTree = ""; }; - A93E6B2910420AC9007D418B /* b2Body.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Body.cpp; sourceTree = ""; }; - A93E6B2A10420AC9007D418B /* b2Body.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Body.h; sourceTree = ""; }; - A93E6B2B10420AC9007D418B /* b2ContactManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ContactManager.cpp; sourceTree = ""; }; - A93E6B2C10420AC9007D418B /* b2ContactManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ContactManager.h; sourceTree = ""; }; - A93E6B2D10420AC9007D418B /* b2Island.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Island.cpp; sourceTree = ""; }; - A93E6B2E10420AC9007D418B /* b2Island.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Island.h; sourceTree = ""; }; - A93E6B2F10420AC9007D418B /* b2World.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2World.cpp; sourceTree = ""; }; - A93E6B3010420AC9007D418B /* b2World.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2World.h; sourceTree = ""; }; - A93E6B3110420AC9007D418B /* b2WorldCallbacks.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2WorldCallbacks.cpp; sourceTree = ""; }; - A93E6B3210420AC9007D418B /* b2WorldCallbacks.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2WorldCallbacks.h; sourceTree = ""; }; - A93E6B3410420AC9007D418B /* b2CircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CircleContact.cpp; sourceTree = ""; }; - A93E6B3510420AC9007D418B /* b2CircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2CircleContact.h; sourceTree = ""; }; - A93E6B3610420AC9007D418B /* b2Contact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Contact.cpp; sourceTree = ""; }; - A93E6B3710420AC9007D418B /* b2Contact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Contact.h; sourceTree = ""; }; - A93E6B3810420AC9007D418B /* b2ContactSolver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ContactSolver.cpp; sourceTree = ""; }; - A93E6B3910420AC9007D418B /* b2ContactSolver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ContactSolver.h; sourceTree = ""; }; - A93E6B3A10420AC9007D418B /* b2NullContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2NullContact.h; sourceTree = ""; }; - A93E6B3B10420AC9007D418B /* b2PolyAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PolyAndCircleContact.cpp; sourceTree = ""; }; - A93E6B3C10420AC9007D418B /* b2PolyAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PolyAndCircleContact.h; sourceTree = ""; }; - A93E6B3D10420AC9007D418B /* b2PolyContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PolyContact.cpp; sourceTree = ""; }; - A93E6B3E10420AC9007D418B /* b2PolyContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PolyContact.h; sourceTree = ""; }; - A93E6B4010420AC9007D418B /* b2DistanceJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2DistanceJoint.cpp; sourceTree = ""; }; - A93E6B4110420AC9007D418B /* b2DistanceJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2DistanceJoint.h; sourceTree = ""; }; - A93E6B4210420AC9007D418B /* b2GearJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2GearJoint.cpp; sourceTree = ""; }; - A93E6B4310420AC9007D418B /* b2GearJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2GearJoint.h; sourceTree = ""; }; - A93E6B4410420AC9007D418B /* b2Joint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Joint.cpp; sourceTree = ""; }; - A93E6B4510420AC9007D418B /* b2Joint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Joint.h; sourceTree = ""; }; - A93E6B4610420AC9007D418B /* b2MouseJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2MouseJoint.cpp; sourceTree = ""; }; - A93E6B4710420ACA007D418B /* b2MouseJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2MouseJoint.h; sourceTree = ""; }; - A93E6B4810420ACA007D418B /* b2PrismaticJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PrismaticJoint.cpp; sourceTree = ""; }; - A93E6B4910420ACA007D418B /* b2PrismaticJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PrismaticJoint.h; sourceTree = ""; }; - A93E6B4A10420ACA007D418B /* b2PulleyJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PulleyJoint.cpp; sourceTree = ""; }; - A93E6B4B10420ACA007D418B /* b2PulleyJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PulleyJoint.h; sourceTree = ""; }; - A93E6B4C10420ACA007D418B /* b2RevoluteJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2RevoluteJoint.cpp; sourceTree = ""; }; - A93E6B4D10420ACA007D418B /* b2RevoluteJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2RevoluteJoint.h; sourceTree = ""; }; A93E6B4E10420ACA007D418B /* World.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = World.cpp; sourceTree = ""; }; A93E6B4F10420ACA007D418B /* World.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = World.h; sourceTree = ""; }; A93E6B5010420ACA007D418B /* wrap_Body.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_Body.cpp; sourceTree = ""; }; @@ -586,6 +527,77 @@ A986DEB2113249A800810279 /* Thread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Thread.h; sourceTree = ""; }; A986DEB3113249A800810279 /* wrap_Thread.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_Thread.cpp; sourceTree = ""; }; A986DEB4113249A800810279 /* wrap_Thread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_Thread.h; sourceTree = ""; }; + A986EBC8132CE6D800F048C8 /* b2BroadPhase.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2BroadPhase.cpp; sourceTree = ""; }; + A986EBC9132CE6D800F048C8 /* b2BroadPhase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2BroadPhase.h; sourceTree = ""; }; + A986EBCA132CE6D800F048C8 /* b2CollideCircle.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CollideCircle.cpp; sourceTree = ""; }; + A986EBCB132CE6D800F048C8 /* b2CollidePolygon.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CollidePolygon.cpp; sourceTree = ""; }; + A986EBCC132CE6D800F048C8 /* b2Collision.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Collision.cpp; sourceTree = ""; }; + A986EBCD132CE6D800F048C8 /* b2Collision.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Collision.h; sourceTree = ""; }; + A986EBCE132CE6D800F048C8 /* b2Distance.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Distance.cpp; sourceTree = ""; }; + A986EBCF132CE6D800F048C8 /* b2Distance.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Distance.h; sourceTree = ""; }; + A986EBD0132CE6D800F048C8 /* b2DynamicTree.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2DynamicTree.cpp; sourceTree = ""; }; + A986EBD1132CE6D800F048C8 /* b2DynamicTree.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2DynamicTree.h; sourceTree = ""; }; + A986EBD2132CE6D800F048C8 /* b2TimeOfImpact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2TimeOfImpact.cpp; sourceTree = ""; }; + A986EBD3132CE6D800F048C8 /* b2TimeOfImpact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2TimeOfImpact.h; sourceTree = ""; }; + A986EBD5132CE6D800F048C8 /* b2CircleShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CircleShape.cpp; sourceTree = ""; }; + A986EBD6132CE6D800F048C8 /* b2CircleShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2CircleShape.h; sourceTree = ""; }; + A986EBD7132CE6D800F048C8 /* b2PolygonShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PolygonShape.cpp; sourceTree = ""; }; + A986EBD8132CE6D800F048C8 /* b2PolygonShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PolygonShape.h; sourceTree = ""; }; + A986EBD9132CE6D800F048C8 /* b2Shape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Shape.h; sourceTree = ""; }; + A986EBDB132CE6D800F048C8 /* b2BlockAllocator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2BlockAllocator.cpp; sourceTree = ""; }; + A986EBDC132CE6D800F048C8 /* b2BlockAllocator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2BlockAllocator.h; sourceTree = ""; }; + A986EBDD132CE6D800F048C8 /* b2Math.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Math.cpp; sourceTree = ""; }; + A986EBDE132CE6D800F048C8 /* b2Math.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Math.h; sourceTree = ""; }; + A986EBDF132CE6D800F048C8 /* b2Settings.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Settings.cpp; sourceTree = ""; }; + A986EBE0132CE6D800F048C8 /* b2Settings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Settings.h; sourceTree = ""; }; + A986EBE1132CE6D800F048C8 /* b2StackAllocator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2StackAllocator.cpp; sourceTree = ""; }; + A986EBE2132CE6D800F048C8 /* b2StackAllocator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2StackAllocator.h; sourceTree = ""; }; + A986EBE4132CE6D800F048C8 /* b2Body.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Body.cpp; sourceTree = ""; }; + A986EBE5132CE6D800F048C8 /* b2Body.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Body.h; sourceTree = ""; }; + A986EBE6132CE6D800F048C8 /* b2ContactManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ContactManager.cpp; sourceTree = ""; }; + A986EBE7132CE6D800F048C8 /* b2ContactManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ContactManager.h; sourceTree = ""; }; + A986EBE8132CE6D800F048C8 /* b2Fixture.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Fixture.cpp; sourceTree = ""; }; + A986EBE9132CE6D800F048C8 /* b2Fixture.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Fixture.h; sourceTree = ""; }; + A986EBEA132CE6D800F048C8 /* b2Island.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Island.cpp; sourceTree = ""; }; + A986EBEB132CE6D800F048C8 /* b2Island.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Island.h; sourceTree = ""; }; + A986EBEC132CE6D800F048C8 /* b2TimeStep.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2TimeStep.h; sourceTree = ""; }; + A986EBED132CE6D800F048C8 /* b2World.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2World.cpp; sourceTree = ""; }; + A986EBEE132CE6D800F048C8 /* b2World.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2World.h; sourceTree = ""; }; + A986EBEF132CE6D800F048C8 /* b2WorldCallbacks.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2WorldCallbacks.cpp; sourceTree = ""; }; + A986EBF0132CE6D800F048C8 /* b2WorldCallbacks.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2WorldCallbacks.h; sourceTree = ""; }; + A986EBF2132CE6D800F048C8 /* b2CircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CircleContact.cpp; sourceTree = ""; }; + A986EBF3132CE6D800F048C8 /* b2CircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2CircleContact.h; sourceTree = ""; }; + A986EBF4132CE6D800F048C8 /* b2Contact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Contact.cpp; sourceTree = ""; }; + A986EBF5132CE6D800F048C8 /* b2Contact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Contact.h; sourceTree = ""; }; + A986EBF6132CE6D800F048C8 /* b2ContactSolver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ContactSolver.cpp; sourceTree = ""; }; + A986EBF7132CE6D800F048C8 /* b2ContactSolver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ContactSolver.h; sourceTree = ""; }; + A986EBF8132CE6D800F048C8 /* b2PolygonAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PolygonAndCircleContact.cpp; sourceTree = ""; }; + A986EBF9132CE6D800F048C8 /* b2PolygonAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PolygonAndCircleContact.h; sourceTree = ""; }; + A986EBFA132CE6D800F048C8 /* b2PolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PolygonContact.cpp; sourceTree = ""; }; + A986EBFB132CE6D800F048C8 /* b2PolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PolygonContact.h; sourceTree = ""; }; + A986EBFC132CE6D800F048C8 /* b2TOISolver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2TOISolver.cpp; sourceTree = ""; }; + A986EBFD132CE6D800F048C8 /* b2TOISolver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2TOISolver.h; sourceTree = ""; }; + A986EBFF132CE6D800F048C8 /* b2DistanceJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2DistanceJoint.cpp; sourceTree = ""; }; + A986EC00132CE6D800F048C8 /* b2DistanceJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2DistanceJoint.h; sourceTree = ""; }; + A986EC01132CE6D800F048C8 /* b2FrictionJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2FrictionJoint.cpp; sourceTree = ""; }; + A986EC02132CE6D800F048C8 /* b2FrictionJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2FrictionJoint.h; sourceTree = ""; }; + A986EC03132CE6D800F048C8 /* b2GearJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2GearJoint.cpp; sourceTree = ""; }; + A986EC04132CE6D800F048C8 /* b2GearJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2GearJoint.h; sourceTree = ""; }; + A986EC05132CE6D800F048C8 /* b2Joint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Joint.cpp; sourceTree = ""; }; + A986EC06132CE6D800F048C8 /* b2Joint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Joint.h; sourceTree = ""; }; + A986EC07132CE6D800F048C8 /* b2LineJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2LineJoint.cpp; sourceTree = ""; }; + A986EC08132CE6D800F048C8 /* b2LineJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2LineJoint.h; sourceTree = ""; }; + A986EC09132CE6D800F048C8 /* b2MouseJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2MouseJoint.cpp; sourceTree = ""; }; + A986EC0A132CE6D800F048C8 /* b2MouseJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2MouseJoint.h; sourceTree = ""; }; + A986EC0B132CE6D800F048C8 /* b2PrismaticJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PrismaticJoint.cpp; sourceTree = ""; }; + A986EC0C132CE6D800F048C8 /* b2PrismaticJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PrismaticJoint.h; sourceTree = ""; }; + A986EC0D132CE6D800F048C8 /* b2PulleyJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PulleyJoint.cpp; sourceTree = ""; }; + A986EC0E132CE6D800F048C8 /* b2PulleyJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PulleyJoint.h; sourceTree = ""; }; + A986EC0F132CE6D800F048C8 /* b2RevoluteJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2RevoluteJoint.cpp; sourceTree = ""; }; + A986EC10132CE6D800F048C8 /* b2RevoluteJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2RevoluteJoint.h; sourceTree = ""; }; + A986EC11132CE6D800F048C8 /* b2WeldJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2WeldJoint.cpp; sourceTree = ""; }; + A986EC12132CE6D800F048C8 /* b2WeldJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2WeldJoint.h; sourceTree = ""; }; + A986ECAC132CE82F00F048C8 /* Box2D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Box2D.h; sourceTree = ""; }; A98D913E10507BF9008E03F2 /* EncodedImageData.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EncodedImageData.h; sourceTree = ""; }; A98D914310507C97008E03F2 /* EncodedImageData.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = EncodedImageData.cpp; sourceTree = ""; }; A9B1AE451197293000D496EB /* love_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = love_Prefix.pch; sourceTree = ""; }; @@ -1125,6 +1137,7 @@ children = ( A93E6AEB10420AC7007D418B /* Body.cpp */, A93E6AEC10420AC7007D418B /* Body.h */, + A986EBC3132CE6D800F048C8 /* Box2D */, A93E6AED10420AC7007D418B /* CircleShape.cpp */, A93E6AEE10420AC7007D418B /* CircleShape.h */, A93E6AEF10420AC7007D418B /* Contact.cpp */, @@ -1134,7 +1147,6 @@ A93E6AF310420AC7007D418B /* GearJoint.cpp */, A93E6AF410420AC7007D418B /* GearJoint.h */, A93E6AF510420AC7007D418B /* graham */, - A93E6AF810420AC8007D418B /* Include */, A93E6AFA10420AC8007D418B /* Joint.cpp */, A93E6AFB10420AC8007D418B /* Joint.h */, A93E6AFC10420AC8007D418B /* MouseJoint.cpp */, @@ -1151,7 +1163,6 @@ A93E6B0710420AC8007D418B /* RevoluteJoint.h */, A93E6B0810420AC8007D418B /* Shape.cpp */, A93E6B0910420AC8007D418B /* Shape.h */, - A93E6B0A10420AC8007D418B /* Source */, A93E6B4E10420ACA007D418B /* World.cpp */, A93E6B4F10420ACA007D418B /* World.h */, A93E6B5010420ACA007D418B /* wrap_Body.cpp */, @@ -1195,130 +1206,6 @@ path = graham; sourceTree = ""; }; - A93E6AF810420AC8007D418B /* Include */ = { - isa = PBXGroup; - children = ( - A93E6AF910420AC8007D418B /* Box2D.h */, - ); - path = Include; - sourceTree = ""; - }; - A93E6B0A10420AC8007D418B /* Source */ = { - isa = PBXGroup; - children = ( - A93E6B0B10420AC8007D418B /* Collision */, - A93E6B1D10420AC9007D418B /* Common */, - A93E6B2810420AC9007D418B /* Dynamics */, - ); - path = Source; - sourceTree = ""; - }; - A93E6B0B10420AC8007D418B /* Collision */ = { - isa = PBXGroup; - children = ( - A93E6B0C10420AC8007D418B /* b2BroadPhase.cpp */, - A93E6B0D10420AC8007D418B /* b2BroadPhase.h */, - A93E6B0E10420AC8007D418B /* b2CollideCircle.cpp */, - A93E6B0F10420AC8007D418B /* b2CollidePoly.cpp */, - A93E6B1010420AC8007D418B /* b2Collision.cpp */, - A93E6B1110420AC8007D418B /* b2Collision.h */, - A93E6B1210420AC8007D418B /* b2Distance.cpp */, - A93E6B1310420AC8007D418B /* b2PairManager.cpp */, - A93E6B1410420AC8007D418B /* b2PairManager.h */, - A93E6B1510420AC8007D418B /* b2TimeOfImpact.cpp */, - A93E6B1610420AC8007D418B /* Shapes */, - ); - path = Collision; - sourceTree = ""; - }; - A93E6B1610420AC8007D418B /* Shapes */ = { - isa = PBXGroup; - children = ( - A93E6B1710420AC8007D418B /* b2CircleShape.cpp */, - A93E6B1810420AC8007D418B /* b2CircleShape.h */, - A93E6B1910420AC8007D418B /* b2PolygonShape.cpp */, - A93E6B1A10420AC8007D418B /* b2PolygonShape.h */, - A93E6B1B10420AC9007D418B /* b2Shape.cpp */, - A93E6B1C10420AC9007D418B /* b2Shape.h */, - ); - path = Shapes; - sourceTree = ""; - }; - A93E6B1D10420AC9007D418B /* Common */ = { - isa = PBXGroup; - children = ( - A93E6B1E10420AC9007D418B /* b2BlockAllocator.cpp */, - A93E6B1F10420AC9007D418B /* b2BlockAllocator.h */, - A93E6B2010420AC9007D418B /* b2Math.cpp */, - A93E6B2110420AC9007D418B /* b2Math.h */, - A93E6B2210420AC9007D418B /* b2Settings.cpp */, - A93E6B2310420AC9007D418B /* b2Settings.h */, - A93E6B2410420AC9007D418B /* b2StackAllocator.cpp */, - A93E6B2510420AC9007D418B /* b2StackAllocator.h */, - A93E6B2610420AC9007D418B /* Fixed.h */, - A93E6B2710420AC9007D418B /* jtypes.h */, - ); - path = Common; - sourceTree = ""; - }; - A93E6B2810420AC9007D418B /* Dynamics */ = { - isa = PBXGroup; - children = ( - A93E6B2910420AC9007D418B /* b2Body.cpp */, - A93E6B2A10420AC9007D418B /* b2Body.h */, - A93E6B2B10420AC9007D418B /* b2ContactManager.cpp */, - A93E6B2C10420AC9007D418B /* b2ContactManager.h */, - A93E6B2D10420AC9007D418B /* b2Island.cpp */, - A93E6B2E10420AC9007D418B /* b2Island.h */, - A93E6B2F10420AC9007D418B /* b2World.cpp */, - A93E6B3010420AC9007D418B /* b2World.h */, - A93E6B3110420AC9007D418B /* b2WorldCallbacks.cpp */, - A93E6B3210420AC9007D418B /* b2WorldCallbacks.h */, - A93E6B3310420AC9007D418B /* Contacts */, - A93E6B3F10420AC9007D418B /* Joints */, - ); - path = Dynamics; - sourceTree = ""; - }; - A93E6B3310420AC9007D418B /* Contacts */ = { - isa = PBXGroup; - children = ( - A93E6B3410420AC9007D418B /* b2CircleContact.cpp */, - A93E6B3510420AC9007D418B /* b2CircleContact.h */, - A93E6B3610420AC9007D418B /* b2Contact.cpp */, - A93E6B3710420AC9007D418B /* b2Contact.h */, - A93E6B3810420AC9007D418B /* b2ContactSolver.cpp */, - A93E6B3910420AC9007D418B /* b2ContactSolver.h */, - A93E6B3A10420AC9007D418B /* b2NullContact.h */, - A93E6B3B10420AC9007D418B /* b2PolyAndCircleContact.cpp */, - A93E6B3C10420AC9007D418B /* b2PolyAndCircleContact.h */, - A93E6B3D10420AC9007D418B /* b2PolyContact.cpp */, - A93E6B3E10420AC9007D418B /* b2PolyContact.h */, - ); - path = Contacts; - sourceTree = ""; - }; - A93E6B3F10420AC9007D418B /* Joints */ = { - isa = PBXGroup; - children = ( - A93E6B4010420AC9007D418B /* b2DistanceJoint.cpp */, - A93E6B4110420AC9007D418B /* b2DistanceJoint.h */, - A93E6B4210420AC9007D418B /* b2GearJoint.cpp */, - A93E6B4310420AC9007D418B /* b2GearJoint.h */, - A93E6B4410420AC9007D418B /* b2Joint.cpp */, - A93E6B4510420AC9007D418B /* b2Joint.h */, - A93E6B4610420AC9007D418B /* b2MouseJoint.cpp */, - A93E6B4710420ACA007D418B /* b2MouseJoint.h */, - A93E6B4810420ACA007D418B /* b2PrismaticJoint.cpp */, - A93E6B4910420ACA007D418B /* b2PrismaticJoint.h */, - A93E6B4A10420ACA007D418B /* b2PulleyJoint.cpp */, - A93E6B4B10420ACA007D418B /* b2PulleyJoint.h */, - A93E6B4C10420ACA007D418B /* b2RevoluteJoint.cpp */, - A93E6B4D10420ACA007D418B /* b2RevoluteJoint.h */, - ); - path = Joints; - sourceTree = ""; - }; A93E6B7410420ACB007D418B /* sound */ = { isa = PBXGroup; children = ( @@ -1428,6 +1315,132 @@ path = sdl; sourceTree = ""; }; + A986EBC3132CE6D800F048C8 /* Box2D */ = { + isa = PBXGroup; + children = ( + A986ECAC132CE82F00F048C8 /* Box2D.h */, + A986EBC7132CE6D800F048C8 /* Collision */, + A986EBDA132CE6D800F048C8 /* Common */, + A986EBE3132CE6D800F048C8 /* Dynamics */, + ); + path = Box2D; + sourceTree = ""; + }; + A986EBC7132CE6D800F048C8 /* Collision */ = { + isa = PBXGroup; + children = ( + A986EBC8132CE6D800F048C8 /* b2BroadPhase.cpp */, + A986EBC9132CE6D800F048C8 /* b2BroadPhase.h */, + A986EBCA132CE6D800F048C8 /* b2CollideCircle.cpp */, + A986EBCB132CE6D800F048C8 /* b2CollidePolygon.cpp */, + A986EBCC132CE6D800F048C8 /* b2Collision.cpp */, + A986EBCD132CE6D800F048C8 /* b2Collision.h */, + A986EBCE132CE6D800F048C8 /* b2Distance.cpp */, + A986EBCF132CE6D800F048C8 /* b2Distance.h */, + A986EBD0132CE6D800F048C8 /* b2DynamicTree.cpp */, + A986EBD1132CE6D800F048C8 /* b2DynamicTree.h */, + A986EBD2132CE6D800F048C8 /* b2TimeOfImpact.cpp */, + A986EBD3132CE6D800F048C8 /* b2TimeOfImpact.h */, + A986EBD4132CE6D800F048C8 /* Shapes */, + ); + path = Collision; + sourceTree = ""; + }; + A986EBD4132CE6D800F048C8 /* Shapes */ = { + isa = PBXGroup; + children = ( + A986EBD5132CE6D800F048C8 /* b2CircleShape.cpp */, + A986EBD6132CE6D800F048C8 /* b2CircleShape.h */, + A986EBD7132CE6D800F048C8 /* b2PolygonShape.cpp */, + A986EBD8132CE6D800F048C8 /* b2PolygonShape.h */, + A986EBD9132CE6D800F048C8 /* b2Shape.h */, + ); + path = Shapes; + sourceTree = ""; + }; + A986EBDA132CE6D800F048C8 /* Common */ = { + isa = PBXGroup; + children = ( + A986EBDB132CE6D800F048C8 /* b2BlockAllocator.cpp */, + A986EBDC132CE6D800F048C8 /* b2BlockAllocator.h */, + A986EBDD132CE6D800F048C8 /* b2Math.cpp */, + A986EBDE132CE6D800F048C8 /* b2Math.h */, + A986EBDF132CE6D800F048C8 /* b2Settings.cpp */, + A986EBE0132CE6D800F048C8 /* b2Settings.h */, + A986EBE1132CE6D800F048C8 /* b2StackAllocator.cpp */, + A986EBE2132CE6D800F048C8 /* b2StackAllocator.h */, + ); + path = Common; + sourceTree = ""; + }; + A986EBE3132CE6D800F048C8 /* Dynamics */ = { + isa = PBXGroup; + children = ( + A986EBE4132CE6D800F048C8 /* b2Body.cpp */, + A986EBE5132CE6D800F048C8 /* b2Body.h */, + A986EBE6132CE6D800F048C8 /* b2ContactManager.cpp */, + A986EBE7132CE6D800F048C8 /* b2ContactManager.h */, + A986EBE8132CE6D800F048C8 /* b2Fixture.cpp */, + A986EBE9132CE6D800F048C8 /* b2Fixture.h */, + A986EBEA132CE6D800F048C8 /* b2Island.cpp */, + A986EBEB132CE6D800F048C8 /* b2Island.h */, + A986EBEC132CE6D800F048C8 /* b2TimeStep.h */, + A986EBED132CE6D800F048C8 /* b2World.cpp */, + A986EBEE132CE6D800F048C8 /* b2World.h */, + A986EBEF132CE6D800F048C8 /* b2WorldCallbacks.cpp */, + A986EBF0132CE6D800F048C8 /* b2WorldCallbacks.h */, + A986EBF1132CE6D800F048C8 /* Contacts */, + A986EBFE132CE6D800F048C8 /* Joints */, + ); + path = Dynamics; + sourceTree = ""; + }; + A986EBF1132CE6D800F048C8 /* Contacts */ = { + isa = PBXGroup; + children = ( + A986EBF2132CE6D800F048C8 /* b2CircleContact.cpp */, + A986EBF3132CE6D800F048C8 /* b2CircleContact.h */, + A986EBF4132CE6D800F048C8 /* b2Contact.cpp */, + A986EBF5132CE6D800F048C8 /* b2Contact.h */, + A986EBF6132CE6D800F048C8 /* b2ContactSolver.cpp */, + A986EBF7132CE6D800F048C8 /* b2ContactSolver.h */, + A986EBF8132CE6D800F048C8 /* b2PolygonAndCircleContact.cpp */, + A986EBF9132CE6D800F048C8 /* b2PolygonAndCircleContact.h */, + A986EBFA132CE6D800F048C8 /* b2PolygonContact.cpp */, + A986EBFB132CE6D800F048C8 /* b2PolygonContact.h */, + A986EBFC132CE6D800F048C8 /* b2TOISolver.cpp */, + A986EBFD132CE6D800F048C8 /* b2TOISolver.h */, + ); + path = Contacts; + sourceTree = ""; + }; + A986EBFE132CE6D800F048C8 /* Joints */ = { + isa = PBXGroup; + children = ( + A986EBFF132CE6D800F048C8 /* b2DistanceJoint.cpp */, + A986EC00132CE6D800F048C8 /* b2DistanceJoint.h */, + A986EC01132CE6D800F048C8 /* b2FrictionJoint.cpp */, + A986EC02132CE6D800F048C8 /* b2FrictionJoint.h */, + A986EC03132CE6D800F048C8 /* b2GearJoint.cpp */, + A986EC04132CE6D800F048C8 /* b2GearJoint.h */, + A986EC05132CE6D800F048C8 /* b2Joint.cpp */, + A986EC06132CE6D800F048C8 /* b2Joint.h */, + A986EC07132CE6D800F048C8 /* b2LineJoint.cpp */, + A986EC08132CE6D800F048C8 /* b2LineJoint.h */, + A986EC09132CE6D800F048C8 /* b2MouseJoint.cpp */, + A986EC0A132CE6D800F048C8 /* b2MouseJoint.h */, + A986EC0B132CE6D800F048C8 /* b2PrismaticJoint.cpp */, + A986EC0C132CE6D800F048C8 /* b2PrismaticJoint.h */, + A986EC0D132CE6D800F048C8 /* b2PulleyJoint.cpp */, + A986EC0E132CE6D800F048C8 /* b2PulleyJoint.h */, + A986EC0F132CE6D800F048C8 /* b2RevoluteJoint.cpp */, + A986EC10132CE6D800F048C8 /* b2RevoluteJoint.h */, + A986EC11132CE6D800F048C8 /* b2WeldJoint.cpp */, + A986EC12132CE6D800F048C8 /* b2WeldJoint.h */, + ); + path = Joints; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -1481,7 +1494,6 @@ files = ( A9DEC1C11046EFA70049C70C /* Love.icns in Resources */, A9DEC1C21046EFA70049C70C /* LoveDocument.icns in Resources */, - A97E3843132A9EDE00198A2F /* love-Info.plist in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1565,65 +1577,34 @@ A946D73C10424AC7002BF36C /* Mouse.cpp in Sources */, A946D73D10424AC7002BF36C /* wrap_Mouse.cpp in Sources */, A946D7DA10424E57002BF36C /* wrap_GearJoint.cpp in Sources */, - A946D7DB10424E57002BF36C /* b2CircleContact.cpp in Sources */, A946D7DC10424E57002BF36C /* wrap_Shape.cpp in Sources */, A946D7DD10424E57002BF36C /* wrap_PolygonShape.cpp in Sources */, A946D7DE10424E57002BF36C /* DistanceJoint.cpp in Sources */, - A946D7DF10424E57002BF36C /* b2PulleyJoint.cpp in Sources */, - A946D7E010424E57002BF36C /* b2Island.cpp in Sources */, - A946D7E110424E57002BF36C /* b2BlockAllocator.cpp in Sources */, A946D7E210424E57002BF36C /* Contact.cpp in Sources */, - A946D7E310424E57002BF36C /* b2Distance.cpp in Sources */, A946D7E410424E57002BF36C /* Joint.cpp in Sources */, - A946D7E510424E57002BF36C /* b2PolyContact.cpp in Sources */, - A946D7E610424E57002BF36C /* b2Joint.cpp in Sources */, - A946D7E710424E57002BF36C /* b2WorldCallbacks.cpp in Sources */, A946D7E810424E57002BF36C /* wrap_PulleyJoint.cpp in Sources */, - A946D7E910424E57002BF36C /* b2Body.cpp in Sources */, - A946D7EA10424E57002BF36C /* b2TimeOfImpact.cpp in Sources */, A946D7EB10424E57002BF36C /* wrap_DistanceJoint.cpp in Sources */, A946D7EC10424E57002BF36C /* CircleShape.cpp in Sources */, - A946D7ED10424E57002BF36C /* b2ContactSolver.cpp in Sources */, A946D7EE10424E57002BF36C /* MouseJoint.cpp in Sources */, A946D7EF10424E57002BF36C /* wrap_CircleShape.cpp in Sources */, A946D7F010424E57002BF36C /* wrap_Contact.cpp in Sources */, - A946D7F110424E57002BF36C /* b2PrismaticJoint.cpp in Sources */, A946D7F210424E57002BF36C /* RevoluteJoint.cpp in Sources */, - A946D7F310424E57002BF36C /* b2Shape.cpp in Sources */, - A946D7F410424E57002BF36C /* b2BroadPhase.cpp in Sources */, - A946D7F510424E57002BF36C /* b2PolygonShape.cpp in Sources */, A946D7F610424E57002BF36C /* PulleyJoint.cpp in Sources */, - A946D7F710424E57002BF36C /* b2CollidePoly.cpp in Sources */, A946D7F810424E57002BF36C /* Shape.cpp in Sources */, A946D7F910424E57002BF36C /* wrap_World.cpp in Sources */, A946D7FA10424E57002BF36C /* wrap_RevoluteJoint.cpp in Sources */, A946D7FB10424E57002BF36C /* wrap_PrismaticJoint.cpp in Sources */, A946D7FC10424E57002BF36C /* GrahamScanConvexHull.cpp in Sources */, - A946D7FD10424E57002BF36C /* b2RevoluteJoint.cpp in Sources */, A946D7FE10424E57002BF36C /* wrap_MouseJoint.cpp in Sources */, A946D7FF10424E57002BF36C /* wrap_Physics.cpp in Sources */, - A946D80010424E57002BF36C /* b2ContactManager.cpp in Sources */, - A946D80110424E57002BF36C /* b2StackAllocator.cpp in Sources */, A946D80210424E57002BF36C /* PrismaticJoint.cpp in Sources */, - A946D80310424E57002BF36C /* b2PairManager.cpp in Sources */, - A946D80410424E57002BF36C /* b2Contact.cpp in Sources */, - A946D80510424E57002BF36C /* b2CollideCircle.cpp in Sources */, - A946D80610424E57002BF36C /* b2DistanceJoint.cpp in Sources */, A946D80710424E57002BF36C /* Body.cpp in Sources */, - A946D80810424E57002BF36C /* b2GearJoint.cpp in Sources */, A946D80910424E57002BF36C /* PolygonShape.cpp in Sources */, A946D80A10424E57002BF36C /* GearJoint.cpp in Sources */, A946D80B10424E57002BF36C /* World.cpp in Sources */, - A946D80C10424E57002BF36C /* b2Math.cpp in Sources */, - A946D80D10424E57002BF36C /* b2CircleShape.cpp in Sources */, - A946D80E10424E57002BF36C /* b2MouseJoint.cpp in Sources */, A946D80F10424E57002BF36C /* Physics.cpp in Sources */, - A946D81010424E57002BF36C /* b2World.cpp in Sources */, - A946D81110424E57002BF36C /* b2Collision.cpp in Sources */, A946D81210424E57002BF36C /* wrap_Joint.cpp in Sources */, - A946D81310424E57002BF36C /* b2PolyAndCircleContact.cpp in Sources */, A946D81410424E57002BF36C /* wrap_Body.cpp in Sources */, - A946D81510424E57002BF36C /* b2Settings.cpp in Sources */, A946D82A10424EE3002BF36C /* Sound.cpp in Sources */, A946D82B10424EE3002BF36C /* Mpg123Decoder.cpp in Sources */, A946D82C10424EE3002BF36C /* Decoder.cpp in Sources */, @@ -1656,6 +1637,41 @@ A9BD60741226C988007DEC63 /* Framebuffer.cpp in Sources */, A9BD60751226C988007DEC63 /* wrap_Framebuffer.cpp in Sources */, A95684F7125D3555001B276B /* b64.cpp in Sources */, + A986EC64132CE6DB00F048C8 /* b2BroadPhase.cpp in Sources */, + A986EC65132CE6DB00F048C8 /* b2CollideCircle.cpp in Sources */, + A986EC66132CE6DB00F048C8 /* b2CollidePolygon.cpp in Sources */, + A986EC67132CE6DB00F048C8 /* b2Collision.cpp in Sources */, + A986EC68132CE6DB00F048C8 /* b2Distance.cpp in Sources */, + A986EC69132CE6DB00F048C8 /* b2DynamicTree.cpp in Sources */, + A986EC6A132CE6DB00F048C8 /* b2TimeOfImpact.cpp in Sources */, + A986EC6B132CE6DB00F048C8 /* b2CircleShape.cpp in Sources */, + A986EC6C132CE6DB00F048C8 /* b2PolygonShape.cpp in Sources */, + A986EC6D132CE6DB00F048C8 /* b2BlockAllocator.cpp in Sources */, + A986EC6E132CE6DB00F048C8 /* b2Math.cpp in Sources */, + A986EC6F132CE6DB00F048C8 /* b2Settings.cpp in Sources */, + A986EC70132CE6DB00F048C8 /* b2StackAllocator.cpp in Sources */, + A986EC71132CE6DB00F048C8 /* b2Body.cpp in Sources */, + A986EC72132CE6DB00F048C8 /* b2ContactManager.cpp in Sources */, + A986EC73132CE6DB00F048C8 /* b2Fixture.cpp in Sources */, + A986EC74132CE6DB00F048C8 /* b2Island.cpp in Sources */, + A986EC75132CE6DB00F048C8 /* b2World.cpp in Sources */, + A986EC76132CE6DB00F048C8 /* b2WorldCallbacks.cpp in Sources */, + A986EC77132CE6DB00F048C8 /* b2CircleContact.cpp in Sources */, + A986EC78132CE6DB00F048C8 /* b2Contact.cpp in Sources */, + A986EC79132CE6DB00F048C8 /* b2ContactSolver.cpp in Sources */, + A986EC7A132CE6DB00F048C8 /* b2PolygonAndCircleContact.cpp in Sources */, + A986EC7B132CE6DB00F048C8 /* b2PolygonContact.cpp in Sources */, + A986EC7C132CE6DB00F048C8 /* b2TOISolver.cpp in Sources */, + A986EC7D132CE6DB00F048C8 /* b2DistanceJoint.cpp in Sources */, + A986EC7E132CE6DB00F048C8 /* b2FrictionJoint.cpp in Sources */, + A986EC7F132CE6DB00F048C8 /* b2GearJoint.cpp in Sources */, + A986EC80132CE6DB00F048C8 /* b2Joint.cpp in Sources */, + A986EC81132CE6DB00F048C8 /* b2LineJoint.cpp in Sources */, + A986EC82132CE6DB00F048C8 /* b2MouseJoint.cpp in Sources */, + A986EC83132CE6DB00F048C8 /* b2PrismaticJoint.cpp in Sources */, + A986EC84132CE6DB00F048C8 /* b2PulleyJoint.cpp in Sources */, + A986EC85132CE6DB00F048C8 /* b2RevoluteJoint.cpp in Sources */, + A986EC86132CE6DB00F048C8 /* b2WeldJoint.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1683,6 +1699,7 @@ /Library/Frameworks/SDL.framework/Headers, ../../src, ../../src/modules, + ../../src/modules/physics/box2d, ); INSTALL_PATH = "$(HOME)/Applications"; LIBRARY_SEARCH_PATHS = ( @@ -1705,6 +1722,14 @@ GCC_MODEL_TUNING = G5; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = love_Prefix.pch; + HEADER_SEARCH_PATHS = ( + /Library/Frameworks/Lua.framework/Headers, + /Library/Frameworks/FreeType.framework/Headers, + /Library/Frameworks/SDL.framework/Headers, + ../../src, + ../../src/modules, + ../../src/modules/physics/box2d, + ); INSTALL_PATH = "$(HOME)/Applications"; LIBRARY_SEARCH_PATHS = ( "$(inherited)", diff --git a/src/modules/physics/box2d/Body.h b/src/modules/physics/box2d/Body.h index 9444a39d5..83996e17c 100644 --- a/src/modules/physics/box2d/Body.h +++ b/src/modules/physics/box2d/Body.h @@ -28,7 +28,7 @@ // Box2D -#include "Include/Box2D.h" +#include namespace love { diff --git a/src/modules/physics/box2d/Box2D/Box2D.h b/src/modules/physics/box2d/Box2D/Box2D.h new file mode 100644 index 000000000..dc5701f51 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Box2D.h @@ -0,0 +1,62 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef BOX2D_H +#define BOX2D_H + +/** +\mainpage Box2D API Documentation + +\section intro_sec Getting Started + +For documentation please see http://box2d.org/documentation.html + +For discussion please visit http://box2d.org/forum +*/ + +// These include files constitute the main Box2D API + +#include + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.cpp b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.cpp new file mode 100644 index 000000000..a950b0be5 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.cpp @@ -0,0 +1,89 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +b2Shape* b2CircleShape::Clone(b2BlockAllocator* allocator) const +{ + void* mem = allocator->Allocate(sizeof(b2CircleShape)); + b2CircleShape* clone = new (mem) b2CircleShape; + *clone = *this; + return clone; +} + +bool b2CircleShape::TestPoint(const b2Transform& transform, const b2Vec2& p) const +{ + b2Vec2 center = transform.position + b2Mul(transform.R, m_p); + b2Vec2 d = p - center; + return b2Dot(d, d) <= m_radius * m_radius; +} + +// Collision Detection in Interactive 3D Environments by Gino van den Bergen +// From Section 3.1.2 +// x = s + a * r +// norm(x) = radius +bool b2CircleShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const +{ + b2Vec2 position = transform.position + b2Mul(transform.R, m_p); + b2Vec2 s = input.p1 - position; + float32 b = b2Dot(s, s) - m_radius * m_radius; + + // Solve quadratic equation. + b2Vec2 r = input.p2 - input.p1; + float32 c = b2Dot(s, r); + float32 rr = b2Dot(r, r); + float32 sigma = c * c - rr * b; + + // Check for negative discriminant and short segment. + if (sigma < 0.0f || rr < b2_epsilon) + { + return false; + } + + // Find the point of intersection of the line with the circle. + float32 a = -(c + b2Sqrt(sigma)); + + // Is the intersection point on the segment? + if (0.0f <= a && a <= input.maxFraction * rr) + { + a /= rr; + output->fraction = a; + output->normal = s + a * r; + output->normal.Normalize(); + return true; + } + + return false; +} + +void b2CircleShape::ComputeAABB(b2AABB* aabb, const b2Transform& transform) const +{ + b2Vec2 p = transform.position + b2Mul(transform.R, m_p); + aabb->lowerBound.Set(p.x - m_radius, p.y - m_radius); + aabb->upperBound.Set(p.x + m_radius, p.y + m_radius); +} + +void b2CircleShape::ComputeMass(b2MassData* massData, float32 density) const +{ + massData->mass = density * b2_pi * m_radius * m_radius; + massData->center = m_p; + + // inertia about the local origin + massData->I = massData->mass * (0.5f * m_radius * m_radius + b2Dot(m_p, m_p)); +} diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.h b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.h new file mode 100644 index 000000000..bb31da898 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.h @@ -0,0 +1,87 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CIRCLE_SHAPE_H +#define B2_CIRCLE_SHAPE_H + +#include + +/// A circle shape. +class b2CircleShape : public b2Shape +{ +public: + b2CircleShape(); + + /// Implement b2Shape. + b2Shape* Clone(b2BlockAllocator* allocator) const; + + /// Implement b2Shape. + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const; + + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform) const; + + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; + + /// Get the supporting vertex index in the given direction. + int32 GetSupport(const b2Vec2& d) const; + + /// Get the supporting vertex in the given direction. + const b2Vec2& GetSupportVertex(const b2Vec2& d) const; + + /// Get the vertex count. + int32 GetVertexCount() const { return 1; } + + /// Get a vertex by index. Used by b2Distance. + const b2Vec2& GetVertex(int32 index) const; + + /// Position + b2Vec2 m_p; +}; + +inline b2CircleShape::b2CircleShape() +{ + m_type = e_circle; + m_radius = 0.0f; + m_p.SetZero(); +} + +inline int32 b2CircleShape::GetSupport(const b2Vec2 &d) const +{ + B2_NOT_USED(d); + return 0; +} + +inline const b2Vec2& b2CircleShape::GetSupportVertex(const b2Vec2 &d) const +{ + B2_NOT_USED(d); + return m_p; +} + +inline const b2Vec2& b2CircleShape::GetVertex(int32 index) const +{ + B2_NOT_USED(index); + b2Assert(index == 0); + return m_p; +} + +#endif diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp new file mode 100644 index 000000000..429e64704 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp @@ -0,0 +1,434 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const +{ + void* mem = allocator->Allocate(sizeof(b2PolygonShape)); + b2PolygonShape* clone = new (mem) b2PolygonShape; + *clone = *this; + return clone; +} + +void b2PolygonShape::SetAsBox(float32 hx, float32 hy) +{ + m_vertexCount = 4; + m_vertices[0].Set(-hx, -hy); + m_vertices[1].Set( hx, -hy); + m_vertices[2].Set( hx, hy); + m_vertices[3].Set(-hx, hy); + m_normals[0].Set(0.0f, -1.0f); + m_normals[1].Set(1.0f, 0.0f); + m_normals[2].Set(0.0f, 1.0f); + m_normals[3].Set(-1.0f, 0.0f); + m_centroid.SetZero(); +} + +void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle) +{ + m_vertexCount = 4; + m_vertices[0].Set(-hx, -hy); + m_vertices[1].Set( hx, -hy); + m_vertices[2].Set( hx, hy); + m_vertices[3].Set(-hx, hy); + m_normals[0].Set(0.0f, -1.0f); + m_normals[1].Set(1.0f, 0.0f); + m_normals[2].Set(0.0f, 1.0f); + m_normals[3].Set(-1.0f, 0.0f); + m_centroid = center; + + b2Transform xf; + xf.position = center; + xf.R.Set(angle); + + // Transform vertices and normals. + for (int32 i = 0; i < m_vertexCount; ++i) + { + m_vertices[i] = b2Mul(xf, m_vertices[i]); + m_normals[i] = b2Mul(xf.R, m_normals[i]); + } +} + +void b2PolygonShape::SetAsEdge(const b2Vec2& v1, const b2Vec2& v2) +{ + m_vertexCount = 2; + m_vertices[0] = v1; + m_vertices[1] = v2; + m_centroid = 0.5f * (v1 + v2); + m_normals[0] = b2Cross(v2 - v1, 1.0f); + m_normals[0].Normalize(); + m_normals[1] = -m_normals[0]; +} + +static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count) +{ + b2Assert(count >= 2); + + b2Vec2 c; c.Set(0.0f, 0.0f); + float32 area = 0.0f; + + if (count == 2) + { + c = 0.5f * (vs[0] + vs[1]); + return c; + } + + // pRef is the reference point for forming triangles. + // It's location doesn't change the result (except for rounding error). + b2Vec2 pRef(0.0f, 0.0f); +#if 0 + // This code would put the reference point inside the polygon. + for (int32 i = 0; i < count; ++i) + { + pRef += vs[i]; + } + pRef *= 1.0f / count; +#endif + + const float32 inv3 = 1.0f / 3.0f; + + for (int32 i = 0; i < count; ++i) + { + // Triangle vertices. + b2Vec2 p1 = pRef; + b2Vec2 p2 = vs[i]; + b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0]; + + b2Vec2 e1 = p2 - p1; + b2Vec2 e2 = p3 - p1; + + float32 D = b2Cross(e1, e2); + + float32 triangleArea = 0.5f * D; + area += triangleArea; + + // Area weighted centroid + c += triangleArea * inv3 * (p1 + p2 + p3); + } + + // Centroid + b2Assert(area > b2_epsilon); + c *= 1.0f / area; + return c; +} + +void b2PolygonShape::Set(const b2Vec2* vertices, int32 count) +{ + b2Assert(2 <= count && count <= b2_maxPolygonVertices); + m_vertexCount = count; + + // Copy vertices. + for (int32 i = 0; i < m_vertexCount; ++i) + { + m_vertices[i] = vertices[i]; + } + + // Compute normals. Ensure the edges have non-zero length. + for (int32 i = 0; i < m_vertexCount; ++i) + { + int32 i1 = i; + int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; + b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; + b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon); + m_normals[i] = b2Cross(edge, 1.0f); + m_normals[i].Normalize(); + } + +#ifdef _DEBUG + // Ensure the polygon is convex and the interior + // is to the left of each edge. + for (int32 i = 0; i < m_vertexCount; ++i) + { + int32 i1 = i; + int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; + b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; + + for (int32 j = 0; j < m_vertexCount; ++j) + { + // Don't check vertices on the current edge. + if (j == i1 || j == i2) + { + continue; + } + + b2Vec2 r = m_vertices[j] - m_vertices[i1]; + + // Your polygon is non-convex (it has an indentation) or + // has colinear edges. + float32 s = b2Cross(edge, r); + b2Assert(s > 0.0f); + } + } +#endif + + // Compute the polygon centroid. + m_centroid = ComputeCentroid(m_vertices, m_vertexCount); +} + +bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const +{ + b2Vec2 pLocal = b2MulT(xf.R, p - xf.position); + + for (int32 i = 0; i < m_vertexCount; ++i) + { + float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]); + if (dot > 0.0f) + { + return false; + } + } + + return true; +} + +bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& xf) const +{ + // Put the ray into the polygon's frame of reference. + b2Vec2 p1 = b2MulT(xf.R, input.p1 - xf.position); + b2Vec2 p2 = b2MulT(xf.R, input.p2 - xf.position); + b2Vec2 d = p2 - p1; + + if (m_vertexCount == 2) + { + b2Vec2 v1 = m_vertices[0]; + b2Vec2 v2 = m_vertices[1]; + b2Vec2 normal = m_normals[0]; + + // q = p1 + t * d + // dot(normal, q - v1) = 0 + // dot(normal, p1 - v1) + t * dot(normal, d) = 0 + float32 numerator = b2Dot(normal, v1 - p1); + float32 denominator = b2Dot(normal, d); + + if (denominator == 0.0f) + { + return false; + } + + float32 t = numerator / denominator; + if (t < 0.0f || 1.0f < t) + { + return false; + } + + b2Vec2 q = p1 + t * d; + + // q = v1 + s * r + // s = dot(q - v1, r) / dot(r, r) + b2Vec2 r = v2 - v1; + float32 rr = b2Dot(r, r); + if (rr == 0.0f) + { + return false; + } + + float32 s = b2Dot(q - v1, r) / rr; + if (s < 0.0f || 1.0f < s) + { + return false; + } + + output->fraction = t; + if (numerator > 0.0f) + { + output->normal = -normal; + } + else + { + output->normal = normal; + } + return true; + } + else + { + float32 lower = 0.0f, upper = input.maxFraction; + + int32 index = -1; + + for (int32 i = 0; i < m_vertexCount; ++i) + { + // p = p1 + a * d + // dot(normal, p - v) = 0 + // dot(normal, p1 - v) + a * dot(normal, d) = 0 + float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1); + float32 denominator = b2Dot(m_normals[i], d); + + if (denominator == 0.0f) + { + if (numerator < 0.0f) + { + return false; + } + } + else + { + // Note: we want this predicate without division: + // lower < numerator / denominator, where denominator < 0 + // Since denominator < 0, we have to flip the inequality: + // lower < numerator / denominator <==> denominator * lower > numerator. + if (denominator < 0.0f && numerator < lower * denominator) + { + // Increase lower. + // The segment enters this half-space. + lower = numerator / denominator; + index = i; + } + else if (denominator > 0.0f && numerator < upper * denominator) + { + // Decrease upper. + // The segment exits this half-space. + upper = numerator / denominator; + } + } + + // The use of epsilon here causes the assert on lower to trip + // in some cases. Apparently the use of epsilon was to make edge + // shapes work, but now those are handled separately. + //if (upper < lower - b2_epsilon) + if (upper < lower) + { + return false; + } + } + + b2Assert(0.0f <= lower && lower <= input.maxFraction); + + if (index >= 0) + { + output->fraction = lower; + output->normal = b2Mul(xf.R, m_normals[index]); + return true; + } + } + + return false; +} + +void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf) const +{ + b2Vec2 lower = b2Mul(xf, m_vertices[0]); + b2Vec2 upper = lower; + + for (int32 i = 1; i < m_vertexCount; ++i) + { + b2Vec2 v = b2Mul(xf, m_vertices[i]); + lower = b2Min(lower, v); + upper = b2Max(upper, v); + } + + b2Vec2 r(m_radius, m_radius); + aabb->lowerBound = lower - r; + aabb->upperBound = upper + r; +} + +void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const +{ + // Polygon mass, centroid, and inertia. + // Let rho be the polygon density in mass per unit area. + // Then: + // mass = rho * int(dA) + // centroid.x = (1/mass) * rho * int(x * dA) + // centroid.y = (1/mass) * rho * int(y * dA) + // I = rho * int((x*x + y*y) * dA) + // + // We can compute these integrals by summing all the integrals + // for each triangle of the polygon. To evaluate the integral + // for a single triangle, we make a change of variables to + // the (u,v) coordinates of the triangle: + // x = x0 + e1x * u + e2x * v + // y = y0 + e1y * u + e2y * v + // where 0 <= u && 0 <= v && u + v <= 1. + // + // We integrate u from [0,1-v] and then v from [0,1]. + // We also need to use the Jacobian of the transformation: + // D = cross(e1, e2) + // + // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) + // + // The rest of the derivation is handled by computer algebra. + + b2Assert(m_vertexCount >= 2); + + // A line segment has zero mass. + if (m_vertexCount == 2) + { + massData->center = 0.5f * (m_vertices[0] + m_vertices[1]); + massData->mass = 0.0f; + massData->I = 0.0f; + return; + } + + b2Vec2 center; center.Set(0.0f, 0.0f); + float32 area = 0.0f; + float32 I = 0.0f; + + // pRef is the reference point for forming triangles. + // It's location doesn't change the result (except for rounding error). + b2Vec2 pRef(0.0f, 0.0f); +#if 0 + // This code would put the reference point inside the polygon. + for (int32 i = 0; i < m_vertexCount; ++i) + { + pRef += m_vertices[i]; + } + pRef *= 1.0f / count; +#endif + + const float32 k_inv3 = 1.0f / 3.0f; + + for (int32 i = 0; i < m_vertexCount; ++i) + { + // Triangle vertices. + b2Vec2 p1 = pRef; + b2Vec2 p2 = m_vertices[i]; + b2Vec2 p3 = i + 1 < m_vertexCount ? m_vertices[i+1] : m_vertices[0]; + + b2Vec2 e1 = p2 - p1; + b2Vec2 e2 = p3 - p1; + + float32 D = b2Cross(e1, e2); + + float32 triangleArea = 0.5f * D; + area += triangleArea; + + // Area weighted centroid + center += triangleArea * k_inv3 * (p1 + p2 + p3); + + float32 px = p1.x, py = p1.y; + float32 ex1 = e1.x, ey1 = e1.y; + float32 ex2 = e2.x, ey2 = e2.y; + + float32 intx2 = k_inv3 * (0.25f * (ex1*ex1 + ex2*ex1 + ex2*ex2) + (px*ex1 + px*ex2)) + 0.5f*px*px; + float32 inty2 = k_inv3 * (0.25f * (ey1*ey1 + ey2*ey1 + ey2*ey2) + (py*ey1 + py*ey2)) + 0.5f*py*py; + + I += D * (intx2 + inty2); + } + + // Total mass + massData->mass = density * area; + + // Center of mass + b2Assert(area > b2_epsilon); + center *= 1.0f / area; + massData->center = center; + + // Inertia tensor relative to the local origin. + massData->I = density * I; +} diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.h b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.h new file mode 100644 index 000000000..564d4b083 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.h @@ -0,0 +1,131 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_POLYGON_SHAPE_H +#define B2_POLYGON_SHAPE_H + +#include + +/// A convex polygon. It is assumed that the interior of the polygon is to +/// the left of each edge. +class b2PolygonShape : public b2Shape +{ +public: + b2PolygonShape(); + + /// Implement b2Shape. + b2Shape* Clone(b2BlockAllocator* allocator) const; + + /// Copy vertices. This assumes the vertices define a convex polygon. + /// It is assumed that the exterior is the the right of each edge. + void Set(const b2Vec2* vertices, int32 vertexCount); + + /// Build vertices to represent an axis-aligned box. + /// @param hx the half-width. + /// @param hy the half-height. + void SetAsBox(float32 hx, float32 hy); + + /// Build vertices to represent an oriented box. + /// @param hx the half-width. + /// @param hy the half-height. + /// @param center the center of the box in local coordinates. + /// @param angle the rotation of the box in local coordinates. + void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle); + + /// Set this as a single edge. + void SetAsEdge(const b2Vec2& v1, const b2Vec2& v2); + + /// @see b2Shape::TestPoint + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const; + + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform) const; + + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; + + /// Get the supporting vertex index in the given direction. + int32 GetSupport(const b2Vec2& d) const; + + /// Get the supporting vertex in the given direction. + const b2Vec2& GetSupportVertex(const b2Vec2& d) const; + + /// Get the vertex count. + int32 GetVertexCount() const { return m_vertexCount; } + + /// Get a vertex by index. + const b2Vec2& GetVertex(int32 index) const; + + b2Vec2 m_centroid; + b2Vec2 m_vertices[b2_maxPolygonVertices]; + b2Vec2 m_normals[b2_maxPolygonVertices]; + int32 m_vertexCount; +}; + +inline b2PolygonShape::b2PolygonShape() +{ + m_type = e_polygon; + m_radius = b2_polygonRadius; + m_vertexCount = 0; + m_centroid.SetZero(); +} + +inline int32 b2PolygonShape::GetSupport(const b2Vec2& d) const +{ + int32 bestIndex = 0; + float32 bestValue = b2Dot(m_vertices[0], d); + for (int32 i = 1; i < m_vertexCount; ++i) + { + float32 value = b2Dot(m_vertices[i], d); + if (value > bestValue) + { + bestIndex = i; + bestValue = value; + } + } + + return bestIndex; +} + +inline const b2Vec2& b2PolygonShape::GetSupportVertex(const b2Vec2& d) const +{ + int32 bestIndex = 0; + float32 bestValue = b2Dot(m_vertices[0], d); + for (int32 i = 1; i < m_vertexCount; ++i) + { + float32 value = b2Dot(m_vertices[i], d); + if (value > bestValue) + { + bestIndex = i; + bestValue = value; + } + } + + return m_vertices[bestIndex]; +} + +inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const +{ + b2Assert(0 <= index && index < m_vertexCount); + return m_vertices[index]; +} + +#endif diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2Shape.h b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2Shape.h new file mode 100644 index 000000000..9082c0ef9 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2Shape.h @@ -0,0 +1,95 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_SHAPE_H +#define B2_SHAPE_H + +#include +#include +#include + +/// This holds the mass data computed for a shape. +struct b2MassData +{ + /// The mass of the shape, usually in kilograms. + float32 mass; + + /// The position of the shape's centroid relative to the shape's origin. + b2Vec2 center; + + /// The rotational inertia of the shape about the local origin. + float32 I; +}; + +/// A shape is used for collision detection. You can create a shape however you like. +/// Shapes used for simulation in b2World are created automatically when a b2Fixture +/// is created. +class b2Shape +{ +public: + + enum Type + { + e_unknown= -1, + e_circle = 0, + e_polygon = 1, + e_typeCount = 2, + }; + + b2Shape() { m_type = e_unknown; } + virtual ~b2Shape() {} + + /// Clone the concrete shape using the provided allocator. + virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0; + + /// Get the type of this shape. You can use this to down cast to the concrete shape. + /// @return the shape type. + Type GetType() const; + + /// Test a point for containment in this shape. This only works for convex shapes. + /// @param xf the shape world transform. + /// @param p a point in world coordinates. + virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0; + + /// Cast a ray against this shape. + /// @param output the ray-cast results. + /// @param input the ray-cast input parameters. + /// @param transform the transform to be applied to the shape. + virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const = 0; + + /// Given a transform, compute the associated axis aligned bounding box for this shape. + /// @param aabb returns the axis aligned box. + /// @param xf the world transform of the shape. + virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf) const = 0; + + /// Compute the mass properties of this shape using its dimensions and density. + /// The inertia tensor is computed about the local origin. + /// @param massData returns the mass data for this shape. + /// @param density the density in kilograms per meter squared. + virtual void ComputeMass(b2MassData* massData, float32 density) const = 0; + + Type m_type; + float32 m_radius; +}; + +inline b2Shape::Type b2Shape::GetType() const +{ + return m_type; +} + +#endif diff --git a/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.cpp b/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.cpp new file mode 100644 index 000000000..12c79678d --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.cpp @@ -0,0 +1,116 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +b2BroadPhase::b2BroadPhase() +{ + m_proxyCount = 0; + + m_pairCapacity = 16; + m_pairCount = 0; + m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); + + m_moveCapacity = 16; + m_moveCount = 0; + m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); +} + +b2BroadPhase::~b2BroadPhase() +{ + b2Free(m_moveBuffer); + b2Free(m_pairBuffer); +} + +int32 b2BroadPhase::CreateProxy(const b2AABB& aabb, void* userData) +{ + int32 proxyId = m_tree.CreateProxy(aabb, userData); + ++m_proxyCount; + BufferMove(proxyId); + return proxyId; +} + +void b2BroadPhase::DestroyProxy(int32 proxyId) +{ + UnBufferMove(proxyId); + --m_proxyCount; + m_tree.DestroyProxy(proxyId); +} + +void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) +{ + bool buffer = m_tree.MoveProxy(proxyId, aabb, displacement); + if (buffer) + { + BufferMove(proxyId); + } +} + +void b2BroadPhase::BufferMove(int32 proxyId) +{ + if (m_moveCount == m_moveCapacity) + { + int32* oldBuffer = m_moveBuffer; + m_moveCapacity *= 2; + m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); + memcpy(m_moveBuffer, oldBuffer, m_moveCount * sizeof(int32)); + b2Free(oldBuffer); + } + + m_moveBuffer[m_moveCount] = proxyId; + ++m_moveCount; +} + +void b2BroadPhase::UnBufferMove(int32 proxyId) +{ + for (int32 i = 0; i < m_moveCount; ++i) + { + if (m_moveBuffer[i] == proxyId) + { + m_moveBuffer[i] = e_nullProxy; + return; + } + } +} + +// This is called from b2DynamicTree::Query when we are gathering pairs. +bool b2BroadPhase::QueryCallback(int32 proxyId) +{ + // A proxy cannot form a pair with itself. + if (proxyId == m_queryProxyId) + { + return true; + } + + // Grow the pair buffer as needed. + if (m_pairCount == m_pairCapacity) + { + b2Pair* oldBuffer = m_pairBuffer; + m_pairCapacity *= 2; + m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); + memcpy(m_pairBuffer, oldBuffer, m_pairCount * sizeof(b2Pair)); + b2Free(oldBuffer); + } + + m_pairBuffer[m_pairCount].proxyIdA = b2Min(proxyId, m_queryProxyId); + m_pairBuffer[m_pairCount].proxyIdB = b2Max(proxyId, m_queryProxyId); + ++m_pairCount; + + return true; +} diff --git a/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.h b/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.h new file mode 100644 index 000000000..bff188e88 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.h @@ -0,0 +1,229 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_BROAD_PHASE_H +#define B2_BROAD_PHASE_H + +#include +#include +#include +#include + +struct b2Pair +{ + int32 proxyIdA; + int32 proxyIdB; + int32 next; +}; + +/// The broad-phase is used for computing pairs and performing volume queries and ray casts. +/// This broad-phase does not persist pairs. Instead, this reports potentially new pairs. +/// It is up to the client to consume the new pairs and to track subsequent overlap. +class b2BroadPhase +{ +public: + + enum + { + e_nullProxy = -1, + }; + + b2BroadPhase(); + ~b2BroadPhase(); + + /// Create a proxy with an initial AABB. Pairs are not reported until + /// UpdatePairs is called. + int32 CreateProxy(const b2AABB& aabb, void* userData); + + /// Destroy a proxy. It is up to the client to remove any pairs. + void DestroyProxy(int32 proxyId); + + /// Call MoveProxy as many times as you like, then when you are done + /// call UpdatePairs to finalized the proxy pairs (for your time step). + void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement); + + /// Get the fat AABB for a proxy. + const b2AABB& GetFatAABB(int32 proxyId) const; + + /// Get user data from a proxy. Returns NULL if the id is invalid. + void* GetUserData(int32 proxyId) const; + + /// Test overlap of fat AABBs. + bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const; + + /// Get the number of proxies. + int32 GetProxyCount() const; + + /// Update the pairs. This results in pair callbacks. This can only add pairs. + template + void UpdatePairs(T* callback); + + /// Query an AABB for overlapping proxies. The callback class + /// is called for each proxy that overlaps the supplied AABB. + template + void Query(T* callback, const b2AABB& aabb) const; + + /// Ray-cast against the proxies in the tree. This relies on the callback + /// to perform a exact ray-cast in the case were the proxy contains a shape. + /// The callback also performs the any collision filtering. This has performance + /// roughly equal to k * log(n), where k is the number of collisions and n is the + /// number of proxies in the tree. + /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). + /// @param callback a callback class that is called for each proxy that is hit by the ray. + template + void RayCast(T* callback, const b2RayCastInput& input) const; + + /// Compute the height of the embedded tree. + int32 ComputeHeight() const; + +private: + + friend class b2DynamicTree; + + void BufferMove(int32 proxyId); + void UnBufferMove(int32 proxyId); + + bool QueryCallback(int32 proxyId); + + b2DynamicTree m_tree; + + int32 m_proxyCount; + + int32* m_moveBuffer; + int32 m_moveCapacity; + int32 m_moveCount; + + b2Pair* m_pairBuffer; + int32 m_pairCapacity; + int32 m_pairCount; + + int32 m_queryProxyId; +}; + +/// This is used to sort pairs. +inline bool b2PairLessThan(const b2Pair& pair1, const b2Pair& pair2) +{ + if (pair1.proxyIdA < pair2.proxyIdA) + { + return true; + } + + if (pair1.proxyIdA == pair2.proxyIdA) + { + return pair1.proxyIdB < pair2.proxyIdB; + } + + return false; +} + +inline void* b2BroadPhase::GetUserData(int32 proxyId) const +{ + return m_tree.GetUserData(proxyId); +} + +inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const +{ + const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA); + const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB); + return b2TestOverlap(aabbA, aabbB); +} + +inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const +{ + return m_tree.GetFatAABB(proxyId); +} + +inline int32 b2BroadPhase::GetProxyCount() const +{ + return m_proxyCount; +} + +inline int32 b2BroadPhase::ComputeHeight() const +{ + return m_tree.ComputeHeight(); +} + +template +void b2BroadPhase::UpdatePairs(T* callback) +{ + // Reset pair buffer + m_pairCount = 0; + + // Perform tree queries for all moving proxies. + for (int32 i = 0; i < m_moveCount; ++i) + { + m_queryProxyId = m_moveBuffer[i]; + if (m_queryProxyId == e_nullProxy) + { + continue; + } + + // We have to query the tree with the fat AABB so that + // we don't fail to create a pair that may touch later. + const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId); + + // Query tree, create pairs and add them pair buffer. + m_tree.Query(this, fatAABB); + } + + // Reset move buffer + m_moveCount = 0; + + // Sort the pair buffer to expose duplicates. + std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan); + + // Send the pairs back to the client. + int32 i = 0; + while (i < m_pairCount) + { + b2Pair* primaryPair = m_pairBuffer + i; + void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA); + void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB); + + callback->AddPair(userDataA, userDataB); + ++i; + + // Skip any duplicate pairs. + while (i < m_pairCount) + { + b2Pair* pair = m_pairBuffer + i; + if (pair->proxyIdA != primaryPair->proxyIdA || pair->proxyIdB != primaryPair->proxyIdB) + { + break; + } + ++i; + } + } + + // Try to keep the tree balanced. + m_tree.Rebalance(4); +} + +template +inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const +{ + m_tree.Query(callback, aabb); +} + +template +inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const +{ + m_tree.RayCast(callback, input); +} + +#endif diff --git a/src/modules/physics/box2d/Box2D/Collision/b2CollideCircle.cpp b/src/modules/physics/box2d/Box2D/Collision/b2CollideCircle.cpp new file mode 100644 index 000000000..6edf89d7b --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/b2CollideCircle.cpp @@ -0,0 +1,154 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +void b2CollideCircles( + b2Manifold* manifold, + const b2CircleShape* circleA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB) +{ + manifold->pointCount = 0; + + b2Vec2 pA = b2Mul(xfA, circleA->m_p); + b2Vec2 pB = b2Mul(xfB, circleB->m_p); + + b2Vec2 d = pB - pA; + float32 distSqr = b2Dot(d, d); + float32 rA = circleA->m_radius, rB = circleB->m_radius; + float32 radius = rA + rB; + if (distSqr > radius * radius) + { + return; + } + + manifold->type = b2Manifold::e_circles; + manifold->localPoint = circleA->m_p; + manifold->localNormal.SetZero(); + manifold->pointCount = 1; + + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; +} + +void b2CollidePolygonAndCircle( + b2Manifold* manifold, + const b2PolygonShape* polygonA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB) +{ + manifold->pointCount = 0; + + // Compute circle position in the frame of the polygon. + b2Vec2 c = b2Mul(xfB, circleB->m_p); + b2Vec2 cLocal = b2MulT(xfA, c); + + // Find the min separating edge. + int32 normalIndex = 0; + float32 separation = -b2_maxFloat; + float32 radius = polygonA->m_radius + circleB->m_radius; + int32 vertexCount = polygonA->m_vertexCount; + const b2Vec2* vertices = polygonA->m_vertices; + const b2Vec2* normals = polygonA->m_normals; + + for (int32 i = 0; i < vertexCount; ++i) + { + float32 s = b2Dot(normals[i], cLocal - vertices[i]); + + if (s > radius) + { + // Early out. + return; + } + + if (s > separation) + { + separation = s; + normalIndex = i; + } + } + + // Vertices that subtend the incident face. + int32 vertIndex1 = normalIndex; + int32 vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; + b2Vec2 v1 = vertices[vertIndex1]; + b2Vec2 v2 = vertices[vertIndex2]; + + // If the center is inside the polygon ... + if (separation < b2_epsilon) + { + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = normals[normalIndex]; + manifold->localPoint = 0.5f * (v1 + v2); + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + return; + } + + // Compute barycentric coordinates + float32 u1 = b2Dot(cLocal - v1, v2 - v1); + float32 u2 = b2Dot(cLocal - v2, v1 - v2); + if (u1 <= 0.0f) + { + if (b2DistanceSquared(cLocal, v1) > radius * radius) + { + return; + } + + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = cLocal - v1; + manifold->localNormal.Normalize(); + manifold->localPoint = v1; + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + } + else if (u2 <= 0.0f) + { + if (b2DistanceSquared(cLocal, v2) > radius * radius) + { + return; + } + + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = cLocal - v2; + manifold->localNormal.Normalize(); + manifold->localPoint = v2; + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + } + else + { + b2Vec2 faceCenter = 0.5f * (v1 + v2); + float32 separation = b2Dot(cLocal - faceCenter, normals[vertIndex1]); + if (separation > radius) + { + return; + } + + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = normals[vertIndex1]; + manifold->localPoint = faceCenter; + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + } +} diff --git a/src/modules/physics/box2d/Source/Collision/b2CollidePoly.cpp b/src/modules/physics/box2d/Box2D/Collision/b2CollidePolygon.cpp similarity index 53% rename from src/modules/physics/box2d/Source/Collision/b2CollidePoly.cpp rename to src/modules/physics/box2d/Box2D/Collision/b2CollidePolygon.cpp index b4aac6749..b37b7ba92 100644 --- a/src/modules/physics/box2d/Source/Collision/b2CollidePoly.cpp +++ b/src/modules/physics/box2d/Box2D/Collision/b2CollidePolygon.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -16,59 +16,19 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#include "b2Collision.h" -#include "Shapes/b2PolygonShape.h" - -struct ClipVertex -{ - b2Vec2 v; - b2ContactID id; -}; - -static int32 ClipSegmentToLine(ClipVertex vOut[2], ClipVertex vIn[2], - const b2Vec2& normal, float32 offset) -{ - // Start with no output points - int32 numOut = 0; - - // Calculate the distance of end points to the line - float32 distance0 = b2Dot(normal, vIn[0].v) - offset; - float32 distance1 = b2Dot(normal, vIn[1].v) - offset; - - // If the points are behind the plane - if (distance0 <= 0.0f) vOut[numOut++] = vIn[0]; - if (distance1 <= 0.0f) vOut[numOut++] = vIn[1]; - - // If the points are on different sides of the plane - if (distance0 * distance1 < 0.0f) - { - // Find intersection point of edge and plane - float32 interp = distance0 / (distance0 - distance1); - vOut[numOut].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v); - if (distance0 > 0.0f) - { - vOut[numOut].id = vIn[0].id; - } - else - { - vOut[numOut].id = vIn[1].id; - } - ++numOut; - } - - return numOut; -} +#include +#include // Find the separation between poly1 and poly2 for a give edge normal on poly1. -static float32 EdgeSeparation(const b2PolygonShape* poly1, const b2XForm& xf1, int32 edge1, - const b2PolygonShape* poly2, const b2XForm& xf2) +static float32 b2EdgeSeparation(const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, + const b2PolygonShape* poly2, const b2Transform& xf2) { - int32 count1 = poly1->GetVertexCount(); - const b2Vec2* vertices1 = poly1->GetVertices(); - const b2Vec2* normals1 = poly1->GetNormals(); + int32 count1 = poly1->m_vertexCount; + const b2Vec2* vertices1 = poly1->m_vertices; + const b2Vec2* normals1 = poly1->m_normals; - int32 count2 = poly2->GetVertexCount(); - const b2Vec2* vertices2 = poly2->GetVertices(); + int32 count2 = poly2->m_vertexCount; + const b2Vec2* vertices2 = poly2->m_vertices; b2Assert(0 <= edge1 && edge1 < count1); @@ -78,7 +38,7 @@ static float32 EdgeSeparation(const b2PolygonShape* poly1, const b2XForm& xf1, i // Find support vertex on poly2 for -normal. int32 index = 0; - float32 minDot = B2_FLT_MAX; + float32 minDot = b2_maxFloat; for (int32 i = 0; i < count2; ++i) { @@ -97,20 +57,20 @@ static float32 EdgeSeparation(const b2PolygonShape* poly1, const b2XForm& xf1, i } // Find the max separation between poly1 and poly2 using edge normals from poly1. -static float32 FindMaxSeparation(int32* edgeIndex, - const b2PolygonShape* poly1, const b2XForm& xf1, - const b2PolygonShape* poly2, const b2XForm& xf2) +static float32 b2FindMaxSeparation(int32* edgeIndex, + const b2PolygonShape* poly1, const b2Transform& xf1, + const b2PolygonShape* poly2, const b2Transform& xf2) { - int32 count1 = poly1->GetVertexCount(); - const b2Vec2* normals1 = poly1->GetNormals(); + int32 count1 = poly1->m_vertexCount; + const b2Vec2* normals1 = poly1->m_normals; // Vector pointing from the centroid of poly1 to the centroid of poly2. - b2Vec2 d = b2Mul(xf2, poly2->GetCentroid()) - b2Mul(xf1, poly1->GetCentroid()); + b2Vec2 d = b2Mul(xf2, poly2->m_centroid) - b2Mul(xf1, poly1->m_centroid); b2Vec2 dLocal1 = b2MulT(xf1.R, d); // Find edge normal on poly1 that has the largest projection onto d. int32 edge = 0; - float32 maxDot = -B2_FLT_MAX; + float32 maxDot = -b2_maxFloat; for (int32 i = 0; i < count1; ++i) { float32 dot = b2Dot(normals1[i], dLocal1); @@ -122,27 +82,15 @@ static float32 FindMaxSeparation(int32* edgeIndex, } // Get the separation for the edge normal. - float32 s = EdgeSeparation(poly1, xf1, edge, poly2, xf2); - if (s > 0.0f) - { - return s; - } + float32 s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2); // Check the separation for the previous edge normal. int32 prevEdge = edge - 1 >= 0 ? edge - 1 : count1 - 1; - float32 sPrev = EdgeSeparation(poly1, xf1, prevEdge, poly2, xf2); - if (sPrev > 0.0f) - { - return sPrev; - } + float32 sPrev = b2EdgeSeparation(poly1, xf1, prevEdge, poly2, xf2); // Check the separation for the next edge normal. int32 nextEdge = edge + 1 < count1 ? edge + 1 : 0; - float32 sNext = EdgeSeparation(poly1, xf1, nextEdge, poly2, xf2); - if (sNext > 0.0f) - { - return sNext; - } + float32 sNext = b2EdgeSeparation(poly1, xf1, nextEdge, poly2, xf2); // Find the best edge and the search direction. int32 bestEdge; @@ -174,11 +122,7 @@ static float32 FindMaxSeparation(int32* edgeIndex, else edge = bestEdge + 1 < count1 ? bestEdge + 1 : 0; - s = EdgeSeparation(poly1, xf1, edge, poly2, xf2); - if (s > 0.0f) - { - return s; - } + s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2); if (s > bestSeparation) { @@ -195,16 +139,16 @@ static float32 FindMaxSeparation(int32* edgeIndex, return bestSeparation; } -static void FindIncidentEdge(ClipVertex c[2], - const b2PolygonShape* poly1, const b2XForm& xf1, int32 edge1, - const b2PolygonShape* poly2, const b2XForm& xf2) +static void b2FindIncidentEdge(b2ClipVertex c[2], + const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, + const b2PolygonShape* poly2, const b2Transform& xf2) { - int32 count1 = poly1->GetVertexCount(); - const b2Vec2* normals1 = poly1->GetNormals(); + int32 count1 = poly1->m_vertexCount; + const b2Vec2* normals1 = poly1->m_normals; - int32 count2 = poly2->GetVertexCount(); - const b2Vec2* vertices2 = poly2->GetVertices(); - const b2Vec2* normals2 = poly2->GetNormals(); + int32 count2 = poly2->m_vertexCount; + const b2Vec2* vertices2 = poly2->m_vertices; + const b2Vec2* normals2 = poly2->m_normals; b2Assert(0 <= edge1 && edge1 < count1); @@ -213,7 +157,7 @@ static void FindIncidentEdge(ClipVertex c[2], // Find the incident edge on poly2. int32 index = 0; - float32 minDot = B2_FLT_MAX; + float32 minDot = b2_maxFloat; for (int32 i = 0; i < count2; ++i) { float32 dot = b2Dot(normal1, normals2[i]); @@ -247,30 +191,30 @@ static void FindIncidentEdge(ClipVertex c[2], // The normal points from 1 to 2 void b2CollidePolygons(b2Manifold* manifold, - const b2PolygonShape* polyA, const b2XForm& xfA, - const b2PolygonShape* polyB, const b2XForm& xfB) + const b2PolygonShape* polyA, const b2Transform& xfA, + const b2PolygonShape* polyB, const b2Transform& xfB) { manifold->pointCount = 0; + float32 totalRadius = polyA->m_radius + polyB->m_radius; int32 edgeA = 0; - float32 separationA = FindMaxSeparation(&edgeA, polyA, xfA, polyB, xfB); - if (separationA > 0.0f) + float32 separationA = b2FindMaxSeparation(&edgeA, polyA, xfA, polyB, xfB); + if (separationA > totalRadius) return; int32 edgeB = 0; - float32 separationB = FindMaxSeparation(&edgeB, polyB, xfB, polyA, xfA); - if (separationB > 0.0f) + float32 separationB = b2FindMaxSeparation(&edgeB, polyB, xfB, polyA, xfA); + if (separationB > totalRadius) return; - const b2PolygonShape* poly1; // reference poly - const b2PolygonShape* poly2; // incident poly - b2XForm xf1, xf2; + const b2PolygonShape* poly1; // reference polygon + const b2PolygonShape* poly2; // incident polygon + b2Transform xf1, xf2; int32 edge1; // reference edge uint8 flip; const float32 k_relativeTol = 0.98f; const float32 k_absoluteTol = 0.001f; - // TODO_ERIN use "radius" of poly for absolute tolerance. if (separationB > k_relativeTol * separationA + k_absoluteTol) { poly1 = polyB; @@ -278,6 +222,7 @@ void b2CollidePolygons(b2Manifold* manifold, xf1 = xfB; xf2 = xfA; edge1 = edgeB; + manifold->type = b2Manifold::e_faceB; flip = 1; } else @@ -287,61 +232,70 @@ void b2CollidePolygons(b2Manifold* manifold, xf1 = xfA; xf2 = xfB; edge1 = edgeA; + manifold->type = b2Manifold::e_faceA; flip = 0; } - ClipVertex incidentEdge[2]; - FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); + b2ClipVertex incidentEdge[2]; + b2FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); - int32 count1 = poly1->GetVertexCount(); - const b2Vec2* vertices1 = poly1->GetVertices(); + int32 count1 = poly1->m_vertexCount; + const b2Vec2* vertices1 = poly1->m_vertices; b2Vec2 v11 = vertices1[edge1]; b2Vec2 v12 = edge1 + 1 < count1 ? vertices1[edge1+1] : vertices1[0]; - b2Vec2 dv = v12 - v11; - b2Vec2 sideNormal = b2Mul(xf1.R, v12 - v11); - sideNormal.Normalize(); - b2Vec2 frontNormal = b2Cross(sideNormal, 1.0f); + b2Vec2 localTangent = v12 - v11; + localTangent.Normalize(); + + b2Vec2 localNormal = b2Cross(localTangent, 1.0f); + b2Vec2 planePoint = 0.5f * (v11 + v12); + + b2Vec2 tangent = b2Mul(xf1.R, localTangent); + b2Vec2 normal = b2Cross(tangent, 1.0f); v11 = b2Mul(xf1, v11); v12 = b2Mul(xf1, v12); - float32 frontOffset = b2Dot(frontNormal, v11); - float32 sideOffset1 = -b2Dot(sideNormal, v11); - float32 sideOffset2 = b2Dot(sideNormal, v12); + // Face offset. + float32 frontOffset = b2Dot(normal, v11); + + // Side offsets, extended by polytope skin thickness. + float32 sideOffset1 = -b2Dot(tangent, v11) + totalRadius; + float32 sideOffset2 = b2Dot(tangent, v12) + totalRadius; // Clip incident edge against extruded edge1 side edges. - ClipVertex clipPoints1[2]; - ClipVertex clipPoints2[2]; + b2ClipVertex clipPoints1[2]; + b2ClipVertex clipPoints2[2]; int np; // Clip to box side 1 - np = ClipSegmentToLine(clipPoints1, incidentEdge, -sideNormal, sideOffset1); + np = b2ClipSegmentToLine(clipPoints1, incidentEdge, -tangent, sideOffset1); if (np < 2) return; // Clip to negative box side 1 - np = ClipSegmentToLine(clipPoints2, clipPoints1, sideNormal, sideOffset2); + np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2); if (np < 2) + { return; + } // Now clipPoints2 contains the clipped points. - manifold->normal = flip ? -frontNormal : frontNormal; + manifold->localNormal = localNormal; + manifold->localPoint = planePoint; int32 pointCount = 0; for (int32 i = 0; i < b2_maxManifoldPoints; ++i) { - float32 separation = b2Dot(frontNormal, clipPoints2[i].v) - frontOffset; + float32 separation = b2Dot(normal, clipPoints2[i].v) - frontOffset; - if (separation <= 0.0f) + if (separation <= totalRadius) { b2ManifoldPoint* cp = manifold->points + pointCount; - cp->separation = separation; - cp->localPoint1 = b2MulT(xfA, clipPoints2[i].v); - cp->localPoint2 = b2MulT(xfB, clipPoints2[i].v); + cp->localPoint = b2MulT(xf2, clipPoints2[i].v); cp->id = clipPoints2[i].id; cp->id.features.flip = flip; ++pointCount; diff --git a/src/modules/physics/box2d/Box2D/Collision/b2Collision.cpp b/src/modules/physics/box2d/Box2D/Collision/b2Collision.cpp new file mode 100644 index 000000000..a86c7c5a8 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/b2Collision.cpp @@ -0,0 +1,250 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +void b2WorldManifold::Initialize(const b2Manifold* manifold, + const b2Transform& xfA, float32 radiusA, + const b2Transform& xfB, float32 radiusB) +{ + if (manifold->pointCount == 0) + { + return; + } + + switch (manifold->type) + { + case b2Manifold::e_circles: + { + normal.Set(1.0f, 0.0f); + b2Vec2 pointA = b2Mul(xfA, manifold->localPoint); + b2Vec2 pointB = b2Mul(xfB, manifold->points[0].localPoint); + if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon) + { + normal = pointB - pointA; + normal.Normalize(); + } + + b2Vec2 cA = pointA + radiusA * normal; + b2Vec2 cB = pointB - radiusB * normal; + points[0] = 0.5f * (cA + cB); + } + break; + + case b2Manifold::e_faceA: + { + normal = b2Mul(xfA.R, manifold->localNormal); + b2Vec2 planePoint = b2Mul(xfA, manifold->localPoint); + + for (int32 i = 0; i < manifold->pointCount; ++i) + { + b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint); + b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint, normal)) * normal; + b2Vec2 cB = clipPoint - radiusB * normal; + points[i] = 0.5f * (cA + cB); + } + } + break; + + case b2Manifold::e_faceB: + { + normal = b2Mul(xfB.R, manifold->localNormal); + b2Vec2 planePoint = b2Mul(xfB, manifold->localPoint); + + for (int32 i = 0; i < manifold->pointCount; ++i) + { + b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint); + b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint, normal)) * normal; + b2Vec2 cA = clipPoint - radiusA * normal; + points[i] = 0.5f * (cA + cB); + } + + // Ensure normal points from A to B. + normal = -normal; + } + break; + } +} + +void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints], + const b2Manifold* manifold1, const b2Manifold* manifold2) +{ + for (int32 i = 0; i < b2_maxManifoldPoints; ++i) + { + state1[i] = b2_nullState; + state2[i] = b2_nullState; + } + + // Detect persists and removes. + for (int32 i = 0; i < manifold1->pointCount; ++i) + { + b2ContactID id = manifold1->points[i].id; + + state1[i] = b2_removeState; + + for (int32 j = 0; j < manifold2->pointCount; ++j) + { + if (manifold2->points[j].id.key == id.key) + { + state1[i] = b2_persistState; + break; + } + } + } + + // Detect persists and adds. + for (int32 i = 0; i < manifold2->pointCount; ++i) + { + b2ContactID id = manifold2->points[i].id; + + state2[i] = b2_addState; + + for (int32 j = 0; j < manifold1->pointCount; ++j) + { + if (manifold1->points[j].id.key == id.key) + { + state2[i] = b2_persistState; + break; + } + } + } +} + +// From Real-time Collision Detection, p179. +bool b2AABB::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const +{ + float32 tmin = -b2_maxFloat; + float32 tmax = b2_maxFloat; + + b2Vec2 p = input.p1; + b2Vec2 d = input.p2 - input.p1; + b2Vec2 absD = b2Abs(d); + + b2Vec2 normal; + + for (int32 i = 0; i < 2; ++i) + { + if (absD(i) < b2_epsilon) + { + // Parallel. + if (p(i) < lowerBound(i) || upperBound(i) < p(i)) + { + return false; + } + } + else + { + float32 inv_d = 1.0f / d(i); + float32 t1 = (lowerBound(i) - p(i)) * inv_d; + float32 t2 = (upperBound(i) - p(i)) * inv_d; + + // Sign of the normal vector. + float32 s = -1.0f; + + if (t1 > t2) + { + b2Swap(t1, t2); + s = 1.0f; + } + + // Push the min up + if (t1 > tmin) + { + normal.SetZero(); + normal(i) = s; + tmin = t1; + } + + // Pull the max down + tmax = b2Min(tmax, t2); + + if (tmin > tmax) + { + return false; + } + } + } + + // Does the ray start inside the box? + // Does the ray intersect beyond the max fraction? + if (tmin < 0.0f || input.maxFraction < tmin) + { + return false; + } + + // Intersection. + output->fraction = tmin; + output->normal = normal; + return true; +} + +// Sutherland-Hodgman clipping. +int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], + const b2Vec2& normal, float32 offset) +{ + // Start with no output points + int32 numOut = 0; + + // Calculate the distance of end points to the line + float32 distance0 = b2Dot(normal, vIn[0].v) - offset; + float32 distance1 = b2Dot(normal, vIn[1].v) - offset; + + // If the points are behind the plane + if (distance0 <= 0.0f) vOut[numOut++] = vIn[0]; + if (distance1 <= 0.0f) vOut[numOut++] = vIn[1]; + + // If the points are on different sides of the plane + if (distance0 * distance1 < 0.0f) + { + // Find intersection point of edge and plane + float32 interp = distance0 / (distance0 - distance1); + vOut[numOut].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v); + if (distance0 > 0.0f) + { + vOut[numOut].id = vIn[0].id; + } + else + { + vOut[numOut].id = vIn[1].id; + } + ++numOut; + } + + return numOut; +} + +bool b2TestOverlap(const b2Shape* shapeA, const b2Shape* shapeB, + const b2Transform& xfA, const b2Transform& xfB) +{ + b2DistanceInput input; + input.proxyA.Set(shapeA); + input.proxyB.Set(shapeB); + input.transformA = xfA; + input.transformB = xfB; + input.useRadii = true; + + b2SimplexCache cache; + cache.count = 0; + + b2DistanceOutput output; + + b2Distance(&output, &cache, &input); + + return output.distance < 10.0f * b2_epsilon; +} diff --git a/src/modules/physics/box2d/Box2D/Collision/b2Collision.h b/src/modules/physics/box2d/Box2D/Collision/b2Collision.h new file mode 100644 index 000000000..baffdbde0 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/b2Collision.h @@ -0,0 +1,240 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_COLLISION_H +#define B2_COLLISION_H + +#include +#include + +/// @file +/// Structures and functions used for computing contact points, distance +/// queries, and TOI queries. + +class b2Shape; +class b2CircleShape; +class b2PolygonShape; + +const uint8 b2_nullFeature = UCHAR_MAX; + +/// Contact ids to facilitate warm starting. +union b2ContactID +{ + /// The features that intersect to form the contact point + struct Features + { + uint8 referenceEdge; ///< The edge that defines the outward contact normal. + uint8 incidentEdge; ///< The edge most anti-parallel to the reference edge. + uint8 incidentVertex; ///< The vertex (0 or 1) on the incident edge that was clipped. + uint8 flip; ///< A value of 1 indicates that the reference edge is on shape2. + } features; + uint32 key; ///< Used to quickly compare contact ids. +}; + +/// A manifold point is a contact point belonging to a contact +/// manifold. It holds details related to the geometry and dynamics +/// of the contact points. +/// The local point usage depends on the manifold type: +/// -e_circles: the local center of circleB +/// -e_faceA: the local center of cirlceB or the clip point of polygonB +/// -e_faceB: the clip point of polygonA +/// This structure is stored across time steps, so we keep it small. +/// Note: the impulses are used for internal caching and may not +/// provide reliable contact forces, especially for high speed collisions. +struct b2ManifoldPoint +{ + b2Vec2 localPoint; ///< usage depends on manifold type + float32 normalImpulse; ///< the non-penetration impulse + float32 tangentImpulse; ///< the friction impulse + b2ContactID id; ///< uniquely identifies a contact point between two shapes +}; + +/// A manifold for two touching convex shapes. +/// Box2D supports multiple types of contact: +/// - clip point versus plane with radius +/// - point versus point with radius (circles) +/// The local point usage depends on the manifold type: +/// -e_circles: the local center of circleA +/// -e_faceA: the center of faceA +/// -e_faceB: the center of faceB +/// Similarly the local normal usage: +/// -e_circles: not used +/// -e_faceA: the normal on polygonA +/// -e_faceB: the normal on polygonB +/// We store contacts in this way so that position correction can +/// account for movement, which is critical for continuous physics. +/// All contact scenarios must be expressed in one of these types. +/// This structure is stored across time steps, so we keep it small. +struct b2Manifold +{ + enum Type + { + e_circles, + e_faceA, + e_faceB + }; + + b2ManifoldPoint points[b2_maxManifoldPoints]; ///< the points of contact + b2Vec2 localNormal; ///< not use for Type::e_points + b2Vec2 localPoint; ///< usage depends on manifold type + Type type; + int32 pointCount; ///< the number of manifold points +}; + +/// This is used to compute the current state of a contact manifold. +struct b2WorldManifold +{ + /// Evaluate the manifold with supplied transforms. This assumes + /// modest motion from the original state. This does not change the + /// point count, impulses, etc. The radii must come from the shapes + /// that generated the manifold. + void Initialize(const b2Manifold* manifold, + const b2Transform& xfA, float32 radiusA, + const b2Transform& xfB, float32 radiusB); + + b2Vec2 normal; ///< world vector pointing from A to B + b2Vec2 points[b2_maxManifoldPoints]; ///< world contact point (point of intersection) +}; + +/// This is used for determining the state of contact points. +enum b2PointState +{ + b2_nullState, ///< point does not exist + b2_addState, ///< point was added in the update + b2_persistState, ///< point persisted across the update + b2_removeState ///< point was removed in the update +}; + +/// Compute the point states given two manifolds. The states pertain to the transition from manifold1 +/// to manifold2. So state1 is either persist or remove while state2 is either add or persist. +void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints], + const b2Manifold* manifold1, const b2Manifold* manifold2); + +/// Used for computing contact manifolds. +struct b2ClipVertex +{ + b2Vec2 v; + b2ContactID id; +}; + +/// Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). +struct b2RayCastInput +{ + b2Vec2 p1, p2; + float32 maxFraction; +}; + +/// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2 +/// come from b2RayCastInput. +struct b2RayCastOutput +{ + b2Vec2 normal; + float32 fraction; +}; + +/// An axis aligned bounding box. +struct b2AABB +{ + /// Verify that the bounds are sorted. + bool IsValid() const; + + /// Get the center of the AABB. + b2Vec2 GetCenter() const + { + return 0.5f * (lowerBound + upperBound); + } + + /// Get the extents of the AABB (half-widths). + b2Vec2 GetExtents() const + { + return 0.5f * (upperBound - lowerBound); + } + + /// Combine two AABBs into this one. + void Combine(const b2AABB& aabb1, const b2AABB& aabb2) + { + lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound); + upperBound = b2Max(aabb1.upperBound, aabb2.upperBound); + } + + /// Does this aabb contain the provided AABB. + bool Contains(const b2AABB& aabb) const + { + bool result = true; + result = result && lowerBound.x <= aabb.lowerBound.x; + result = result && lowerBound.y <= aabb.lowerBound.y; + result = result && aabb.upperBound.x <= upperBound.x; + result = result && aabb.upperBound.y <= upperBound.y; + return result; + } + + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const; + + b2Vec2 lowerBound; ///< the lower vertex + b2Vec2 upperBound; ///< the upper vertex +}; + +/// Compute the collision manifold between two circles. +void b2CollideCircles(b2Manifold* manifold, + const b2CircleShape* circle1, const b2Transform& xf1, + const b2CircleShape* circle2, const b2Transform& xf2); + +/// Compute the collision manifold between a polygon and a circle. +void b2CollidePolygonAndCircle(b2Manifold* manifold, + const b2PolygonShape* polygon, const b2Transform& xf1, + const b2CircleShape* circle, const b2Transform& xf2); + +/// Compute the collision manifold between two polygons. +void b2CollidePolygons(b2Manifold* manifold, + const b2PolygonShape* polygon1, const b2Transform& xf1, + const b2PolygonShape* polygon2, const b2Transform& xf2); + +/// Clipping for contact manifolds. +int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], + const b2Vec2& normal, float32 offset); + +/// Determine if two generic shapes overlap. +bool b2TestOverlap(const b2Shape* shapeA, const b2Shape* shapeB, + const b2Transform& xfA, const b2Transform& xfB); + +// ---------------- Inline Functions ------------------------------------------ + +inline bool b2AABB::IsValid() const +{ + b2Vec2 d = upperBound - lowerBound; + bool valid = d.x >= 0.0f && d.y >= 0.0f; + valid = valid && lowerBound.IsValid() && upperBound.IsValid(); + return valid; +} + +inline bool b2TestOverlap(const b2AABB& a, const b2AABB& b) +{ + b2Vec2 d1, d2; + d1 = b.lowerBound - a.upperBound; + d2 = a.lowerBound - b.upperBound; + + if (d1.x > 0.0f || d1.y > 0.0f) + return false; + + if (d2.x > 0.0f || d2.y > 0.0f) + return false; + + return true; +} + +#endif diff --git a/src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp b/src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp new file mode 100644 index 000000000..f95c82f21 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp @@ -0,0 +1,571 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates. +int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + +void b2DistanceProxy::Set(const b2Shape* shape) +{ + switch (shape->GetType()) + { + case b2Shape::e_circle: + { + const b2CircleShape* circle = (b2CircleShape*)shape; + m_vertices = &circle->m_p; + m_count = 1; + m_radius = circle->m_radius; + } + break; + + case b2Shape::e_polygon: + { + const b2PolygonShape* polygon = (b2PolygonShape*)shape; + m_vertices = polygon->m_vertices; + m_count = polygon->m_vertexCount; + m_radius = polygon->m_radius; + } + break; + + default: + b2Assert(false); + } +} + + +struct b2SimplexVertex +{ + b2Vec2 wA; // support point in proxyA + b2Vec2 wB; // support point in proxyB + b2Vec2 w; // wB - wA + float32 a; // barycentric coordinate for closest point + int32 indexA; // wA index + int32 indexB; // wB index +}; + +struct b2Simplex +{ + void ReadCache( const b2SimplexCache* cache, + const b2DistanceProxy* proxyA, const b2Transform& transformA, + const b2DistanceProxy* proxyB, const b2Transform& transformB) + { + b2Assert(cache->count <= 3); + + // Copy data from cache. + m_count = cache->count; + b2SimplexVertex* vertices = &m_v1; + for (int32 i = 0; i < m_count; ++i) + { + b2SimplexVertex* v = vertices + i; + v->indexA = cache->indexA[i]; + v->indexB = cache->indexB[i]; + b2Vec2 wALocal = proxyA->GetVertex(v->indexA); + b2Vec2 wBLocal = proxyB->GetVertex(v->indexB); + v->wA = b2Mul(transformA, wALocal); + v->wB = b2Mul(transformB, wBLocal); + v->w = v->wB - v->wA; + v->a = 0.0f; + } + + // Compute the new simplex metric, if it is substantially different than + // old metric then flush the simplex. + if (m_count > 1) + { + float32 metric1 = cache->metric; + float32 metric2 = GetMetric(); + if (metric2 < 0.5f * metric1 || 2.0f * metric1 < metric2 || metric2 < b2_epsilon) + { + // Reset the simplex. + m_count = 0; + } + } + + // If the cache is empty or invalid ... + if (m_count == 0) + { + b2SimplexVertex* v = vertices + 0; + v->indexA = 0; + v->indexB = 0; + b2Vec2 wALocal = proxyA->GetVertex(0); + b2Vec2 wBLocal = proxyB->GetVertex(0); + v->wA = b2Mul(transformA, wALocal); + v->wB = b2Mul(transformB, wBLocal); + v->w = v->wB - v->wA; + m_count = 1; + } + } + + void WriteCache(b2SimplexCache* cache) const + { + cache->metric = GetMetric(); + cache->count = uint16(m_count); + const b2SimplexVertex* vertices = &m_v1; + for (int32 i = 0; i < m_count; ++i) + { + cache->indexA[i] = uint8(vertices[i].indexA); + cache->indexB[i] = uint8(vertices[i].indexB); + } + } + + b2Vec2 GetSearchDirection() const + { + switch (m_count) + { + case 1: + return -m_v1.w; + + case 2: + { + b2Vec2 e12 = m_v2.w - m_v1.w; + float32 sgn = b2Cross(e12, -m_v1.w); + if (sgn > 0.0f) + { + // Origin is left of e12. + return b2Cross(1.0f, e12); + } + else + { + // Origin is right of e12. + return b2Cross(e12, 1.0f); + } + } + + default: + b2Assert(false); + return b2Vec2_zero; + } + } + + b2Vec2 GetClosestPoint() const + { + switch (m_count) + { + case 0: + b2Assert(false); + return b2Vec2_zero; + + case 1: + return m_v1.w; + + case 2: + return m_v1.a * m_v1.w + m_v2.a * m_v2.w; + + case 3: + return b2Vec2_zero; + + default: + b2Assert(false); + return b2Vec2_zero; + } + } + + void GetWitnessPoints(b2Vec2* pA, b2Vec2* pB) const + { + switch (m_count) + { + case 0: + b2Assert(false); + break; + + case 1: + *pA = m_v1.wA; + *pB = m_v1.wB; + break; + + case 2: + *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA; + *pB = m_v1.a * m_v1.wB + m_v2.a * m_v2.wB; + break; + + case 3: + *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA + m_v3.a * m_v3.wA; + *pB = *pA; + break; + + default: + b2Assert(false); + break; + } + } + + float32 GetMetric() const + { + switch (m_count) + { + case 0: + b2Assert(false); + return 0.0; + + case 1: + return 0.0f; + + case 2: + return b2Distance(m_v1.w, m_v2.w); + + case 3: + return b2Cross(m_v2.w - m_v1.w, m_v3.w - m_v1.w); + + default: + b2Assert(false); + return 0.0f; + } + } + + void Solve2(); + void Solve3(); + + b2SimplexVertex m_v1, m_v2, m_v3; + int32 m_count; +}; + + +// Solve a line segment using barycentric coordinates. +// +// p = a1 * w1 + a2 * w2 +// a1 + a2 = 1 +// +// The vector from the origin to the closest point on the line is +// perpendicular to the line. +// e12 = w2 - w1 +// dot(p, e) = 0 +// a1 * dot(w1, e) + a2 * dot(w2, e) = 0 +// +// 2-by-2 linear system +// [1 1 ][a1] = [1] +// [w1.e12 w2.e12][a2] = [0] +// +// Define +// d12_1 = dot(w2, e12) +// d12_2 = -dot(w1, e12) +// d12 = d12_1 + d12_2 +// +// Solution +// a1 = d12_1 / d12 +// a2 = d12_2 / d12 +void b2Simplex::Solve2() +{ + b2Vec2 w1 = m_v1.w; + b2Vec2 w2 = m_v2.w; + b2Vec2 e12 = w2 - w1; + + // w1 region + float32 d12_2 = -b2Dot(w1, e12); + if (d12_2 <= 0.0f) + { + // a2 <= 0, so we clamp it to 0 + m_v1.a = 1.0f; + m_count = 1; + return; + } + + // w2 region + float32 d12_1 = b2Dot(w2, e12); + if (d12_1 <= 0.0f) + { + // a1 <= 0, so we clamp it to 0 + m_v2.a = 1.0f; + m_count = 1; + m_v1 = m_v2; + return; + } + + // Must be in e12 region. + float32 inv_d12 = 1.0f / (d12_1 + d12_2); + m_v1.a = d12_1 * inv_d12; + m_v2.a = d12_2 * inv_d12; + m_count = 2; +} + +// Possible regions: +// - points[2] +// - edge points[0]-points[2] +// - edge points[1]-points[2] +// - inside the triangle +void b2Simplex::Solve3() +{ + b2Vec2 w1 = m_v1.w; + b2Vec2 w2 = m_v2.w; + b2Vec2 w3 = m_v3.w; + + // Edge12 + // [1 1 ][a1] = [1] + // [w1.e12 w2.e12][a2] = [0] + // a3 = 0 + b2Vec2 e12 = w2 - w1; + float32 w1e12 = b2Dot(w1, e12); + float32 w2e12 = b2Dot(w2, e12); + float32 d12_1 = w2e12; + float32 d12_2 = -w1e12; + + // Edge13 + // [1 1 ][a1] = [1] + // [w1.e13 w3.e13][a3] = [0] + // a2 = 0 + b2Vec2 e13 = w3 - w1; + float32 w1e13 = b2Dot(w1, e13); + float32 w3e13 = b2Dot(w3, e13); + float32 d13_1 = w3e13; + float32 d13_2 = -w1e13; + + // Edge23 + // [1 1 ][a2] = [1] + // [w2.e23 w3.e23][a3] = [0] + // a1 = 0 + b2Vec2 e23 = w3 - w2; + float32 w2e23 = b2Dot(w2, e23); + float32 w3e23 = b2Dot(w3, e23); + float32 d23_1 = w3e23; + float32 d23_2 = -w2e23; + + // Triangle123 + float32 n123 = b2Cross(e12, e13); + + float32 d123_1 = n123 * b2Cross(w2, w3); + float32 d123_2 = n123 * b2Cross(w3, w1); + float32 d123_3 = n123 * b2Cross(w1, w2); + + // w1 region + if (d12_2 <= 0.0f && d13_2 <= 0.0f) + { + m_v1.a = 1.0f; + m_count = 1; + return; + } + + // e12 + if (d12_1 > 0.0f && d12_2 > 0.0f && d123_3 <= 0.0f) + { + float32 inv_d12 = 1.0f / (d12_1 + d12_2); + m_v1.a = d12_1 * inv_d12; + m_v2.a = d12_2 * inv_d12; + m_count = 2; + return; + } + + // e13 + if (d13_1 > 0.0f && d13_2 > 0.0f && d123_2 <= 0.0f) + { + float32 inv_d13 = 1.0f / (d13_1 + d13_2); + m_v1.a = d13_1 * inv_d13; + m_v3.a = d13_2 * inv_d13; + m_count = 2; + m_v2 = m_v3; + return; + } + + // w2 region + if (d12_1 <= 0.0f && d23_2 <= 0.0f) + { + m_v2.a = 1.0f; + m_count = 1; + m_v1 = m_v2; + return; + } + + // w3 region + if (d13_1 <= 0.0f && d23_1 <= 0.0f) + { + m_v3.a = 1.0f; + m_count = 1; + m_v1 = m_v3; + return; + } + + // e23 + if (d23_1 > 0.0f && d23_2 > 0.0f && d123_1 <= 0.0f) + { + float32 inv_d23 = 1.0f / (d23_1 + d23_2); + m_v2.a = d23_1 * inv_d23; + m_v3.a = d23_2 * inv_d23; + m_count = 2; + m_v1 = m_v3; + return; + } + + // Must be in triangle123 + float32 inv_d123 = 1.0f / (d123_1 + d123_2 + d123_3); + m_v1.a = d123_1 * inv_d123; + m_v2.a = d123_2 * inv_d123; + m_v3.a = d123_3 * inv_d123; + m_count = 3; +} + +void b2Distance(b2DistanceOutput* output, + b2SimplexCache* cache, + const b2DistanceInput* input) +{ + ++b2_gjkCalls; + + const b2DistanceProxy* proxyA = &input->proxyA; + const b2DistanceProxy* proxyB = &input->proxyB; + + b2Transform transformA = input->transformA; + b2Transform transformB = input->transformB; + + // Initialize the simplex. + b2Simplex simplex; + simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB); + + // Get simplex vertices as an array. + b2SimplexVertex* vertices = &simplex.m_v1; + const int32 k_maxIters = 20; + + // These store the vertices of the last simplex so that we + // can check for duplicates and prevent cycling. + int32 saveA[3], saveB[3]; + int32 saveCount = 0; + + b2Vec2 closestPoint = simplex.GetClosestPoint(); + float32 distanceSqr1 = closestPoint.LengthSquared(); + float32 distanceSqr2 = distanceSqr1; + + // Main iteration loop. + int32 iter = 0; + while (iter < k_maxIters) + { + // Copy simplex so we can identify duplicates. + saveCount = simplex.m_count; + for (int32 i = 0; i < saveCount; ++i) + { + saveA[i] = vertices[i].indexA; + saveB[i] = vertices[i].indexB; + } + + switch (simplex.m_count) + { + case 1: + break; + + case 2: + simplex.Solve2(); + break; + + case 3: + simplex.Solve3(); + break; + + default: + b2Assert(false); + } + + // If we have 3 points, then the origin is in the corresponding triangle. + if (simplex.m_count == 3) + { + break; + } + + // Compute closest point. + b2Vec2 p = simplex.GetClosestPoint(); + distanceSqr2 = p.LengthSquared(); + + // Ensure progress + if (distanceSqr2 >= distanceSqr1) + { + //break; + } + distanceSqr1 = distanceSqr2; + + // Get search direction. + b2Vec2 d = simplex.GetSearchDirection(); + + // Ensure the search direction is numerically fit. + if (d.LengthSquared() < b2_epsilon * b2_epsilon) + { + // The origin is probably contained by a line segment + // or triangle. Thus the shapes are overlapped. + + // We can't return zero here even though there may be overlap. + // In case the simplex is a point, segment, or triangle it is difficult + // to determine if the origin is contained in the CSO or very close to it. + break; + } + + // Compute a tentative new simplex vertex using support points. + b2SimplexVertex* vertex = vertices + simplex.m_count; + vertex->indexA = proxyA->GetSupport(b2MulT(transformA.R, -d)); + vertex->wA = b2Mul(transformA, proxyA->GetVertex(vertex->indexA)); + b2Vec2 wBLocal; + vertex->indexB = proxyB->GetSupport(b2MulT(transformB.R, d)); + vertex->wB = b2Mul(transformB, proxyB->GetVertex(vertex->indexB)); + vertex->w = vertex->wB - vertex->wA; + + // Iteration count is equated to the number of support point calls. + ++iter; + ++b2_gjkIters; + + // Check for duplicate support points. This is the main termination criteria. + bool duplicate = false; + for (int32 i = 0; i < saveCount; ++i) + { + if (vertex->indexA == saveA[i] && vertex->indexB == saveB[i]) + { + duplicate = true; + break; + } + } + + // If we found a duplicate support point we must exit to avoid cycling. + if (duplicate) + { + break; + } + + // New vertex is ok and needed. + ++simplex.m_count; + } + + b2_gjkMaxIters = b2Max(b2_gjkMaxIters, iter); + + // Prepare output. + simplex.GetWitnessPoints(&output->pointA, &output->pointB); + output->distance = b2Distance(output->pointA, output->pointB); + output->iterations = iter; + + // Cache the simplex. + simplex.WriteCache(cache); + + // Apply radii if requested. + if (input->useRadii) + { + float32 rA = proxyA->m_radius; + float32 rB = proxyB->m_radius; + + if (output->distance > rA + rB && output->distance > b2_epsilon) + { + // Shapes are still no overlapped. + // Move the witness points to the outer surface. + output->distance -= rA + rB; + b2Vec2 normal = output->pointB - output->pointA; + normal.Normalize(); + output->pointA += rA * normal; + output->pointB -= rB * normal; + } + else + { + // Shapes are overlapped when radii are considered. + // Move the witness points to the middle. + b2Vec2 p = 0.5f * (output->pointA + output->pointB); + output->pointA = p; + output->pointB = p; + output->distance = 0.0f; + } + } +} diff --git a/src/modules/physics/box2d/Box2D/Collision/b2Distance.h b/src/modules/physics/box2d/Box2D/Collision/b2Distance.h new file mode 100644 index 000000000..e56ea0a7b --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/b2Distance.h @@ -0,0 +1,141 @@ + +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_DISTANCE_H +#define B2_DISTANCE_H + +#include +#include + +class b2Shape; + +/// A distance proxy is used by the GJK algorithm. +/// It encapsulates any shape. +struct b2DistanceProxy +{ + b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {} + + /// Initialize the proxy using the given shape. The shape + /// must remain in scope while the proxy is in use. + void Set(const b2Shape* shape); + + /// Get the supporting vertex index in the given direction. + int32 GetSupport(const b2Vec2& d) const; + + /// Get the supporting vertex in the given direction. + const b2Vec2& GetSupportVertex(const b2Vec2& d) const; + + /// Get the vertex count. + int32 GetVertexCount() const; + + /// Get a vertex by index. Used by b2Distance. + const b2Vec2& GetVertex(int32 index) const; + + const b2Vec2* m_vertices; + int32 m_count; + float32 m_radius; +}; + +/// Used to warm start b2Distance. +/// Set count to zero on first call. +struct b2SimplexCache +{ + float32 metric; ///< length or area + uint16 count; + uint8 indexA[3]; ///< vertices on shape A + uint8 indexB[3]; ///< vertices on shape B +}; + +/// Input for b2Distance. +/// You have to option to use the shape radii +/// in the computation. Even +struct b2DistanceInput +{ + b2DistanceProxy proxyA; + b2DistanceProxy proxyB; + b2Transform transformA; + b2Transform transformB; + bool useRadii; +}; + +/// Output for b2Distance. +struct b2DistanceOutput +{ + b2Vec2 pointA; ///< closest point on shapeA + b2Vec2 pointB; ///< closest point on shapeB + float32 distance; + int32 iterations; ///< number of GJK iterations used +}; + +/// Compute the closest points between two shapes. Supports any combination of: +/// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/output. +/// On the first call set b2SimplexCache.count to zero. +void b2Distance(b2DistanceOutput* output, + b2SimplexCache* cache, + const b2DistanceInput* input); + + +////////////////////////////////////////////////////////////////////////// + +inline int32 b2DistanceProxy::GetVertexCount() const +{ + return m_count; +} + +inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const +{ + b2Assert(0 <= index && index < m_count); + return m_vertices[index]; +} + +inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const +{ + int32 bestIndex = 0; + float32 bestValue = b2Dot(m_vertices[0], d); + for (int32 i = 1; i < m_count; ++i) + { + float32 value = b2Dot(m_vertices[i], d); + if (value > bestValue) + { + bestIndex = i; + bestValue = value; + } + } + + return bestIndex; +} + +inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) const +{ + int32 bestIndex = 0; + float32 bestValue = b2Dot(m_vertices[0], d); + for (int32 i = 1; i < m_count; ++i) + { + float32 value = b2Dot(m_vertices[i], d); + if (value > bestValue) + { + bestIndex = i; + bestValue = value; + } + } + + return m_vertices[bestIndex]; +} + +#endif diff --git a/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.cpp b/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.cpp new file mode 100644 index 000000000..d8a05ebdf --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.cpp @@ -0,0 +1,365 @@ +/* +* Copyright (c) 2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +b2DynamicTree::b2DynamicTree() +{ + m_root = b2_nullNode; + + m_nodeCapacity = 16; + m_nodeCount = 0; + m_nodes = (b2DynamicTreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2DynamicTreeNode)); + memset(m_nodes, 0, m_nodeCapacity * sizeof(b2DynamicTreeNode)); + + // Build a linked list for the free list. + for (int32 i = 0; i < m_nodeCapacity - 1; ++i) + { + m_nodes[i].next = i + 1; + } + m_nodes[m_nodeCapacity-1].next = b2_nullNode; + m_freeList = 0; + + m_path = 0; + + m_insertionCount = 0; +} + +b2DynamicTree::~b2DynamicTree() +{ + // This frees the entire tree in one shot. + b2Free(m_nodes); +} + +// Allocate a node from the pool. Grow the pool if necessary. +int32 b2DynamicTree::AllocateNode() +{ + // Expand the node pool as needed. + if (m_freeList == b2_nullNode) + { + b2Assert(m_nodeCount == m_nodeCapacity); + + // The free list is empty. Rebuild a bigger pool. + b2DynamicTreeNode* oldNodes = m_nodes; + m_nodeCapacity *= 2; + m_nodes = (b2DynamicTreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2DynamicTreeNode)); + memcpy(m_nodes, oldNodes, m_nodeCount * sizeof(b2DynamicTreeNode)); + b2Free(oldNodes); + + // Build a linked list for the free list. The parent + // pointer becomes the "next" pointer. + for (int32 i = m_nodeCount; i < m_nodeCapacity - 1; ++i) + { + m_nodes[i].next = i + 1; + } + m_nodes[m_nodeCapacity-1].next = b2_nullNode; + m_freeList = m_nodeCount; + } + + // Peel a node off the free list. + int32 nodeId = m_freeList; + m_freeList = m_nodes[nodeId].next; + m_nodes[nodeId].parent = b2_nullNode; + m_nodes[nodeId].child1 = b2_nullNode; + m_nodes[nodeId].child2 = b2_nullNode; + ++m_nodeCount; + return nodeId; +} + +// Return a node to the pool. +void b2DynamicTree::FreeNode(int32 nodeId) +{ + b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); + b2Assert(0 < m_nodeCount); + m_nodes[nodeId].next = m_freeList; + m_freeList = nodeId; + --m_nodeCount; +} + +// Create a proxy in the tree as a leaf node. We return the index +// of the node instead of a pointer so that we can grow +// the node pool. +int32 b2DynamicTree::CreateProxy(const b2AABB& aabb, void* userData) +{ + int32 proxyId = AllocateNode(); + + // Fatten the aabb. + b2Vec2 r(b2_aabbExtension, b2_aabbExtension); + m_nodes[proxyId].aabb.lowerBound = aabb.lowerBound - r; + m_nodes[proxyId].aabb.upperBound = aabb.upperBound + r; + m_nodes[proxyId].userData = userData; + + InsertLeaf(proxyId); + + // Rebalance if necessary. + int32 iterationCount = m_nodeCount >> 4; + int32 tryCount = 0; + int32 height = ComputeHeight(); + while (height > 64 && tryCount < 10) + { + Rebalance(iterationCount); + height = ComputeHeight(); + ++tryCount; + } + + return proxyId; +} + +void b2DynamicTree::DestroyProxy(int32 proxyId) +{ + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + b2Assert(m_nodes[proxyId].IsLeaf()); + + RemoveLeaf(proxyId); + FreeNode(proxyId); +} + +bool b2DynamicTree::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) +{ + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + + b2Assert(m_nodes[proxyId].IsLeaf()); + + if (m_nodes[proxyId].aabb.Contains(aabb)) + { + return false; + } + + RemoveLeaf(proxyId); + + // Extend AABB. + b2AABB b = aabb; + b2Vec2 r(b2_aabbExtension, b2_aabbExtension); + b.lowerBound = b.lowerBound - r; + b.upperBound = b.upperBound + r; + + // Predict AABB displacement. + b2Vec2 d = b2_aabbMultiplier * displacement; + + if (d.x < 0.0f) + { + b.lowerBound.x += d.x; + } + else + { + b.upperBound.x += d.x; + } + + if (d.y < 0.0f) + { + b.lowerBound.y += d.y; + } + else + { + b.upperBound.y += d.y; + } + + m_nodes[proxyId].aabb = b; + + InsertLeaf(proxyId); + return true; +} + +void b2DynamicTree::InsertLeaf(int32 leaf) +{ + ++m_insertionCount; + + if (m_root == b2_nullNode) + { + m_root = leaf; + m_nodes[m_root].parent = b2_nullNode; + return; + } + + // Find the best sibling for this node. + b2Vec2 center = m_nodes[leaf].aabb.GetCenter(); + int32 sibling = m_root; + if (m_nodes[sibling].IsLeaf() == false) + { + do + { + int32 child1 = m_nodes[sibling].child1; + int32 child2 = m_nodes[sibling].child2; + + b2Vec2 delta1 = b2Abs(m_nodes[child1].aabb.GetCenter() - center); + b2Vec2 delta2 = b2Abs(m_nodes[child2].aabb.GetCenter() - center); + + float32 norm1 = delta1.x + delta1.y; + float32 norm2 = delta2.x + delta2.y; + + if (norm1 < norm2) + { + sibling = child1; + } + else + { + sibling = child2; + } + + } + while(m_nodes[sibling].IsLeaf() == false); + } + + // Create a parent for the siblings. + int32 node1 = m_nodes[sibling].parent; + int32 node2 = AllocateNode(); + m_nodes[node2].parent = node1; + m_nodes[node2].userData = NULL; + m_nodes[node2].aabb.Combine(m_nodes[leaf].aabb, m_nodes[sibling].aabb); + + if (node1 != b2_nullNode) + { + if (m_nodes[m_nodes[sibling].parent].child1 == sibling) + { + m_nodes[node1].child1 = node2; + } + else + { + m_nodes[node1].child2 = node2; + } + + m_nodes[node2].child1 = sibling; + m_nodes[node2].child2 = leaf; + m_nodes[sibling].parent = node2; + m_nodes[leaf].parent = node2; + + do + { + if (m_nodes[node1].aabb.Contains(m_nodes[node2].aabb)) + { + break; + } + + m_nodes[node1].aabb.Combine(m_nodes[m_nodes[node1].child1].aabb, m_nodes[m_nodes[node1].child2].aabb); + node2 = node1; + node1 = m_nodes[node1].parent; + } + while(node1 != b2_nullNode); + } + else + { + m_nodes[node2].child1 = sibling; + m_nodes[node2].child2 = leaf; + m_nodes[sibling].parent = node2; + m_nodes[leaf].parent = node2; + m_root = node2; + } +} + +void b2DynamicTree::RemoveLeaf(int32 leaf) +{ + if (leaf == m_root) + { + m_root = b2_nullNode; + return; + } + + int32 node2 = m_nodes[leaf].parent; + int32 node1 = m_nodes[node2].parent; + int32 sibling; + if (m_nodes[node2].child1 == leaf) + { + sibling = m_nodes[node2].child2; + } + else + { + sibling = m_nodes[node2].child1; + } + + if (node1 != b2_nullNode) + { + // Destroy node2 and connect node1 to sibling. + if (m_nodes[node1].child1 == node2) + { + m_nodes[node1].child1 = sibling; + } + else + { + m_nodes[node1].child2 = sibling; + } + m_nodes[sibling].parent = node1; + FreeNode(node2); + + // Adjust ancestor bounds. + while (node1 != b2_nullNode) + { + b2AABB oldAABB = m_nodes[node1].aabb; + m_nodes[node1].aabb.Combine(m_nodes[m_nodes[node1].child1].aabb, m_nodes[m_nodes[node1].child2].aabb); + + if (oldAABB.Contains(m_nodes[node1].aabb)) + { + break; + } + + node1 = m_nodes[node1].parent; + } + } + else + { + m_root = sibling; + m_nodes[sibling].parent = b2_nullNode; + FreeNode(node2); + } +} + +void b2DynamicTree::Rebalance(int32 iterations) +{ + if (m_root == b2_nullNode) + { + return; + } + + for (int32 i = 0; i < iterations; ++i) + { + int32 node = m_root; + + uint32 bit = 0; + while (m_nodes[node].IsLeaf() == false) + { + int32* children = &m_nodes[node].child1; + node = children[(m_path >> bit) & 1]; + bit = (bit + 1) & (8* sizeof(uint32) - 1); + } + ++m_path; + + RemoveLeaf(node); + InsertLeaf(node); + } +} + +// Compute the height of a sub-tree. +int32 b2DynamicTree::ComputeHeight(int32 nodeId) const +{ + if (nodeId == b2_nullNode) + { + return 0; + } + + b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); + b2DynamicTreeNode* node = m_nodes + nodeId; + int32 height1 = ComputeHeight(node->child1); + int32 height2 = ComputeHeight(node->child2); + return 1 + b2Max(height1, height2); +} + +int32 b2DynamicTree::ComputeHeight() const +{ + return ComputeHeight(m_root); +} diff --git a/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.h b/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.h new file mode 100644 index 000000000..b67686b5c --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.h @@ -0,0 +1,286 @@ +/* +* Copyright (c) 2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_DYNAMIC_TREE_H +#define B2_DYNAMIC_TREE_H + +#include + +/// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. + +#define b2_nullNode (-1) + +/// A node in the dynamic tree. The client does not interact with this directly. +struct b2DynamicTreeNode +{ + bool IsLeaf() const + { + return child1 == b2_nullNode; + } + + /// This is the fattened AABB. + b2AABB aabb; + + //int32 userData; + void* userData; + + union + { + int32 parent; + int32 next; + }; + + int32 child1; + int32 child2; +}; + +/// A dynamic tree arranges data in a binary tree to accelerate +/// queries such as volume queries and ray casts. Leafs are proxies +/// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor +/// so that the proxy AABB is bigger than the client object. This allows the client +/// object to move by small amounts without triggering a tree update. +/// +/// Nodes are pooled and relocatable, so we use node indices rather than pointers. +class b2DynamicTree +{ +public: + + /// Constructing the tree initializes the node pool. + b2DynamicTree(); + + /// Destroy the tree, freeing the node pool. + ~b2DynamicTree(); + + /// Create a proxy. Provide a tight fitting AABB and a userData pointer. + int32 CreateProxy(const b2AABB& aabb, void* userData); + + /// Destroy a proxy. This asserts if the id is invalid. + void DestroyProxy(int32 proxyId); + + /// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB, + /// then the proxy is removed from the tree and re-inserted. Otherwise + /// the function returns immediately. + /// @return true if the proxy was re-inserted. + bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement); + + /// Perform some iterations to re-balance the tree. + void Rebalance(int32 iterations); + + /// Get proxy user data. + /// @return the proxy user data or 0 if the id is invalid. + void* GetUserData(int32 proxyId) const; + + /// Get the fat AABB for a proxy. + const b2AABB& GetFatAABB(int32 proxyId) const; + + /// Compute the height of the tree. + int32 ComputeHeight() const; + + /// Query an AABB for overlapping proxies. The callback class + /// is called for each proxy that overlaps the supplied AABB. + template + void Query(T* callback, const b2AABB& aabb) const; + + /// Ray-cast against the proxies in the tree. This relies on the callback + /// to perform a exact ray-cast in the case were the proxy contains a shape. + /// The callback also performs the any collision filtering. This has performance + /// roughly equal to k * log(n), where k is the number of collisions and n is the + /// number of proxies in the tree. + /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). + /// @param callback a callback class that is called for each proxy that is hit by the ray. + template + void RayCast(T* callback, const b2RayCastInput& input) const; + +private: + + int32 AllocateNode(); + void FreeNode(int32 node); + + void InsertLeaf(int32 node); + void RemoveLeaf(int32 node); + + int32 ComputeHeight(int32 nodeId) const; + + int32 m_root; + + b2DynamicTreeNode* m_nodes; + int32 m_nodeCount; + int32 m_nodeCapacity; + + int32 m_freeList; + + /// This is used incrementally traverse the tree for re-balancing. + uint32 m_path; + + int32 m_insertionCount; +}; + +inline void* b2DynamicTree::GetUserData(int32 proxyId) const +{ + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + return m_nodes[proxyId].userData; +} + +inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const +{ + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + return m_nodes[proxyId].aabb; +} + +template +inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const +{ + const int32 k_stackSize = 128; + int32 stack[k_stackSize]; + + int32 count = 0; + stack[count++] = m_root; + + while (count > 0) + { + int32 nodeId = stack[--count]; + if (nodeId == b2_nullNode) + { + continue; + } + + const b2DynamicTreeNode* node = m_nodes + nodeId; + + if (b2TestOverlap(node->aabb, aabb)) + { + if (node->IsLeaf()) + { + bool proceed = callback->QueryCallback(nodeId); + if (proceed == false) + { + return; + } + } + else + { + if (count < k_stackSize) + { + stack[count++] = node->child1; + } + + if (count < k_stackSize) + { + stack[count++] = node->child2; + } + } + } + } +} + +template +inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) const +{ + b2Vec2 p1 = input.p1; + b2Vec2 p2 = input.p2; + b2Vec2 r = p2 - p1; + b2Assert(r.LengthSquared() > 0.0f); + r.Normalize(); + + // v is perpendicular to the segment. + b2Vec2 v = b2Cross(1.0f, r); + b2Vec2 abs_v = b2Abs(v); + + // Separating axis for segment (Gino, p80). + // |dot(v, p1 - c)| > dot(|v|, h) + + float32 maxFraction = input.maxFraction; + + // Build a bounding box for the segment. + b2AABB segmentAABB; + { + b2Vec2 t = p1 + maxFraction * (p2 - p1); + segmentAABB.lowerBound = b2Min(p1, t); + segmentAABB.upperBound = b2Max(p1, t); + } + + const int32 k_stackSize = 128; + int32 stack[k_stackSize]; + + int32 count = 0; + stack[count++] = m_root; + + while (count > 0) + { + int32 nodeId = stack[--count]; + if (nodeId == b2_nullNode) + { + continue; + } + + const b2DynamicTreeNode* node = m_nodes + nodeId; + + if (b2TestOverlap(node->aabb, segmentAABB) == false) + { + continue; + } + + // Separating axis for segment (Gino, p80). + // |dot(v, p1 - c)| > dot(|v|, h) + b2Vec2 c = node->aabb.GetCenter(); + b2Vec2 h = node->aabb.GetExtents(); + float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h); + if (separation > 0.0f) + { + continue; + } + + if (node->IsLeaf()) + { + b2RayCastInput subInput; + subInput.p1 = input.p1; + subInput.p2 = input.p2; + subInput.maxFraction = maxFraction; + + float32 value = callback->RayCastCallback(subInput, nodeId); + + if (value == 0.0f) + { + // The client has terminated the ray cast. + return; + } + + if (value > 0.0f) + { + // Update segment bounding box. + maxFraction = value; + b2Vec2 t = p1 + maxFraction * (p2 - p1); + segmentAABB.lowerBound = b2Min(p1, t); + segmentAABB.upperBound = b2Max(p1, t); + } + } + else + { + if (count < k_stackSize) + { + stack[count++] = node->child1; + } + + if (count < k_stackSize) + { + stack[count++] = node->child2; + } + } + } +} + +#endif diff --git a/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.cpp b/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.cpp new file mode 100644 index 000000000..b1f2f4e5a --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.cpp @@ -0,0 +1,483 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +#include + +int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; +int32 b2_toiRootIters, b2_toiMaxRootIters; + +int32 b2_toiMaxOptIters; + +struct b2SeparationFunction +{ + enum Type + { + e_points, + e_faceA, + e_faceB + }; + + // TODO_ERIN might not need to return the separation + + float32 Initialize(const b2SimplexCache* cache, + const b2DistanceProxy* proxyA, const b2Sweep& sweepA, + const b2DistanceProxy* proxyB, const b2Sweep& sweepB) + { + m_proxyA = proxyA; + m_proxyB = proxyB; + int32 count = cache->count; + b2Assert(0 < count && count < 3); + + m_sweepA = sweepA; + m_sweepB = sweepB; + + b2Transform xfA, xfB; + m_sweepA.GetTransform(&xfA, 0.0f); + m_sweepB.GetTransform(&xfB, 0.0f); + + if (count == 1) + { + m_type = e_points; + b2Vec2 localPointA = m_proxyA->GetVertex(cache->indexA[0]); + b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); + b2Vec2 pointA = b2Mul(xfA, localPointA); + b2Vec2 pointB = b2Mul(xfB, localPointB); + m_axis = pointB - pointA; + float32 s = m_axis.Normalize(); + return s; + } + else if (cache->indexA[0] == cache->indexA[1]) + { + // Two points on B and one on A. + m_type = e_faceB; + b2Vec2 localPointB1 = proxyB->GetVertex(cache->indexB[0]); + b2Vec2 localPointB2 = proxyB->GetVertex(cache->indexB[1]); + + m_axis = b2Cross(localPointB2 - localPointB1, 1.0f); + m_axis.Normalize(); + b2Vec2 normal = b2Mul(xfB.R, m_axis); + + m_localPoint = 0.5f * (localPointB1 + localPointB2); + b2Vec2 pointB = b2Mul(xfB, m_localPoint); + + b2Vec2 localPointA = proxyA->GetVertex(cache->indexA[0]); + b2Vec2 pointA = b2Mul(xfA, localPointA); + + float32 s = b2Dot(pointA - pointB, normal); + if (s < 0.0f) + { + m_axis = -m_axis; + s = -s; + } + return s; + } + else + { + // Two points on A and one or two points on B. + m_type = e_faceA; + b2Vec2 localPointA1 = m_proxyA->GetVertex(cache->indexA[0]); + b2Vec2 localPointA2 = m_proxyA->GetVertex(cache->indexA[1]); + + m_axis = b2Cross(localPointA2 - localPointA1, 1.0f); + m_axis.Normalize(); + b2Vec2 normal = b2Mul(xfA.R, m_axis); + + m_localPoint = 0.5f * (localPointA1 + localPointA2); + b2Vec2 pointA = b2Mul(xfA, m_localPoint); + + b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); + b2Vec2 pointB = b2Mul(xfB, localPointB); + + float32 s = b2Dot(pointB - pointA, normal); + if (s < 0.0f) + { + m_axis = -m_axis; + s = -s; + } + return s; + } + } + + float32 FindMinSeparation(int32* indexA, int32* indexB, float32 t) const + { + b2Transform xfA, xfB; + m_sweepA.GetTransform(&xfA, t); + m_sweepB.GetTransform(&xfB, t); + + switch (m_type) + { + case e_points: + { + b2Vec2 axisA = b2MulT(xfA.R, m_axis); + b2Vec2 axisB = b2MulT(xfB.R, -m_axis); + + *indexA = m_proxyA->GetSupport(axisA); + *indexB = m_proxyB->GetSupport(axisB); + + b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); + b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); + + b2Vec2 pointA = b2Mul(xfA, localPointA); + b2Vec2 pointB = b2Mul(xfB, localPointB); + + float32 separation = b2Dot(pointB - pointA, m_axis); + return separation; + } + + case e_faceA: + { + b2Vec2 normal = b2Mul(xfA.R, m_axis); + b2Vec2 pointA = b2Mul(xfA, m_localPoint); + + b2Vec2 axisB = b2MulT(xfB.R, -normal); + + *indexA = -1; + *indexB = m_proxyB->GetSupport(axisB); + + b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); + b2Vec2 pointB = b2Mul(xfB, localPointB); + + float32 separation = b2Dot(pointB - pointA, normal); + return separation; + } + + case e_faceB: + { + b2Vec2 normal = b2Mul(xfB.R, m_axis); + b2Vec2 pointB = b2Mul(xfB, m_localPoint); + + b2Vec2 axisA = b2MulT(xfA.R, -normal); + + *indexB = -1; + *indexA = m_proxyA->GetSupport(axisA); + + b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); + b2Vec2 pointA = b2Mul(xfA, localPointA); + + float32 separation = b2Dot(pointA - pointB, normal); + return separation; + } + + default: + b2Assert(false); + *indexA = -1; + *indexB = -1; + return 0.0f; + } + } + + float32 Evaluate(int32 indexA, int32 indexB, float32 t) const + { + b2Transform xfA, xfB; + m_sweepA.GetTransform(&xfA, t); + m_sweepB.GetTransform(&xfB, t); + + switch (m_type) + { + case e_points: + { + b2Vec2 axisA = b2MulT(xfA.R, m_axis); + b2Vec2 axisB = b2MulT(xfB.R, -m_axis); + + b2Vec2 localPointA = m_proxyA->GetVertex(indexA); + b2Vec2 localPointB = m_proxyB->GetVertex(indexB); + + b2Vec2 pointA = b2Mul(xfA, localPointA); + b2Vec2 pointB = b2Mul(xfB, localPointB); + float32 separation = b2Dot(pointB - pointA, m_axis); + + return separation; + } + + case e_faceA: + { + b2Vec2 normal = b2Mul(xfA.R, m_axis); + b2Vec2 pointA = b2Mul(xfA, m_localPoint); + + b2Vec2 axisB = b2MulT(xfB.R, -normal); + + b2Vec2 localPointB = m_proxyB->GetVertex(indexB); + b2Vec2 pointB = b2Mul(xfB, localPointB); + + float32 separation = b2Dot(pointB - pointA, normal); + return separation; + } + + case e_faceB: + { + b2Vec2 normal = b2Mul(xfB.R, m_axis); + b2Vec2 pointB = b2Mul(xfB, m_localPoint); + + b2Vec2 axisA = b2MulT(xfA.R, -normal); + + b2Vec2 localPointA = m_proxyA->GetVertex(indexA); + b2Vec2 pointA = b2Mul(xfA, localPointA); + + float32 separation = b2Dot(pointA - pointB, normal); + return separation; + } + + default: + b2Assert(false); + return 0.0f; + } + } + + const b2DistanceProxy* m_proxyA; + const b2DistanceProxy* m_proxyB; + b2Sweep m_sweepA, m_sweepB; + Type m_type; + b2Vec2 m_localPoint; + b2Vec2 m_axis; +}; + +// CCD via the local separating axis method. This seeks progression +// by computing the largest time at which separation is maintained. +void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input) +{ + ++b2_toiCalls; + + output->state = b2TOIOutput::e_unknown; + output->t = input->tMax; + + const b2DistanceProxy* proxyA = &input->proxyA; + const b2DistanceProxy* proxyB = &input->proxyB; + + b2Sweep sweepA = input->sweepA; + b2Sweep sweepB = input->sweepB; + + // Large rotations can make the root finder fail, so we normalize the + // sweep angles. + sweepA.Normalize(); + sweepB.Normalize(); + + float32 tMax = input->tMax; + + float32 totalRadius = proxyA->m_radius + proxyB->m_radius; + float32 target = b2Max(b2_linearSlop, totalRadius - 3.0f * b2_linearSlop); + float32 tolerance = 0.25f * b2_linearSlop; + b2Assert(target > tolerance); + + float32 t1 = 0.0f; + const int32 k_maxIterations = 20; // TODO_ERIN b2Settings + int32 iter = 0; + + // Prepare input for distance query. + b2SimplexCache cache; + cache.count = 0; + b2DistanceInput distanceInput; + distanceInput.proxyA = input->proxyA; + distanceInput.proxyB = input->proxyB; + distanceInput.useRadii = false; + + // The outer loop progressively attempts to compute new separating axes. + // This loop terminates when an axis is repeated (no progress is made). + for(;;) + { + b2Transform xfA, xfB; + sweepA.GetTransform(&xfA, t1); + sweepB.GetTransform(&xfB, t1); + + // Get the distance between shapes. We can also use the results + // to get a separating axis. + distanceInput.transformA = xfA; + distanceInput.transformB = xfB; + b2DistanceOutput distanceOutput; + b2Distance(&distanceOutput, &cache, &distanceInput); + + // If the shapes are overlapped, we give up on continuous collision. + if (distanceOutput.distance <= 0.0f) + { + // Failure! + output->state = b2TOIOutput::e_overlapped; + output->t = 0.0f; + break; + } + + if (distanceOutput.distance < target + tolerance) + { + // Victory! + output->state = b2TOIOutput::e_touching; + output->t = t1; + break; + } + + // Initialize the separating axis. + b2SeparationFunction fcn; + fcn.Initialize(&cache, proxyA, sweepA, proxyB, sweepB); +#if 0 + // Dump the curve seen by the root finder + { + const int32 N = 100; + float32 dx = 1.0f / N; + float32 xs[N+1]; + float32 fs[N+1]; + + float32 x = 0.0f; + + for (int32 i = 0; i <= N; ++i) + { + sweepA.GetTransform(&xfA, x); + sweepB.GetTransform(&xfB, x); + float32 f = fcn.Evaluate(xfA, xfB) - target; + + printf("%g %g\n", x, f); + + xs[i] = x; + fs[i] = f; + + x += dx; + } + } +#endif + + // Compute the TOI on the separating axis. We do this by successively + // resolving the deepest point. This loop is bounded by the number of vertices. + bool done = false; + float32 t2 = tMax; + int32 pushBackIter = 0; + for (;;) + { + // Find the deepest point at t2. Store the witness point indices. + int32 indexA, indexB; + float32 s2 = fcn.FindMinSeparation(&indexA, &indexB, t2); + + // Is the final configuration separated? + if (s2 > target + tolerance) + { + // Victory! + output->state = b2TOIOutput::e_separated; + output->t = tMax; + done = true; + break; + } + + // Has the separation reached tolerance? + if (s2 > target - tolerance) + { + // Advance the sweeps + t1 = t2; + break; + } + + // Compute the initial separation of the witness points. + float32 s1 = fcn.Evaluate(indexA, indexB, t1); + + // Check for initial overlap. This might happen if the root finder + // runs out of iterations. + if (s1 < target - tolerance) + { + output->state = b2TOIOutput::e_failed; + output->t = t1; + done = true; + break; + } + + // Check for touching + if (s1 <= target + tolerance) + { + // Victory! t1 should hold the TOI (could be 0.0). + output->state = b2TOIOutput::e_touching; + output->t = t1; + done = true; + break; + } + + // Compute 1D root of: f(x) - target = 0 + int32 rootIterCount = 0; + float32 a1 = t1, a2 = t2; + for (;;) + { + // Use a mix of the secant rule and bisection. + float32 t; + if (rootIterCount & 1) + { + // Secant rule to improve convergence. + t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); + } + else + { + // Bisection to guarantee progress. + t = 0.5f * (a1 + a2); + } + + float32 s = fcn.Evaluate(indexA, indexB, t); + + if (b2Abs(s - target) < tolerance) + { + // t2 holds a tentative value for t1 + t2 = t; + break; + } + + // Ensure we continue to bracket the root. + if (s > target) + { + a1 = t; + s1 = s; + } + else + { + a2 = t; + s2 = s; + } + + ++rootIterCount; + ++b2_toiRootIters; + + if (rootIterCount == 50) + { + break; + } + } + + b2_toiMaxRootIters = b2Max(b2_toiMaxRootIters, rootIterCount); + + ++pushBackIter; + + if (pushBackIter == b2_maxPolygonVertices) + { + break; + } + } + + ++iter; + ++b2_toiIters; + + if (done) + { + break; + } + + if (iter == k_maxIterations) + { + // Root finder got stuck. Semi-victory. + output->state = b2TOIOutput::e_failed; + output->t = t1; + break; + } + } + + b2_toiMaxIters = b2Max(b2_toiMaxIters, iter); +} diff --git a/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.h b/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.h new file mode 100644 index 000000000..b59fb831c --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.h @@ -0,0 +1,59 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_TIME_OF_IMPACT_H +#define B2_TIME_OF_IMPACT_H + +#include +#include +#include + +/// Input parameters for b2TimeOfImpact +struct b2TOIInput +{ + b2DistanceProxy proxyA; + b2DistanceProxy proxyB; + b2Sweep sweepA; + b2Sweep sweepB; + float32 tMax; // defines sweep interval [0, tMax] +}; + +// Output parameters for b2TimeOfImpact. +struct b2TOIOutput +{ + enum State + { + e_unknown, + e_failed, + e_overlapped, + e_touching, + e_separated + }; + + State state; + float32 t; +}; + +/// Compute the upper bound on time before two shapes penetrate. Time is represented as +/// a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate, +/// non-tunneling collision. If you change the time interval, you should call this function +/// again. +/// Note: use b2Distance to compute the contact point and normal at the time of impact. +void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input); + +#endif diff --git a/src/modules/physics/box2d/Source/Common/b2BlockAllocator.cpp b/src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.cpp similarity index 91% rename from src/modules/physics/box2d/Source/Common/b2BlockAllocator.cpp rename to src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.cpp index 99c6dcd93..ba06f0494 100644 --- a/src/modules/physics/box2d/Source/Common/b2BlockAllocator.cpp +++ b/src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -16,11 +16,11 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#include "b2BlockAllocator.h" +#include #include -#include #include -#include +#include +#include int32 b2BlockAllocator::s_blockSizes[b2_blockSizes] = { @@ -164,14 +164,13 @@ void b2BlockAllocator::Free(void* p, int32 size) // Verify the memory address and size is valid. int32 blockSize = s_blockSizes[index]; bool found = false; - int32 gap = (int32)((int8*)&m_chunks->blocks - (int8*)m_chunks); for (int32 i = 0; i < m_chunkCount; ++i) { b2Chunk* chunk = m_chunks + i; if (chunk->blockSize != blockSize) { b2Assert( (int8*)p + blockSize <= (int8*)chunk->blocks || - (int8*)chunk->blocks + b2_chunkSize + gap <= (int8*)p); + (int8*)chunk->blocks + b2_chunkSize <= (int8*)p); } else { diff --git a/src/modules/physics/box2d/Source/Common/b2BlockAllocator.h b/src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.h similarity index 91% rename from src/modules/physics/box2d/Source/Common/b2BlockAllocator.h rename to src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.h index fa137211c..93eb2e311 100644 --- a/src/modules/physics/box2d/Source/Common/b2BlockAllocator.h +++ b/src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -19,7 +19,7 @@ #ifndef B2_BLOCK_ALLOCATOR_H #define B2_BLOCK_ALLOCATOR_H -#include "b2Settings.h" +#include const int32 b2_chunkSize = 4096; const int32 b2_maxBlockSize = 640; diff --git a/src/modules/physics/box2d/Box2D/Common/b2Math.cpp b/src/modules/physics/box2d/Box2D/Common/b2Math.cpp new file mode 100644 index 000000000..f15a43bd5 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Common/b2Math.cpp @@ -0,0 +1,55 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +const b2Vec2 b2Vec2_zero(0.0f, 0.0f); +const b2Mat22 b2Mat22_identity(1.0f, 0.0f, 0.0f, 1.0f); +const b2Transform b2Transform_identity(b2Vec2_zero, b2Mat22_identity); + +/// Solve A * x = b, where b is a column vector. This is more efficient +/// than computing the inverse in one-shot cases. +b2Vec3 b2Mat33::Solve33(const b2Vec3& b) const +{ + float32 det = b2Dot(col1, b2Cross(col2, col3)); + if (det != 0.0f) + { + det = 1.0f / det; + } + b2Vec3 x; + x.x = det * b2Dot(b, b2Cross(col2, col3)); + x.y = det * b2Dot(col1, b2Cross(b, col3)); + x.z = det * b2Dot(col1, b2Cross(col2, b)); + return x; +} + +/// Solve A * x = b, where b is a column vector. This is more efficient +/// than computing the inverse in one-shot cases. +b2Vec2 b2Mat33::Solve22(const b2Vec2& b) const +{ + float32 a11 = col1.x, a12 = col2.x, a21 = col1.y, a22 = col2.y; + float32 det = a11 * a22 - a12 * a21; + if (det != 0.0f) + { + det = 1.0f / det; + } + b2Vec2 x; + x.x = det * (a22 * b.x - a12 * b.y); + x.y = det * (a11 * b.y - a21 * b.x); + return x; +} diff --git a/src/modules/physics/box2d/Source/Common/b2Math.h b/src/modules/physics/box2d/Box2D/Common/b2Math.h similarity index 60% rename from src/modules/physics/box2d/Source/Common/b2Math.h rename to src/modules/physics/box2d/Box2D/Common/b2Math.h index 3b1ad56c2..c29f59430 100644 --- a/src/modules/physics/box2d/Source/Common/b2Math.h +++ b/src/modules/physics/box2d/Box2D/Common/b2Math.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -19,49 +19,25 @@ #ifndef B2_MATH_H #define B2_MATH_H -#include "b2Settings.h" +#include + #include #include -#include - -#include - -#ifdef TARGET_FLOAT32_IS_FIXED - -inline Fixed b2Min(const Fixed& a, const Fixed& b) -{ - return a < b ? a : b; -} - -inline Fixed b2Max(const Fixed& a, const Fixed& b) -{ - return a > b ? a : b; -} - -inline Fixed b2Clamp(Fixed a, Fixed low, Fixed high) -{ - return b2Max(low, b2Min(a, high)); -} - -inline bool b2IsValid(Fixed x) -{ - return true; -} - -#define b2Sqrt(x) sqrt(x) -#define b2Atan2(y, x) atan2(y, x) - -#else +#include +#include /// This function is used to ensure that a floating point number is /// not a NaN or infinity. inline bool b2IsValid(float32 x) { -#ifdef _MSC_VER - return _finite(x) != 0; -#else - return finite(x) != 0; -#endif + if (x != x) + { + // NaN. + return false; + } + + float32 infinity = std::numeric_limits::infinity(); + return -infinity < x && x < infinity; } /// This is a approximate yet fast inverse square-root. @@ -84,15 +60,12 @@ inline float32 b2InvSqrt(float32 x) #define b2Sqrt(x) sqrtf(x) #define b2Atan2(y, x) atan2f(y, x) -#endif - inline float32 b2Abs(float32 a) { return a > 0.0f ? a : -a; } /// A 2D column vector. - struct b2Vec2 { /// Default constructor does nothing (for performance). @@ -110,6 +83,18 @@ struct b2Vec2 /// Negate this vector. b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; } + /// Read from and indexed element. + float32 operator () (int32 i) const + { + return (&x)[i]; + } + + /// Write to an indexed element. + float32& operator () (int32 i) + { + return (&x)[i]; + } + /// Add a vector to this vector. void operator += (const b2Vec2& v) { @@ -131,20 +116,7 @@ struct b2Vec2 /// Get the length of this vector (the norm). float32 Length() const { -#ifdef TARGET_FLOAT32_IS_FIXED - float est = b2Abs(x) + b2Abs(y); - if(est == 0.0f) { - return 0.0; - } else if(est < 0.1) { - return (1.0/256.0) * b2Vec2(x<<8, y<<8).Length(); - } else if(est < 180.0f) { - return b2Sqrt(x * x + y * y); - } else { - return 256.0 * (b2Vec2(x>>8, y>>8).Length()); - } -#else return b2Sqrt(x * x + y * y); -#endif } /// Get the length squared. For performance, use this instead of @@ -155,38 +127,10 @@ struct b2Vec2 } /// Convert this vector into a unit vector. Returns the length. -#ifdef TARGET_FLOAT32_IS_FIXED float32 Normalize() { float32 length = Length(); - if (length < B2_FLT_EPSILON) - { - return 0.0f; - } -#ifdef NORMALIZE_BY_INVERT_MULTIPLY - if (length < (1.0/16.0)) { - x = x << 4; - y = y << 4; - return (1.0/16.0)*Normalize(); - } else if(length > 16.0) { - x = x >> 4; - y = y >> 4; - return 16.0*Normalize(); - } - float32 invLength = 1.0f / length; - x *= invLength; - y *= invLength; -#else - x /= length; - y /= length; -#endif - return length; - } -#else - float32 Normalize() - { - float32 length = Length(); - if (length < B2_FLT_EPSILON) + if (length < b2_epsilon) { return 0.0f; } @@ -196,7 +140,6 @@ struct b2Vec2 return length; } -#endif /// Does this vector contain finite coordinates? bool IsValid() const @@ -207,6 +150,45 @@ struct b2Vec2 float32 x, y; }; +/// A 2D column vector with 3 elements. +struct b2Vec3 +{ + /// Default constructor does nothing (for performance). + b2Vec3() {} + + /// Construct using coordinates. + b2Vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {} + + /// Set this vector to all zeros. + void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; } + + /// Set this vector to some specified coordinates. + void Set(float32 x_, float32 y_, float32 z_) { x = x_; y = y_; z = z_; } + + /// Negate this vector. + b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; } + + /// Add a vector to this vector. + void operator += (const b2Vec3& v) + { + x += v.x; y += v.y; z += v.z; + } + + /// Subtract a vector from this vector. + void operator -= (const b2Vec3& v) + { + x -= v.x; y -= v.y; z -= v.z; + } + + /// Multiply this vector by a scalar. + void operator *= (float32 s) + { + x *= s; y *= s; z *= s; + } + + float32 x, y, z; +}; + /// A 2-by-2 matrix. Stored in column-major order. struct b2Mat22 { @@ -231,6 +213,7 @@ struct b2Mat22 /// an orthonormal rotation matrix. explicit b2Mat22(float32 angle) { + // TODO_ERIN compute sin+cos together. float32 c = cosf(angle), s = sinf(angle); col1.x = c; col2.x = -s; col1.y = s; col2.y = c; @@ -273,79 +256,15 @@ struct b2Mat22 return b2Atan2(col1.y, col1.x); } -#ifdef TARGET_FLOAT32_IS_FIXED - - /// Compute the inverse of this matrix, such that inv(A) * A = identity. - b2Mat22 Invert() const - { - float32 a = col1.x, b = col2.x, c = col1.y, d = col2.y; - float32 det = a * d - b * c; - b2Mat22 B; - int n = 0; - - if(b2Abs(det) <= (B2_FLT_EPSILON<<8)) - { - n = 3; - a = a<= 16.0)? 4 : 0; - b2Assert(det != 0.0f); - det = float32(1<> n; B.col2.x = (-det * b) >> n; - B.col1.y = (-det * c) >> n; B.col2.y = ( det * a) >> n; - } - - return B; - } - - // Solve A * x = b - b2Vec2 Solve(const b2Vec2& b) const - { - float32 a11 = col1.x, a12 = col2.x, a21 = col1.y, a22 = col2.y; - float32 det = a11 * a22 - a12 * a21; - int n = 0; - b2Vec2 x; - - - if(b2Abs(det) <= (B2_FLT_EPSILON<<8)) - { - n = 3; - a11 = col1.x<= 16.0) ? 4 : 0; - b2Assert(det != 0.0f); - det = float32(1<> n; - x.y = (det * (a11 * b.y - a21 * b.x)) >> n; - } - - return x; - } - -#else - b2Mat22 Invert() const + b2Mat22 GetInverse() const { float32 a = col1.x, b = col2.x, c = col1.y, d = col2.y; b2Mat22 B; float32 det = a * d - b * c; - b2Assert(det != 0.0f); - det = float32(1.0f) / det; + if (det != 0.0f) + { + det = 1.0f / det; + } B.col1.x = det * d; B.col2.x = -det * b; B.col1.y = -det * c; B.col2.y = det * a; return B; @@ -357,27 +276,62 @@ struct b2Mat22 { float32 a11 = col1.x, a12 = col2.x, a21 = col1.y, a22 = col2.y; float32 det = a11 * a22 - a12 * a21; - b2Assert(det != 0.0f); - det = 1.0f / det; + if (det != 0.0f) + { + det = 1.0f / det; + } b2Vec2 x; x.x = det * (a22 * b.x - a12 * b.y); x.y = det * (a11 * b.y - a21 * b.x); return x; } -#endif b2Vec2 col1, col2; }; -/// A transform contains translation and rotation. It is used to represent -/// the position and orientation of rigid frames. -struct b2XForm +/// A 3-by-3 matrix. Stored in column-major order. +struct b2Mat33 { /// The default constructor does nothing (for performance). - b2XForm() {} + b2Mat33() {} + + /// Construct this matrix using columns. + b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3) + { + col1 = c1; + col2 = c2; + col3 = c3; + } + + /// Set this matrix to all zeros. + void SetZero() + { + col1.SetZero(); + col2.SetZero(); + col3.SetZero(); + } + + /// Solve A * x = b, where b is a column vector. This is more efficient + /// than computing the inverse in one-shot cases. + b2Vec3 Solve33(const b2Vec3& b) const; + + /// Solve A * x = b, where b is a column vector. This is more efficient + /// than computing the inverse in one-shot cases. Solve only the upper + /// 2-by-2 matrix equation. + b2Vec2 Solve22(const b2Vec2& b) const; + + b2Vec3 col1, col2, col3; +}; + +/// A transform contains translation and rotation. It is used to represent +/// the position and orientation of rigid frames. +struct b2Transform +{ + /// The default constructor does nothing (for performance). + b2Transform() {} /// Initialize using a position vector and a rotation matrix. - b2XForm(const b2Vec2& position, const b2Mat22& R) : position(position), R(R) {} + b2Transform(const b2Vec2& position, const b2Mat22& R) : position(position), R(R) {} /// Set this to the identity transform. void SetIdentity() @@ -386,6 +340,19 @@ struct b2XForm R.SetIdentity(); } + /// Set this based on the position and angle. + void Set(const b2Vec2& p, float32 angle) + { + position = p; + R.Set(angle); + } + + /// Calculate the angle that the rotation matrix represents. + float32 GetAngle() const + { + return b2Atan2(R.col1.y, R.col1.x); + } + b2Vec2 position; b2Mat22 R; }; @@ -397,25 +364,27 @@ struct b2XForm struct b2Sweep { /// Get the interpolated transform at a specific time. - /// @param t the normalized time in [0,1]. - void GetXForm(b2XForm* xf, float32 t) const; + /// @param alpha is a factor in [0,1], where 0 indicates t0. + void GetTransform(b2Transform* xf, float32 alpha) const; /// Advance the sweep forward, yielding a new initial state. /// @param t the new initial time. void Advance(float32 t); + /// Normalize the angles. + void Normalize(); + b2Vec2 localCenter; ///< local center of mass position b2Vec2 c0, c; ///< center world positions float32 a0, a; ///< world angles - float32 t0; ///< time interval = [t0,1], where t0 is in [0,1] }; extern const b2Vec2 b2Vec2_zero; extern const b2Mat22 b2Mat22_identity; -extern const b2XForm b2XForm_identity; +extern const b2Transform b2Transform_identity; -/// Peform the dot product on two vectors. +/// Perform the dot product on two vectors. inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b) { return a.x * b.x + a.y * b.y; @@ -431,54 +400,45 @@ inline float32 b2Cross(const b2Vec2& a, const b2Vec2& b) /// a vector. inline b2Vec2 b2Cross(const b2Vec2& a, float32 s) { - b2Vec2 v; v.Set(s * a.y, -s * a.x); - return v; + return b2Vec2(s * a.y, -s * a.x); } /// Perform the cross product on a scalar and a vector. In 2D this produces /// a vector. inline b2Vec2 b2Cross(float32 s, const b2Vec2& a) { - b2Vec2 v; v.Set(-s * a.y, s * a.x); - return v; + return b2Vec2(-s * a.y, s * a.x); } /// Multiply a matrix times a vector. If a rotation matrix is provided, /// then this transforms the vector from one frame to another. inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v) { - b2Vec2 u; - u.Set(A.col1.x * v.x + A.col2.x * v.y, A.col1.y * v.x + A.col2.y * v.y); - return u; + return b2Vec2(A.col1.x * v.x + A.col2.x * v.y, A.col1.y * v.x + A.col2.y * v.y); } /// Multiply a matrix transpose times a vector. If a rotation matrix is provided, /// then this transforms the vector from one frame to another (inverse transform). inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v) { - b2Vec2 u; - u.Set(b2Dot(v, A.col1), b2Dot(v, A.col2)); - return u; + return b2Vec2(b2Dot(v, A.col1), b2Dot(v, A.col2)); } /// Add two vectors component-wise. inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b) { - b2Vec2 v; v.Set(a.x + b.x, a.y + b.y); - return v; + return b2Vec2(a.x + b.x, a.y + b.y); } /// Subtract two vectors component-wise. inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b) { - b2Vec2 v; v.Set(a.x - b.x, a.y - b.y); - return v; + return b2Vec2(a.x - b.x, a.y - b.y); } inline b2Vec2 operator * (float32 s, const b2Vec2& a) { - b2Vec2 v; v.Set(s * a.x, s * a.y); - return v; + return b2Vec2(s * a.x, s * a.y); } inline bool operator == (const b2Vec2& a, const b2Vec2& b) @@ -498,52 +458,81 @@ inline float32 b2DistanceSquared(const b2Vec2& a, const b2Vec2& b) return b2Dot(c, c); } +inline b2Vec3 operator * (float32 s, const b2Vec3& a) +{ + return b2Vec3(s * a.x, s * a.y, s * a.z); +} + +/// Add two vectors component-wise. +inline b2Vec3 operator + (const b2Vec3& a, const b2Vec3& b) +{ + return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z); +} + +/// Subtract two vectors component-wise. +inline b2Vec3 operator - (const b2Vec3& a, const b2Vec3& b) +{ + return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z); +} + +/// Perform the dot product on two vectors. +inline float32 b2Dot(const b2Vec3& a, const b2Vec3& b) +{ + return a.x * b.x + a.y * b.y + a.z * b.z; +} + +/// Perform the cross product on two vectors. +inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b) +{ + return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); +} + inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B) { - b2Mat22 C; - C.Set(A.col1 + B.col1, A.col2 + B.col2); - return C; + return b2Mat22(A.col1 + B.col1, A.col2 + B.col2); } // A * B inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B) { - b2Mat22 C; - C.Set(b2Mul(A, B.col1), b2Mul(A, B.col2)); - return C; + return b2Mat22(b2Mul(A, B.col1), b2Mul(A, B.col2)); } // A^T * B inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B) { - b2Vec2 c1; c1.Set(b2Dot(A.col1, B.col1), b2Dot(A.col2, B.col1)); - b2Vec2 c2; c2.Set(b2Dot(A.col1, B.col2), b2Dot(A.col2, B.col2)); - b2Mat22 C; - C.Set(c1, c2); - return C; + b2Vec2 c1(b2Dot(A.col1, B.col1), b2Dot(A.col2, B.col1)); + b2Vec2 c2(b2Dot(A.col1, B.col2), b2Dot(A.col2, B.col2)); + return b2Mat22(c1, c2); } -inline b2Vec2 b2Mul(const b2XForm& T, const b2Vec2& v) +/// Multiply a matrix times a vector. +inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v) { - return T.position + b2Mul(T.R, v); + return v.x * A.col1 + v.y * A.col2 + v.z * A.col3; } -inline b2Vec2 b2MulT(const b2XForm& T, const b2Vec2& v) +inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v) +{ + float32 x = T.position.x + T.R.col1.x * v.x + T.R.col2.x * v.y; + float32 y = T.position.y + T.R.col1.y * v.x + T.R.col2.y * v.y; + + return b2Vec2(x, y); +} + +inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v) { return b2MulT(T.R, v - T.position); } inline b2Vec2 b2Abs(const b2Vec2& a) { - b2Vec2 b; b.Set(b2Abs(a.x), b2Abs(a.y)); - return b; + return b2Vec2(b2Abs(a.x), b2Abs(a.y)); } inline b2Mat22 b2Abs(const b2Mat22& A) { - b2Mat22 B; - B.Set(b2Abs(A.col1), b2Abs(A.col2)); - return B; + return b2Mat22(b2Abs(A.col1), b2Abs(A.col2)); } template @@ -554,10 +543,7 @@ inline T b2Min(T a, T b) inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b) { - b2Vec2 c; - c.x = b2Min(a.x, b.x); - c.y = b2Min(a.y, b.y); - return c; + return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y)); } template @@ -568,10 +554,7 @@ inline T b2Max(T a, T b) inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b) { - b2Vec2 c; - c.x = b2Max(a.x, b.x); - c.y = b2Max(a.y, b.y); - return c; + return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y)); } template @@ -592,26 +575,6 @@ template inline void b2Swap(T& a, T& b) b = tmp; } -#define RAND_LIMIT 32767 - -// Random number in range [-1,1] -inline float32 b2Random() -{ - float32 r = (float32)(rand() & (RAND_LIMIT)); - r /= RAND_LIMIT; - r = 2.0f * r - 1.0f; - return r; -} - -/// Random floating point number in range [lo, hi] -inline float32 b2Random(float32 lo, float32 hi) -{ - float32 r = (float32)(rand() & (RAND_LIMIT)); - r /= RAND_LIMIT; - r = (hi - lo) * r + lo; - return r; -} - /// "Next Largest Power of 2 /// Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm /// that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with @@ -633,4 +596,29 @@ inline bool b2IsPowerOfTwo(uint32 x) return result; } +inline void b2Sweep::GetTransform(b2Transform* xf, float32 alpha) const +{ + xf->position = (1.0f - alpha) * c0 + alpha * c; + float32 angle = (1.0f - alpha) * a0 + alpha * a; + xf->R.Set(angle); + + // Shift to origin + xf->position -= b2Mul(xf->R, localCenter); +} + +inline void b2Sweep::Advance(float32 t) +{ + c0 = (1.0f - t) * c0 + t * c; + a0 = (1.0f - t) * a0 + t * a; +} + +/// Normalize an angle in radians to be between -pi and pi +inline void b2Sweep::Normalize() +{ + float32 twoPi = 2.0f * b2_pi; + float32 d = twoPi * floorf(a0 / twoPi); + a0 -= d; + a -= d; +} + #endif diff --git a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2NullContact.h b/src/modules/physics/box2d/Box2D/Common/b2Settings.cpp similarity index 70% rename from src/modules/physics/box2d/Source/Dynamics/Contacts/b2NullContact.h rename to src/modules/physics/box2d/Box2D/Common/b2Settings.cpp index ce62d8b0b..da308149f 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2NullContact.h +++ b/src/modules/physics/box2d/Box2D/Common/b2Settings.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -16,18 +16,18 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#ifndef B2_NULL_CONTACT_H -#define B2_NULL_CONTACT_H +#include +#include -#include "../../Common/b2Math.h" -#include "b2Contact.h" +b2Version b2_version = {2, 1, 2}; -class b2NullContact : public b2Contact +// Memory allocators. Modify these to use your own allocator. +void* b2Alloc(int32 size) { -public: - b2NullContact() {} - void Evaluate(b2ContactListener*) {} - b2Manifold* GetManifolds() { return NULL; } -}; + return malloc(size); +} -#endif +void b2Free(void* mem) +{ + free(mem); +} diff --git a/src/modules/physics/box2d/Source/Common/b2Settings.h b/src/modules/physics/box2d/Box2D/Common/b2Settings.h similarity index 57% rename from src/modules/physics/box2d/Source/Common/b2Settings.h rename to src/modules/physics/box2d/Box2D/Common/b2Settings.h index 22866b0ef..1aa8c2661 100644 --- a/src/modules/physics/box2d/Source/Common/b2Settings.h +++ b/src/modules/physics/box2d/Box2D/Common/b2Settings.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -19,23 +19,11 @@ #ifndef B2_SETTINGS_H #define B2_SETTINGS_H -#include -//#include +#include #include -#define B2_NOT_USED(x) x +#define B2_NOT_USED(x) ((void)(x)) #define b2Assert(A) assert(A) -//#define b2Assert(A) {if(!(A)) throw love::Exception("Box2D error: " #A);} - - -// need to include NDS jtypes.h instead of -// usual typedefs because NDS jtypes defines -// them slightly differently, oh well. -#ifdef TARGET_IS_NDS - -#include "jtypes.h" - -#else typedef signed char int8; typedef signed short int16; @@ -43,108 +31,93 @@ typedef signed int int32; typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned int uint32; - -#endif - -#ifdef TARGET_FLOAT32_IS_FIXED - -#include "Fixed.h" - -typedef Fixed float32; -#define B2_FLT_MAX FIXED_MAX -#define B2_FLT_EPSILON FIXED_EPSILON -#define B2FORCE_SCALE(x) ((x)<<7) -#define B2FORCE_INV_SCALE(x) ((x)>>7) - -#else - typedef float float32; -#define B2_FLT_MAX FLT_MAX -#define B2_FLT_EPSILON FLT_EPSILON -#define B2FORCE_SCALE(x) (x) -#define B2FORCE_INV_SCALE(x) (x) -#endif - -const float32 b2_pi = 3.14159265359f; +#define b2_maxFloat FLT_MAX +#define b2_epsilon FLT_EPSILON +#define b2_pi 3.14159265359f /// @file /// Global tuning constants based on meters-kilograms-seconds (MKS) units. /// // Collision -const int32 b2_maxManifoldPoints = 2; -const int32 b2_maxPolygonVertices = 8; -const int32 b2_maxProxies = 2048; // this must be a power of two -const int32 b2_maxPairs = 8 * b2_maxProxies; // this must be a power of two -// Dynamics +/// The maximum number of contact points between two convex shapes. +#define b2_maxManifoldPoints 2 + +/// The maximum number of vertices on a convex polygon. +#define b2_maxPolygonVertices 8 + +/// This is used to fatten AABBs in the dynamic tree. This allows proxies +/// to move by a small amount without triggering a tree adjustment. +/// This is in meters. +#define b2_aabbExtension 0.1f + +/// This is used to fatten AABBs in the dynamic tree. This is used to predict +/// the future position based on the current displacement. +/// This is a dimensionless multiplier. +#define b2_aabbMultiplier 2.0f /// A small length used as a collision and constraint tolerance. Usually it is /// chosen to be numerically significant, but visually insignificant. -const float32 b2_linearSlop = 0.005f; // 0.5 cm +#define b2_linearSlop 0.005f /// A small angle used as a collision and constraint tolerance. Usually it is /// chosen to be numerically significant, but visually insignificant. -const float32 b2_angularSlop = 2.0f / 180.0f * b2_pi; // 2 degrees +#define b2_angularSlop (2.0f / 180.0f * b2_pi) -/// Continuous collision detection (CCD) works with core, shrunken shapes. This is the -/// amount by which shapes are automatically shrunk to work with CCD. This must be -/// larger than b2_linearSlop. -const float32 b2_toiSlop = 8.0f * b2_linearSlop; +/// The radius of the polygon/edge shape skin. This should not be modified. Making +/// this smaller means polygons will have an insufficient buffer for continuous collision. +/// Making it larger may create artifacts for vertex collision. +#define b2_polygonRadius (2.0f * b2_linearSlop) -/// Maximum number of contacts to be handled to solve a TOI island. -const int32 b2_maxTOIContactsPerIsland = 32; + +// Dynamics + +/// Maximum number of contacts to be handled to solve a TOI impact. +#define b2_maxTOIContacts 32 /// A velocity threshold for elastic collisions. Any collision with a relative linear /// velocity below this threshold will be treated as inelastic. -const float32 b2_velocityThreshold = 1.0f; // 1 m/s +#define b2_velocityThreshold 1.0f /// The maximum linear position correction used when solving constraints. This helps to /// prevent overshoot. -const float32 b2_maxLinearCorrection = 0.2f; // 20 cm +#define b2_maxLinearCorrection 0.2f /// The maximum angular position correction used when solving constraints. This helps to /// prevent overshoot. -const float32 b2_maxAngularCorrection = 8.0f / 180.0f * b2_pi; // 8 degrees +#define b2_maxAngularCorrection (8.0f / 180.0f * b2_pi) /// The maximum linear velocity of a body. This limit is very large and is used /// to prevent numerical problems. You shouldn't need to adjust this. -#ifdef TARGET_FLOAT32_IS_FIXED -const float32 b2_maxLinearVelocity = 100.0f; -#else -const float32 b2_maxLinearVelocity = 200.0f; -const float32 b2_maxLinearVelocitySquared = b2_maxLinearVelocity * b2_maxLinearVelocity; -#endif +#define b2_maxTranslation 2.0f +#define b2_maxTranslationSquared (b2_maxTranslation * b2_maxTranslation) /// The maximum angular velocity of a body. This limit is very large and is used /// to prevent numerical problems. You shouldn't need to adjust this. -const float32 b2_maxAngularVelocity = 250.0f; -#ifndef TARGET_FLOAT32_IS_FIXED -const float32 b2_maxAngularVelocitySquared = b2_maxAngularVelocity * b2_maxAngularVelocity; -#endif +#define b2_maxRotation (0.5f * b2_pi) +#define b2_maxRotationSquared (b2_maxRotation * b2_maxRotation) /// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so /// that overlap is removed in one time step. However using values close to 1 often lead /// to overshoot. -const float32 b2_contactBaumgarte = 0.2f; +#define b2_contactBaumgarte 0.2f // Sleep /// The time that a body must be still before it will go to sleep. -const float32 b2_timeToSleep = 0.5f; // half a second +#define b2_timeToSleep 0.5f /// A body cannot sleep if its linear velocity is above this tolerance. -const float32 b2_linearSleepTolerance = 0.01f; // 1 cm/s +#define b2_linearSleepTolerance 0.01f /// A body cannot sleep if its angular velocity is above this tolerance. -const float32 b2_angularSleepTolerance = 2.0f / 180.0f; // 2 degrees/s +#define b2_angularSleepTolerance (2.0f / 180.0f * b2_pi) // Memory Allocation -/// The current number of bytes allocated through b2Alloc. -extern int32 b2_byteCount; - /// Implement this function to use your own memory allocator. void* b2Alloc(int32 size); diff --git a/src/modules/physics/box2d/Source/Common/b2StackAllocator.cpp b/src/modules/physics/box2d/Box2D/Common/b2StackAllocator.cpp similarity index 89% rename from src/modules/physics/box2d/Source/Common/b2StackAllocator.cpp rename to src/modules/physics/box2d/Box2D/Common/b2StackAllocator.cpp index c58c97af0..cb2c42e01 100644 --- a/src/modules/physics/box2d/Source/Common/b2StackAllocator.cpp +++ b/src/modules/physics/box2d/Box2D/Common/b2StackAllocator.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -16,8 +16,8 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#include "b2StackAllocator.h" -#include "b2Math.h" +#include +#include b2StackAllocator::b2StackAllocator() { diff --git a/src/modules/physics/box2d/Source/Common/b2StackAllocator.h b/src/modules/physics/box2d/Box2D/Common/b2StackAllocator.h similarity index 90% rename from src/modules/physics/box2d/Source/Common/b2StackAllocator.h rename to src/modules/physics/box2d/Box2D/Common/b2StackAllocator.h index e8faa840b..315cc02ff 100644 --- a/src/modules/physics/box2d/Source/Common/b2StackAllocator.h +++ b/src/modules/physics/box2d/Box2D/Common/b2StackAllocator.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -19,7 +19,7 @@ #ifndef B2_STACK_ALLOCATOR_H #define B2_STACK_ALLOCATOR_H -#include "b2Settings.h" +#include const int32 b2_stackSize = 100 * 1024; // 100k const int32 b2_maxStackEntries = 32; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.cpp new file mode 100644 index 000000000..6df009125 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.cpp @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include + +#include + +b2Contact* b2CircleContact::Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2CircleContact)); + return new (mem) b2CircleContact(fixtureA, fixtureB); +} + +void b2CircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2CircleContact*)contact)->~b2CircleContact(); + allocator->Free(contact, sizeof(b2CircleContact)); +} + +b2CircleContact::b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) + : b2Contact(fixtureA, fixtureB) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_circle); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); +} + +void b2CircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollideCircles(manifold, + (b2CircleShape*)m_fixtureA->GetShape(), xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2CircleContact.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.h similarity index 66% rename from src/modules/physics/box2d/Source/Dynamics/Contacts/b2CircleContact.h rename to src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.h index ba2afbdcf..afc277aa0 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2CircleContact.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -16,31 +16,23 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#ifndef CIRCLE_CONTACT_H -#define CIRCLE_CONTACT_H +#ifndef B2_CIRCLE_CONTACT_H +#define B2_CIRCLE_CONTACT_H -#include "../../Common/b2Math.h" -#include "../../Collision/b2Collision.h" -#include "b2Contact.h" +#include class b2BlockAllocator; class b2CircleContact : public b2Contact { public: - static b2Contact* Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator); + static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator); static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - b2CircleContact(b2Shape* shape1, b2Shape* shape2); + b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); ~b2CircleContact() {} - void Evaluate(b2ContactListener* listener); - b2Manifold* GetManifolds() - { - return &m_manifold; - } - - b2Manifold m_manifold; + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); }; #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp new file mode 100644 index 000000000..e7ad1ca5b --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp @@ -0,0 +1,226 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +b2ContactRegister b2Contact::s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; +bool b2Contact::s_initialized = false; + +void b2Contact::InitializeRegisters() +{ + AddType(b2CircleContact::Create, b2CircleContact::Destroy, b2Shape::e_circle, b2Shape::e_circle); + AddType(b2PolygonAndCircleContact::Create, b2PolygonAndCircleContact::Destroy, b2Shape::e_polygon, b2Shape::e_circle); + AddType(b2PolygonContact::Create, b2PolygonContact::Destroy, b2Shape::e_polygon, b2Shape::e_polygon); +} + +void b2Contact::AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destoryFcn, + b2Shape::Type type1, b2Shape::Type type2) +{ + b2Assert(b2Shape::e_unknown < type1 && type1 < b2Shape::e_typeCount); + b2Assert(b2Shape::e_unknown < type2 && type2 < b2Shape::e_typeCount); + + s_registers[type1][type2].createFcn = createFcn; + s_registers[type1][type2].destroyFcn = destoryFcn; + s_registers[type1][type2].primary = true; + + if (type1 != type2) + { + s_registers[type2][type1].createFcn = createFcn; + s_registers[type2][type1].destroyFcn = destoryFcn; + s_registers[type2][type1].primary = false; + } +} + +b2Contact* b2Contact::Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator) +{ + if (s_initialized == false) + { + InitializeRegisters(); + s_initialized = true; + } + + b2Shape::Type type1 = fixtureA->GetType(); + b2Shape::Type type2 = fixtureB->GetType(); + + b2Assert(b2Shape::e_unknown < type1 && type1 < b2Shape::e_typeCount); + b2Assert(b2Shape::e_unknown < type2 && type2 < b2Shape::e_typeCount); + + b2ContactCreateFcn* createFcn = s_registers[type1][type2].createFcn; + if (createFcn) + { + if (s_registers[type1][type2].primary) + { + return createFcn(fixtureA, fixtureB, allocator); + } + else + { + return createFcn(fixtureB, fixtureA, allocator); + } + } + else + { + return NULL; + } +} + +void b2Contact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + b2Assert(s_initialized == true); + + if (contact->m_manifold.pointCount > 0) + { + contact->GetFixtureA()->GetBody()->SetAwake(true); + contact->GetFixtureB()->GetBody()->SetAwake(true); + } + + b2Shape::Type typeA = contact->GetFixtureA()->GetType(); + b2Shape::Type typeB = contact->GetFixtureB()->GetType(); + + b2Assert(b2Shape::e_unknown < typeA && typeB < b2Shape::e_typeCount); + b2Assert(b2Shape::e_unknown < typeA && typeB < b2Shape::e_typeCount); + + b2ContactDestroyFcn* destroyFcn = s_registers[typeA][typeB].destroyFcn; + destroyFcn(contact, allocator); +} + +b2Contact::b2Contact(b2Fixture* fA, b2Fixture* fB) +{ + m_flags = e_enabledFlag; + + m_fixtureA = fA; + m_fixtureB = fB; + + m_manifold.pointCount = 0; + + m_prev = NULL; + m_next = NULL; + + m_nodeA.contact = NULL; + m_nodeA.prev = NULL; + m_nodeA.next = NULL; + m_nodeA.other = NULL; + + m_nodeB.contact = NULL; + m_nodeB.prev = NULL; + m_nodeB.next = NULL; + m_nodeB.other = NULL; + + m_toiCount = 0; +} + +// Update the contact manifold and touching status. +// Note: do not assume the fixture AABBs are overlapping or are valid. +void b2Contact::Update(b2ContactListener* listener) +{ + b2Manifold oldManifold = m_manifold; + + // Re-enable this contact. + m_flags |= e_enabledFlag; + + bool touching = false; + bool wasTouching = (m_flags & e_touchingFlag) == e_touchingFlag; + + bool sensorA = m_fixtureA->IsSensor(); + bool sensorB = m_fixtureB->IsSensor(); + bool sensor = sensorA || sensorB; + + b2Body* bodyA = m_fixtureA->GetBody(); + b2Body* bodyB = m_fixtureB->GetBody(); + const b2Transform& xfA = bodyA->GetTransform(); + const b2Transform& xfB = bodyB->GetTransform(); + + // Is this contact a sensor? + if (sensor) + { + const b2Shape* shapeA = m_fixtureA->GetShape(); + const b2Shape* shapeB = m_fixtureB->GetShape(); + touching = b2TestOverlap(shapeA, shapeB, xfA, xfB); + + // Sensors don't generate manifolds. + m_manifold.pointCount = 0; + } + else + { + Evaluate(&m_manifold, xfA, xfB); + touching = m_manifold.pointCount > 0; + + // Match old contact ids to new contact ids and copy the + // stored impulses to warm start the solver. + for (int32 i = 0; i < m_manifold.pointCount; ++i) + { + b2ManifoldPoint* mp2 = m_manifold.points + i; + mp2->normalImpulse = 0.0f; + mp2->tangentImpulse = 0.0f; + b2ContactID id2 = mp2->id; + + for (int32 j = 0; j < oldManifold.pointCount; ++j) + { + b2ManifoldPoint* mp1 = oldManifold.points + j; + + if (mp1->id.key == id2.key) + { + mp2->normalImpulse = mp1->normalImpulse; + mp2->tangentImpulse = mp1->tangentImpulse; + break; + } + } + } + + if (touching != wasTouching) + { + bodyA->SetAwake(true); + bodyB->SetAwake(true); + } + } + + if (touching) + { + m_flags |= e_touchingFlag; + } + else + { + m_flags &= ~e_touchingFlag; + } + + if (wasTouching == false && touching == true && listener) + { + listener->BeginContact(this); + } + + if (wasTouching == true && touching == false && listener) + { + listener->EndContact(this); + } + + if (sensor == false && touching && listener) + { + listener->PreSolve(this, &oldManifold); + } +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.h new file mode 100644 index 000000000..a6add3dc4 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.h @@ -0,0 +1,242 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CONTACT_H +#define B2_CONTACT_H + +#include +#include +#include +#include +#include + +class b2Body; +class b2Contact; +class b2Fixture; +class b2World; +class b2BlockAllocator; +class b2StackAllocator; +class b2ContactListener; + +typedef b2Contact* b2ContactCreateFcn(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator); +typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator); + +struct b2ContactRegister +{ + b2ContactCreateFcn* createFcn; + b2ContactDestroyFcn* destroyFcn; + bool primary; +}; + +/// A contact edge is used to connect bodies and contacts together +/// in a contact graph where each body is a node and each contact +/// is an edge. A contact edge belongs to a doubly linked list +/// maintained in each attached body. Each contact has two contact +/// nodes, one for each attached body. +struct b2ContactEdge +{ + b2Body* other; ///< provides quick access to the other body attached. + b2Contact* contact; ///< the contact + b2ContactEdge* prev; ///< the previous contact edge in the body's contact list + b2ContactEdge* next; ///< the next contact edge in the body's contact list +}; + +/// The class manages contact between two shapes. A contact exists for each overlapping +/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist +/// that has no contact points. +class b2Contact +{ +public: + + /// Get the contact manifold. Do not modify the manifold unless you understand the + /// internals of Box2D. + b2Manifold* GetManifold(); + const b2Manifold* GetManifold() const; + + /// Get the world manifold. + void GetWorldManifold(b2WorldManifold* worldManifold) const; + + /// Is this contact touching? + bool IsTouching() const; + + /// Enable/disable this contact. This can be used inside the pre-solve + /// contact listener. The contact is only disabled for the current + /// time step (or sub-step in continuous collisions). + void SetEnabled(bool flag); + + /// Has this contact been disabled? + bool IsEnabled() const; + + /// Get the next contact in the world's contact list. + b2Contact* GetNext(); + const b2Contact* GetNext() const; + + /// Get the first fixture in this contact. + b2Fixture* GetFixtureA(); + const b2Fixture* GetFixtureA() const; + + /// Get the second fixture in this contact. + b2Fixture* GetFixtureB(); + const b2Fixture* GetFixtureB() const; + + /// Evaluate this contact with your own manifold and transforms. + virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) = 0; + +protected: + friend class b2ContactManager; + friend class b2World; + friend class b2ContactSolver; + friend class b2Body; + friend class b2Fixture; + + // Flags stored in m_flags + enum + { + // Used when crawling contact graph when forming islands. + e_islandFlag = 0x0001, + + // Set when the shapes are touching. + e_touchingFlag = 0x0002, + + // This contact can be disabled (by user) + e_enabledFlag = 0x0004, + + // This contact needs filtering because a fixture filter was changed. + e_filterFlag = 0x0008, + + // This bullet contact had a TOI event + e_bulletHitFlag = 0x0010, + + }; + + /// Flag this contact for filtering. Filtering will occur the next time step. + void FlagForFiltering(); + + static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn, + b2Shape::Type typeA, b2Shape::Type typeB); + static void InitializeRegisters(); + static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::Type typeB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2Contact() : m_fixtureA(NULL), m_fixtureB(NULL) {} + b2Contact(b2Fixture* fixtureA, b2Fixture* fixtureB); + virtual ~b2Contact() {} + + void Update(b2ContactListener* listener); + + static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; + static bool s_initialized; + + uint32 m_flags; + + // World pool and list pointers. + b2Contact* m_prev; + b2Contact* m_next; + + // Nodes for connecting bodies. + b2ContactEdge m_nodeA; + b2ContactEdge m_nodeB; + + b2Fixture* m_fixtureA; + b2Fixture* m_fixtureB; + + b2Manifold m_manifold; + + int32 m_toiCount; +// float32 m_toi; +}; + +inline b2Manifold* b2Contact::GetManifold() +{ + return &m_manifold; +} + +inline const b2Manifold* b2Contact::GetManifold() const +{ + return &m_manifold; +} + +inline void b2Contact::GetWorldManifold(b2WorldManifold* worldManifold) const +{ + const b2Body* bodyA = m_fixtureA->GetBody(); + const b2Body* bodyB = m_fixtureB->GetBody(); + const b2Shape* shapeA = m_fixtureA->GetShape(); + const b2Shape* shapeB = m_fixtureB->GetShape(); + + worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA->m_radius, bodyB->GetTransform(), shapeB->m_radius); +} + +inline void b2Contact::SetEnabled(bool flag) +{ + if (flag) + { + m_flags |= e_enabledFlag; + } + else + { + m_flags &= ~e_enabledFlag; + } +} + +inline bool b2Contact::IsEnabled() const +{ + return (m_flags & e_enabledFlag) == e_enabledFlag; +} + +inline bool b2Contact::IsTouching() const +{ + return (m_flags & e_touchingFlag) == e_touchingFlag; +} + +inline b2Contact* b2Contact::GetNext() +{ + return m_next; +} + +inline const b2Contact* b2Contact::GetNext() const +{ + return m_next; +} + +inline b2Fixture* b2Contact::GetFixtureA() +{ + return m_fixtureA; +} + +inline const b2Fixture* b2Contact::GetFixtureA() const +{ + return m_fixtureA; +} + +inline b2Fixture* b2Contact::GetFixtureB() +{ + return m_fixtureB; +} + +inline const b2Fixture* b2Contact::GetFixtureB() const +{ + return m_fixtureB; +} + +inline void b2Contact::FlagForFiltering() +{ + m_flags |= e_filterFlag; +} + +#endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.cpp new file mode 100644 index 000000000..f65fb60ee --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.cpp @@ -0,0 +1,623 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include + +#define B2_DEBUG_SOLVER 0 + +b2ContactSolver::b2ContactSolver(b2Contact** contacts, int32 contactCount, + b2StackAllocator* allocator, float32 impulseRatio) +{ + m_allocator = allocator; + + m_constraintCount = contactCount; + m_constraints = (b2ContactConstraint*)m_allocator->Allocate(m_constraintCount * sizeof(b2ContactConstraint)); + + for (int32 i = 0; i < m_constraintCount; ++i) + { + b2Contact* contact = contacts[i]; + + b2Fixture* fixtureA = contact->m_fixtureA; + b2Fixture* fixtureB = contact->m_fixtureB; + b2Shape* shapeA = fixtureA->GetShape(); + b2Shape* shapeB = fixtureB->GetShape(); + float32 radiusA = shapeA->m_radius; + float32 radiusB = shapeB->m_radius; + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + b2Manifold* manifold = contact->GetManifold(); + + float32 friction = b2MixFriction(fixtureA->GetFriction(), fixtureB->GetFriction()); + float32 restitution = b2MixRestitution(fixtureA->GetRestitution(), fixtureB->GetRestitution()); + + b2Vec2 vA = bodyA->m_linearVelocity; + b2Vec2 vB = bodyB->m_linearVelocity; + float32 wA = bodyA->m_angularVelocity; + float32 wB = bodyB->m_angularVelocity; + + b2Assert(manifold->pointCount > 0); + + b2WorldManifold worldManifold; + worldManifold.Initialize(manifold, bodyA->m_xf, radiusA, bodyB->m_xf, radiusB); + + b2ContactConstraint* cc = m_constraints + i; + cc->bodyA = bodyA; + cc->bodyB = bodyB; + cc->manifold = manifold; + cc->normal = worldManifold.normal; + cc->pointCount = manifold->pointCount; + cc->friction = friction; + + cc->localNormal = manifold->localNormal; + cc->localPoint = manifold->localPoint; + cc->radius = radiusA + radiusB; + cc->type = manifold->type; + + for (int32 j = 0; j < cc->pointCount; ++j) + { + b2ManifoldPoint* cp = manifold->points + j; + b2ContactConstraintPoint* ccp = cc->points + j; + + ccp->normalImpulse = impulseRatio * cp->normalImpulse; + ccp->tangentImpulse = impulseRatio * cp->tangentImpulse; + + ccp->localPoint = cp->localPoint; + + ccp->rA = worldManifold.points[j] - bodyA->m_sweep.c; + ccp->rB = worldManifold.points[j] - bodyB->m_sweep.c; + + float32 rnA = b2Cross(ccp->rA, cc->normal); + float32 rnB = b2Cross(ccp->rB, cc->normal); + rnA *= rnA; + rnB *= rnB; + + float32 kNormal = bodyA->m_invMass + bodyB->m_invMass + bodyA->m_invI * rnA + bodyB->m_invI * rnB; + + b2Assert(kNormal > b2_epsilon); + ccp->normalMass = 1.0f / kNormal; + + b2Vec2 tangent = b2Cross(cc->normal, 1.0f); + + float32 rtA = b2Cross(ccp->rA, tangent); + float32 rtB = b2Cross(ccp->rB, tangent); + rtA *= rtA; + rtB *= rtB; + + float32 kTangent = bodyA->m_invMass + bodyB->m_invMass + bodyA->m_invI * rtA + bodyB->m_invI * rtB; + + b2Assert(kTangent > b2_epsilon); + ccp->tangentMass = 1.0f / kTangent; + + // Setup a velocity bias for restitution. + ccp->velocityBias = 0.0f; + float32 vRel = b2Dot(cc->normal, vB + b2Cross(wB, ccp->rB) - vA - b2Cross(wA, ccp->rA)); + if (vRel < -b2_velocityThreshold) + { + ccp->velocityBias = -restitution * vRel; + } + } + + // If we have two points, then prepare the block solver. + if (cc->pointCount == 2) + { + b2ContactConstraintPoint* ccp1 = cc->points + 0; + b2ContactConstraintPoint* ccp2 = cc->points + 1; + + float32 invMassA = bodyA->m_invMass; + float32 invIA = bodyA->m_invI; + float32 invMassB = bodyB->m_invMass; + float32 invIB = bodyB->m_invI; + + float32 rn1A = b2Cross(ccp1->rA, cc->normal); + float32 rn1B = b2Cross(ccp1->rB, cc->normal); + float32 rn2A = b2Cross(ccp2->rA, cc->normal); + float32 rn2B = b2Cross(ccp2->rB, cc->normal); + + float32 k11 = invMassA + invMassB + invIA * rn1A * rn1A + invIB * rn1B * rn1B; + float32 k22 = invMassA + invMassB + invIA * rn2A * rn2A + invIB * rn2B * rn2B; + float32 k12 = invMassA + invMassB + invIA * rn1A * rn2A + invIB * rn1B * rn2B; + + // Ensure a reasonable condition number. + const float32 k_maxConditionNumber = 100.0f; + if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) + { + // K is safe to invert. + cc->K.col1.Set(k11, k12); + cc->K.col2.Set(k12, k22); + cc->normalMass = cc->K.GetInverse(); + } + else + { + // The constraints are redundant, just use one. + // TODO_ERIN use deepest? + cc->pointCount = 1; + } + } + } +} + +b2ContactSolver::~b2ContactSolver() +{ + m_allocator->Free(m_constraints); +} + +void b2ContactSolver::WarmStart() +{ + // Warm start. + for (int32 i = 0; i < m_constraintCount; ++i) + { + b2ContactConstraint* c = m_constraints + i; + + b2Body* bodyA = c->bodyA; + b2Body* bodyB = c->bodyB; + float32 invMassA = bodyA->m_invMass; + float32 invIA = bodyA->m_invI; + float32 invMassB = bodyB->m_invMass; + float32 invIB = bodyB->m_invI; + b2Vec2 normal = c->normal; + b2Vec2 tangent = b2Cross(normal, 1.0f); + + for (int32 j = 0; j < c->pointCount; ++j) + { + b2ContactConstraintPoint* ccp = c->points + j; + b2Vec2 P = ccp->normalImpulse * normal + ccp->tangentImpulse * tangent; + bodyA->m_angularVelocity -= invIA * b2Cross(ccp->rA, P); + bodyA->m_linearVelocity -= invMassA * P; + bodyB->m_angularVelocity += invIB * b2Cross(ccp->rB, P); + bodyB->m_linearVelocity += invMassB * P; + } + } +} + +void b2ContactSolver::SolveVelocityConstraints() +{ + for (int32 i = 0; i < m_constraintCount; ++i) + { + b2ContactConstraint* c = m_constraints + i; + b2Body* bodyA = c->bodyA; + b2Body* bodyB = c->bodyB; + float32 wA = bodyA->m_angularVelocity; + float32 wB = bodyB->m_angularVelocity; + b2Vec2 vA = bodyA->m_linearVelocity; + b2Vec2 vB = bodyB->m_linearVelocity; + float32 invMassA = bodyA->m_invMass; + float32 invIA = bodyA->m_invI; + float32 invMassB = bodyB->m_invMass; + float32 invIB = bodyB->m_invI; + b2Vec2 normal = c->normal; + b2Vec2 tangent = b2Cross(normal, 1.0f); + float32 friction = c->friction; + + b2Assert(c->pointCount == 1 || c->pointCount == 2); + + // Solve tangent constraints + for (int32 j = 0; j < c->pointCount; ++j) + { + b2ContactConstraintPoint* ccp = c->points + j; + + // Relative velocity at contact + b2Vec2 dv = vB + b2Cross(wB, ccp->rB) - vA - b2Cross(wA, ccp->rA); + + // Compute tangent force + float32 vt = b2Dot(dv, tangent); + float32 lambda = ccp->tangentMass * (-vt); + + // b2Clamp the accumulated force + float32 maxFriction = friction * ccp->normalImpulse; + float32 newImpulse = b2Clamp(ccp->tangentImpulse + lambda, -maxFriction, maxFriction); + lambda = newImpulse - ccp->tangentImpulse; + + // Apply contact impulse + b2Vec2 P = lambda * tangent; + + vA -= invMassA * P; + wA -= invIA * b2Cross(ccp->rA, P); + + vB += invMassB * P; + wB += invIB * b2Cross(ccp->rB, P); + + ccp->tangentImpulse = newImpulse; + } + + // Solve normal constraints + if (c->pointCount == 1) + { + b2ContactConstraintPoint* ccp = c->points + 0; + + // Relative velocity at contact + b2Vec2 dv = vB + b2Cross(wB, ccp->rB) - vA - b2Cross(wA, ccp->rA); + + // Compute normal impulse + float32 vn = b2Dot(dv, normal); + float32 lambda = -ccp->normalMass * (vn - ccp->velocityBias); + + // b2Clamp the accumulated impulse + float32 newImpulse = b2Max(ccp->normalImpulse + lambda, 0.0f); + lambda = newImpulse - ccp->normalImpulse; + + // Apply contact impulse + b2Vec2 P = lambda * normal; + vA -= invMassA * P; + wA -= invIA * b2Cross(ccp->rA, P); + + vB += invMassB * P; + wB += invIB * b2Cross(ccp->rB, P); + ccp->normalImpulse = newImpulse; + } + else + { + // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite). + // Build the mini LCP for this contact patch + // + // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2 + // + // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) + // b = vn_0 - velocityBias + // + // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i + // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases + // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid + // solution that satisfies the problem is chosen. + // + // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires + // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i). + // + // Substitute: + // + // x = x' - a + // + // Plug into above equation: + // + // vn = A * x + b + // = A * (x' - a) + b + // = A * x' + b - A * a + // = A * x' + b' + // b' = b - A * a; + + b2ContactConstraintPoint* cp1 = c->points + 0; + b2ContactConstraintPoint* cp2 = c->points + 1; + + b2Vec2 a(cp1->normalImpulse, cp2->normalImpulse); + b2Assert(a.x >= 0.0f && a.y >= 0.0f); + + // Relative velocity at contact + b2Vec2 dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); + b2Vec2 dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); + + // Compute normal velocity + float32 vn1 = b2Dot(dv1, normal); + float32 vn2 = b2Dot(dv2, normal); + + b2Vec2 b; + b.x = vn1 - cp1->velocityBias; + b.y = vn2 - cp2->velocityBias; + b -= b2Mul(c->K, a); + + const float32 k_errorTol = 1e-3f; + B2_NOT_USED(k_errorTol); + + for (;;) + { + // + // Case 1: vn = 0 + // + // 0 = A * x' + b' + // + // Solve for x': + // + // x' = - inv(A) * b' + // + b2Vec2 x = - b2Mul(c->normalMass, b); + + if (x.x >= 0.0f && x.y >= 0.0f) + { + // Resubstitute for the incremental impulse + b2Vec2 d = x - a; + + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= invMassA * (P1 + P2); + wA -= invIA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + + vB += invMassB * (P1 + P2); + wB += invIB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; + +#if B2_DEBUG_SOLVER == 1 + // Postconditions + dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); + dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); + + // Compute normal velocity + vn1 = b2Dot(dv1, normal); + vn2 = b2Dot(dv2, normal); + + b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); + b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); +#endif + break; + } + + // + // Case 2: vn1 = 0 and x2 = 0 + // + // 0 = a11 * x1' + a12 * 0 + b1' + // vn2 = a21 * x1' + a22 * 0 + b2' + // + x.x = - cp1->normalMass * b.x; + x.y = 0.0f; + vn1 = 0.0f; + vn2 = c->K.col1.y * x.x + b.y; + + if (x.x >= 0.0f && vn2 >= 0.0f) + { + // Resubstitute for the incremental impulse + b2Vec2 d = x - a; + + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= invMassA * (P1 + P2); + wA -= invIA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + + vB += invMassB * (P1 + P2); + wB += invIB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; + +#if B2_DEBUG_SOLVER == 1 + // Postconditions + dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); + + // Compute normal velocity + vn1 = b2Dot(dv1, normal); + + b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); +#endif + break; + } + + + // + // Case 3: vn2 = 0 and x1 = 0 + // + // vn1 = a11 * 0 + a12 * x2' + b1' + // 0 = a21 * 0 + a22 * x2' + b2' + // + x.x = 0.0f; + x.y = - cp2->normalMass * b.y; + vn1 = c->K.col2.x * x.y + b.x; + vn2 = 0.0f; + + if (x.y >= 0.0f && vn1 >= 0.0f) + { + // Resubstitute for the incremental impulse + b2Vec2 d = x - a; + + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= invMassA * (P1 + P2); + wA -= invIA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + + vB += invMassB * (P1 + P2); + wB += invIB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; + +#if B2_DEBUG_SOLVER == 1 + // Postconditions + dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); + + // Compute normal velocity + vn2 = b2Dot(dv2, normal); + + b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); +#endif + break; + } + + // + // Case 4: x1 = 0 and x2 = 0 + // + // vn1 = b1 + // vn2 = b2; + x.x = 0.0f; + x.y = 0.0f; + vn1 = b.x; + vn2 = b.y; + + if (vn1 >= 0.0f && vn2 >= 0.0f ) + { + // Resubstitute for the incremental impulse + b2Vec2 d = x - a; + + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= invMassA * (P1 + P2); + wA -= invIA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + + vB += invMassB * (P1 + P2); + wB += invIB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; + + break; + } + + // No solution, give up. This is hit sometimes, but it doesn't seem to matter. + break; + } + } + + bodyA->m_linearVelocity = vA; + bodyA->m_angularVelocity = wA; + bodyB->m_linearVelocity = vB; + bodyB->m_angularVelocity = wB; + } +} + +void b2ContactSolver::StoreImpulses() +{ + for (int32 i = 0; i < m_constraintCount; ++i) + { + b2ContactConstraint* c = m_constraints + i; + b2Manifold* m = c->manifold; + + for (int32 j = 0; j < c->pointCount; ++j) + { + m->points[j].normalImpulse = c->points[j].normalImpulse; + m->points[j].tangentImpulse = c->points[j].tangentImpulse; + } + } +} + +struct b2PositionSolverManifold +{ + void Initialize(b2ContactConstraint* cc, int32 index) + { + b2Assert(cc->pointCount > 0); + + switch (cc->type) + { + case b2Manifold::e_circles: + { + b2Vec2 pointA = cc->bodyA->GetWorldPoint(cc->localPoint); + b2Vec2 pointB = cc->bodyB->GetWorldPoint(cc->points[0].localPoint); + if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon) + { + normal = pointB - pointA; + normal.Normalize(); + } + else + { + normal.Set(1.0f, 0.0f); + } + + point = 0.5f * (pointA + pointB); + separation = b2Dot(pointB - pointA, normal) - cc->radius; + } + break; + + case b2Manifold::e_faceA: + { + normal = cc->bodyA->GetWorldVector(cc->localNormal); + b2Vec2 planePoint = cc->bodyA->GetWorldPoint(cc->localPoint); + + b2Vec2 clipPoint = cc->bodyB->GetWorldPoint(cc->points[index].localPoint); + separation = b2Dot(clipPoint - planePoint, normal) - cc->radius; + point = clipPoint; + } + break; + + case b2Manifold::e_faceB: + { + normal = cc->bodyB->GetWorldVector(cc->localNormal); + b2Vec2 planePoint = cc->bodyB->GetWorldPoint(cc->localPoint); + + b2Vec2 clipPoint = cc->bodyA->GetWorldPoint(cc->points[index].localPoint); + separation = b2Dot(clipPoint - planePoint, normal) - cc->radius; + point = clipPoint; + + // Ensure normal points from A to B + normal = -normal; + } + break; + } + } + + b2Vec2 normal; + b2Vec2 point; + float32 separation; +}; + +// Sequential solver. +bool b2ContactSolver::SolvePositionConstraints(float32 baumgarte) +{ + float32 minSeparation = 0.0f; + + for (int32 i = 0; i < m_constraintCount; ++i) + { + b2ContactConstraint* c = m_constraints + i; + b2Body* bodyA = c->bodyA; + b2Body* bodyB = c->bodyB; + + float32 invMassA = bodyA->m_mass * bodyA->m_invMass; + float32 invIA = bodyA->m_mass * bodyA->m_invI; + float32 invMassB = bodyB->m_mass * bodyB->m_invMass; + float32 invIB = bodyB->m_mass * bodyB->m_invI; + + // Solve normal constraints + for (int32 j = 0; j < c->pointCount; ++j) + { + b2PositionSolverManifold psm; + psm.Initialize(c, j); + b2Vec2 normal = psm.normal; + + b2Vec2 point = psm.point; + float32 separation = psm.separation; + + b2Vec2 rA = point - bodyA->m_sweep.c; + b2Vec2 rB = point - bodyB->m_sweep.c; + + // Track max constraint error. + minSeparation = b2Min(minSeparation, separation); + + // Prevent large corrections and allow slop. + float32 C = b2Clamp(baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); + + // Compute the effective mass. + float32 rnA = b2Cross(rA, normal); + float32 rnB = b2Cross(rB, normal); + float32 K = invMassA + invMassB + invIA * rnA * rnA + invIB * rnB * rnB; + + // Compute normal impulse + float32 impulse = K > 0.0f ? - C / K : 0.0f; + + b2Vec2 P = impulse * normal; + + bodyA->m_sweep.c -= invMassA * P; + bodyA->m_sweep.a -= invIA * b2Cross(rA, P); + bodyA->SynchronizeTransform(); + + bodyB->m_sweep.c += invMassB * P; + bodyB->m_sweep.a += invIB * b2Cross(rB, P); + bodyB->SynchronizeTransform(); + } + } + + // We can't expect minSpeparation >= -b2_linearSlop because we don't + // push the separation above -b2_linearSlop. + return minSeparation >= -1.5f * b2_linearSlop; +} diff --git a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2ContactSolver.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.h similarity index 67% rename from src/modules/physics/box2d/Source/Dynamics/Contacts/b2ContactSolver.h rename to src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.h index 04118c79e..b8555bbb4 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2ContactSolver.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -16,59 +16,60 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#ifndef CONTACT_SOLVER_H -#define CONTACT_SOLVER_H +#ifndef B2_CONTACT_SOLVER_H +#define B2_CONTACT_SOLVER_H -#include "../../Common/b2Math.h" -#include "../../Collision/b2Collision.h" -#include "../b2World.h" +#include +#include +#include class b2Contact; class b2Body; -class b2Island; class b2StackAllocator; struct b2ContactConstraintPoint { - b2Vec2 localAnchor1; - b2Vec2 localAnchor2; - b2Vec2 r1; - b2Vec2 r2; + b2Vec2 localPoint; + b2Vec2 rA; + b2Vec2 rB; float32 normalImpulse; float32 tangentImpulse; - float32 positionImpulse; float32 normalMass; float32 tangentMass; - float32 equalizedMass; - float32 separation; float32 velocityBias; }; struct b2ContactConstraint { b2ContactConstraintPoint points[b2_maxManifoldPoints]; + b2Vec2 localNormal; + b2Vec2 localPoint; b2Vec2 normal; - b2Manifold* manifold; - b2Body* body1; - b2Body* body2; + b2Mat22 normalMass; + b2Mat22 K; + b2Body* bodyA; + b2Body* bodyB; + b2Manifold::Type type; + float32 radius; float32 friction; - float32 restitution; int32 pointCount; + b2Manifold* manifold; }; class b2ContactSolver { public: - b2ContactSolver(const b2TimeStep& step, b2Contact** contacts, int32 contactCount, b2StackAllocator* allocator); + b2ContactSolver(b2Contact** contacts, int32 contactCount, + b2StackAllocator* allocator, float32 impulseRatio); + ~b2ContactSolver(); - void InitVelocityConstraints(const b2TimeStep& step); + void WarmStart(); void SolveVelocityConstraints(); - void FinalizeVelocityConstraints(); + void StoreImpulses(); bool SolvePositionConstraints(float32 baumgarte); - b2TimeStep m_step; b2StackAllocator* m_allocator; b2ContactConstraint* m_constraints; int m_constraintCount; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp new file mode 100644 index 000000000..837722d92 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include + +#include + +b2Contact* b2PolygonAndCircleContact::Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2PolygonAndCircleContact)); + return new (mem) b2PolygonAndCircleContact(fixtureA, fixtureB); +} + +void b2PolygonAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2PolygonAndCircleContact*)contact)->~b2PolygonAndCircleContact(); + allocator->Free(contact, sizeof(b2PolygonAndCircleContact)); +} + +b2PolygonAndCircleContact::b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) +: b2Contact(fixtureA, fixtureB) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); +} + +void b2PolygonAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollidePolygonAndCircle( manifold, + (b2PolygonShape*)m_fixtureA->GetShape(), xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2PolyAndCircleContact.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h similarity index 63% rename from src/modules/physics/box2d/Source/Dynamics/Contacts/b2PolyAndCircleContact.h rename to src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h index 47b3cb87c..684b2ae04 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2PolyAndCircleContact.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -16,29 +16,23 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#ifndef POLY_AND_CIRCLE_CONTACT_H -#define POLY_AND_CIRCLE_CONTACT_H +#ifndef B2_POLYGON_AND_CIRCLE_CONTACT_H +#define B2_POLYGON_AND_CIRCLE_CONTACT_H -#include "b2Contact.h" +#include class b2BlockAllocator; -class b2PolyAndCircleContact : public b2Contact +class b2PolygonAndCircleContact : public b2Contact { public: - static b2Contact* Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator); + static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator); static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - b2PolyAndCircleContact(b2Shape* shape1, b2Shape* shape2); - ~b2PolyAndCircleContact() {} + b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2PolygonAndCircleContact() {} - void Evaluate(b2ContactListener* listener); - b2Manifold* GetManifolds() - { - return &m_manifold; - } - - b2Manifold m_manifold; + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); }; #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.cpp new file mode 100644 index 000000000..eab2af579 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.cpp @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include + +#include + +b2Contact* b2PolygonContact::Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2PolygonContact)); + return new (mem) b2PolygonContact(fixtureA, fixtureB); +} + +void b2PolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2PolygonContact*)contact)->~b2PolygonContact(); + allocator->Free(contact, sizeof(b2PolygonContact)); +} + +b2PolygonContact::b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) + : b2Contact(fixtureA, fixtureB) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); + b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); +} + +void b2PolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollidePolygons( manifold, + (b2PolygonShape*)m_fixtureA->GetShape(), xfA, + (b2PolygonShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2PolyContact.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.h similarity index 69% rename from src/modules/physics/box2d/Source/Dynamics/Contacts/b2PolyContact.h rename to src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.h index b8a3e73c0..af544c2e7 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2PolyContact.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -16,29 +16,23 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#ifndef POLYCONTACT_H -#define POLYCONTACT_H +#ifndef B2_POLYGON_CONTACT_H +#define B2_POLYGON_CONTACT_H -#include "b2Contact.h" +#include class b2BlockAllocator; class b2PolygonContact : public b2Contact { public: - static b2Contact* Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator); + static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator); static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - b2PolygonContact(b2Shape* shape1, b2Shape* shape2); + b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); ~b2PolygonContact() {} - void Evaluate(b2ContactListener* listener); - b2Manifold* GetManifolds() - { - return &m_manifold; - } - - b2Manifold m_manifold; + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); }; #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.cpp new file mode 100644 index 000000000..567cd7125 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.cpp @@ -0,0 +1,231 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +struct b2TOIConstraint +{ + b2Vec2 localPoints[b2_maxManifoldPoints]; + b2Vec2 localNormal; + b2Vec2 localPoint; + b2Manifold::Type type; + float32 radius; + int32 pointCount; + b2Body* bodyA; + b2Body* bodyB; +}; + +b2TOISolver::b2TOISolver(b2StackAllocator* allocator) +{ + m_allocator = allocator; + m_constraints = NULL; + m_count = NULL; + m_toiBody = NULL; +} + +b2TOISolver::~b2TOISolver() +{ + Clear(); +} + +void b2TOISolver::Clear() +{ + if (m_allocator && m_constraints) + { + m_allocator->Free(m_constraints); + m_constraints = NULL; + } +} + +void b2TOISolver::Initialize(b2Contact** contacts, int32 count, b2Body* toiBody) +{ + Clear(); + + m_count = count; + m_toiBody = toiBody; + + m_constraints = (b2TOIConstraint*) m_allocator->Allocate(m_count * sizeof(b2TOIConstraint)); + + for (int32 i = 0; i < m_count; ++i) + { + b2Contact* contact = contacts[i]; + + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); + b2Shape* shapeA = fixtureA->GetShape(); + b2Shape* shapeB = fixtureB->GetShape(); + float32 radiusA = shapeA->m_radius; + float32 radiusB = shapeB->m_radius; + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + b2Manifold* manifold = contact->GetManifold(); + + b2Assert(manifold->pointCount > 0); + + b2TOIConstraint* constraint = m_constraints + i; + constraint->bodyA = bodyA; + constraint->bodyB = bodyB; + constraint->localNormal = manifold->localNormal; + constraint->localPoint = manifold->localPoint; + constraint->type = manifold->type; + constraint->pointCount = manifold->pointCount; + constraint->radius = radiusA + radiusB; + + for (int32 j = 0; j < constraint->pointCount; ++j) + { + b2ManifoldPoint* cp = manifold->points + j; + constraint->localPoints[j] = cp->localPoint; + } + } +} + +struct b2TOISolverManifold +{ + void Initialize(b2TOIConstraint* cc, int32 index) + { + b2Assert(cc->pointCount > 0); + + switch (cc->type) + { + case b2Manifold::e_circles: + { + b2Vec2 pointA = cc->bodyA->GetWorldPoint(cc->localPoint); + b2Vec2 pointB = cc->bodyB->GetWorldPoint(cc->localPoints[0]); + if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon) + { + normal = pointB - pointA; + normal.Normalize(); + } + else + { + normal.Set(1.0f, 0.0f); + } + + point = 0.5f * (pointA + pointB); + separation = b2Dot(pointB - pointA, normal) - cc->radius; + } + break; + + case b2Manifold::e_faceA: + { + normal = cc->bodyA->GetWorldVector(cc->localNormal); + b2Vec2 planePoint = cc->bodyA->GetWorldPoint(cc->localPoint); + + b2Vec2 clipPoint = cc->bodyB->GetWorldPoint(cc->localPoints[index]); + separation = b2Dot(clipPoint - planePoint, normal) - cc->radius; + point = clipPoint; + } + break; + + case b2Manifold::e_faceB: + { + normal = cc->bodyB->GetWorldVector(cc->localNormal); + b2Vec2 planePoint = cc->bodyB->GetWorldPoint(cc->localPoint); + + b2Vec2 clipPoint = cc->bodyA->GetWorldPoint(cc->localPoints[index]); + separation = b2Dot(clipPoint - planePoint, normal) - cc->radius; + point = clipPoint; + + // Ensure normal points from A to B + normal = -normal; + } + break; + } + } + + b2Vec2 normal; + b2Vec2 point; + float32 separation; +}; + +// Push out the toi body to provide clearance for further simulation. +bool b2TOISolver::Solve(float32 baumgarte) +{ + float32 minSeparation = 0.0f; + + for (int32 i = 0; i < m_count; ++i) + { + b2TOIConstraint* c = m_constraints + i; + b2Body* bodyA = c->bodyA; + b2Body* bodyB = c->bodyB; + + float32 massA = bodyA->m_mass; + float32 massB = bodyB->m_mass; + + // Only the TOI body should move. + if (bodyA == m_toiBody) + { + massB = 0.0f; + } + else + { + massA = 0.0f; + } + + float32 invMassA = massA * bodyA->m_invMass; + float32 invIA = massA * bodyA->m_invI; + float32 invMassB = massB * bodyB->m_invMass; + float32 invIB = massB * bodyB->m_invI; + + // Solve normal constraints + for (int32 j = 0; j < c->pointCount; ++j) + { + b2TOISolverManifold psm; + psm.Initialize(c, j); + b2Vec2 normal = psm.normal; + + b2Vec2 point = psm.point; + float32 separation = psm.separation; + + b2Vec2 rA = point - bodyA->m_sweep.c; + b2Vec2 rB = point - bodyB->m_sweep.c; + + // Track max constraint error. + minSeparation = b2Min(minSeparation, separation); + + // Prevent large corrections and allow slop. + float32 C = b2Clamp(baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); + + // Compute the effective mass. + float32 rnA = b2Cross(rA, normal); + float32 rnB = b2Cross(rB, normal); + float32 K = invMassA + invMassB + invIA * rnA * rnA + invIB * rnB * rnB; + + // Compute normal impulse + float32 impulse = K > 0.0f ? - C / K : 0.0f; + + b2Vec2 P = impulse * normal; + + bodyA->m_sweep.c -= invMassA * P; + bodyA->m_sweep.a -= invIA * b2Cross(rA, P); + bodyA->SynchronizeTransform(); + + bodyB->m_sweep.c += invMassB * P; + bodyB->m_sweep.a += invIB * b2Cross(rB, P); + bodyB->SynchronizeTransform(); + } + } + + // We can't expect minSpeparation >= -b2_linearSlop because we don't + // push the separation above -b2_linearSlop. + return minSeparation >= -1.5f * b2_linearSlop; +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.h new file mode 100644 index 000000000..c092e2a81 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.h @@ -0,0 +1,51 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_TOI_SOLVER_H +#define B2_TOI_SOLVER_H + +#include + +class b2Contact; +class b2Body; +struct b2TOIConstraint; +class b2StackAllocator; + +/// This is a pure position solver for a single movable body in contact with +/// multiple non-moving bodies. +class b2TOISolver +{ +public: + b2TOISolver(b2StackAllocator* allocator); + ~b2TOISolver(); + + void Initialize(b2Contact** contacts, int32 contactCount, b2Body* toiBody); + void Clear(); + + // Perform one solver iteration. Returns true if converged. + bool Solve(float32 baumgarte); + +private: + + b2TOIConstraint* m_constraints; + int32 m_count; + b2Body* m_toiBody; + b2StackAllocator* m_allocator; +}; + +#endif diff --git a/src/modules/physics/box2d/Source/Dynamics/Joints/b2DistanceJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp similarity index 67% rename from src/modules/physics/box2d/Source/Dynamics/Joints/b2DistanceJoint.cpp rename to src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp index a52e2f971..3469bd9e1 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Joints/b2DistanceJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp @@ -16,9 +16,9 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#include "b2DistanceJoint.h" -#include "../b2Body.h" -#include "../b2World.h" +#include +#include +#include // 1-D constrained system // m (v2 - v1) = lambda @@ -38,10 +38,10 @@ void b2DistanceJointDef::Initialize(b2Body* b1, b2Body* b2, const b2Vec2& anchor1, const b2Vec2& anchor2) { - body1 = b1; - body2 = b2; - localAnchor1 = body1->GetLocalPoint(anchor1); - localAnchor2 = body2->GetLocalPoint(anchor2); + bodyA = b1; + bodyB = b2; + localAnchorA = bodyA->GetLocalPoint(anchor1); + localAnchorB = bodyB->GetLocalPoint(anchor2); b2Vec2 d = anchor2 - anchor1; length = d.Length(); } @@ -50,27 +50,24 @@ void b2DistanceJointDef::Initialize(b2Body* b1, b2Body* b2, b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def) : b2Joint(def) { - m_localAnchor1 = def->localAnchor1; - m_localAnchor2 = def->localAnchor2; + m_localAnchor1 = def->localAnchorA; + m_localAnchor2 = def->localAnchorB; m_length = def->length; m_frequencyHz = def->frequencyHz; m_dampingRatio = def->dampingRatio; m_impulse = 0.0f; m_gamma = 0.0f; m_bias = 0.0f; - m_inv_dt = 0.0f; } void b2DistanceJoint::InitVelocityConstraints(const b2TimeStep& step) { - m_inv_dt = step.inv_dt; - - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; // Compute the effective mass matrix. - b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); + b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); + b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); m_u = b2->m_sweep.c + r2 - b1->m_sweep.c - r1; // Handle singularity. @@ -87,8 +84,8 @@ void b2DistanceJoint::InitVelocityConstraints(const b2TimeStep& step) float32 cr1u = b2Cross(r1, m_u); float32 cr2u = b2Cross(r2, m_u); float32 invMass = b1->m_invMass + b1->m_invI * cr1u * cr1u + b2->m_invMass + b2->m_invI * cr2u * cr2u; - b2Assert(invMass > B2_FLT_EPSILON); - m_mass = 1.0f / invMass; + + m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; if (m_frequencyHz > 0.0f) { @@ -104,15 +101,19 @@ void b2DistanceJoint::InitVelocityConstraints(const b2TimeStep& step) float32 k = m_mass * omega * omega; // magic formulas - m_gamma = 1.0f / (step.dt * (d + step.dt * k)); + m_gamma = step.dt * (d + step.dt * k); + m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; m_bias = C * step.dt * k * m_gamma; - m_mass = 1.0f / (invMass + m_gamma); + m_mass = invMass + m_gamma; + m_mass = m_mass != 0.0f ? 1.0f / m_mass : 0.0f; } if (step.warmStarting) { + // Scale the impulse to support a variable time step. m_impulse *= step.dtRatio; + b2Vec2 P = m_impulse * m_u; b1->m_linearVelocity -= b1->m_invMass * P; b1->m_angularVelocity -= b1->m_invI * b2Cross(r1, P); @@ -129,11 +130,11 @@ void b2DistanceJoint::SolveVelocityConstraints(const b2TimeStep& step) { B2_NOT_USED(step); - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; - b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); + b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); + b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); // Cdot = dot(u, v + cross(w, r)) b2Vec2 v1 = b1->m_linearVelocity + b2Cross(b1->m_angularVelocity, r1); @@ -150,18 +151,21 @@ void b2DistanceJoint::SolveVelocityConstraints(const b2TimeStep& step) b2->m_angularVelocity += b2->m_invI * b2Cross(r2, P); } -bool b2DistanceJoint::SolvePositionConstraints() +bool b2DistanceJoint::SolvePositionConstraints(float32 baumgarte) { + B2_NOT_USED(baumgarte); + if (m_frequencyHz > 0.0f) { + // There is no position correction for soft distance constraints. return true; } - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; - b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); + b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); + b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); b2Vec2 d = b2->m_sweep.c + r2 - b1->m_sweep.c - r1; @@ -184,23 +188,24 @@ bool b2DistanceJoint::SolvePositionConstraints() return b2Abs(C) < b2_linearSlop; } -b2Vec2 b2DistanceJoint::GetAnchor1() const +b2Vec2 b2DistanceJoint::GetAnchorA() const { - return m_body1->GetWorldPoint(m_localAnchor1); + return m_bodyA->GetWorldPoint(m_localAnchor1); } -b2Vec2 b2DistanceJoint::GetAnchor2() const +b2Vec2 b2DistanceJoint::GetAnchorB() const { - return m_body2->GetWorldPoint(m_localAnchor2); + return m_bodyB->GetWorldPoint(m_localAnchor2); } -b2Vec2 b2DistanceJoint::GetReactionForce() const +b2Vec2 b2DistanceJoint::GetReactionForce(float32 inv_dt) const { - b2Vec2 F = (m_inv_dt * m_impulse) * m_u; + b2Vec2 F = (inv_dt * m_impulse) * m_u; return F; } -float32 b2DistanceJoint::GetReactionTorque() const +float32 b2DistanceJoint::GetReactionTorque(float32 inv_dt) const { + B2_NOT_USED(inv_dt); return 0.0f; } diff --git a/src/modules/physics/box2d/Source/Dynamics/Joints/b2DistanceJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h similarity index 59% rename from src/modules/physics/box2d/Source/Dynamics/Joints/b2DistanceJoint.h rename to src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h index b97aad8b7..448faa668 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Joints/b2DistanceJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h @@ -19,7 +19,7 @@ #ifndef B2_DISTANCE_JOINT_H #define B2_DISTANCE_JOINT_H -#include "b2Joint.h" +#include /// Distance joint definition. This requires defining an /// anchor point on both bodies and the non-zero length of the @@ -32,8 +32,8 @@ struct b2DistanceJointDef : public b2JointDef b2DistanceJointDef() { type = e_distanceJoint; - localAnchor1.Set(0.0f, 0.0f); - localAnchor2.Set(0.0f, 0.0f); + localAnchorA.Set(0.0f, 0.0f); + localAnchorB.Set(0.0f, 0.0f); length = 1.0f; frequencyHz = 0.0f; dampingRatio = 0.0f; @@ -41,19 +41,19 @@ struct b2DistanceJointDef : public b2JointDef /// Initialize the bodies, anchors, and length using the world /// anchors. - void Initialize(b2Body* body1, b2Body* body2, - const b2Vec2& anchor1, const b2Vec2& anchor2); + void Initialize(b2Body* bodyA, b2Body* bodyB, + const b2Vec2& anchorA, const b2Vec2& anchorB); /// The local anchor point relative to body1's origin. - b2Vec2 localAnchor1; + b2Vec2 localAnchorA; /// The local anchor point relative to body2's origin. - b2Vec2 localAnchor2; + b2Vec2 localAnchorB; - /// The equilibrium length between the anchor points. + /// The natural length between the anchor points. float32 length; - /// The response speed. + /// The mass-spring-damper frequency in Hertz. float32 frequencyHz; /// The damping ratio. 0 = no damping, 1 = critical damping. @@ -67,19 +67,33 @@ class b2DistanceJoint : public b2Joint { public: - b2Vec2 GetAnchor1() const; - b2Vec2 GetAnchor2() const; + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; - b2Vec2 GetReactionForce() const; - float32 GetReactionTorque() const; + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; - //--------------- Internals Below ------------------- + /// Set/get the natural length. + /// Manipulating the length can lead to non-physical behavior when the frequency is zero. + void SetLength(float32 length); + float32 GetLength() const; + // Set/get frequency in Hz. + void SetFrequency(float32 hz); + float32 GetFrequency() const; + + // Set/get damping ratio. + void SetDampingRatio(float32 ratio); + float32 GetDampingRatio() const; + +protected: + + friend class b2Joint; b2DistanceJoint(const b2DistanceJointDef* data); void InitVelocityConstraints(const b2TimeStep& step); void SolveVelocityConstraints(const b2TimeStep& step); - bool SolvePositionConstraints(); + bool SolvePositionConstraints(float32 baumgarte); b2Vec2 m_localAnchor1; b2Vec2 m_localAnchor2; @@ -89,8 +103,38 @@ public: float32 m_gamma; float32 m_bias; float32 m_impulse; - float32 m_mass; // effective mass for the constraint. + float32 m_mass; float32 m_length; }; +inline void b2DistanceJoint::SetLength(float32 length) +{ + m_length = length; +} + +inline float32 b2DistanceJoint::GetLength() const +{ + return m_length; +} + +inline void b2DistanceJoint::SetFrequency(float32 hz) +{ + m_frequencyHz = hz; +} + +inline float32 b2DistanceJoint::GetFrequency() const +{ + return m_frequencyHz; +} + +inline void b2DistanceJoint::SetDampingRatio(float32 ratio) +{ + m_dampingRatio = ratio; +} + +inline float32 b2DistanceJoint::GetDampingRatio() const +{ + return m_dampingRatio; +} + #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp new file mode 100644 index 000000000..9097deec3 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp @@ -0,0 +1,229 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Point-to-point constraint +// Cdot = v2 - v1 +// = v2 + cross(w2, r2) - v1 - cross(w1, r1) +// J = [-I -r1_skew I r2_skew ] +// Identity used: +// w k % (rx i + ry j) = w * (-ry i + rx j) + +// Angle constraint +// Cdot = w2 - w1 +// J = [0 0 -1 0 0 1] +// K = invI1 + invI2 + +void b2FrictionJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) +{ + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); +} + +b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + + m_linearImpulse.SetZero(); + m_angularImpulse = 0.0f; + + m_maxForce = def->maxForce; + m_maxTorque = def->maxTorque; +} + +void b2FrictionJoint::InitVelocityConstraints(const b2TimeStep& step) +{ + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + + // Compute the effective mass matrix. + b2Vec2 rA = b2Mul(bA->GetTransform().R, m_localAnchorA - bA->GetLocalCenter()); + b2Vec2 rB = b2Mul(bB->GetTransform().R, m_localAnchorB - bB->GetLocalCenter()); + + // J = [-I -r1_skew I r2_skew] + // [ 0 -1 0 1] + // r_skew = [-ry; rx] + + // Matlab + // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] + // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] + // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] + + float32 mA = bA->m_invMass, mB = bB->m_invMass; + float32 iA = bA->m_invI, iB = bB->m_invI; + + b2Mat22 K1; + K1.col1.x = mA + mB; K1.col2.x = 0.0f; + K1.col1.y = 0.0f; K1.col2.y = mA + mB; + + b2Mat22 K2; + K2.col1.x = iA * rA.y * rA.y; K2.col2.x = -iA * rA.x * rA.y; + K2.col1.y = -iA * rA.x * rA.y; K2.col2.y = iA * rA.x * rA.x; + + b2Mat22 K3; + K3.col1.x = iB * rB.y * rB.y; K3.col2.x = -iB * rB.x * rB.y; + K3.col1.y = -iB * rB.x * rB.y; K3.col2.y = iB * rB.x * rB.x; + + b2Mat22 K = K1 + K2 + K3; + m_linearMass = K.GetInverse(); + + m_angularMass = iA + iB; + if (m_angularMass > 0.0f) + { + m_angularMass = 1.0f / m_angularMass; + } + + if (step.warmStarting) + { + // Scale impulses to support a variable time step. + m_linearImpulse *= step.dtRatio; + m_angularImpulse *= step.dtRatio; + + b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y); + + bA->m_linearVelocity -= mA * P; + bA->m_angularVelocity -= iA * (b2Cross(rA, P) + m_angularImpulse); + + bB->m_linearVelocity += mB * P; + bB->m_angularVelocity += iB * (b2Cross(rB, P) + m_angularImpulse); + } + else + { + m_linearImpulse.SetZero(); + m_angularImpulse = 0.0f; + } +} + +void b2FrictionJoint::SolveVelocityConstraints(const b2TimeStep& step) +{ + B2_NOT_USED(step); + + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + + b2Vec2 vA = bA->m_linearVelocity; + float32 wA = bA->m_angularVelocity; + b2Vec2 vB = bB->m_linearVelocity; + float32 wB = bB->m_angularVelocity; + + float32 mA = bA->m_invMass, mB = bB->m_invMass; + float32 iA = bA->m_invI, iB = bB->m_invI; + + b2Vec2 rA = b2Mul(bA->GetTransform().R, m_localAnchorA - bA->GetLocalCenter()); + b2Vec2 rB = b2Mul(bB->GetTransform().R, m_localAnchorB - bB->GetLocalCenter()); + + // Solve angular friction + { + float32 Cdot = wB - wA; + float32 impulse = -m_angularMass * Cdot; + + float32 oldImpulse = m_angularImpulse; + float32 maxImpulse = step.dt * m_maxTorque; + m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_angularImpulse - oldImpulse; + + wA -= iA * impulse; + wB += iB * impulse; + } + + // Solve linear friction + { + b2Vec2 Cdot = vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA); + + b2Vec2 impulse = -b2Mul(m_linearMass, Cdot); + b2Vec2 oldImpulse = m_linearImpulse; + m_linearImpulse += impulse; + + float32 maxImpulse = step.dt * m_maxForce; + + if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) + { + m_linearImpulse.Normalize(); + m_linearImpulse *= maxImpulse; + } + + impulse = m_linearImpulse - oldImpulse; + + vA -= mA * impulse; + wA -= iA * b2Cross(rA, impulse); + + vB += mB * impulse; + wB += iB * b2Cross(rB, impulse); + } + + bA->m_linearVelocity = vA; + bA->m_angularVelocity = wA; + bB->m_linearVelocity = vB; + bB->m_angularVelocity = wB; +} + +bool b2FrictionJoint::SolvePositionConstraints(float32 baumgarte) +{ + B2_NOT_USED(baumgarte); + + return true; +} + +b2Vec2 b2FrictionJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2FrictionJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2FrictionJoint::GetReactionForce(float32 inv_dt) const +{ + return inv_dt * m_linearImpulse; +} + +float32 b2FrictionJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_angularImpulse; +} + +void b2FrictionJoint::SetMaxForce(float32 force) +{ + b2Assert(b2IsValid(force) && force >= 0.0f); + m_maxForce = force; +} + +float32 b2FrictionJoint::GetMaxForce() const +{ + return m_maxForce; +} + +void b2FrictionJoint::SetMaxTorque(float32 torque) +{ + b2Assert(b2IsValid(torque) && torque >= 0.0f); + m_maxTorque = torque; +} + +float32 b2FrictionJoint::GetMaxTorque() const +{ + return m_maxTorque; +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h new file mode 100644 index 000000000..b4c4af261 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h @@ -0,0 +1,99 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_FRICTION_JOINT_H +#define B2_FRICTION_JOINT_H + +#include + +/// Friction joint definition. +struct b2FrictionJointDef : public b2JointDef +{ + b2FrictionJointDef() + { + type = e_frictionJoint; + localAnchorA.SetZero(); + localAnchorB.SetZero(); + maxForce = 0.0f; + maxTorque = 0.0f; + } + + /// Initialize the bodies, anchors, axis, and reference angle using the world + /// anchor and world axis. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The maximum friction force in N. + float32 maxForce; + + /// The maximum friction torque in N-m. + float32 maxTorque; +}; + +/// Friction joint. This is used for top-down friction. +/// It provides 2D translational friction and angular friction. +class b2FrictionJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// Set the maximum friction force in N. + void SetMaxForce(float32 force); + + /// Get the maximum friction force in N. + float32 GetMaxForce() const; + + /// Set the maximum friction torque in N*m. + void SetMaxTorque(float32 torque); + + /// Get the maximum friction torque in N*m. + float32 GetMaxTorque() const; + +protected: + + friend class b2Joint; + + b2FrictionJoint(const b2FrictionJointDef* def); + + void InitVelocityConstraints(const b2TimeStep& step); + void SolveVelocityConstraints(const b2TimeStep& step); + bool SolvePositionConstraints(float32 baumgarte); + + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + + b2Mat22 m_linearMass; + float32 m_angularMass; + + b2Vec2 m_linearImpulse; + float32 m_angularImpulse; + + float32 m_maxForce; + float32 m_maxTorque; +}; + +#endif diff --git a/src/modules/physics/box2d/Source/Dynamics/Joints/b2GearJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp similarity index 57% rename from src/modules/physics/box2d/Source/Dynamics/Joints/b2GearJoint.cpp rename to src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp index 08eda2d52..89b17ee2c 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Joints/b2GearJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp @@ -16,11 +16,11 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#include "b2GearJoint.h" -#include "b2RevoluteJoint.h" -#include "b2PrismaticJoint.h" -#include "../b2Body.h" -#include "../b2World.h" +#include +#include +#include +#include +#include // Gear Joint: // C0 = (coordinate1 + ratio * coordinate2)_initial @@ -50,8 +50,8 @@ b2GearJoint::b2GearJoint(const b2GearJointDef* def) b2Assert(type1 == e_revoluteJoint || type1 == e_prismaticJoint); b2Assert(type2 == e_revoluteJoint || type2 == e_prismaticJoint); - b2Assert(def->joint1->GetBody1()->IsStatic()); - b2Assert(def->joint2->GetBody1()->IsStatic()); + b2Assert(def->joint1->GetBodyA()->GetType() == b2_staticBody); + b2Assert(def->joint2->GetBodyA()->GetType() == b2_staticBody); m_revolute1 = NULL; m_prismatic1 = NULL; @@ -60,8 +60,8 @@ b2GearJoint::b2GearJoint(const b2GearJointDef* def) float32 coordinate1, coordinate2; - m_ground1 = def->joint1->GetBody1(); - m_body1 = def->joint1->GetBody2(); + m_ground1 = def->joint1->GetBodyA(); + m_bodyA = def->joint1->GetBodyB(); if (type1 == e_revoluteJoint) { m_revolute1 = (b2RevoluteJoint*)def->joint1; @@ -77,8 +77,8 @@ b2GearJoint::b2GearJoint(const b2GearJointDef* def) coordinate1 = m_prismatic1->GetJointTranslation(); } - m_ground2 = def->joint2->GetBody1(); - m_body2 = def->joint2->GetBody2(); + m_ground2 = def->joint2->GetBodyA(); + m_bodyB = def->joint2->GetBodyB(); if (type2 == e_revoluteJoint) { m_revolute2 = (b2RevoluteJoint*)def->joint2; @@ -98,92 +98,93 @@ b2GearJoint::b2GearJoint(const b2GearJointDef* def) m_constant = coordinate1 + m_ratio * coordinate2; - m_force = 0.0f; + m_impulse = 0.0f; } void b2GearJoint::InitVelocityConstraints(const b2TimeStep& step) { b2Body* g1 = m_ground1; b2Body* g2 = m_ground2; - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; float32 K = 0.0f; m_J.SetZero(); if (m_revolute1) { - m_J.angular1 = -1.0f; + m_J.angularA = -1.0f; K += b1->m_invI; } else { - b2Vec2 ug = b2Mul(g1->GetXForm().R, m_prismatic1->m_localXAxis1); - b2Vec2 r = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); + b2Vec2 ug = b2Mul(g1->GetTransform().R, m_prismatic1->m_localXAxis1); + b2Vec2 r = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); float32 crug = b2Cross(r, ug); - m_J.linear1 = -ug; - m_J.angular1 = -crug; + m_J.linearA = -ug; + m_J.angularA = -crug; K += b1->m_invMass + b1->m_invI * crug * crug; } if (m_revolute2) { - m_J.angular2 = -m_ratio; + m_J.angularB = -m_ratio; K += m_ratio * m_ratio * b2->m_invI; } else { - b2Vec2 ug = b2Mul(g2->GetXForm().R, m_prismatic2->m_localXAxis1); - b2Vec2 r = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); + b2Vec2 ug = b2Mul(g2->GetTransform().R, m_prismatic2->m_localXAxis1); + b2Vec2 r = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); float32 crug = b2Cross(r, ug); - m_J.linear2 = -m_ratio * ug; - m_J.angular2 = -m_ratio * crug; + m_J.linearB = -m_ratio * ug; + m_J.angularB = -m_ratio * crug; K += m_ratio * m_ratio * (b2->m_invMass + b2->m_invI * crug * crug); } // Compute effective mass. - b2Assert(K > 0.0f); - m_mass = 1.0f / K; + m_mass = K > 0.0f ? 1.0f / K : 0.0f; if (step.warmStarting) { // Warm starting. - float32 P = B2FORCE_SCALE(step.dt) * m_force; - b1->m_linearVelocity += b1->m_invMass * P * m_J.linear1; - b1->m_angularVelocity += b1->m_invI * P * m_J.angular1; - b2->m_linearVelocity += b2->m_invMass * P * m_J.linear2; - b2->m_angularVelocity += b2->m_invI * P * m_J.angular2; + b1->m_linearVelocity += b1->m_invMass * m_impulse * m_J.linearA; + b1->m_angularVelocity += b1->m_invI * m_impulse * m_J.angularA; + b2->m_linearVelocity += b2->m_invMass * m_impulse * m_J.linearB; + b2->m_angularVelocity += b2->m_invI * m_impulse * m_J.angularB; } else { - m_force = 0.0f; + m_impulse = 0.0f; } } void b2GearJoint::SolveVelocityConstraints(const b2TimeStep& step) { - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; + B2_NOT_USED(step); + + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; float32 Cdot = m_J.Compute( b1->m_linearVelocity, b1->m_angularVelocity, b2->m_linearVelocity, b2->m_angularVelocity); - float32 force = -B2FORCE_INV_SCALE(step.inv_dt) * m_mass * Cdot; - m_force += force; + float32 impulse = m_mass * (-Cdot); + m_impulse += impulse; - float32 P = B2FORCE_SCALE(step.dt) * force; - b1->m_linearVelocity += b1->m_invMass * P * m_J.linear1; - b1->m_angularVelocity += b1->m_invI * P * m_J.angular1; - b2->m_linearVelocity += b2->m_invMass * P * m_J.linear2; - b2->m_angularVelocity += b2->m_invI * P * m_J.angular2; + b1->m_linearVelocity += b1->m_invMass * impulse * m_J.linearA; + b1->m_angularVelocity += b1->m_invI * impulse * m_J.angularA; + b2->m_linearVelocity += b2->m_invMass * impulse * m_J.linearB; + b2->m_angularVelocity += b2->m_invI * impulse * m_J.angularB; } -bool b2GearJoint::SolvePositionConstraints() +bool b2GearJoint::SolvePositionConstraints(float32 baumgarte) { + B2_NOT_USED(baumgarte); + float32 linearError = 0.0f; - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; float32 coordinate1, coordinate2; if (m_revolute1) @@ -206,48 +207,53 @@ bool b2GearJoint::SolvePositionConstraints() float32 C = m_constant - (coordinate1 + m_ratio * coordinate2); - float32 impulse = -m_mass * C; + float32 impulse = m_mass * (-C); - b1->m_sweep.c += b1->m_invMass * impulse * m_J.linear1; - b1->m_sweep.a += b1->m_invI * impulse * m_J.angular1; - b2->m_sweep.c += b2->m_invMass * impulse * m_J.linear2; - b2->m_sweep.a += b2->m_invI * impulse * m_J.angular2; + b1->m_sweep.c += b1->m_invMass * impulse * m_J.linearA; + b1->m_sweep.a += b1->m_invI * impulse * m_J.angularA; + b2->m_sweep.c += b2->m_invMass * impulse * m_J.linearB; + b2->m_sweep.a += b2->m_invI * impulse * m_J.angularB; b1->SynchronizeTransform(); b2->SynchronizeTransform(); + // TODO_ERIN not implemented return linearError < b2_linearSlop; } -b2Vec2 b2GearJoint::GetAnchor1() const +b2Vec2 b2GearJoint::GetAnchorA() const { - return m_body1->GetWorldPoint(m_localAnchor1); + return m_bodyA->GetWorldPoint(m_localAnchor1); } -b2Vec2 b2GearJoint::GetAnchor2() const +b2Vec2 b2GearJoint::GetAnchorB() const { - return m_body2->GetWorldPoint(m_localAnchor2); + return m_bodyB->GetWorldPoint(m_localAnchor2); } -b2Vec2 b2GearJoint::GetReactionForce() const +b2Vec2 b2GearJoint::GetReactionForce(float32 inv_dt) const { // TODO_ERIN not tested - b2Vec2 F = B2FORCE_SCALE(m_force) * m_J.linear2; - return F; + b2Vec2 P = m_impulse * m_J.linearB; + return inv_dt * P; } -float32 b2GearJoint::GetReactionTorque() const +float32 b2GearJoint::GetReactionTorque(float32 inv_dt) const { // TODO_ERIN not tested - b2Vec2 r = b2Mul(m_body2->GetXForm().R, m_localAnchor2 - m_body2->GetLocalCenter()); - b2Vec2 F = m_force * m_J.linear2; - float32 T = B2FORCE_SCALE(m_force * m_J.angular2 - b2Cross(r, F)); - return T; + b2Vec2 r = b2Mul(m_bodyB->GetTransform().R, m_localAnchor2 - m_bodyB->GetLocalCenter()); + b2Vec2 P = m_impulse * m_J.linearB; + float32 L = m_impulse * m_J.angularB - b2Cross(r, P); + return inv_dt * L; +} + +void b2GearJoint::SetRatio(float32 ratio) +{ + b2Assert(b2IsValid(ratio)); + m_ratio = ratio; } float32 b2GearJoint::GetRatio() const { return m_ratio; } - - diff --git a/src/modules/physics/box2d/Source/Dynamics/Joints/b2GearJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.h similarity index 85% rename from src/modules/physics/box2d/Source/Dynamics/Joints/b2GearJoint.h rename to src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.h index f48f53c44..eccca0da0 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Joints/b2GearJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.h @@ -19,7 +19,7 @@ #ifndef B2_GEAR_JOINT_H #define B2_GEAR_JOINT_H -#include "b2Joint.h" +#include class b2RevoluteJoint; class b2PrismaticJoint; @@ -60,22 +60,24 @@ struct b2GearJointDef : public b2JointDef class b2GearJoint : public b2Joint { public: - b2Vec2 GetAnchor1() const; - b2Vec2 GetAnchor2() const; + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; - b2Vec2 GetReactionForce() const; - float32 GetReactionTorque() const; + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; - /// Get the gear ratio. + /// Set/Get the gear ratio. + void SetRatio(float32 ratio); float32 GetRatio() const; - //--------------- Internals Below ------------------- +protected: + friend class b2Joint; b2GearJoint(const b2GearJointDef* data); void InitVelocityConstraints(const b2TimeStep& step); void SolveVelocityConstraints(const b2TimeStep& step); - bool SolvePositionConstraints(); + bool SolvePositionConstraints(float32 baumgarte); b2Body* m_ground1; b2Body* m_ground2; @@ -103,7 +105,7 @@ public: float32 m_mass; // Impulse for accumulation/warm starting. - float32 m_force; + float32 m_impulse; }; #endif diff --git a/src/modules/physics/box2d/Source/Dynamics/Joints/b2Joint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.cpp similarity index 61% rename from src/modules/physics/box2d/Source/Dynamics/Joints/b2Joint.cpp rename to src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.cpp index 77dcef47f..a7e19d34d 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Joints/b2Joint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.cpp @@ -16,17 +16,19 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#include "b2Joint.h" -#include "b2DistanceJoint.h" -#include "b2MouseJoint.h" -#include "b2RevoluteJoint.h" -#include "b2PrismaticJoint.h" -#include "b2PulleyJoint.h" -#include "b2GearJoint.h" -#include "../b2Body.h" -#include "../b2World.h" -#include "../../Common/b2BlockAllocator.h" -#include "../../Collision/b2BroadPhase.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -78,6 +80,27 @@ b2Joint* b2Joint::Create(const b2JointDef* def, b2BlockAllocator* allocator) } break; + case e_lineJoint: + { + void* mem = allocator->Allocate(sizeof(b2LineJoint)); + joint = new (mem) b2LineJoint((b2LineJointDef*)def); + } + break; + + case e_weldJoint: + { + void* mem = allocator->Allocate(sizeof(b2WeldJoint)); + joint = new (mem) b2WeldJoint((b2WeldJointDef*)def); + } + break; + + case e_frictionJoint: + { + void* mem = allocator->Allocate(sizeof(b2FrictionJoint)); + joint = new (mem) b2FrictionJoint((b2FrictionJointDef*)def); + } + break; + default: b2Assert(false); break; @@ -115,6 +138,18 @@ void b2Joint::Destroy(b2Joint* joint, b2BlockAllocator* allocator) allocator->Free(joint, sizeof(b2GearJoint)); break; + case e_lineJoint: + allocator->Free(joint, sizeof(b2LineJoint)); + break; + + case e_weldJoint: + allocator->Free(joint, sizeof(b2WeldJoint)); + break; + + case e_frictionJoint: + allocator->Free(joint, sizeof(b2FrictionJoint)); + break; + default: b2Assert(false); break; @@ -123,12 +158,29 @@ void b2Joint::Destroy(b2Joint* joint, b2BlockAllocator* allocator) b2Joint::b2Joint(const b2JointDef* def) { + b2Assert(def->bodyA != def->bodyB); + m_type = def->type; m_prev = NULL; m_next = NULL; - m_body1 = def->body1; - m_body2 = def->body2; + m_bodyA = def->bodyA; + m_bodyB = def->bodyB; m_collideConnected = def->collideConnected; m_islandFlag = false; m_userData = def->userData; + + m_edgeA.joint = NULL; + m_edgeA.other = NULL; + m_edgeA.prev = NULL; + m_edgeA.next = NULL; + + m_edgeB.joint = NULL; + m_edgeB.other = NULL; + m_edgeB.prev = NULL; + m_edgeB.next = NULL; +} + +bool b2Joint::IsActive() const +{ + return m_bodyA->IsActive() && m_bodyB->IsActive(); } diff --git a/src/modules/physics/box2d/Source/Dynamics/Joints/b2Joint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.h similarity index 69% rename from src/modules/physics/box2d/Source/Dynamics/Joints/b2Joint.h rename to src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.h index 03dcfdebc..213ad7d1d 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Joints/b2Joint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.h @@ -16,10 +16,10 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#ifndef JOINT_H -#define JOINT_H +#ifndef B2_JOINT_H +#define B2_JOINT_H -#include "../../Common/b2Math.h" +#include class b2Body; class b2Joint; @@ -34,7 +34,10 @@ enum b2JointType e_distanceJoint, e_pulleyJoint, e_mouseJoint, - e_gearJoint + e_gearJoint, + e_lineJoint, + e_weldJoint, + e_frictionJoint, }; enum b2LimitState @@ -47,10 +50,10 @@ enum b2LimitState struct b2Jacobian { - b2Vec2 linear1; - float32 angular1; - b2Vec2 linear2; - float32 angular2; + b2Vec2 linearA; + float32 angularA; + b2Vec2 linearB; + float32 angularB; void SetZero(); void Set(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2); @@ -77,8 +80,8 @@ struct b2JointDef { type = e_unknownJoint; userData = NULL; - body1 = NULL; - body2 = NULL; + bodyA = NULL; + bodyB = NULL; collideConnected = false; } @@ -89,10 +92,10 @@ struct b2JointDef void* userData; /// The first attached body. - b2Body* body1; + b2Body* bodyA; /// The second attached body. - b2Body* body2; + b2Body* bodyB; /// Set this flag to true if the attached bodies should collide. bool collideConnected; @@ -108,33 +111,35 @@ public: b2JointType GetType() const; /// Get the first body attached to this joint. - b2Body* GetBody1(); + b2Body* GetBodyA(); /// Get the second body attached to this joint. - b2Body* GetBody2(); + b2Body* GetBodyB(); - /// Get the anchor point on body1 in world coordinates. - virtual b2Vec2 GetAnchor1() const = 0; + /// Get the anchor point on bodyA in world coordinates. + virtual b2Vec2 GetAnchorA() const = 0; - /// Get the anchor point on body2 in world coordinates. - virtual b2Vec2 GetAnchor2() const = 0; + /// Get the anchor point on bodyB in world coordinates. + virtual b2Vec2 GetAnchorB() const = 0; - /// Get the reaction force on body2 at the joint anchor. - virtual b2Vec2 GetReactionForce() const = 0; + /// Get the reaction force on body2 at the joint anchor in Newtons. + virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0; - /// Get the reaction torque on body2. - virtual float32 GetReactionTorque() const = 0; + /// Get the reaction torque on body2 in N*m. + virtual float32 GetReactionTorque(float32 inv_dt) const = 0; /// Get the next joint the world joint list. b2Joint* GetNext(); /// Get the user data pointer. - void* GetUserData(); + void* GetUserData() const; /// Set the user data pointer. void SetUserData(void* data); - //--------------- Internals Below ------------------- + /// Short-cut function to determine if either body is inactive. + bool IsActive() const; + protected: friend class b2World; friend class b2Body; @@ -150,42 +155,42 @@ protected: virtual void SolveVelocityConstraints(const b2TimeStep& step) = 0; // This returns true if the position errors are within tolerance. - virtual void InitPositionConstraints() {} - virtual bool SolvePositionConstraints() = 0; + virtual bool SolvePositionConstraints(float32 baumgarte) = 0; b2JointType m_type; b2Joint* m_prev; b2Joint* m_next; - b2JointEdge m_node1; - b2JointEdge m_node2; - b2Body* m_body1; - b2Body* m_body2; - - float32 m_inv_dt; + b2JointEdge m_edgeA; + b2JointEdge m_edgeB; + b2Body* m_bodyA; + b2Body* m_bodyB; bool m_islandFlag; - + bool m_collideConnected; void* m_userData; -public: - bool m_collideConnected; + + // Cache here per time step to reduce cache misses. + b2Vec2 m_localCenterA, m_localCenterB; + float32 m_invMassA, m_invIA; + float32 m_invMassB, m_invIB; }; inline void b2Jacobian::SetZero() { - linear1.SetZero(); angular1 = 0.0f; - linear2.SetZero(); angular2 = 0.0f; + linearA.SetZero(); angularA = 0.0f; + linearB.SetZero(); angularB = 0.0f; } inline void b2Jacobian::Set(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2) { - linear1 = x1; angular1 = a1; - linear2 = x2; angular2 = a2; + linearA = x1; angularA = a1; + linearB = x2; angularB = a2; } inline float32 b2Jacobian::Compute(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2) { - return b2Dot(linear1, x1) + angular1 * a1 + b2Dot(linear2, x2) + angular2 * a2; + return b2Dot(linearA, x1) + angularA * a1 + b2Dot(linearB, x2) + angularB * a2; } inline b2JointType b2Joint::GetType() const @@ -193,14 +198,14 @@ inline b2JointType b2Joint::GetType() const return m_type; } -inline b2Body* b2Joint::GetBody1() +inline b2Body* b2Joint::GetBodyA() { - return m_body1; + return m_bodyA; } -inline b2Body* b2Joint::GetBody2() +inline b2Body* b2Joint::GetBodyB() { - return m_body2; + return m_bodyB; } inline b2Joint* b2Joint::GetNext() @@ -208,7 +213,7 @@ inline b2Joint* b2Joint::GetNext() return m_next; } -inline void* b2Joint::GetUserData() +inline void* b2Joint::GetUserData() const { return m_userData; } diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.cpp new file mode 100644 index 000000000..b6b0a1cb2 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.cpp @@ -0,0 +1,591 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Linear constraint (point-to-line) +// d = p2 - p1 = x2 + r2 - x1 - r1 +// C = dot(perp, d) +// Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1)) +// = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2) +// J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)] +// +// K = J * invM * JT +// +// J = [-a -s1 a s2] +// a = perp +// s1 = cross(d + r1, a) = cross(p2 - x1, a) +// s2 = cross(r2, a) = cross(p2 - x2, a) + + +// Motor/Limit linear constraint +// C = dot(ax1, d) +// Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2) +// J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)] + +// Block Solver +// We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even +// when the mass has poor distribution (leading to large torques about the joint anchor points). +// +// The Jacobian has 3 rows: +// J = [-uT -s1 uT s2] // linear +// [-vT -a1 vT a2] // limit +// +// u = perp +// v = axis +// s1 = cross(d + r1, u), s2 = cross(r2, u) +// a1 = cross(d + r1, v), a2 = cross(r2, v) + +// M * (v2 - v1) = JT * df +// J * v2 = bias +// +// v2 = v1 + invM * JT * df +// J * (v1 + invM * JT * df) = bias +// K * df = bias - J * v1 = -Cdot +// K = J * invM * JT +// Cdot = J * v1 - bias +// +// Now solve for f2. +// df = f2 - f1 +// K * (f2 - f1) = -Cdot +// f2 = invK * (-Cdot) + f1 +// +// Clamp accumulated limit impulse. +// lower: f2(2) = max(f2(2), 0) +// upper: f2(2) = min(f2(2), 0) +// +// Solve for correct f2(1) +// K(1,1) * f2(1) = -Cdot(1) - K(1,2) * f2(2) + K(1,1:2) * f1 +// = -Cdot(1) - K(1,2) * f2(2) + K(1,1) * f1(1) + K(1,2) * f1(2) +// K(1,1) * f2(1) = -Cdot(1) - K(1,2) * (f2(2) - f1(2)) + K(1,1) * f1(1) +// f2(1) = invK(1,1) * (-Cdot(1) - K(1,2) * (f2(2) - f1(2))) + f1(1) +// +// Now compute impulse to be applied: +// df = f2 - f1 + +void b2LineJointDef::Initialize(b2Body* b1, b2Body* b2, const b2Vec2& anchor, const b2Vec2& axis) +{ + bodyA = b1; + bodyB = b2; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + localAxisA = bodyA->GetLocalVector(axis); +} + +b2LineJoint::b2LineJoint(const b2LineJointDef* def) +: b2Joint(def) +{ + m_localAnchor1 = def->localAnchorA; + m_localAnchor2 = def->localAnchorB; + m_localXAxis1 = def->localAxisA; + m_localYAxis1 = b2Cross(1.0f, m_localXAxis1); + + m_impulse.SetZero(); + m_motorMass = 0.0; + m_motorImpulse = 0.0f; + + m_lowerTranslation = def->lowerTranslation; + m_upperTranslation = def->upperTranslation; + m_maxMotorForce = def->maxMotorForce; + m_motorSpeed = def->motorSpeed; + m_enableLimit = def->enableLimit; + m_enableMotor = def->enableMotor; + m_limitState = e_inactiveLimit; + + m_axis.SetZero(); + m_perp.SetZero(); +} + +void b2LineJoint::InitVelocityConstraints(const b2TimeStep& step) +{ + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + m_localCenterA = b1->GetLocalCenter(); + m_localCenterB = b2->GetLocalCenter(); + + b2Transform xf1 = b1->GetTransform(); + b2Transform xf2 = b2->GetTransform(); + + // Compute the effective masses. + b2Vec2 r1 = b2Mul(xf1.R, m_localAnchor1 - m_localCenterA); + b2Vec2 r2 = b2Mul(xf2.R, m_localAnchor2 - m_localCenterB); + b2Vec2 d = b2->m_sweep.c + r2 - b1->m_sweep.c - r1; + + m_invMassA = b1->m_invMass; + m_invIA = b1->m_invI; + m_invMassB = b2->m_invMass; + m_invIB = b2->m_invI; + + // Compute motor Jacobian and effective mass. + { + m_axis = b2Mul(xf1.R, m_localXAxis1); + m_a1 = b2Cross(d + r1, m_axis); + m_a2 = b2Cross(r2, m_axis); + + m_motorMass = m_invMassA + m_invMassB + m_invIA * m_a1 * m_a1 + m_invIB * m_a2 * m_a2; + if (m_motorMass > b2_epsilon) + { + m_motorMass = 1.0f / m_motorMass; + } + else + { + m_motorMass = 0.0f; + } + } + + // Prismatic constraint. + { + m_perp = b2Mul(xf1.R, m_localYAxis1); + + m_s1 = b2Cross(d + r1, m_perp); + m_s2 = b2Cross(r2, m_perp); + + float32 m1 = m_invMassA, m2 = m_invMassB; + float32 i1 = m_invIA, i2 = m_invIB; + + float32 k11 = m1 + m2 + i1 * m_s1 * m_s1 + i2 * m_s2 * m_s2; + float32 k12 = i1 * m_s1 * m_a1 + i2 * m_s2 * m_a2; + float32 k22 = m1 + m2 + i1 * m_a1 * m_a1 + i2 * m_a2 * m_a2; + + m_K.col1.Set(k11, k12); + m_K.col2.Set(k12, k22); + } + + // Compute motor and limit terms. + if (m_enableLimit) + { + float32 jointTranslation = b2Dot(m_axis, d); + if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) + { + m_limitState = e_equalLimits; + } + else if (jointTranslation <= m_lowerTranslation) + { + if (m_limitState != e_atLowerLimit) + { + m_limitState = e_atLowerLimit; + m_impulse.y = 0.0f; + } + } + else if (jointTranslation >= m_upperTranslation) + { + if (m_limitState != e_atUpperLimit) + { + m_limitState = e_atUpperLimit; + m_impulse.y = 0.0f; + } + } + else + { + m_limitState = e_inactiveLimit; + m_impulse.y = 0.0f; + } + } + else + { + m_limitState = e_inactiveLimit; + } + + if (m_enableMotor == false) + { + m_motorImpulse = 0.0f; + } + + if (step.warmStarting) + { + // Account for variable time step. + m_impulse *= step.dtRatio; + m_motorImpulse *= step.dtRatio; + + b2Vec2 P = m_impulse.x * m_perp + (m_motorImpulse + m_impulse.y) * m_axis; + float32 L1 = m_impulse.x * m_s1 + (m_motorImpulse + m_impulse.y) * m_a1; + float32 L2 = m_impulse.x * m_s2 + (m_motorImpulse + m_impulse.y) * m_a2; + + b1->m_linearVelocity -= m_invMassA * P; + b1->m_angularVelocity -= m_invIA * L1; + + b2->m_linearVelocity += m_invMassB * P; + b2->m_angularVelocity += m_invIB * L2; + } + else + { + m_impulse.SetZero(); + m_motorImpulse = 0.0f; + } +} + +void b2LineJoint::SolveVelocityConstraints(const b2TimeStep& step) +{ + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + b2Vec2 v1 = b1->m_linearVelocity; + float32 w1 = b1->m_angularVelocity; + b2Vec2 v2 = b2->m_linearVelocity; + float32 w2 = b2->m_angularVelocity; + + // Solve linear motor constraint. + if (m_enableMotor && m_limitState != e_equalLimits) + { + float32 Cdot = b2Dot(m_axis, v2 - v1) + m_a2 * w2 - m_a1 * w1; + float32 impulse = m_motorMass * (m_motorSpeed - Cdot); + float32 oldImpulse = m_motorImpulse; + float32 maxImpulse = step.dt * m_maxMotorForce; + m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_motorImpulse - oldImpulse; + + b2Vec2 P = impulse * m_axis; + float32 L1 = impulse * m_a1; + float32 L2 = impulse * m_a2; + + v1 -= m_invMassA * P; + w1 -= m_invIA * L1; + + v2 += m_invMassB * P; + w2 += m_invIB * L2; + } + + float32 Cdot1 = b2Dot(m_perp, v2 - v1) + m_s2 * w2 - m_s1 * w1; + + if (m_enableLimit && m_limitState != e_inactiveLimit) + { + // Solve prismatic and limit constraint in block form. + float32 Cdot2 = b2Dot(m_axis, v2 - v1) + m_a2 * w2 - m_a1 * w1; + b2Vec2 Cdot(Cdot1, Cdot2); + + b2Vec2 f1 = m_impulse; + b2Vec2 df = m_K.Solve(-Cdot); + m_impulse += df; + + if (m_limitState == e_atLowerLimit) + { + m_impulse.y = b2Max(m_impulse.y, 0.0f); + } + else if (m_limitState == e_atUpperLimit) + { + m_impulse.y = b2Min(m_impulse.y, 0.0f); + } + + // f2(1) = invK(1,1) * (-Cdot(1) - K(1,2) * (f2(2) - f1(2))) + f1(1) + float32 b = -Cdot1 - (m_impulse.y - f1.y) * m_K.col2.x; + float32 f2r; + if (m_K.col1.x != 0.0f) + { + f2r = b / m_K.col1.x + f1.x; + } + else + { + f2r = f1.x; + } + + m_impulse.x = f2r; + + df = m_impulse - f1; + + b2Vec2 P = df.x * m_perp + df.y * m_axis; + float32 L1 = df.x * m_s1 + df.y * m_a1; + float32 L2 = df.x * m_s2 + df.y * m_a2; + + v1 -= m_invMassA * P; + w1 -= m_invIA * L1; + + v2 += m_invMassB * P; + w2 += m_invIB * L2; + } + else + { + // Limit is inactive, just solve the prismatic constraint in block form. + float32 df; + if (m_K.col1.x != 0.0f) + { + df = - Cdot1 / m_K.col1.x; + } + else + { + df = 0.0f; + } + m_impulse.x += df; + + b2Vec2 P = df * m_perp; + float32 L1 = df * m_s1; + float32 L2 = df * m_s2; + + v1 -= m_invMassA * P; + w1 -= m_invIA * L1; + + v2 += m_invMassB * P; + w2 += m_invIB * L2; + } + + b1->m_linearVelocity = v1; + b1->m_angularVelocity = w1; + b2->m_linearVelocity = v2; + b2->m_angularVelocity = w2; +} + +bool b2LineJoint::SolvePositionConstraints(float32 baumgarte) +{ + B2_NOT_USED(baumgarte); + + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + b2Vec2 c1 = b1->m_sweep.c; + float32 a1 = b1->m_sweep.a; + + b2Vec2 c2 = b2->m_sweep.c; + float32 a2 = b2->m_sweep.a; + + // Solve linear limit constraint. + float32 linearError = 0.0f, angularError = 0.0f; + bool active = false; + float32 C2 = 0.0f; + + b2Mat22 R1(a1), R2(a2); + + b2Vec2 r1 = b2Mul(R1, m_localAnchor1 - m_localCenterA); + b2Vec2 r2 = b2Mul(R2, m_localAnchor2 - m_localCenterB); + b2Vec2 d = c2 + r2 - c1 - r1; + + if (m_enableLimit) + { + m_axis = b2Mul(R1, m_localXAxis1); + + m_a1 = b2Cross(d + r1, m_axis); + m_a2 = b2Cross(r2, m_axis); + + float32 translation = b2Dot(m_axis, d); + if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) + { + // Prevent large angular corrections + C2 = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection); + linearError = b2Abs(translation); + active = true; + } + else if (translation <= m_lowerTranslation) + { + // Prevent large linear corrections and allow some slop. + C2 = b2Clamp(translation - m_lowerTranslation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); + linearError = m_lowerTranslation - translation; + active = true; + } + else if (translation >= m_upperTranslation) + { + // Prevent large linear corrections and allow some slop. + C2 = b2Clamp(translation - m_upperTranslation - b2_linearSlop, 0.0f, b2_maxLinearCorrection); + linearError = translation - m_upperTranslation; + active = true; + } + } + + m_perp = b2Mul(R1, m_localYAxis1); + + m_s1 = b2Cross(d + r1, m_perp); + m_s2 = b2Cross(r2, m_perp); + + b2Vec2 impulse; + float32 C1; + C1 = b2Dot(m_perp, d); + + linearError = b2Max(linearError, b2Abs(C1)); + angularError = 0.0f; + + if (active) + { + float32 m1 = m_invMassA, m2 = m_invMassB; + float32 i1 = m_invIA, i2 = m_invIB; + + float32 k11 = m1 + m2 + i1 * m_s1 * m_s1 + i2 * m_s2 * m_s2; + float32 k12 = i1 * m_s1 * m_a1 + i2 * m_s2 * m_a2; + float32 k22 = m1 + m2 + i1 * m_a1 * m_a1 + i2 * m_a2 * m_a2; + + m_K.col1.Set(k11, k12); + m_K.col2.Set(k12, k22); + + b2Vec2 C; + C.x = C1; + C.y = C2; + + impulse = m_K.Solve(-C); + } + else + { + float32 m1 = m_invMassA, m2 = m_invMassB; + float32 i1 = m_invIA, i2 = m_invIB; + + float32 k11 = m1 + m2 + i1 * m_s1 * m_s1 + i2 * m_s2 * m_s2; + + float32 impulse1; + if (k11 != 0.0f) + { + impulse1 = - C1 / k11; + } + else + { + impulse1 = 0.0f; + } + + impulse.x = impulse1; + impulse.y = 0.0f; + } + + b2Vec2 P = impulse.x * m_perp + impulse.y * m_axis; + float32 L1 = impulse.x * m_s1 + impulse.y * m_a1; + float32 L2 = impulse.x * m_s2 + impulse.y * m_a2; + + c1 -= m_invMassA * P; + a1 -= m_invIA * L1; + c2 += m_invMassB * P; + a2 += m_invIB * L2; + + // TODO_ERIN remove need for this. + b1->m_sweep.c = c1; + b1->m_sweep.a = a1; + b2->m_sweep.c = c2; + b2->m_sweep.a = a2; + b1->SynchronizeTransform(); + b2->SynchronizeTransform(); + + return linearError <= b2_linearSlop && angularError <= b2_angularSlop; +} + +b2Vec2 b2LineJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchor1); +} + +b2Vec2 b2LineJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchor2); +} + +b2Vec2 b2LineJoint::GetReactionForce(float32 inv_dt) const +{ + return inv_dt * (m_impulse.x * m_perp + (m_motorImpulse + m_impulse.y) * m_axis); +} + +float32 b2LineJoint::GetReactionTorque(float32 inv_dt) const +{ + B2_NOT_USED(inv_dt); + return 0.0f; +} + +float32 b2LineJoint::GetJointTranslation() const +{ + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + b2Vec2 p1 = b1->GetWorldPoint(m_localAnchor1); + b2Vec2 p2 = b2->GetWorldPoint(m_localAnchor2); + b2Vec2 d = p2 - p1; + b2Vec2 axis = b1->GetWorldVector(m_localXAxis1); + + float32 translation = b2Dot(d, axis); + return translation; +} + +float32 b2LineJoint::GetJointSpeed() const +{ + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); + b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); + b2Vec2 p1 = b1->m_sweep.c + r1; + b2Vec2 p2 = b2->m_sweep.c + r2; + b2Vec2 d = p2 - p1; + b2Vec2 axis = b1->GetWorldVector(m_localXAxis1); + + b2Vec2 v1 = b1->m_linearVelocity; + b2Vec2 v2 = b2->m_linearVelocity; + float32 w1 = b1->m_angularVelocity; + float32 w2 = b2->m_angularVelocity; + + float32 speed = b2Dot(d, b2Cross(w1, axis)) + b2Dot(axis, v2 + b2Cross(w2, r2) - v1 - b2Cross(w1, r1)); + return speed; +} + +bool b2LineJoint::IsLimitEnabled() const +{ + return m_enableLimit; +} + +void b2LineJoint::EnableLimit(bool flag) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableLimit = flag; +} + +float32 b2LineJoint::GetLowerLimit() const +{ + return m_lowerTranslation; +} + +float32 b2LineJoint::GetUpperLimit() const +{ + return m_upperTranslation; +} + +void b2LineJoint::SetLimits(float32 lower, float32 upper) +{ + b2Assert(lower <= upper); + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_lowerTranslation = lower; + m_upperTranslation = upper; +} + +bool b2LineJoint::IsMotorEnabled() const +{ + return m_enableMotor; +} + +void b2LineJoint::EnableMotor(bool flag) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableMotor = flag; +} + +void b2LineJoint::SetMotorSpeed(float32 speed) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_motorSpeed = speed; +} + +void b2LineJoint::SetMaxMotorForce(float32 force) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_maxMotorForce = force; +} + +float32 b2LineJoint::GetMotorForce() const +{ + return m_motorImpulse; +} + + + + + diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.h new file mode 100644 index 000000000..803e4c12d --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.h @@ -0,0 +1,170 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_LINE_JOINT_H +#define B2_LINE_JOINT_H + +#include + +/// Line joint definition. This requires defining a line of +/// motion using an axis and an anchor point. The definition uses local +/// anchor points and a local axis so that the initial configuration +/// can violate the constraint slightly. The joint translation is zero +/// when the local anchor points coincide in world space. Using local +/// anchors and a local axis helps when saving and loading a game. +struct b2LineJointDef : public b2JointDef +{ + b2LineJointDef() + { + type = e_lineJoint; + localAnchorA.SetZero(); + localAnchorB.SetZero(); + localAxisA.Set(1.0f, 0.0f); + enableLimit = false; + lowerTranslation = 0.0f; + upperTranslation = 0.0f; + enableMotor = false; + maxMotorForce = 0.0f; + motorSpeed = 0.0f; + } + + /// Initialize the bodies, anchors, axis, and reference angle using the world + /// anchor and world axis. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); + + /// The local anchor point relative to body1's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to body2's origin. + b2Vec2 localAnchorB; + + /// The local translation axis in body1. + b2Vec2 localAxisA; + + /// Enable/disable the joint limit. + bool enableLimit; + + /// The lower translation limit, usually in meters. + float32 lowerTranslation; + + /// The upper translation limit, usually in meters. + float32 upperTranslation; + + /// Enable/disable the joint motor. + bool enableMotor; + + /// The maximum motor torque, usually in N-m. + float32 maxMotorForce; + + /// The desired motor speed in radians per second. + float32 motorSpeed; +}; + +/// A line joint. This joint provides two degrees of freedom: translation +/// along an axis fixed in body1 and rotation in the plane. You can use a +/// joint limit to restrict the range of motion and a joint motor to drive +/// the motion or to model joint friction. +class b2LineJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// Get the current joint translation, usually in meters. + float32 GetJointTranslation() const; + + /// Get the current joint translation speed, usually in meters per second. + float32 GetJointSpeed() const; + + /// Is the joint limit enabled? + bool IsLimitEnabled() const; + + /// Enable/disable the joint limit. + void EnableLimit(bool flag); + + /// Get the lower joint limit, usually in meters. + float32 GetLowerLimit() const; + + /// Get the upper joint limit, usually in meters. + float32 GetUpperLimit() const; + + /// Set the joint limits, usually in meters. + void SetLimits(float32 lower, float32 upper); + + /// Is the joint motor enabled? + bool IsMotorEnabled() const; + + /// Enable/disable the joint motor. + void EnableMotor(bool flag); + + /// Set the motor speed, usually in meters per second. + void SetMotorSpeed(float32 speed); + + /// Get the motor speed, usually in meters per second. + float32 GetMotorSpeed() const; + + /// Set/Get the maximum motor force, usually in N. + void SetMaxMotorForce(float32 force); + float32 GetMaxMotorForce() const; + + /// Get the current motor force, usually in N. + float32 GetMotorForce() const; + +protected: + + friend class b2Joint; + b2LineJoint(const b2LineJointDef* def); + + void InitVelocityConstraints(const b2TimeStep& step); + void SolveVelocityConstraints(const b2TimeStep& step); + bool SolvePositionConstraints(float32 baumgarte); + + b2Vec2 m_localAnchor1; + b2Vec2 m_localAnchor2; + b2Vec2 m_localXAxis1; + b2Vec2 m_localYAxis1; + + b2Vec2 m_axis, m_perp; + float32 m_s1, m_s2; + float32 m_a1, m_a2; + + b2Mat22 m_K; + b2Vec2 m_impulse; + + float32 m_motorMass; // effective mass for motor/limit translational constraint. + float32 m_motorImpulse; + + float32 m_lowerTranslation; + float32 m_upperTranslation; + float32 m_maxMotorForce; + float32 m_motorSpeed; + + bool m_enableLimit; + bool m_enableMotor; + b2LimitState m_limitState; +}; + +inline float32 b2LineJoint::GetMotorSpeed() const +{ + return m_motorSpeed; +} + +#endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.cpp new file mode 100644 index 000000000..b72ac5f30 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.cpp @@ -0,0 +1,197 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// p = attached point, m = mouse point +// C = p - m +// Cdot = v +// = v + cross(w, r) +// J = [I r_skew] +// Identity used: +// w k % (rx i + ry j) = w * (-ry i + rx j) + +b2MouseJoint::b2MouseJoint(const b2MouseJointDef* def) +: b2Joint(def) +{ + b2Assert(def->target.IsValid()); + b2Assert(b2IsValid(def->maxForce) && def->maxForce >= 0.0f); + b2Assert(b2IsValid(def->frequencyHz) && def->frequencyHz >= 0.0f); + b2Assert(b2IsValid(def->dampingRatio) && def->dampingRatio >= 0.0f); + + m_target = def->target; + m_localAnchor = b2MulT(m_bodyB->GetTransform(), m_target); + + m_maxForce = def->maxForce; + m_impulse.SetZero(); + + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; + + m_beta = 0.0f; + m_gamma = 0.0f; +} + +void b2MouseJoint::SetTarget(const b2Vec2& target) +{ + if (m_bodyB->IsAwake() == false) + { + m_bodyB->SetAwake(true); + } + m_target = target; +} + +const b2Vec2& b2MouseJoint::GetTarget() const +{ + return m_target; +} + +void b2MouseJoint::SetMaxForce(float32 force) +{ + m_maxForce = force; +} + +float32 b2MouseJoint::GetMaxForce() const +{ + return m_maxForce; +} + +void b2MouseJoint::SetFrequency(float32 hz) +{ + m_frequencyHz = hz; +} + +float32 b2MouseJoint::GetFrequency() const +{ + return m_frequencyHz; +} + +void b2MouseJoint::SetDampingRatio(float32 ratio) +{ + m_dampingRatio = ratio; +} + +float32 b2MouseJoint::GetDampingRatio() const +{ + return m_dampingRatio; +} + +void b2MouseJoint::InitVelocityConstraints(const b2TimeStep& step) +{ + b2Body* b = m_bodyB; + + float32 mass = b->GetMass(); + + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; + + // Damping coefficient + float32 d = 2.0f * mass * m_dampingRatio * omega; + + // Spring stiffness + float32 k = mass * (omega * omega); + + // magic formulas + // gamma has units of inverse mass. + // beta has units of inverse time. + b2Assert(d + step.dt * k > b2_epsilon); + m_gamma = step.dt * (d + step.dt * k); + if (m_gamma != 0.0f) + { + m_gamma = 1.0f / m_gamma; + } + m_beta = step.dt * k * m_gamma; + + // Compute the effective mass matrix. + b2Vec2 r = b2Mul(b->GetTransform().R, m_localAnchor - b->GetLocalCenter()); + + // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] + // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] + // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] + float32 invMass = b->m_invMass; + float32 invI = b->m_invI; + + b2Mat22 K1; + K1.col1.x = invMass; K1.col2.x = 0.0f; + K1.col1.y = 0.0f; K1.col2.y = invMass; + + b2Mat22 K2; + K2.col1.x = invI * r.y * r.y; K2.col2.x = -invI * r.x * r.y; + K2.col1.y = -invI * r.x * r.y; K2.col2.y = invI * r.x * r.x; + + b2Mat22 K = K1 + K2; + K.col1.x += m_gamma; + K.col2.y += m_gamma; + + m_mass = K.GetInverse(); + + m_C = b->m_sweep.c + r - m_target; + + // Cheat with some damping + b->m_angularVelocity *= 0.98f; + + // Warm starting. + m_impulse *= step.dtRatio; + b->m_linearVelocity += invMass * m_impulse; + b->m_angularVelocity += invI * b2Cross(r, m_impulse); +} + +void b2MouseJoint::SolveVelocityConstraints(const b2TimeStep& step) +{ + b2Body* b = m_bodyB; + + b2Vec2 r = b2Mul(b->GetTransform().R, m_localAnchor - b->GetLocalCenter()); + + // Cdot = v + cross(w, r) + b2Vec2 Cdot = b->m_linearVelocity + b2Cross(b->m_angularVelocity, r); + b2Vec2 impulse = b2Mul(m_mass, -(Cdot + m_beta * m_C + m_gamma * m_impulse)); + + b2Vec2 oldImpulse = m_impulse; + m_impulse += impulse; + float32 maxImpulse = step.dt * m_maxForce; + if (m_impulse.LengthSquared() > maxImpulse * maxImpulse) + { + m_impulse *= maxImpulse / m_impulse.Length(); + } + impulse = m_impulse - oldImpulse; + + b->m_linearVelocity += b->m_invMass * impulse; + b->m_angularVelocity += b->m_invI * b2Cross(r, impulse); +} + +b2Vec2 b2MouseJoint::GetAnchorA() const +{ + return m_target; +} + +b2Vec2 b2MouseJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchor); +} + +b2Vec2 b2MouseJoint::GetReactionForce(float32 inv_dt) const +{ + return inv_dt * m_impulse; +} + +float32 b2MouseJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * 0.0f; +} diff --git a/src/modules/physics/box2d/Source/Dynamics/Joints/b2MouseJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.h similarity index 70% rename from src/modules/physics/box2d/Source/Dynamics/Joints/b2MouseJoint.h rename to src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.h index 3d9e59005..cd1959a42 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Joints/b2MouseJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.h @@ -19,7 +19,7 @@ #ifndef B2_MOUSE_JOINT_H #define B2_MOUSE_JOINT_H -#include "b2Joint.h" +#include /// Mouse joint definition. This requires a world target point, /// tuning parameters, and the time step. @@ -32,7 +32,6 @@ struct b2MouseJointDef : public b2JointDef maxForce = 0.0f; frequencyHz = 5.0f; dampingRatio = 0.7f; - timeStep = 1.0f / 60.0f; } /// The initial world target point. This is assumed @@ -49,44 +48,55 @@ struct b2MouseJointDef : public b2JointDef /// The damping ratio. 0 = no damping, 1 = critical damping. float32 dampingRatio; - - /// The time step used in the simulation. - float32 timeStep; }; /// A mouse joint is used to make a point on a body track a /// specified world point. This a soft constraint with a maximum /// force. This allows the constraint to stretch and without /// applying huge forces. +/// NOTE: this joint is not documented in the manual because it was +/// developed to be used in the testbed. If you want to learn how to +/// use the mouse joint, look at the testbed. class b2MouseJoint : public b2Joint { public: /// Implements b2Joint. - b2Vec2 GetAnchor1() const; + b2Vec2 GetAnchorA() const; /// Implements b2Joint. - b2Vec2 GetAnchor2() const; + b2Vec2 GetAnchorB() const; /// Implements b2Joint. - b2Vec2 GetReactionForce() const; + b2Vec2 GetReactionForce(float32 inv_dt) const; /// Implements b2Joint. - float32 GetReactionTorque() const; + float32 GetReactionTorque(float32 inv_dt) const; /// Use this to update the target point. void SetTarget(const b2Vec2& target); + const b2Vec2& GetTarget() const; - //--------------- Internals Below ------------------- + /// Set/get the maximum force in Newtons. + void SetMaxForce(float32 force); + float32 GetMaxForce() const; + + /// Set/get the frequency in Hertz. + void SetFrequency(float32 hz); + float32 GetFrequency() const; + + /// Set/get the damping ratio (dimensionless). + void SetDampingRatio(float32 ratio); + float32 GetDampingRatio() const; + +protected: + friend class b2Joint; b2MouseJoint(const b2MouseJointDef* def); void InitVelocityConstraints(const b2TimeStep& step); void SolveVelocityConstraints(const b2TimeStep& step); - bool SolvePositionConstraints() - { - return true; - } + bool SolvePositionConstraints(float32 baumgarte) { B2_NOT_USED(baumgarte); return true; } b2Vec2 m_localAnchor; b2Vec2 m_target; @@ -95,8 +105,10 @@ public: b2Mat22 m_mass; // effective mass for point-to-point constraint. b2Vec2 m_C; // position error float32 m_maxForce; - float32 m_beta; // bias factor - float32 m_gamma; // softness + float32 m_frequencyHz; + float32 m_dampingRatio; + float32 m_beta; + float32 m_gamma; }; #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp new file mode 100644 index 000000000..a019888a4 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp @@ -0,0 +1,586 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Linear constraint (point-to-line) +// d = p2 - p1 = x2 + r2 - x1 - r1 +// C = dot(perp, d) +// Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1)) +// = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2) +// J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)] +// +// Angular constraint +// C = a2 - a1 + a_initial +// Cdot = w2 - w1 +// J = [0 0 -1 0 0 1] +// +// K = J * invM * JT +// +// J = [-a -s1 a s2] +// [0 -1 0 1] +// a = perp +// s1 = cross(d + r1, a) = cross(p2 - x1, a) +// s2 = cross(r2, a) = cross(p2 - x2, a) + + +// Motor/Limit linear constraint +// C = dot(ax1, d) +// Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2) +// J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)] + +// Block Solver +// We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even +// when the mass has poor distribution (leading to large torques about the joint anchor points). +// +// The Jacobian has 3 rows: +// J = [-uT -s1 uT s2] // linear +// [0 -1 0 1] // angular +// [-vT -a1 vT a2] // limit +// +// u = perp +// v = axis +// s1 = cross(d + r1, u), s2 = cross(r2, u) +// a1 = cross(d + r1, v), a2 = cross(r2, v) + +// M * (v2 - v1) = JT * df +// J * v2 = bias +// +// v2 = v1 + invM * JT * df +// J * (v1 + invM * JT * df) = bias +// K * df = bias - J * v1 = -Cdot +// K = J * invM * JT +// Cdot = J * v1 - bias +// +// Now solve for f2. +// df = f2 - f1 +// K * (f2 - f1) = -Cdot +// f2 = invK * (-Cdot) + f1 +// +// Clamp accumulated limit impulse. +// lower: f2(3) = max(f2(3), 0) +// upper: f2(3) = min(f2(3), 0) +// +// Solve for correct f2(1:2) +// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:3) * f1 +// = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:2) * f1(1:2) + K(1:2,3) * f1(3) +// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3)) + K(1:2,1:2) * f1(1:2) +// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) +// +// Now compute impulse to be applied: +// df = f2 - f1 + +void b2PrismaticJointDef::Initialize(b2Body* b1, b2Body* b2, const b2Vec2& anchor, const b2Vec2& axis) +{ + bodyA = b1; + bodyB = b2; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + localAxis1 = bodyA->GetLocalVector(axis); + referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); +} + +b2PrismaticJoint::b2PrismaticJoint(const b2PrismaticJointDef* def) +: b2Joint(def) +{ + m_localAnchor1 = def->localAnchorA; + m_localAnchor2 = def->localAnchorB; + m_localXAxis1 = def->localAxis1; + m_localYAxis1 = b2Cross(1.0f, m_localXAxis1); + m_refAngle = def->referenceAngle; + + m_impulse.SetZero(); + m_motorMass = 0.0; + m_motorImpulse = 0.0f; + + m_lowerTranslation = def->lowerTranslation; + m_upperTranslation = def->upperTranslation; + m_maxMotorForce = def->maxMotorForce; + m_motorSpeed = def->motorSpeed; + m_enableLimit = def->enableLimit; + m_enableMotor = def->enableMotor; + m_limitState = e_inactiveLimit; + + m_axis.SetZero(); + m_perp.SetZero(); +} + +void b2PrismaticJoint::InitVelocityConstraints(const b2TimeStep& step) +{ + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + m_localCenterA = b1->GetLocalCenter(); + m_localCenterB = b2->GetLocalCenter(); + + b2Transform xf1 = b1->GetTransform(); + b2Transform xf2 = b2->GetTransform(); + + // Compute the effective masses. + b2Vec2 r1 = b2Mul(xf1.R, m_localAnchor1 - m_localCenterA); + b2Vec2 r2 = b2Mul(xf2.R, m_localAnchor2 - m_localCenterB); + b2Vec2 d = b2->m_sweep.c + r2 - b1->m_sweep.c - r1; + + m_invMassA = b1->m_invMass; + m_invIA = b1->m_invI; + m_invMassB = b2->m_invMass; + m_invIB = b2->m_invI; + + // Compute motor Jacobian and effective mass. + { + m_axis = b2Mul(xf1.R, m_localXAxis1); + m_a1 = b2Cross(d + r1, m_axis); + m_a2 = b2Cross(r2, m_axis); + + m_motorMass = m_invMassA + m_invMassB + m_invIA * m_a1 * m_a1 + m_invIB * m_a2 * m_a2; + if (m_motorMass > b2_epsilon) + { + m_motorMass = 1.0f / m_motorMass; + } + } + + // Prismatic constraint. + { + m_perp = b2Mul(xf1.R, m_localYAxis1); + + m_s1 = b2Cross(d + r1, m_perp); + m_s2 = b2Cross(r2, m_perp); + + float32 m1 = m_invMassA, m2 = m_invMassB; + float32 i1 = m_invIA, i2 = m_invIB; + + float32 k11 = m1 + m2 + i1 * m_s1 * m_s1 + i2 * m_s2 * m_s2; + float32 k12 = i1 * m_s1 + i2 * m_s2; + float32 k13 = i1 * m_s1 * m_a1 + i2 * m_s2 * m_a2; + float32 k22 = i1 + i2; + float32 k23 = i1 * m_a1 + i2 * m_a2; + float32 k33 = m1 + m2 + i1 * m_a1 * m_a1 + i2 * m_a2 * m_a2; + + m_K.col1.Set(k11, k12, k13); + m_K.col2.Set(k12, k22, k23); + m_K.col3.Set(k13, k23, k33); + } + + // Compute motor and limit terms. + if (m_enableLimit) + { + float32 jointTranslation = b2Dot(m_axis, d); + if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) + { + m_limitState = e_equalLimits; + } + else if (jointTranslation <= m_lowerTranslation) + { + if (m_limitState != e_atLowerLimit) + { + m_limitState = e_atLowerLimit; + m_impulse.z = 0.0f; + } + } + else if (jointTranslation >= m_upperTranslation) + { + if (m_limitState != e_atUpperLimit) + { + m_limitState = e_atUpperLimit; + m_impulse.z = 0.0f; + } + } + else + { + m_limitState = e_inactiveLimit; + m_impulse.z = 0.0f; + } + } + else + { + m_limitState = e_inactiveLimit; + m_impulse.z = 0.0f; + } + + if (m_enableMotor == false) + { + m_motorImpulse = 0.0f; + } + + if (step.warmStarting) + { + // Account for variable time step. + m_impulse *= step.dtRatio; + m_motorImpulse *= step.dtRatio; + + b2Vec2 P = m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis; + float32 L1 = m_impulse.x * m_s1 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a1; + float32 L2 = m_impulse.x * m_s2 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a2; + + b1->m_linearVelocity -= m_invMassA * P; + b1->m_angularVelocity -= m_invIA * L1; + + b2->m_linearVelocity += m_invMassB * P; + b2->m_angularVelocity += m_invIB * L2; + } + else + { + m_impulse.SetZero(); + m_motorImpulse = 0.0f; + } +} + +void b2PrismaticJoint::SolveVelocityConstraints(const b2TimeStep& step) +{ + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + b2Vec2 v1 = b1->m_linearVelocity; + float32 w1 = b1->m_angularVelocity; + b2Vec2 v2 = b2->m_linearVelocity; + float32 w2 = b2->m_angularVelocity; + + // Solve linear motor constraint. + if (m_enableMotor && m_limitState != e_equalLimits) + { + float32 Cdot = b2Dot(m_axis, v2 - v1) + m_a2 * w2 - m_a1 * w1; + float32 impulse = m_motorMass * (m_motorSpeed - Cdot); + float32 oldImpulse = m_motorImpulse; + float32 maxImpulse = step.dt * m_maxMotorForce; + m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_motorImpulse - oldImpulse; + + b2Vec2 P = impulse * m_axis; + float32 L1 = impulse * m_a1; + float32 L2 = impulse * m_a2; + + v1 -= m_invMassA * P; + w1 -= m_invIA * L1; + + v2 += m_invMassB * P; + w2 += m_invIB * L2; + } + + b2Vec2 Cdot1; + Cdot1.x = b2Dot(m_perp, v2 - v1) + m_s2 * w2 - m_s1 * w1; + Cdot1.y = w2 - w1; + + if (m_enableLimit && m_limitState != e_inactiveLimit) + { + // Solve prismatic and limit constraint in block form. + float32 Cdot2; + Cdot2 = b2Dot(m_axis, v2 - v1) + m_a2 * w2 - m_a1 * w1; + b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); + + b2Vec3 f1 = m_impulse; + b2Vec3 df = m_K.Solve33(-Cdot); + m_impulse += df; + + if (m_limitState == e_atLowerLimit) + { + m_impulse.z = b2Max(m_impulse.z, 0.0f); + } + else if (m_limitState == e_atUpperLimit) + { + m_impulse.z = b2Min(m_impulse.z, 0.0f); + } + + // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) + b2Vec2 b = -Cdot1 - (m_impulse.z - f1.z) * b2Vec2(m_K.col3.x, m_K.col3.y); + b2Vec2 f2r = m_K.Solve22(b) + b2Vec2(f1.x, f1.y); + m_impulse.x = f2r.x; + m_impulse.y = f2r.y; + + df = m_impulse - f1; + + b2Vec2 P = df.x * m_perp + df.z * m_axis; + float32 L1 = df.x * m_s1 + df.y + df.z * m_a1; + float32 L2 = df.x * m_s2 + df.y + df.z * m_a2; + + v1 -= m_invMassA * P; + w1 -= m_invIA * L1; + + v2 += m_invMassB * P; + w2 += m_invIB * L2; + } + else + { + // Limit is inactive, just solve the prismatic constraint in block form. + b2Vec2 df = m_K.Solve22(-Cdot1); + m_impulse.x += df.x; + m_impulse.y += df.y; + + b2Vec2 P = df.x * m_perp; + float32 L1 = df.x * m_s1 + df.y; + float32 L2 = df.x * m_s2 + df.y; + + v1 -= m_invMassA * P; + w1 -= m_invIA * L1; + + v2 += m_invMassB * P; + w2 += m_invIB * L2; + } + + b1->m_linearVelocity = v1; + b1->m_angularVelocity = w1; + b2->m_linearVelocity = v2; + b2->m_angularVelocity = w2; +} + +bool b2PrismaticJoint::SolvePositionConstraints(float32 baumgarte) +{ + B2_NOT_USED(baumgarte); + + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + b2Vec2 c1 = b1->m_sweep.c; + float32 a1 = b1->m_sweep.a; + + b2Vec2 c2 = b2->m_sweep.c; + float32 a2 = b2->m_sweep.a; + + // Solve linear limit constraint. + float32 linearError = 0.0f, angularError = 0.0f; + bool active = false; + float32 C2 = 0.0f; + + b2Mat22 R1(a1), R2(a2); + + b2Vec2 r1 = b2Mul(R1, m_localAnchor1 - m_localCenterA); + b2Vec2 r2 = b2Mul(R2, m_localAnchor2 - m_localCenterB); + b2Vec2 d = c2 + r2 - c1 - r1; + + if (m_enableLimit) + { + m_axis = b2Mul(R1, m_localXAxis1); + + m_a1 = b2Cross(d + r1, m_axis); + m_a2 = b2Cross(r2, m_axis); + + float32 translation = b2Dot(m_axis, d); + if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) + { + // Prevent large angular corrections + C2 = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection); + linearError = b2Abs(translation); + active = true; + } + else if (translation <= m_lowerTranslation) + { + // Prevent large linear corrections and allow some slop. + C2 = b2Clamp(translation - m_lowerTranslation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); + linearError = m_lowerTranslation - translation; + active = true; + } + else if (translation >= m_upperTranslation) + { + // Prevent large linear corrections and allow some slop. + C2 = b2Clamp(translation - m_upperTranslation - b2_linearSlop, 0.0f, b2_maxLinearCorrection); + linearError = translation - m_upperTranslation; + active = true; + } + } + + m_perp = b2Mul(R1, m_localYAxis1); + + m_s1 = b2Cross(d + r1, m_perp); + m_s2 = b2Cross(r2, m_perp); + + b2Vec3 impulse; + b2Vec2 C1; + C1.x = b2Dot(m_perp, d); + C1.y = a2 - a1 - m_refAngle; + + linearError = b2Max(linearError, b2Abs(C1.x)); + angularError = b2Abs(C1.y); + + if (active) + { + float32 m1 = m_invMassA, m2 = m_invMassB; + float32 i1 = m_invIA, i2 = m_invIB; + + float32 k11 = m1 + m2 + i1 * m_s1 * m_s1 + i2 * m_s2 * m_s2; + float32 k12 = i1 * m_s1 + i2 * m_s2; + float32 k13 = i1 * m_s1 * m_a1 + i2 * m_s2 * m_a2; + float32 k22 = i1 + i2; + float32 k23 = i1 * m_a1 + i2 * m_a2; + float32 k33 = m1 + m2 + i1 * m_a1 * m_a1 + i2 * m_a2 * m_a2; + + m_K.col1.Set(k11, k12, k13); + m_K.col2.Set(k12, k22, k23); + m_K.col3.Set(k13, k23, k33); + + b2Vec3 C; + C.x = C1.x; + C.y = C1.y; + C.z = C2; + + impulse = m_K.Solve33(-C); + } + else + { + float32 m1 = m_invMassA, m2 = m_invMassB; + float32 i1 = m_invIA, i2 = m_invIB; + + float32 k11 = m1 + m2 + i1 * m_s1 * m_s1 + i2 * m_s2 * m_s2; + float32 k12 = i1 * m_s1 + i2 * m_s2; + float32 k22 = i1 + i2; + + m_K.col1.Set(k11, k12, 0.0f); + m_K.col2.Set(k12, k22, 0.0f); + + b2Vec2 impulse1 = m_K.Solve22(-C1); + impulse.x = impulse1.x; + impulse.y = impulse1.y; + impulse.z = 0.0f; + } + + b2Vec2 P = impulse.x * m_perp + impulse.z * m_axis; + float32 L1 = impulse.x * m_s1 + impulse.y + impulse.z * m_a1; + float32 L2 = impulse.x * m_s2 + impulse.y + impulse.z * m_a2; + + c1 -= m_invMassA * P; + a1 -= m_invIA * L1; + c2 += m_invMassB * P; + a2 += m_invIB * L2; + + // TODO_ERIN remove need for this. + b1->m_sweep.c = c1; + b1->m_sweep.a = a1; + b2->m_sweep.c = c2; + b2->m_sweep.a = a2; + b1->SynchronizeTransform(); + b2->SynchronizeTransform(); + + return linearError <= b2_linearSlop && angularError <= b2_angularSlop; +} + +b2Vec2 b2PrismaticJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchor1); +} + +b2Vec2 b2PrismaticJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchor2); +} + +b2Vec2 b2PrismaticJoint::GetReactionForce(float32 inv_dt) const +{ + return inv_dt * (m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis); +} + +float32 b2PrismaticJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_impulse.y; +} + +float32 b2PrismaticJoint::GetJointTranslation() const +{ + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + b2Vec2 p1 = b1->GetWorldPoint(m_localAnchor1); + b2Vec2 p2 = b2->GetWorldPoint(m_localAnchor2); + b2Vec2 d = p2 - p1; + b2Vec2 axis = b1->GetWorldVector(m_localXAxis1); + + float32 translation = b2Dot(d, axis); + return translation; +} + +float32 b2PrismaticJoint::GetJointSpeed() const +{ + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); + b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); + b2Vec2 p1 = b1->m_sweep.c + r1; + b2Vec2 p2 = b2->m_sweep.c + r2; + b2Vec2 d = p2 - p1; + b2Vec2 axis = b1->GetWorldVector(m_localXAxis1); + + b2Vec2 v1 = b1->m_linearVelocity; + b2Vec2 v2 = b2->m_linearVelocity; + float32 w1 = b1->m_angularVelocity; + float32 w2 = b2->m_angularVelocity; + + float32 speed = b2Dot(d, b2Cross(w1, axis)) + b2Dot(axis, v2 + b2Cross(w2, r2) - v1 - b2Cross(w1, r1)); + return speed; +} + +bool b2PrismaticJoint::IsLimitEnabled() const +{ + return m_enableLimit; +} + +void b2PrismaticJoint::EnableLimit(bool flag) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableLimit = flag; +} + +float32 b2PrismaticJoint::GetLowerLimit() const +{ + return m_lowerTranslation; +} + +float32 b2PrismaticJoint::GetUpperLimit() const +{ + return m_upperTranslation; +} + +void b2PrismaticJoint::SetLimits(float32 lower, float32 upper) +{ + b2Assert(lower <= upper); + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_lowerTranslation = lower; + m_upperTranslation = upper; +} + +bool b2PrismaticJoint::IsMotorEnabled() const +{ + return m_enableMotor; +} + +void b2PrismaticJoint::EnableMotor(bool flag) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableMotor = flag; +} + +void b2PrismaticJoint::SetMotorSpeed(float32 speed) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_motorSpeed = speed; +} + +void b2PrismaticJoint::SetMaxMotorForce(float32 force) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_maxMotorForce = force; +} + +float32 b2PrismaticJoint::GetMotorForce() const +{ + return m_motorImpulse; +} diff --git a/src/modules/physics/box2d/Source/Dynamics/Joints/b2PrismaticJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h similarity index 83% rename from src/modules/physics/box2d/Source/Dynamics/Joints/b2PrismaticJoint.h rename to src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h index 23a1a07db..7a12c5df8 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Joints/b2PrismaticJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h @@ -19,7 +19,7 @@ #ifndef B2_PRISMATIC_JOINT_H #define B2_PRISMATIC_JOINT_H -#include "b2Joint.h" +#include /// Prismatic joint definition. This requires defining a line of /// motion using an axis and an anchor point. The definition uses local @@ -27,13 +27,14 @@ /// can violate the constraint slightly. The joint translation is zero /// when the local anchor points coincide in world space. Using local /// anchors and a local axis helps when saving and loading a game. +/// @warning at least one body should by dynamic with a non-fixed rotation. struct b2PrismaticJointDef : public b2JointDef { b2PrismaticJointDef() { type = e_prismaticJoint; - localAnchor1.SetZero(); - localAnchor2.SetZero(); + localAnchorA.SetZero(); + localAnchorB.SetZero(); localAxis1.Set(1.0f, 0.0f); referenceAngle = 0.0f; enableLimit = false; @@ -46,13 +47,13 @@ struct b2PrismaticJointDef : public b2JointDef /// Initialize the bodies, anchors, axis, and reference angle using the world /// anchor and world axis. - void Initialize(b2Body* body1, b2Body* body2, const b2Vec2& anchor, const b2Vec2& axis); + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); /// The local anchor point relative to body1's origin. - b2Vec2 localAnchor1; + b2Vec2 localAnchorA; /// The local anchor point relative to body2's origin. - b2Vec2 localAnchor2; + b2Vec2 localAnchorB; /// The local translation axis in body1. b2Vec2 localAxis1; @@ -86,11 +87,11 @@ struct b2PrismaticJointDef : public b2JointDef class b2PrismaticJoint : public b2Joint { public: - b2Vec2 GetAnchor1() const; - b2Vec2 GetAnchor2() const; + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; - b2Vec2 GetReactionForce() const; - float32 GetReactionTorque() const; + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; /// Get the current joint translation, usually in meters. float32 GetJointTranslation() const; @@ -131,13 +132,14 @@ public: /// Get the current motor force, usually in N. float32 GetMotorForce() const; - //--------------- Internals Below ------------------- - +protected: + friend class b2Joint; + friend class b2GearJoint; b2PrismaticJoint(const b2PrismaticJointDef* def); void InitVelocityConstraints(const b2TimeStep& step); void SolveVelocityConstraints(const b2TimeStep& step); - bool SolvePositionConstraints(); + bool SolvePositionConstraints(float32 baumgarte); b2Vec2 m_localAnchor1; b2Vec2 m_localAnchor2; @@ -145,18 +147,15 @@ public: b2Vec2 m_localYAxis1; float32 m_refAngle; - b2Jacobian m_linearJacobian; - float32 m_linearMass; // effective mass for point-to-line constraint. - float32 m_force; - - float32 m_angularMass; // effective mass for angular constraint. - float32 m_torque; + b2Vec2 m_axis, m_perp; + float32 m_s1, m_s2; + float32 m_a1, m_a2; + + b2Mat33 m_K; + b2Vec3 m_impulse; - b2Jacobian m_motorJacobian; float32 m_motorMass; // effective mass for motor/limit translational constraint. - float32 m_motorForce; - float32 m_limitForce; - float32 m_limitPositionImpulse; + float32 m_motorImpulse; float32 m_lowerTranslation; float32 m_upperTranslation; diff --git a/src/modules/physics/box2d/Source/Dynamics/Joints/b2PulleyJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp similarity index 57% rename from src/modules/physics/box2d/Source/Dynamics/Joints/b2PulleyJoint.cpp rename to src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp index 3311910cf..beb7db8fb 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Joints/b2PulleyJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp @@ -16,9 +16,9 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#include "b2PulleyJoint.h" -#include "../b2Body.h" -#include "../b2World.h" +#include +#include +#include // Pulley: // length1 = norm(p1 - s1) @@ -44,58 +44,57 @@ void b2PulleyJointDef::Initialize(b2Body* b1, b2Body* b2, const b2Vec2& anchor1, const b2Vec2& anchor2, float32 r) { - body1 = b1; - body2 = b2; - groundAnchor1 = ga1; - groundAnchor2 = ga2; - localAnchor1 = body1->GetLocalPoint(anchor1); - localAnchor2 = body2->GetLocalPoint(anchor2); + bodyA = b1; + bodyB = b2; + groundAnchorA = ga1; + groundAnchorB = ga2; + localAnchorA = bodyA->GetLocalPoint(anchor1); + localAnchorB = bodyB->GetLocalPoint(anchor2); b2Vec2 d1 = anchor1 - ga1; - length1 = d1.Length(); + lengthA = d1.Length(); b2Vec2 d2 = anchor2 - ga2; - length2 = d2.Length(); + lengthB = d2.Length(); ratio = r; - b2Assert(ratio > B2_FLT_EPSILON); - float32 C = length1 + ratio * length2; - maxLength1 = C - ratio * b2_minPulleyLength; - maxLength2 = (C - b2_minPulleyLength) / ratio; + b2Assert(ratio > b2_epsilon); + float32 C = lengthA + ratio * lengthB; + maxLengthA = C - ratio * b2_minPulleyLength; + maxLengthB = (C - b2_minPulleyLength) / ratio; } b2PulleyJoint::b2PulleyJoint(const b2PulleyJointDef* def) : b2Joint(def) { - m_ground = m_body1->GetWorld()->GetGroundBody(); - m_groundAnchor1 = def->groundAnchor1 - m_ground->GetXForm().position; - m_groundAnchor2 = def->groundAnchor2 - m_ground->GetXForm().position; - m_localAnchor1 = def->localAnchor1; - m_localAnchor2 = def->localAnchor2; + m_groundAnchor1 = def->groundAnchorA; + m_groundAnchor2 = def->groundAnchorB; + m_localAnchor1 = def->localAnchorA; + m_localAnchor2 = def->localAnchorB; b2Assert(def->ratio != 0.0f); m_ratio = def->ratio; - m_constant = def->length1 + m_ratio * def->length2; + m_constant = def->lengthA + m_ratio * def->lengthB; - m_maxLength1 = b2Min(def->maxLength1, m_constant - m_ratio * b2_minPulleyLength); - m_maxLength2 = b2Min(def->maxLength2, (m_constant - b2_minPulleyLength) / m_ratio); + m_maxLength1 = b2Min(def->maxLengthA, m_constant - m_ratio * b2_minPulleyLength); + m_maxLength2 = b2Min(def->maxLengthB, (m_constant - b2_minPulleyLength) / m_ratio); - m_force = 0.0f; - m_limitForce1 = 0.0f; - m_limitForce2 = 0.0f; + m_impulse = 0.0f; + m_limitImpulse1 = 0.0f; + m_limitImpulse2 = 0.0f; } void b2PulleyJoint::InitVelocityConstraints(const b2TimeStep& step) { - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; - b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); + b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); + b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); b2Vec2 p1 = b1->m_sweep.c + r1; b2Vec2 p2 = b2->m_sweep.c + r2; - b2Vec2 s1 = m_ground->GetXForm().position + m_groundAnchor1; - b2Vec2 s2 = m_ground->GetXForm().position + m_groundAnchor2; + b2Vec2 s1 = m_groundAnchor1; + b2Vec2 s2 = m_groundAnchor2; // Get the pulley axes. m_u1 = p1 - s1; @@ -126,34 +125,31 @@ void b2PulleyJoint::InitVelocityConstraints(const b2TimeStep& step) if (C > 0.0f) { m_state = e_inactiveLimit; - m_force = 0.0f; + m_impulse = 0.0f; } else { m_state = e_atUpperLimit; - m_positionImpulse = 0.0f; } if (length1 < m_maxLength1) { m_limitState1 = e_inactiveLimit; - m_limitForce1 = 0.0f; + m_limitImpulse1 = 0.0f; } else { m_limitState1 = e_atUpperLimit; - m_limitPositionImpulse1 = 0.0f; } if (length2 < m_maxLength2) { m_limitState2 = e_inactiveLimit; - m_limitForce2 = 0.0f; + m_limitImpulse2 = 0.0f; } else { m_limitState2 = e_atUpperLimit; - m_limitPositionImpulse2 = 0.0f; } // Compute effective mass. @@ -163,18 +159,23 @@ void b2PulleyJoint::InitVelocityConstraints(const b2TimeStep& step) m_limitMass1 = b1->m_invMass + b1->m_invI * cr1u1 * cr1u1; m_limitMass2 = b2->m_invMass + b2->m_invI * cr2u2 * cr2u2; m_pulleyMass = m_limitMass1 + m_ratio * m_ratio * m_limitMass2; - b2Assert(m_limitMass1 > B2_FLT_EPSILON); - b2Assert(m_limitMass2 > B2_FLT_EPSILON); - b2Assert(m_pulleyMass > B2_FLT_EPSILON); + b2Assert(m_limitMass1 > b2_epsilon); + b2Assert(m_limitMass2 > b2_epsilon); + b2Assert(m_pulleyMass > b2_epsilon); m_limitMass1 = 1.0f / m_limitMass1; m_limitMass2 = 1.0f / m_limitMass2; m_pulleyMass = 1.0f / m_pulleyMass; if (step.warmStarting) { + // Scale impulses to support variable time steps. + m_impulse *= step.dtRatio; + m_limitImpulse1 *= step.dtRatio; + m_limitImpulse2 *= step.dtRatio; + // Warm starting. - b2Vec2 P1 = B2FORCE_SCALE(step.dt) * (-m_force - m_limitForce1) * m_u1; - b2Vec2 P2 = B2FORCE_SCALE(step.dt) * (-m_ratio * m_force - m_limitForce2) * m_u2; + b2Vec2 P1 = -(m_impulse + m_limitImpulse1) * m_u1; + b2Vec2 P2 = (-m_ratio * m_impulse - m_limitImpulse2) * m_u2; b1->m_linearVelocity += b1->m_invMass * P1; b1->m_angularVelocity += b1->m_invI * b2Cross(r1, P1); b2->m_linearVelocity += b2->m_invMass * P2; @@ -182,19 +183,21 @@ void b2PulleyJoint::InitVelocityConstraints(const b2TimeStep& step) } else { - m_force = 0.0f; - m_limitForce1 = 0.0f; - m_limitForce2 = 0.0f; + m_impulse = 0.0f; + m_limitImpulse1 = 0.0f; + m_limitImpulse2 = 0.0f; } } void b2PulleyJoint::SolveVelocityConstraints(const b2TimeStep& step) { - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; + B2_NOT_USED(step); - b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); + b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); if (m_state == e_atUpperLimit) { @@ -202,13 +205,13 @@ void b2PulleyJoint::SolveVelocityConstraints(const b2TimeStep& step) b2Vec2 v2 = b2->m_linearVelocity + b2Cross(b2->m_angularVelocity, r2); float32 Cdot = -b2Dot(m_u1, v1) - m_ratio * b2Dot(m_u2, v2); - float32 force = -B2FORCE_INV_SCALE(step.inv_dt) * m_pulleyMass * Cdot; - float32 oldForce = m_force; - m_force = b2Max(0.0f, m_force + force); - force = m_force - oldForce; + float32 impulse = m_pulleyMass * (-Cdot); + float32 oldImpulse = m_impulse; + m_impulse = b2Max(0.0f, m_impulse + impulse); + impulse = m_impulse - oldImpulse; - b2Vec2 P1 = -B2FORCE_SCALE(step.dt) * force * m_u1; - b2Vec2 P2 = -B2FORCE_SCALE(step.dt) * m_ratio * force * m_u2; + b2Vec2 P1 = -impulse * m_u1; + b2Vec2 P2 = -m_ratio * impulse * m_u2; b1->m_linearVelocity += b1->m_invMass * P1; b1->m_angularVelocity += b1->m_invI * b2Cross(r1, P1); b2->m_linearVelocity += b2->m_invMass * P2; @@ -220,12 +223,12 @@ void b2PulleyJoint::SolveVelocityConstraints(const b2TimeStep& step) b2Vec2 v1 = b1->m_linearVelocity + b2Cross(b1->m_angularVelocity, r1); float32 Cdot = -b2Dot(m_u1, v1); - float32 force = -B2FORCE_INV_SCALE(step.inv_dt) * m_limitMass1 * Cdot; - float32 oldForce = m_limitForce1; - m_limitForce1 = b2Max(0.0f, m_limitForce1 + force); - force = m_limitForce1 - oldForce; + float32 impulse = -m_limitMass1 * Cdot; + float32 oldImpulse = m_limitImpulse1; + m_limitImpulse1 = b2Max(0.0f, m_limitImpulse1 + impulse); + impulse = m_limitImpulse1 - oldImpulse; - b2Vec2 P1 = -B2FORCE_SCALE(step.dt) * force * m_u1; + b2Vec2 P1 = -impulse * m_u1; b1->m_linearVelocity += b1->m_invMass * P1; b1->m_angularVelocity += b1->m_invI * b2Cross(r1, P1); } @@ -235,31 +238,33 @@ void b2PulleyJoint::SolveVelocityConstraints(const b2TimeStep& step) b2Vec2 v2 = b2->m_linearVelocity + b2Cross(b2->m_angularVelocity, r2); float32 Cdot = -b2Dot(m_u2, v2); - float32 force = -B2FORCE_INV_SCALE(step.inv_dt) * m_limitMass2 * Cdot; - float32 oldForce = m_limitForce2; - m_limitForce2 = b2Max(0.0f, m_limitForce2 + force); - force = m_limitForce2 - oldForce; + float32 impulse = -m_limitMass2 * Cdot; + float32 oldImpulse = m_limitImpulse2; + m_limitImpulse2 = b2Max(0.0f, m_limitImpulse2 + impulse); + impulse = m_limitImpulse2 - oldImpulse; - b2Vec2 P2 = -B2FORCE_SCALE(step.dt) * force * m_u2; + b2Vec2 P2 = -impulse * m_u2; b2->m_linearVelocity += b2->m_invMass * P2; b2->m_angularVelocity += b2->m_invI * b2Cross(r2, P2); } } -bool b2PulleyJoint::SolvePositionConstraints() +bool b2PulleyJoint::SolvePositionConstraints(float32 baumgarte) { - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; + B2_NOT_USED(baumgarte); - b2Vec2 s1 = m_ground->GetXForm().position + m_groundAnchor1; - b2Vec2 s2 = m_ground->GetXForm().position + m_groundAnchor2; + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + b2Vec2 s1 = m_groundAnchor1; + b2Vec2 s2 = m_groundAnchor2; float32 linearError = 0.0f; if (m_state == e_atUpperLimit) { - b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); + b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); + b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); b2Vec2 p1 = b1->m_sweep.c + r1; b2Vec2 p2 = b2->m_sweep.c + r2; @@ -294,9 +299,6 @@ bool b2PulleyJoint::SolvePositionConstraints() C = b2Clamp(C + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); float32 impulse = -m_pulleyMass * C; - float32 oldImpulse = m_positionImpulse; - m_positionImpulse = b2Max(0.0f, m_positionImpulse + impulse); - impulse = m_positionImpulse - oldImpulse; b2Vec2 P1 = -impulse * m_u1; b2Vec2 P2 = -m_ratio * impulse * m_u2; @@ -312,7 +314,7 @@ bool b2PulleyJoint::SolvePositionConstraints() if (m_limitState1 == e_atUpperLimit) { - b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); + b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); b2Vec2 p1 = b1->m_sweep.c + r1; m_u1 = p1 - s1; @@ -331,9 +333,6 @@ bool b2PulleyJoint::SolvePositionConstraints() linearError = b2Max(linearError, -C); C = b2Clamp(C + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); float32 impulse = -m_limitMass1 * C; - float32 oldLimitPositionImpulse = m_limitPositionImpulse1; - m_limitPositionImpulse1 = b2Max(0.0f, m_limitPositionImpulse1 + impulse); - impulse = m_limitPositionImpulse1 - oldLimitPositionImpulse; b2Vec2 P1 = -impulse * m_u1; b1->m_sweep.c += b1->m_invMass * P1; @@ -344,7 +343,7 @@ bool b2PulleyJoint::SolvePositionConstraints() if (m_limitState2 == e_atUpperLimit) { - b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); + b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); b2Vec2 p2 = b2->m_sweep.c + r2; m_u2 = p2 - s2; @@ -363,9 +362,6 @@ bool b2PulleyJoint::SolvePositionConstraints() linearError = b2Max(linearError, -C); C = b2Clamp(C + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); float32 impulse = -m_limitMass2 * C; - float32 oldLimitPositionImpulse = m_limitPositionImpulse2; - m_limitPositionImpulse2 = b2Max(0.0f, m_limitPositionImpulse2 + impulse); - impulse = m_limitPositionImpulse2 - oldLimitPositionImpulse; b2Vec2 P2 = -impulse * m_u2; b2->m_sweep.c += b2->m_invMass * P2; @@ -377,49 +373,50 @@ bool b2PulleyJoint::SolvePositionConstraints() return linearError < b2_linearSlop; } -b2Vec2 b2PulleyJoint::GetAnchor1() const +b2Vec2 b2PulleyJoint::GetAnchorA() const { - return m_body1->GetWorldPoint(m_localAnchor1); + return m_bodyA->GetWorldPoint(m_localAnchor1); } -b2Vec2 b2PulleyJoint::GetAnchor2() const +b2Vec2 b2PulleyJoint::GetAnchorB() const { - return m_body2->GetWorldPoint(m_localAnchor2); + return m_bodyB->GetWorldPoint(m_localAnchor2); } -b2Vec2 b2PulleyJoint::GetReactionForce() const +b2Vec2 b2PulleyJoint::GetReactionForce(float32 inv_dt) const { - b2Vec2 F = B2FORCE_SCALE(m_force) * m_u2; - return F; + b2Vec2 P = m_impulse * m_u2; + return inv_dt * P; } -float32 b2PulleyJoint::GetReactionTorque() const +float32 b2PulleyJoint::GetReactionTorque(float32 inv_dt) const { + B2_NOT_USED(inv_dt); return 0.0f; } -b2Vec2 b2PulleyJoint::GetGroundAnchor1() const +b2Vec2 b2PulleyJoint::GetGroundAnchorA() const { - return m_ground->GetXForm().position + m_groundAnchor1; + return m_groundAnchor1; } -b2Vec2 b2PulleyJoint::GetGroundAnchor2() const +b2Vec2 b2PulleyJoint::GetGroundAnchorB() const { - return m_ground->GetXForm().position + m_groundAnchor2; + return m_groundAnchor2; } float32 b2PulleyJoint::GetLength1() const { - b2Vec2 p = m_body1->GetWorldPoint(m_localAnchor1); - b2Vec2 s = m_ground->GetXForm().position + m_groundAnchor1; + b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchor1); + b2Vec2 s = m_groundAnchor1; b2Vec2 d = p - s; return d.Length(); } float32 b2PulleyJoint::GetLength2() const { - b2Vec2 p = m_body2->GetWorldPoint(m_localAnchor2); - b2Vec2 s = m_ground->GetXForm().position + m_groundAnchor2; + b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchor2); + b2Vec2 s = m_groundAnchor2; b2Vec2 d = p - s; return d.Length(); } diff --git a/src/modules/physics/box2d/Source/Dynamics/Joints/b2PulleyJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.h similarity index 65% rename from src/modules/physics/box2d/Source/Dynamics/Joints/b2PulleyJoint.h rename to src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.h index fb65797ea..189decb31 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Joints/b2PulleyJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.h @@ -19,7 +19,7 @@ #ifndef B2_PULLEY_JOINT_H #define B2_PULLEY_JOINT_H -#include "b2Joint.h" +#include const float32 b2_minPulleyLength = 2.0f; @@ -31,47 +31,47 @@ struct b2PulleyJointDef : public b2JointDef b2PulleyJointDef() { type = e_pulleyJoint; - groundAnchor1.Set(-1.0f, 1.0f); - groundAnchor2.Set(1.0f, 1.0f); - localAnchor1.Set(-1.0f, 0.0f); - localAnchor2.Set(1.0f, 0.0f); - length1 = 0.0f; - maxLength1 = 0.0f; - length2 = 0.0f; - maxLength2 = 0.0f; + groundAnchorA.Set(-1.0f, 1.0f); + groundAnchorB.Set(1.0f, 1.0f); + localAnchorA.Set(-1.0f, 0.0f); + localAnchorB.Set(1.0f, 0.0f); + lengthA = 0.0f; + maxLengthA = 0.0f; + lengthB = 0.0f; + maxLengthB = 0.0f; ratio = 1.0f; collideConnected = true; } /// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors. - void Initialize(b2Body* body1, b2Body* body2, - const b2Vec2& groundAnchor1, const b2Vec2& groundAnchor2, - const b2Vec2& anchor1, const b2Vec2& anchor2, + void Initialize(b2Body* bodyA, b2Body* bodyB, + const b2Vec2& groundAnchorA, const b2Vec2& groundAnchorB, + const b2Vec2& anchorA, const b2Vec2& anchorB, float32 ratio); /// The first ground anchor in world coordinates. This point never moves. - b2Vec2 groundAnchor1; + b2Vec2 groundAnchorA; /// The second ground anchor in world coordinates. This point never moves. - b2Vec2 groundAnchor2; + b2Vec2 groundAnchorB; - /// The local anchor point relative to body1's origin. - b2Vec2 localAnchor1; + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; - /// The local anchor point relative to body2's origin. - b2Vec2 localAnchor2; + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; - /// The a reference length for the segment attached to body1. - float32 length1; + /// The a reference length for the segment attached to bodyA. + float32 lengthA; - /// The maximum length of the segment attached to body1. - float32 maxLength1; + /// The maximum length of the segment attached to bodyA. + float32 maxLengthA; - /// The a reference length for the segment attached to body2. - float32 length2; + /// The a reference length for the segment attached to bodyB. + float32 lengthB; - /// The maximum length of the segment attached to body2. - float32 maxLength2; + /// The maximum length of the segment attached to bodyB. + float32 maxLengthB; /// The pulley ratio, used to simulate a block-and-tackle. float32 ratio; @@ -86,17 +86,17 @@ struct b2PulleyJointDef : public b2JointDef class b2PulleyJoint : public b2Joint { public: - b2Vec2 GetAnchor1() const; - b2Vec2 GetAnchor2() const; + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; - b2Vec2 GetReactionForce() const; - float32 GetReactionTorque() const; + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; /// Get the first ground anchor. - b2Vec2 GetGroundAnchor1() const; + b2Vec2 GetGroundAnchorA() const; /// Get the second ground anchor. - b2Vec2 GetGroundAnchor2() const; + b2Vec2 GetGroundAnchorB() const; /// Get the current length of the segment attached to body1. float32 GetLength1() const; @@ -107,15 +107,15 @@ public: /// Get the pulley ratio. float32 GetRatio() const; - //--------------- Internals Below ------------------- +protected: + friend class b2Joint; b2PulleyJoint(const b2PulleyJointDef* data); void InitVelocityConstraints(const b2TimeStep& step); void SolveVelocityConstraints(const b2TimeStep& step); - bool SolvePositionConstraints(); + bool SolvePositionConstraints(float32 baumgarte); - b2Body* m_ground; b2Vec2 m_groundAnchor1; b2Vec2 m_groundAnchor2; b2Vec2 m_localAnchor1; @@ -136,14 +136,9 @@ public: float32 m_limitMass2; // Impulses for accumulation/warm starting. - float32 m_force; - float32 m_limitForce1; - float32 m_limitForce2; - - // Position impulses for accumulation. - float32 m_positionImpulse; - float32 m_limitPositionImpulse1; - float32 m_limitPositionImpulse2; + float32 m_impulse; + float32 m_limitImpulse1; + float32 m_limitImpulse2; b2LimitState m_state; b2LimitState m_limitState1; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp new file mode 100644 index 000000000..f9845265a --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp @@ -0,0 +1,478 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Point-to-point constraint +// C = p2 - p1 +// Cdot = v2 - v1 +// = v2 + cross(w2, r2) - v1 - cross(w1, r1) +// J = [-I -r1_skew I r2_skew ] +// Identity used: +// w k % (rx i + ry j) = w * (-ry i + rx j) + +// Motor constraint +// Cdot = w2 - w1 +// J = [0 0 -1 0 0 1] +// K = invI1 + invI2 + +void b2RevoluteJointDef::Initialize(b2Body* b1, b2Body* b2, const b2Vec2& anchor) +{ + bodyA = b1; + bodyB = b2; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); +} + +b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def) +: b2Joint(def) +{ + m_localAnchor1 = def->localAnchorA; + m_localAnchor2 = def->localAnchorB; + m_referenceAngle = def->referenceAngle; + + m_impulse.SetZero(); + m_motorImpulse = 0.0f; + + m_lowerAngle = def->lowerAngle; + m_upperAngle = def->upperAngle; + m_maxMotorTorque = def->maxMotorTorque; + m_motorSpeed = def->motorSpeed; + m_enableLimit = def->enableLimit; + m_enableMotor = def->enableMotor; + m_limitState = e_inactiveLimit; +} + +void b2RevoluteJoint::InitVelocityConstraints(const b2TimeStep& step) +{ + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + if (m_enableMotor || m_enableLimit) + { + // You cannot create a rotation limit between bodies that + // both have fixed rotation. + b2Assert(b1->m_invI > 0.0f || b2->m_invI > 0.0f); + } + + // Compute the effective mass matrix. + b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); + b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); + + // J = [-I -r1_skew I r2_skew] + // [ 0 -1 0 1] + // r_skew = [-ry; rx] + + // Matlab + // K = [ m1+r1y^2*i1+m2+r2y^2*i2, -r1y*i1*r1x-r2y*i2*r2x, -r1y*i1-r2y*i2] + // [ -r1y*i1*r1x-r2y*i2*r2x, m1+r1x^2*i1+m2+r2x^2*i2, r1x*i1+r2x*i2] + // [ -r1y*i1-r2y*i2, r1x*i1+r2x*i2, i1+i2] + + float32 m1 = b1->m_invMass, m2 = b2->m_invMass; + float32 i1 = b1->m_invI, i2 = b2->m_invI; + + m_mass.col1.x = m1 + m2 + r1.y * r1.y * i1 + r2.y * r2.y * i2; + m_mass.col2.x = -r1.y * r1.x * i1 - r2.y * r2.x * i2; + m_mass.col3.x = -r1.y * i1 - r2.y * i2; + m_mass.col1.y = m_mass.col2.x; + m_mass.col2.y = m1 + m2 + r1.x * r1.x * i1 + r2.x * r2.x * i2; + m_mass.col3.y = r1.x * i1 + r2.x * i2; + m_mass.col1.z = m_mass.col3.x; + m_mass.col2.z = m_mass.col3.y; + m_mass.col3.z = i1 + i2; + + m_motorMass = i1 + i2; + if (m_motorMass > 0.0f) + { + m_motorMass = 1.0f / m_motorMass; + } + + if (m_enableMotor == false) + { + m_motorImpulse = 0.0f; + } + + if (m_enableLimit) + { + float32 jointAngle = b2->m_sweep.a - b1->m_sweep.a - m_referenceAngle; + if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop) + { + m_limitState = e_equalLimits; + } + else if (jointAngle <= m_lowerAngle) + { + if (m_limitState != e_atLowerLimit) + { + m_impulse.z = 0.0f; + } + m_limitState = e_atLowerLimit; + } + else if (jointAngle >= m_upperAngle) + { + if (m_limitState != e_atUpperLimit) + { + m_impulse.z = 0.0f; + } + m_limitState = e_atUpperLimit; + } + else + { + m_limitState = e_inactiveLimit; + m_impulse.z = 0.0f; + } + } + else + { + m_limitState = e_inactiveLimit; + } + + if (step.warmStarting) + { + // Scale impulses to support a variable time step. + m_impulse *= step.dtRatio; + m_motorImpulse *= step.dtRatio; + + b2Vec2 P(m_impulse.x, m_impulse.y); + + b1->m_linearVelocity -= m1 * P; + b1->m_angularVelocity -= i1 * (b2Cross(r1, P) + m_motorImpulse + m_impulse.z); + + b2->m_linearVelocity += m2 * P; + b2->m_angularVelocity += i2 * (b2Cross(r2, P) + m_motorImpulse + m_impulse.z); + } + else + { + m_impulse.SetZero(); + m_motorImpulse = 0.0f; + } +} + +void b2RevoluteJoint::SolveVelocityConstraints(const b2TimeStep& step) +{ + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + b2Vec2 v1 = b1->m_linearVelocity; + float32 w1 = b1->m_angularVelocity; + b2Vec2 v2 = b2->m_linearVelocity; + float32 w2 = b2->m_angularVelocity; + + float32 m1 = b1->m_invMass, m2 = b2->m_invMass; + float32 i1 = b1->m_invI, i2 = b2->m_invI; + + // Solve motor constraint. + if (m_enableMotor && m_limitState != e_equalLimits) + { + float32 Cdot = w2 - w1 - m_motorSpeed; + float32 impulse = m_motorMass * (-Cdot); + float32 oldImpulse = m_motorImpulse; + float32 maxImpulse = step.dt * m_maxMotorTorque; + m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_motorImpulse - oldImpulse; + + w1 -= i1 * impulse; + w2 += i2 * impulse; + } + + // Solve limit constraint. + if (m_enableLimit && m_limitState != e_inactiveLimit) + { + b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); + b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); + + // Solve point-to-point constraint + b2Vec2 Cdot1 = v2 + b2Cross(w2, r2) - v1 - b2Cross(w1, r1); + float32 Cdot2 = w2 - w1; + b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); + + b2Vec3 impulse = m_mass.Solve33(-Cdot); + + if (m_limitState == e_equalLimits) + { + m_impulse += impulse; + } + else if (m_limitState == e_atLowerLimit) + { + float32 newImpulse = m_impulse.z + impulse.z; + if (newImpulse < 0.0f) + { + b2Vec2 reduced = m_mass.Solve22(-Cdot1); + impulse.x = reduced.x; + impulse.y = reduced.y; + impulse.z = -m_impulse.z; + m_impulse.x += reduced.x; + m_impulse.y += reduced.y; + m_impulse.z = 0.0f; + } + } + else if (m_limitState == e_atUpperLimit) + { + float32 newImpulse = m_impulse.z + impulse.z; + if (newImpulse > 0.0f) + { + b2Vec2 reduced = m_mass.Solve22(-Cdot1); + impulse.x = reduced.x; + impulse.y = reduced.y; + impulse.z = -m_impulse.z; + m_impulse.x += reduced.x; + m_impulse.y += reduced.y; + m_impulse.z = 0.0f; + } + } + + b2Vec2 P(impulse.x, impulse.y); + + v1 -= m1 * P; + w1 -= i1 * (b2Cross(r1, P) + impulse.z); + + v2 += m2 * P; + w2 += i2 * (b2Cross(r2, P) + impulse.z); + } + else + { + b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); + b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); + + // Solve point-to-point constraint + b2Vec2 Cdot = v2 + b2Cross(w2, r2) - v1 - b2Cross(w1, r1); + b2Vec2 impulse = m_mass.Solve22(-Cdot); + + m_impulse.x += impulse.x; + m_impulse.y += impulse.y; + + v1 -= m1 * impulse; + w1 -= i1 * b2Cross(r1, impulse); + + v2 += m2 * impulse; + w2 += i2 * b2Cross(r2, impulse); + } + + b1->m_linearVelocity = v1; + b1->m_angularVelocity = w1; + b2->m_linearVelocity = v2; + b2->m_angularVelocity = w2; +} + +bool b2RevoluteJoint::SolvePositionConstraints(float32 baumgarte) +{ + // TODO_ERIN block solve with limit. + + B2_NOT_USED(baumgarte); + + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + + float32 angularError = 0.0f; + float32 positionError = 0.0f; + + // Solve angular limit constraint. + if (m_enableLimit && m_limitState != e_inactiveLimit) + { + float32 angle = b2->m_sweep.a - b1->m_sweep.a - m_referenceAngle; + float32 limitImpulse = 0.0f; + + if (m_limitState == e_equalLimits) + { + // Prevent large angular corrections + float32 C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection); + limitImpulse = -m_motorMass * C; + angularError = b2Abs(C); + } + else if (m_limitState == e_atLowerLimit) + { + float32 C = angle - m_lowerAngle; + angularError = -C; + + // Prevent large angular corrections and allow some slop. + C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0.0f); + limitImpulse = -m_motorMass * C; + } + else if (m_limitState == e_atUpperLimit) + { + float32 C = angle - m_upperAngle; + angularError = C; + + // Prevent large angular corrections and allow some slop. + C = b2Clamp(C - b2_angularSlop, 0.0f, b2_maxAngularCorrection); + limitImpulse = -m_motorMass * C; + } + + b1->m_sweep.a -= b1->m_invI * limitImpulse; + b2->m_sweep.a += b2->m_invI * limitImpulse; + + b1->SynchronizeTransform(); + b2->SynchronizeTransform(); + } + + // Solve point-to-point constraint. + { + b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); + b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); + + b2Vec2 C = b2->m_sweep.c + r2 - b1->m_sweep.c - r1; + positionError = C.Length(); + + float32 invMass1 = b1->m_invMass, invMass2 = b2->m_invMass; + float32 invI1 = b1->m_invI, invI2 = b2->m_invI; + + // Handle large detachment. + const float32 k_allowedStretch = 10.0f * b2_linearSlop; + if (C.LengthSquared() > k_allowedStretch * k_allowedStretch) + { + // Use a particle solution (no rotation). + b2Vec2 u = C; u.Normalize(); + float32 m = invMass1 + invMass2; + if (m > 0.0f) + { + m = 1.0f / m; + } + b2Vec2 impulse = m * (-C); + const float32 k_beta = 0.5f; + b1->m_sweep.c -= k_beta * invMass1 * impulse; + b2->m_sweep.c += k_beta * invMass2 * impulse; + + C = b2->m_sweep.c + r2 - b1->m_sweep.c - r1; + } + + b2Mat22 K1; + K1.col1.x = invMass1 + invMass2; K1.col2.x = 0.0f; + K1.col1.y = 0.0f; K1.col2.y = invMass1 + invMass2; + + b2Mat22 K2; + K2.col1.x = invI1 * r1.y * r1.y; K2.col2.x = -invI1 * r1.x * r1.y; + K2.col1.y = -invI1 * r1.x * r1.y; K2.col2.y = invI1 * r1.x * r1.x; + + b2Mat22 K3; + K3.col1.x = invI2 * r2.y * r2.y; K3.col2.x = -invI2 * r2.x * r2.y; + K3.col1.y = -invI2 * r2.x * r2.y; K3.col2.y = invI2 * r2.x * r2.x; + + b2Mat22 K = K1 + K2 + K3; + b2Vec2 impulse = K.Solve(-C); + + b1->m_sweep.c -= b1->m_invMass * impulse; + b1->m_sweep.a -= b1->m_invI * b2Cross(r1, impulse); + + b2->m_sweep.c += b2->m_invMass * impulse; + b2->m_sweep.a += b2->m_invI * b2Cross(r2, impulse); + + b1->SynchronizeTransform(); + b2->SynchronizeTransform(); + } + + return positionError <= b2_linearSlop && angularError <= b2_angularSlop; +} + +b2Vec2 b2RevoluteJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchor1); +} + +b2Vec2 b2RevoluteJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchor2); +} + +b2Vec2 b2RevoluteJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 P(m_impulse.x, m_impulse.y); + return inv_dt * P; +} + +float32 b2RevoluteJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_impulse.z; +} + +float32 b2RevoluteJoint::GetJointAngle() const +{ + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + return b2->m_sweep.a - b1->m_sweep.a - m_referenceAngle; +} + +float32 b2RevoluteJoint::GetJointSpeed() const +{ + b2Body* b1 = m_bodyA; + b2Body* b2 = m_bodyB; + return b2->m_angularVelocity - b1->m_angularVelocity; +} + +bool b2RevoluteJoint::IsMotorEnabled() const +{ + return m_enableMotor; +} + +void b2RevoluteJoint::EnableMotor(bool flag) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableMotor = flag; +} + +float32 b2RevoluteJoint::GetMotorTorque() const +{ + return m_motorImpulse; +} + +void b2RevoluteJoint::SetMotorSpeed(float32 speed) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_motorSpeed = speed; +} + +void b2RevoluteJoint::SetMaxMotorTorque(float32 torque) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_maxMotorTorque = torque; +} + +bool b2RevoluteJoint::IsLimitEnabled() const +{ + return m_enableLimit; +} + +void b2RevoluteJoint::EnableLimit(bool flag) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableLimit = flag; +} + +float32 b2RevoluteJoint::GetLowerLimit() const +{ + return m_lowerAngle; +} + +float32 b2RevoluteJoint::GetUpperLimit() const +{ + return m_upperAngle; +} + +void b2RevoluteJoint::SetLimits(float32 lower, float32 upper) +{ + b2Assert(lower <= upper); + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_lowerAngle = lower; + m_upperAngle = upper; +} diff --git a/src/modules/physics/box2d/Source/Dynamics/Joints/b2RevoluteJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h similarity index 82% rename from src/modules/physics/box2d/Source/Dynamics/Joints/b2RevoluteJoint.h rename to src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h index ebec2f5ef..c0180beba 100644 --- a/src/modules/physics/box2d/Source/Dynamics/Joints/b2RevoluteJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h @@ -19,7 +19,7 @@ #ifndef B2_REVOLUTE_JOINT_H #define B2_REVOLUTE_JOINT_H -#include "b2Joint.h" +#include /// Revolute joint definition. This requires defining an /// anchor point where the bodies are joined. The definition @@ -37,8 +37,8 @@ struct b2RevoluteJointDef : public b2JointDef b2RevoluteJointDef() { type = e_revoluteJoint; - localAnchor1.Set(0.0f, 0.0f); - localAnchor2.Set(0.0f, 0.0f); + localAnchorA.Set(0.0f, 0.0f); + localAnchorB.Set(0.0f, 0.0f); referenceAngle = 0.0f; lowerAngle = 0.0f; upperAngle = 0.0f; @@ -48,15 +48,15 @@ struct b2RevoluteJointDef : public b2JointDef enableMotor = false; } - /// Initialize the bodies, anchors, and reference angle using the world - /// anchor. - void Initialize(b2Body* body1, b2Body* body2, const b2Vec2& anchor); + /// Initialize the bodies, anchors, and reference angle using a world + /// anchor point. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); /// The local anchor point relative to body1's origin. - b2Vec2 localAnchor1; + b2Vec2 localAnchorA; /// The local anchor point relative to body2's origin. - b2Vec2 localAnchor2; + b2Vec2 localAnchorB; /// The body2 angle minus body1 angle in the reference state (radians). float32 referenceAngle; @@ -81,7 +81,7 @@ struct b2RevoluteJointDef : public b2JointDef float32 maxMotorTorque; }; -/// A revolute joint constrains to bodies to share a common point while they +/// A revolute joint constrains two bodies to share a common point while they /// are free to rotate about the point. The relative rotation about the shared /// point is the joint angle. You can limit the relative rotation with /// a joint limit that specifies a lower and upper angle. You can use a motor @@ -90,11 +90,11 @@ struct b2RevoluteJointDef : public b2JointDef class b2RevoluteJoint : public b2Joint { public: - b2Vec2 GetAnchor1() const; - b2Vec2 GetAnchor2() const; + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; - b2Vec2 GetReactionForce() const; - float32 GetReactionTorque() const; + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; /// Get the current joint angle in radians. float32 GetJointAngle() const; @@ -135,22 +135,24 @@ public: /// Get the current motor torque, usually in N-m. float32 GetMotorTorque() const; - //--------------- Internals Below ------------------- +protected: + + friend class b2Joint; + friend class b2GearJoint; + b2RevoluteJoint(const b2RevoluteJointDef* def); void InitVelocityConstraints(const b2TimeStep& step); void SolveVelocityConstraints(const b2TimeStep& step); - bool SolvePositionConstraints(); + bool SolvePositionConstraints(float32 baumgarte); b2Vec2 m_localAnchor1; // relative b2Vec2 m_localAnchor2; - b2Vec2 m_pivotForce; - float32 m_motorForce; - float32 m_limitForce; - float32 m_limitPositionImpulse; + b2Vec3 m_impulse; + float32 m_motorImpulse; - b2Mat22 m_pivotMass; // effective mass for point-to-point constraint. + b2Mat33 m_mass; // effective mass for point-to-point constraint. float32 m_motorMass; // effective mass for motor/limit angular constraint. bool m_enableMotor; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp new file mode 100644 index 000000000..49b5513ba --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp @@ -0,0 +1,219 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Point-to-point constraint +// C = p2 - p1 +// Cdot = v2 - v1 +// = v2 + cross(w2, r2) - v1 - cross(w1, r1) +// J = [-I -r1_skew I r2_skew ] +// Identity used: +// w k % (rx i + ry j) = w * (-ry i + rx j) + +// Angle constraint +// C = angle2 - angle1 - referenceAngle +// Cdot = w2 - w1 +// J = [0 0 -1 0 0 1] +// K = invI1 + invI2 + +void b2WeldJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) +{ + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); +} + +b2WeldJoint::b2WeldJoint(const b2WeldJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_referenceAngle = def->referenceAngle; + + m_impulse.SetZero(); +} + +void b2WeldJoint::InitVelocityConstraints(const b2TimeStep& step) +{ + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + + // Compute the effective mass matrix. + b2Vec2 rA = b2Mul(bA->GetTransform().R, m_localAnchorA - bA->GetLocalCenter()); + b2Vec2 rB = b2Mul(bB->GetTransform().R, m_localAnchorB - bB->GetLocalCenter()); + + // J = [-I -r1_skew I r2_skew] + // [ 0 -1 0 1] + // r_skew = [-ry; rx] + + // Matlab + // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] + // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] + // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] + + float32 mA = bA->m_invMass, mB = bB->m_invMass; + float32 iA = bA->m_invI, iB = bB->m_invI; + + m_mass.col1.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; + m_mass.col2.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; + m_mass.col3.x = -rA.y * iA - rB.y * iB; + m_mass.col1.y = m_mass.col2.x; + m_mass.col2.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; + m_mass.col3.y = rA.x * iA + rB.x * iB; + m_mass.col1.z = m_mass.col3.x; + m_mass.col2.z = m_mass.col3.y; + m_mass.col3.z = iA + iB; + + if (step.warmStarting) + { + // Scale impulses to support a variable time step. + m_impulse *= step.dtRatio; + + b2Vec2 P(m_impulse.x, m_impulse.y); + + bA->m_linearVelocity -= mA * P; + bA->m_angularVelocity -= iA * (b2Cross(rA, P) + m_impulse.z); + + bB->m_linearVelocity += mB * P; + bB->m_angularVelocity += iB * (b2Cross(rB, P) + m_impulse.z); + } + else + { + m_impulse.SetZero(); + } +} + +void b2WeldJoint::SolveVelocityConstraints(const b2TimeStep& step) +{ + B2_NOT_USED(step); + + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + + b2Vec2 vA = bA->m_linearVelocity; + float32 wA = bA->m_angularVelocity; + b2Vec2 vB = bB->m_linearVelocity; + float32 wB = bB->m_angularVelocity; + + float32 mA = bA->m_invMass, mB = bB->m_invMass; + float32 iA = bA->m_invI, iB = bB->m_invI; + + b2Vec2 rA = b2Mul(bA->GetTransform().R, m_localAnchorA - bA->GetLocalCenter()); + b2Vec2 rB = b2Mul(bB->GetTransform().R, m_localAnchorB - bB->GetLocalCenter()); + + // Solve point-to-point constraint + b2Vec2 Cdot1 = vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA); + float32 Cdot2 = wB - wA; + b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); + + b2Vec3 impulse = m_mass.Solve33(-Cdot); + m_impulse += impulse; + + b2Vec2 P(impulse.x, impulse.y); + + vA -= mA * P; + wA -= iA * (b2Cross(rA, P) + impulse.z); + + vB += mB * P; + wB += iB * (b2Cross(rB, P) + impulse.z); + + bA->m_linearVelocity = vA; + bA->m_angularVelocity = wA; + bB->m_linearVelocity = vB; + bB->m_angularVelocity = wB; +} + +bool b2WeldJoint::SolvePositionConstraints(float32 baumgarte) +{ + B2_NOT_USED(baumgarte); + + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + + float32 mA = bA->m_invMass, mB = bB->m_invMass; + float32 iA = bA->m_invI, iB = bB->m_invI; + + b2Vec2 rA = b2Mul(bA->GetTransform().R, m_localAnchorA - bA->GetLocalCenter()); + b2Vec2 rB = b2Mul(bB->GetTransform().R, m_localAnchorB - bB->GetLocalCenter()); + + b2Vec2 C1 = bB->m_sweep.c + rB - bA->m_sweep.c - rA; + float32 C2 = bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle; + + // Handle large detachment. + const float32 k_allowedStretch = 10.0f * b2_linearSlop; + float32 positionError = C1.Length(); + float32 angularError = b2Abs(C2); + if (positionError > k_allowedStretch) + { + iA *= 1.0f; + iB *= 1.0f; + } + + m_mass.col1.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; + m_mass.col2.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; + m_mass.col3.x = -rA.y * iA - rB.y * iB; + m_mass.col1.y = m_mass.col2.x; + m_mass.col2.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; + m_mass.col3.y = rA.x * iA + rB.x * iB; + m_mass.col1.z = m_mass.col3.x; + m_mass.col2.z = m_mass.col3.y; + m_mass.col3.z = iA + iB; + + b2Vec3 C(C1.x, C1.y, C2); + + b2Vec3 impulse = m_mass.Solve33(-C); + + b2Vec2 P(impulse.x, impulse.y); + + bA->m_sweep.c -= mA * P; + bA->m_sweep.a -= iA * (b2Cross(rA, P) + impulse.z); + + bB->m_sweep.c += mB * P; + bB->m_sweep.a += iB * (b2Cross(rB, P) + impulse.z); + + bA->SynchronizeTransform(); + bB->SynchronizeTransform(); + + return positionError <= b2_linearSlop && angularError <= b2_angularSlop; +} + +b2Vec2 b2WeldJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2WeldJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2WeldJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 P(m_impulse.x, m_impulse.y); + return inv_dt * P; +} + +float32 b2WeldJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_impulse.z; +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h new file mode 100644 index 000000000..4e63b6aa6 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h @@ -0,0 +1,82 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_WELD_JOINT_H +#define B2_WELD_JOINT_H + +#include + +/// Weld joint definition. You need to specify local anchor points +/// where they are attached and the relative body angle. The position +/// of the anchor points is important for computing the reaction torque. +struct b2WeldJointDef : public b2JointDef +{ + b2WeldJointDef() + { + type = e_weldJoint; + localAnchorA.Set(0.0f, 0.0f); + localAnchorB.Set(0.0f, 0.0f); + referenceAngle = 0.0f; + } + + /// Initialize the bodies, anchors, and reference angle using a world + /// anchor point. + void Initialize(b2Body* body1, b2Body* body2, const b2Vec2& anchor); + + /// The local anchor point relative to body1's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to body2's origin. + b2Vec2 localAnchorB; + + /// The body2 angle minus body1 angle in the reference state (radians). + float32 referenceAngle; +}; + +/// A weld joint essentially glues two bodies together. A weld joint may +/// distort somewhat because the island constraint solver is approximate. +class b2WeldJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + +protected: + + friend class b2Joint; + + b2WeldJoint(const b2WeldJointDef* def); + + void InitVelocityConstraints(const b2TimeStep& step); + void SolveVelocityConstraints(const b2TimeStep& step); + + bool SolvePositionConstraints(float32 baumgarte); + + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_referenceAngle; + + b2Vec3 m_impulse; + + b2Mat33 m_mass; +}; + +#endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp new file mode 100644 index 000000000..4b8865148 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp @@ -0,0 +1,470 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +b2Body::b2Body(const b2BodyDef* bd, b2World* world) +{ + b2Assert(bd->position.IsValid()); + b2Assert(bd->linearVelocity.IsValid()); + b2Assert(b2IsValid(bd->angle)); + b2Assert(b2IsValid(bd->angularVelocity)); + b2Assert(b2IsValid(bd->inertiaScale) && bd->inertiaScale >= 0.0f); + b2Assert(b2IsValid(bd->angularDamping) && bd->angularDamping >= 0.0f); + b2Assert(b2IsValid(bd->linearDamping) && bd->linearDamping >= 0.0f); + + m_flags = 0; + + if (bd->bullet) + { + m_flags |= e_bulletFlag; + } + if (bd->fixedRotation) + { + m_flags |= e_fixedRotationFlag; + } + if (bd->allowSleep) + { + m_flags |= e_autoSleepFlag; + } + if (bd->awake) + { + m_flags |= e_awakeFlag; + } + if (bd->active) + { + m_flags |= e_activeFlag; + } + + m_world = world; + + m_xf.position = bd->position; + m_xf.R.Set(bd->angle); + + m_sweep.localCenter.SetZero(); + m_sweep.a0 = m_sweep.a = bd->angle; + m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + + m_jointList = NULL; + m_contactList = NULL; + m_prev = NULL; + m_next = NULL; + + m_linearVelocity = bd->linearVelocity; + m_angularVelocity = bd->angularVelocity; + + m_linearDamping = bd->linearDamping; + m_angularDamping = bd->angularDamping; + + m_force.SetZero(); + m_torque = 0.0f; + + m_sleepTime = 0.0f; + + m_type = bd->type; + + if (m_type == b2_dynamicBody) + { + m_mass = 1.0f; + m_invMass = 1.0f; + } + else + { + m_mass = 0.0f; + m_invMass = 0.0f; + } + + m_I = 0.0f; + m_invI = 0.0f; + + m_userData = bd->userData; + + m_fixtureList = NULL; + m_fixtureCount = 0; +} + +b2Body::~b2Body() +{ + // shapes and joints are destroyed in b2World::Destroy +} + +void b2Body::SetType(b2BodyType type) +{ + if (m_type == type) + { + return; + } + + m_type = type; + + ResetMassData(); + + if (m_type == b2_staticBody) + { + m_linearVelocity.SetZero(); + m_angularVelocity = 0.0f; + } + + SetAwake(true); + + m_force.SetZero(); + m_torque = 0.0f; + + // Since the body type changed, we need to flag contacts for filtering. + for (b2ContactEdge* ce = m_contactList; ce; ce = ce->next) + { + ce->contact->FlagForFiltering(); + } +} + +b2Fixture* b2Body::CreateFixture(const b2FixtureDef* def) +{ + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return NULL; + } + + b2BlockAllocator* allocator = &m_world->m_blockAllocator; + + void* memory = allocator->Allocate(sizeof(b2Fixture)); + b2Fixture* fixture = new (memory) b2Fixture; + fixture->Create(allocator, this, def); + + if (m_flags & e_activeFlag) + { + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + fixture->CreateProxy(broadPhase, m_xf); + } + + fixture->m_next = m_fixtureList; + m_fixtureList = fixture; + ++m_fixtureCount; + + fixture->m_body = this; + + // Adjust mass properties if needed. + if (fixture->m_density > 0.0f) + { + ResetMassData(); + } + + // Let the world know we have a new fixture. This will cause new contacts + // to be created at the beginning of the next time step. + m_world->m_flags |= b2World::e_newFixture; + + return fixture; +} + +b2Fixture* b2Body::CreateFixture(const b2Shape* shape, float32 density) +{ + b2FixtureDef def; + def.shape = shape; + def.density = density; + + return CreateFixture(&def); +} + +void b2Body::DestroyFixture(b2Fixture* fixture) +{ + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } + + b2Assert(fixture->m_body == this); + + // Remove the fixture from this body's singly linked list. + b2Assert(m_fixtureCount > 0); + b2Fixture** node = &m_fixtureList; + bool found = false; + while (*node != NULL) + { + if (*node == fixture) + { + *node = fixture->m_next; + found = true; + break; + } + + node = &(*node)->m_next; + } + + // You tried to remove a shape that is not attached to this body. + b2Assert(found); + + // Destroy any contacts associated with the fixture. + b2ContactEdge* edge = m_contactList; + while (edge) + { + b2Contact* c = edge->contact; + edge = edge->next; + + b2Fixture* fixtureA = c->GetFixtureA(); + b2Fixture* fixtureB = c->GetFixtureB(); + + if (fixture == fixtureA || fixture == fixtureB) + { + // This destroys the contact and removes it from + // this body's contact list. + m_world->m_contactManager.Destroy(c); + } + } + + b2BlockAllocator* allocator = &m_world->m_blockAllocator; + + if (m_flags & e_activeFlag) + { + b2Assert(fixture->m_proxyId != b2BroadPhase::e_nullProxy); + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + fixture->DestroyProxy(broadPhase); + } + else + { + b2Assert(fixture->m_proxyId == b2BroadPhase::e_nullProxy); + } + + fixture->Destroy(allocator); + fixture->m_body = NULL; + fixture->m_next = NULL; + fixture->~b2Fixture(); + allocator->Free(fixture, sizeof(b2Fixture)); + + --m_fixtureCount; + + // Reset the mass data. + ResetMassData(); +} + +void b2Body::ResetMassData() +{ + // Compute mass data from shapes. Each shape has its own density. + m_mass = 0.0f; + m_invMass = 0.0f; + m_I = 0.0f; + m_invI = 0.0f; + m_sweep.localCenter.SetZero(); + + // Static and kinematic bodies have zero mass. + if (m_type == b2_staticBody || m_type == b2_kinematicBody) + { + m_sweep.c0 = m_sweep.c = m_xf.position; + return; + } + + b2Assert(m_type == b2_dynamicBody); + + // Accumulate mass over all fixtures. + b2Vec2 center = b2Vec2_zero; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + if (f->m_density == 0.0f) + { + continue; + } + + b2MassData massData; + f->GetMassData(&massData); + m_mass += massData.mass; + center += massData.mass * massData.center; + m_I += massData.I; + } + + // Compute center of mass. + if (m_mass > 0.0f) + { + m_invMass = 1.0f / m_mass; + center *= m_invMass; + } + else + { + // Force all dynamic bodies to have a positive mass. + m_mass = 1.0f; + m_invMass = 1.0f; + } + + if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) + { + // Center the inertia about the center of mass. + m_I -= m_mass * b2Dot(center, center); + b2Assert(m_I > 0.0f); + m_invI = 1.0f / m_I; + + } + else + { + m_I = 0.0f; + m_invI = 0.0f; + } + + // Move center of mass. + b2Vec2 oldCenter = m_sweep.c; + m_sweep.localCenter = center; + m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + + // Update center of mass velocity. + m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); +} + +void b2Body::SetMassData(const b2MassData* massData) +{ + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } + + if (m_type != b2_dynamicBody) + { + return; + } + + m_invMass = 0.0f; + m_I = 0.0f; + m_invI = 0.0f; + + m_mass = massData->mass; + if (m_mass <= 0.0f) + { + m_mass = 1.0f; + } + + m_invMass = 1.0f / m_mass; + + if (massData->I > 0.0f && (m_flags & b2Body::e_fixedRotationFlag) == 0) + { + m_I = massData->I - m_mass * b2Dot(massData->center, massData->center); + b2Assert(m_I > 0.0f); + m_invI = 1.0f / m_I; + } + + // Move center of mass. + b2Vec2 oldCenter = m_sweep.c; + m_sweep.localCenter = massData->center; + m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + + // Update center of mass velocity. + m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); +} + +bool b2Body::ShouldCollide(const b2Body* other) const +{ + // At least one body should be dynamic. + if (m_type != b2_dynamicBody && other->m_type != b2_dynamicBody) + { + return false; + } + + // Does a joint prevent collision? + for (b2JointEdge* jn = m_jointList; jn; jn = jn->next) + { + if (jn->other == other) + { + if (jn->joint->m_collideConnected == false) + { + return false; + } + } + } + + return true; +} + +void b2Body::SetTransform(const b2Vec2& position, float32 angle) +{ + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } + + m_xf.R.Set(angle); + m_xf.position = position; + + m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + m_sweep.a0 = m_sweep.a = angle; + + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->Synchronize(broadPhase, m_xf, m_xf); + } + + m_world->m_contactManager.FindNewContacts(); +} + +void b2Body::SynchronizeFixtures() +{ + b2Transform xf1; + xf1.R.Set(m_sweep.a0); + xf1.position = m_sweep.c0 - b2Mul(xf1.R, m_sweep.localCenter); + + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->Synchronize(broadPhase, xf1, m_xf); + } +} + +void b2Body::SetActive(bool flag) +{ + if (flag == IsActive()) + { + return; + } + + if (flag) + { + m_flags |= e_activeFlag; + + // Create all proxies. + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->CreateProxy(broadPhase, m_xf); + } + + // Contacts are created the next time step. + } + else + { + m_flags &= ~e_activeFlag; + + // Destroy all proxies. + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->DestroyProxy(broadPhase); + } + + // Destroy the attached contacts. + b2ContactEdge* ce = m_contactList; + while (ce) + { + b2ContactEdge* ce0 = ce; + ce = ce->next; + m_world->m_contactManager.Destroy(ce0->contact); + } + m_contactList = NULL; + } +} \ No newline at end of file diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Body.h b/src/modules/physics/box2d/Box2D/Dynamics/b2Body.h new file mode 100644 index 000000000..f2f915faa --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Body.h @@ -0,0 +1,802 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_BODY_H +#define B2_BODY_H + +#include +#include +#include + +class b2Fixture; +class b2Joint; +class b2Contact; +class b2Controller; +class b2World; +struct b2FixtureDef; +struct b2JointEdge; +struct b2ContactEdge; + +/// The body type. +/// static: zero mass, zero velocity, may be manually moved +/// kinematic: zero mass, non-zero velocity set by user, moved by solver +/// dynamic: positive mass, non-zero velocity determined by forces, moved by solver +enum b2BodyType +{ + b2_staticBody = 0, + b2_kinematicBody, + b2_dynamicBody, +}; + +/// A body definition holds all the data needed to construct a rigid body. +/// You can safely re-use body definitions. Shapes are added to a body after construction. +struct b2BodyDef +{ + /// This constructor sets the body definition default values. + b2BodyDef() + { + userData = NULL; + position.Set(0.0f, 0.0f); + angle = 0.0f; + linearVelocity.Set(0.0f, 0.0f); + angularVelocity = 0.0f; + linearDamping = 0.0f; + angularDamping = 0.0f; + allowSleep = true; + awake = true; + fixedRotation = false; + bullet = false; + type = b2_staticBody; + active = true; + inertiaScale = 1.0f; + } + + /// The body type: static, kinematic, or dynamic. + /// Note: if a dynamic body would have zero mass, the mass is set to one. + b2BodyType type; + + /// The world position of the body. Avoid creating bodies at the origin + /// since this can lead to many overlapping shapes. + b2Vec2 position; + + /// The world angle of the body in radians. + float32 angle; + + /// The linear velocity of the body's origin in world co-ordinates. + b2Vec2 linearVelocity; + + /// The angular velocity of the body. + float32 angularVelocity; + + /// Linear damping is use to reduce the linear velocity. The damping parameter + /// can be larger than 1.0f but the damping effect becomes sensitive to the + /// time step when the damping parameter is large. + float32 linearDamping; + + /// Angular damping is use to reduce the angular velocity. The damping parameter + /// can be larger than 1.0f but the damping effect becomes sensitive to the + /// time step when the damping parameter is large. + float32 angularDamping; + + /// Set this flag to false if this body should never fall asleep. Note that + /// this increases CPU usage. + bool allowSleep; + + /// Is this body initially awake or sleeping? + bool awake; + + /// Should this body be prevented from rotating? Useful for characters. + bool fixedRotation; + + /// Is this a fast moving body that should be prevented from tunneling through + /// other moving bodies? Note that all bodies are prevented from tunneling through + /// kinematic and static bodies. This setting is only considered on dynamic bodies. + /// @warning You should use this flag sparingly since it increases processing time. + bool bullet; + + /// Does this body start out active? + bool active; + + /// Use this to store application specific body data. + void* userData; + + /// Experimental: scales the inertia tensor. + float32 inertiaScale; +}; + +/// A rigid body. These are created via b2World::CreateBody. +class b2Body +{ +public: + /// Creates a fixture and attach it to this body. Use this function if you need + /// to set some fixture parameters, like friction. Otherwise you can create the + /// fixture directly from a shape. + /// If the density is non-zero, this function automatically updates the mass of the body. + /// Contacts are not created until the next time step. + /// @param def the fixture definition. + /// @warning This function is locked during callbacks. + b2Fixture* CreateFixture(const b2FixtureDef* def); + + /// Creates a fixture from a shape and attach it to this body. + /// This is a convenience function. Use b2FixtureDef if you need to set parameters + /// like friction, restitution, user data, or filtering. + /// If the density is non-zero, this function automatically updates the mass of the body. + /// @param shape the shape to be cloned. + /// @param density the shape density (set to zero for static bodies). + /// @warning This function is locked during callbacks. + b2Fixture* CreateFixture(const b2Shape* shape, float32 density); + + /// Destroy a fixture. This removes the fixture from the broad-phase and + /// destroys all contacts associated with this fixture. This will + /// automatically adjust the mass of the body if the body is dynamic and the + /// fixture has positive density. + /// All fixtures attached to a body are implicitly destroyed when the body is destroyed. + /// @param fixture the fixture to be removed. + /// @warning This function is locked during callbacks. + void DestroyFixture(b2Fixture* fixture); + + /// Set the position of the body's origin and rotation. + /// This breaks any contacts and wakes the other bodies. + /// Manipulating a body's transform may cause non-physical behavior. + /// @param position the world position of the body's local origin. + /// @param angle the world rotation in radians. + void SetTransform(const b2Vec2& position, float32 angle); + + /// Get the body transform for the body's origin. + /// @return the world transform of the body's origin. + const b2Transform& GetTransform() const; + + /// Get the world body origin position. + /// @return the world position of the body's origin. + const b2Vec2& GetPosition() const; + + /// Get the angle in radians. + /// @return the current world rotation angle in radians. + float32 GetAngle() const; + + /// Get the world position of the center of mass. + const b2Vec2& GetWorldCenter() const; + + /// Get the local position of the center of mass. + const b2Vec2& GetLocalCenter() const; + + /// Set the linear velocity of the center of mass. + /// @param v the new linear velocity of the center of mass. + void SetLinearVelocity(const b2Vec2& v); + + /// Get the linear velocity of the center of mass. + /// @return the linear velocity of the center of mass. + b2Vec2 GetLinearVelocity() const; + + /// Set the angular velocity. + /// @param omega the new angular velocity in radians/second. + void SetAngularVelocity(float32 omega); + + /// Get the angular velocity. + /// @return the angular velocity in radians/second. + float32 GetAngularVelocity() const; + + /// Apply a force at a world point. If the force is not + /// applied at the center of mass, it will generate a torque and + /// affect the angular velocity. This wakes up the body. + /// @param force the world force vector, usually in Newtons (N). + /// @param point the world position of the point of application. + void ApplyForce(const b2Vec2& force, const b2Vec2& point); + + /// Apply a torque. This affects the angular velocity + /// without affecting the linear velocity of the center of mass. + /// This wakes up the body. + /// @param torque about the z-axis (out of the screen), usually in N-m. + void ApplyTorque(float32 torque); + + /// Apply an impulse at a point. This immediately modifies the velocity. + /// It also modifies the angular velocity if the point of application + /// is not at the center of mass. This wakes up the body. + /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s. + /// @param point the world position of the point of application. + void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point); + + /// Apply an angular impulse. + /// @param impulse the angular impulse in units of kg*m*m/s + void ApplyAngularImpulse(float32 impulse); + + /// Get the total mass of the body. + /// @return the mass, usually in kilograms (kg). + float32 GetMass() const; + + /// Get the rotational inertia of the body about the local origin. + /// @return the rotational inertia, usually in kg-m^2. + float32 GetInertia() const; + + /// Get the mass data of the body. + /// @return a struct containing the mass, inertia and center of the body. + void GetMassData(b2MassData* data) const; + + /// Set the mass properties to override the mass properties of the fixtures. + /// Note that this changes the center of mass position. + /// Note that creating or destroying fixtures can also alter the mass. + /// This function has no effect if the body isn't dynamic. + /// @param massData the mass properties. + void SetMassData(const b2MassData* data); + + /// This resets the mass properties to the sum of the mass properties of the fixtures. + /// This normally does not need to be called unless you called SetMassData to override + /// the mass and you later want to reset the mass. + void ResetMassData(); + + /// Get the world coordinates of a point given the local coordinates. + /// @param localPoint a point on the body measured relative the the body's origin. + /// @return the same point expressed in world coordinates. + b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const; + + /// Get the world coordinates of a vector given the local coordinates. + /// @param localVector a vector fixed in the body. + /// @return the same vector expressed in world coordinates. + b2Vec2 GetWorldVector(const b2Vec2& localVector) const; + + /// Gets a local point relative to the body's origin given a world point. + /// @param a point in world coordinates. + /// @return the corresponding local point relative to the body's origin. + b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const; + + /// Gets a local vector given a world vector. + /// @param a vector in world coordinates. + /// @return the corresponding local vector. + b2Vec2 GetLocalVector(const b2Vec2& worldVector) const; + + /// Get the world linear velocity of a world point attached to this body. + /// @param a point in world coordinates. + /// @return the world velocity of a point. + b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const; + + /// Get the world velocity of a local point. + /// @param a point in local coordinates. + /// @return the world velocity of a point. + b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const; + + /// Get the linear damping of the body. + float32 GetLinearDamping() const; + + /// Set the linear damping of the body. + void SetLinearDamping(float32 linearDamping); + + /// Get the angular damping of the body. + float32 GetAngularDamping() const; + + /// Set the angular damping of the body. + void SetAngularDamping(float32 angularDamping); + + /// Set the type of this body. This may alter the mass and velocity. + void SetType(b2BodyType type); + + /// Get the type of this body. + b2BodyType GetType() const; + + /// Should this body be treated like a bullet for continuous collision detection? + void SetBullet(bool flag); + + /// Is this body treated like a bullet for continuous collision detection? + bool IsBullet() const; + + /// You can disable sleeping on this body. If you disable sleeping, the + /// body will be woken. + void SetSleepingAllowed(bool flag); + + /// Is this body allowed to sleep + bool IsSleepingAllowed() const; + + /// Set the sleep state of the body. A sleeping body has very + /// low CPU cost. + /// @param flag set to true to put body to sleep, false to wake it. + void SetAwake(bool flag); + + /// Get the sleeping state of this body. + /// @return true if the body is sleeping. + bool IsAwake() const; + + /// Set the active state of the body. An inactive body is not + /// simulated and cannot be collided with or woken up. + /// If you pass a flag of true, all fixtures will be added to the + /// broad-phase. + /// If you pass a flag of false, all fixtures will be removed from + /// the broad-phase and all contacts will be destroyed. + /// Fixtures and joints are otherwise unaffected. You may continue + /// to create/destroy fixtures and joints on inactive bodies. + /// Fixtures on an inactive body are implicitly inactive and will + /// not participate in collisions, ray-casts, or queries. + /// Joints connected to an inactive body are implicitly inactive. + /// An inactive body is still owned by a b2World object and remains + /// in the body list. + void SetActive(bool flag); + + /// Get the active state of the body. + bool IsActive() const; + + /// Set this body to have fixed rotation. This causes the mass + /// to be reset. + void SetFixedRotation(bool flag); + + /// Does this body have fixed rotation? + bool IsFixedRotation() const; + + /// Get the list of all fixtures attached to this body. + b2Fixture* GetFixtureList(); + const b2Fixture* GetFixtureList() const; + + /// Get the list of all joints attached to this body. + b2JointEdge* GetJointList(); + const b2JointEdge* GetJointList() const; + + /// Get the list of all contacts attached to this body. + /// @warning this list changes during the time step and you may + /// miss some collisions if you don't use b2ContactListener. + b2ContactEdge* GetContactList(); + const b2ContactEdge* GetContactList() const; + + /// Get the next body in the world's body list. + b2Body* GetNext(); + const b2Body* GetNext() const; + + /// Get the user data pointer that was provided in the body definition. + void* GetUserData() const; + + /// Set the user data. Use this to store your application specific data. + void SetUserData(void* data); + + /// Get the parent world of this body. + b2World* GetWorld(); + const b2World* GetWorld() const; + +private: + + friend class b2World; + friend class b2Island; + friend class b2ContactManager; + friend class b2ContactSolver; + friend class b2TOISolver; + + friend class b2DistanceJoint; + friend class b2GearJoint; + friend class b2LineJoint; + friend class b2MouseJoint; + friend class b2PrismaticJoint; + friend class b2PulleyJoint; + friend class b2RevoluteJoint; + friend class b2WeldJoint; + friend class b2FrictionJoint; + + // m_flags + enum + { + e_islandFlag = 0x0001, + e_awakeFlag = 0x0002, + e_autoSleepFlag = 0x0004, + e_bulletFlag = 0x0008, + e_fixedRotationFlag = 0x0010, + e_activeFlag = 0x0020, + e_toiFlag = 0x0040, + }; + + b2Body(const b2BodyDef* bd, b2World* world); + ~b2Body(); + + void SynchronizeFixtures(); + void SynchronizeTransform(); + + // This is used to prevent connected bodies from colliding. + // It may lie, depending on the collideConnected flag. + bool ShouldCollide(const b2Body* other) const; + + void Advance(float32 t); + + b2BodyType m_type; + + uint16 m_flags; + + int32 m_islandIndex; + + b2Transform m_xf; // the body origin transform + b2Sweep m_sweep; // the swept motion for CCD + + b2Vec2 m_linearVelocity; + float32 m_angularVelocity; + + b2Vec2 m_force; + float32 m_torque; + + b2World* m_world; + b2Body* m_prev; + b2Body* m_next; + + b2Fixture* m_fixtureList; + int32 m_fixtureCount; + + b2JointEdge* m_jointList; + b2ContactEdge* m_contactList; + + float32 m_mass, m_invMass; + + // Rotational inertia about the center of mass. + float32 m_I, m_invI; + + float32 m_linearDamping; + float32 m_angularDamping; + + float32 m_sleepTime; + + void* m_userData; +}; + +inline b2BodyType b2Body::GetType() const +{ + return m_type; +} + +inline const b2Transform& b2Body::GetTransform() const +{ + return m_xf; +} + +inline const b2Vec2& b2Body::GetPosition() const +{ + return m_xf.position; +} + +inline float32 b2Body::GetAngle() const +{ + return m_sweep.a; +} + +inline const b2Vec2& b2Body::GetWorldCenter() const +{ + return m_sweep.c; +} + +inline const b2Vec2& b2Body::GetLocalCenter() const +{ + return m_sweep.localCenter; +} + +inline void b2Body::SetLinearVelocity(const b2Vec2& v) +{ + if (m_type == b2_staticBody) + { + return; + } + + if (b2Dot(v,v) > 0.0f) + { + SetAwake(true); + } + + m_linearVelocity = v; +} + +inline b2Vec2 b2Body::GetLinearVelocity() const +{ + return m_linearVelocity; +} + +inline void b2Body::SetAngularVelocity(float32 w) +{ + if (m_type == b2_staticBody) + { + return; + } + + if (w * w > 0.0f) + { + SetAwake(true); + } + + m_angularVelocity = w; +} + +inline float32 b2Body::GetAngularVelocity() const +{ + return m_angularVelocity; +} + +inline float32 b2Body::GetMass() const +{ + return m_mass; +} + +inline float32 b2Body::GetInertia() const +{ + return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); +} + +inline void b2Body::GetMassData(b2MassData* data) const +{ + data->mass = m_mass; + data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); + data->center = m_sweep.localCenter; +} + +inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const +{ + return b2Mul(m_xf, localPoint); +} + +inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const +{ + return b2Mul(m_xf.R, localVector); +} + +inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const +{ + return b2MulT(m_xf, worldPoint); +} + +inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const +{ + return b2MulT(m_xf.R, worldVector); +} + +inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const +{ + return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_sweep.c); +} + +inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const +{ + return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint)); +} + +inline float32 b2Body::GetLinearDamping() const +{ + return m_linearDamping; +} + +inline void b2Body::SetLinearDamping(float32 linearDamping) +{ + m_linearDamping = linearDamping; +} + +inline float32 b2Body::GetAngularDamping() const +{ + return m_angularDamping; +} + +inline void b2Body::SetAngularDamping(float32 angularDamping) +{ + m_angularDamping = angularDamping; +} + +inline void b2Body::SetBullet(bool flag) +{ + if (flag) + { + m_flags |= e_bulletFlag; + } + else + { + m_flags &= ~e_bulletFlag; + } +} + +inline bool b2Body::IsBullet() const +{ + return (m_flags & e_bulletFlag) == e_bulletFlag; +} + +inline void b2Body::SetAwake(bool flag) +{ + if (flag) + { + if ((m_flags & e_awakeFlag) == 0) + { + m_flags |= e_awakeFlag; + m_sleepTime = 0.0f; + } + } + else + { + m_flags &= ~e_awakeFlag; + m_sleepTime = 0.0f; + m_linearVelocity.SetZero(); + m_angularVelocity = 0.0f; + m_force.SetZero(); + m_torque = 0.0f; + } +} + +inline bool b2Body::IsAwake() const +{ + return (m_flags & e_awakeFlag) == e_awakeFlag; +} + +inline bool b2Body::IsActive() const +{ + return (m_flags & e_activeFlag) == e_activeFlag; +} + +inline void b2Body::SetFixedRotation(bool flag) +{ + if (flag) + { + m_flags |= e_fixedRotationFlag; + } + else + { + m_flags &= ~e_fixedRotationFlag; + } + + ResetMassData(); +} + +inline bool b2Body::IsFixedRotation() const +{ + return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag; +} + +inline void b2Body::SetSleepingAllowed(bool flag) +{ + if (flag) + { + m_flags |= e_autoSleepFlag; + } + else + { + m_flags &= ~e_autoSleepFlag; + SetAwake(true); + } +} + +inline bool b2Body::IsSleepingAllowed() const +{ + return (m_flags & e_autoSleepFlag) == e_autoSleepFlag; +} + +inline b2Fixture* b2Body::GetFixtureList() +{ + return m_fixtureList; +} + +inline const b2Fixture* b2Body::GetFixtureList() const +{ + return m_fixtureList; +} + +inline b2JointEdge* b2Body::GetJointList() +{ + return m_jointList; +} + +inline const b2JointEdge* b2Body::GetJointList() const +{ + return m_jointList; +} + +inline b2ContactEdge* b2Body::GetContactList() +{ + return m_contactList; +} + +inline const b2ContactEdge* b2Body::GetContactList() const +{ + return m_contactList; +} + +inline b2Body* b2Body::GetNext() +{ + return m_next; +} + +inline const b2Body* b2Body::GetNext() const +{ + return m_next; +} + +inline void b2Body::SetUserData(void* data) +{ + m_userData = data; +} + +inline void* b2Body::GetUserData() const +{ + return m_userData; +} + +inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + + m_force += force; + m_torque += b2Cross(point - m_sweep.c, force); +} + +inline void b2Body::ApplyTorque(float32 torque) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + + m_torque += torque; +} + +inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + m_linearVelocity += m_invMass * impulse; + m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse); +} + +inline void b2Body::ApplyAngularImpulse(float32 impulse) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + m_angularVelocity += m_invI * impulse; +} + +inline void b2Body::SynchronizeTransform() +{ + m_xf.R.Set(m_sweep.a); + m_xf.position = m_sweep.c - b2Mul(m_xf.R, m_sweep.localCenter); +} + +inline void b2Body::Advance(float32 t) +{ + // Advance to the new safe time. + m_sweep.Advance(t); + m_sweep.c = m_sweep.c0; + m_sweep.a = m_sweep.a0; + SynchronizeTransform(); +} + +inline b2World* b2Body::GetWorld() +{ + return m_world; +} + +inline const b2World* b2Body::GetWorld() const +{ + return m_world; +} + +#endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp new file mode 100644 index 000000000..d8d96ddbc --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp @@ -0,0 +1,266 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +b2ContactFilter b2_defaultFilter; +b2ContactListener b2_defaultListener; + +b2ContactManager::b2ContactManager() +{ + m_contactList = NULL; + m_contactCount = 0; + m_contactFilter = &b2_defaultFilter; + m_contactListener = &b2_defaultListener; + m_allocator = NULL; +} + +void b2ContactManager::Destroy(b2Contact* c) +{ + b2Fixture* fixtureA = c->GetFixtureA(); + b2Fixture* fixtureB = c->GetFixtureB(); + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + + if (m_contactListener && c->IsTouching()) + { + m_contactListener->EndContact(c); + } + + // Remove from the world. + if (c->m_prev) + { + c->m_prev->m_next = c->m_next; + } + + if (c->m_next) + { + c->m_next->m_prev = c->m_prev; + } + + if (c == m_contactList) + { + m_contactList = c->m_next; + } + + // Remove from body 1 + if (c->m_nodeA.prev) + { + c->m_nodeA.prev->next = c->m_nodeA.next; + } + + if (c->m_nodeA.next) + { + c->m_nodeA.next->prev = c->m_nodeA.prev; + } + + if (&c->m_nodeA == bodyA->m_contactList) + { + bodyA->m_contactList = c->m_nodeA.next; + } + + // Remove from body 2 + if (c->m_nodeB.prev) + { + c->m_nodeB.prev->next = c->m_nodeB.next; + } + + if (c->m_nodeB.next) + { + c->m_nodeB.next->prev = c->m_nodeB.prev; + } + + if (&c->m_nodeB == bodyB->m_contactList) + { + bodyB->m_contactList = c->m_nodeB.next; + } + + // Call the factory. + b2Contact::Destroy(c, m_allocator); + --m_contactCount; +} + +// This is the top level collision call for the time step. Here +// all the narrow phase collision is processed for the world +// contact list. +void b2ContactManager::Collide() +{ + // Update awake contacts. + b2Contact* c = m_contactList; + while (c) + { + b2Fixture* fixtureA = c->GetFixtureA(); + b2Fixture* fixtureB = c->GetFixtureB(); + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + + if (bodyA->IsAwake() == false && bodyB->IsAwake() == false) + { + c = c->GetNext(); + continue; + } + + // Is this contact flagged for filtering? + if (c->m_flags & b2Contact::e_filterFlag) + { + // Should these bodies collide? + if (bodyB->ShouldCollide(bodyA) == false) + { + b2Contact* cNuke = c; + c = cNuke->GetNext(); + Destroy(cNuke); + continue; + } + + // Check user filtering. + if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) + { + b2Contact* cNuke = c; + c = cNuke->GetNext(); + Destroy(cNuke); + continue; + } + + // Clear the filtering flag. + c->m_flags &= ~b2Contact::e_filterFlag; + } + + int32 proxyIdA = fixtureA->m_proxyId; + int32 proxyIdB = fixtureB->m_proxyId; + bool overlap = m_broadPhase.TestOverlap(proxyIdA, proxyIdB); + + // Here we destroy contacts that cease to overlap in the broad-phase. + if (overlap == false) + { + b2Contact* cNuke = c; + c = cNuke->GetNext(); + Destroy(cNuke); + continue; + } + + // The contact persists. + c->Update(m_contactListener); + c = c->GetNext(); + } +} + +void b2ContactManager::FindNewContacts() +{ + m_broadPhase.UpdatePairs(this); +} + +void b2ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB) +{ + b2Fixture* fixtureA = (b2Fixture*)proxyUserDataA; + b2Fixture* fixtureB = (b2Fixture*)proxyUserDataB; + + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + + // Are the fixtures on the same body? + if (bodyA == bodyB) + { + return; + } + + // Does a contact already exist? + b2ContactEdge* edge = bodyB->GetContactList(); + while (edge) + { + if (edge->other == bodyA) + { + b2Fixture* fA = edge->contact->GetFixtureA(); + b2Fixture* fB = edge->contact->GetFixtureB(); + if (fA == fixtureA && fB == fixtureB) + { + // A contact already exists. + return; + } + + if (fA == fixtureB && fB == fixtureA) + { + // A contact already exists. + return; + } + } + + edge = edge->next; + } + + // Does a joint override collision? Is at least one body dynamic? + if (bodyB->ShouldCollide(bodyA) == false) + { + return; + } + + // Check user filtering. + if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) + { + return; + } + + // Call the factory. + b2Contact* c = b2Contact::Create(fixtureA, fixtureB, m_allocator); + + // Contact creation may swap fixtures. + fixtureA = c->GetFixtureA(); + fixtureB = c->GetFixtureB(); + bodyA = fixtureA->GetBody(); + bodyB = fixtureB->GetBody(); + + // Insert into the world. + c->m_prev = NULL; + c->m_next = m_contactList; + if (m_contactList != NULL) + { + m_contactList->m_prev = c; + } + m_contactList = c; + + // Connect to island graph. + + // Connect to body A + c->m_nodeA.contact = c; + c->m_nodeA.other = bodyB; + + c->m_nodeA.prev = NULL; + c->m_nodeA.next = bodyA->m_contactList; + if (bodyA->m_contactList != NULL) + { + bodyA->m_contactList->prev = &c->m_nodeA; + } + bodyA->m_contactList = &c->m_nodeA; + + // Connect to body B + c->m_nodeB.contact = c; + c->m_nodeB.other = bodyA; + + c->m_nodeB.prev = NULL; + c->m_nodeB.next = bodyB->m_contactList; + if (bodyB->m_contactList != NULL) + { + bodyB->m_contactList->prev = &c->m_nodeB; + } + bodyB->m_contactList = &c->m_nodeB; + + ++m_contactCount; +} diff --git a/src/modules/physics/box2d/Source/Dynamics/b2ContactManager.h b/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.h similarity index 58% rename from src/modules/physics/box2d/Source/Dynamics/b2ContactManager.h rename to src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.h index 7bba1a103..fcba54ae7 100644 --- a/src/modules/physics/box2d/Source/Dynamics/b2ContactManager.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -19,36 +19,34 @@ #ifndef B2_CONTACT_MANAGER_H #define B2_CONTACT_MANAGER_H -#include "../Collision/b2BroadPhase.h" -#include "../Dynamics/Contacts/b2NullContact.h" +#include -class b2World; class b2Contact; -struct b2TimeStep; +class b2ContactFilter; +class b2ContactListener; +class b2BlockAllocator; // Delegate of b2World. -class b2ContactManager : public b2PairCallback +class b2ContactManager { public: - b2ContactManager() : m_world(NULL), m_destroyImmediate(false) {} + b2ContactManager(); - // Implements PairCallback - void* PairAdded(void* proxyUserData1, void* proxyUserData2); + // Broad-phase callback. + void AddPair(void* proxyUserDataA, void* proxyUserDataB); - // Implements PairCallback - void PairRemoved(void* proxyUserData1, void* proxyUserData2, void* pairUserData); + void FindNewContacts(); void Destroy(b2Contact* c); void Collide(); - - b2World* m_world; - - // This lets us provide broadphase proxy pair user data for - // contacts that shouldn't exist. - b2NullContact m_nullContact; - - bool m_destroyImmediate; + + b2BroadPhase m_broadPhase; + b2Contact* m_contactList; + int32 m_contactCount; + b2ContactFilter* m_contactFilter; + b2ContactListener* m_contactListener; + b2BlockAllocator* m_allocator; }; #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp new file mode 100644 index 000000000..31355b572 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp @@ -0,0 +1,163 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include +#include + + +b2Fixture::b2Fixture() +{ + m_userData = NULL; + m_body = NULL; + m_next = NULL; + m_proxyId = b2BroadPhase::e_nullProxy; + m_shape = NULL; + m_density = 0.0f; +} + +b2Fixture::~b2Fixture() +{ + b2Assert(m_shape == NULL); + b2Assert(m_proxyId == b2BroadPhase::e_nullProxy); +} + +void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def) +{ + m_userData = def->userData; + m_friction = def->friction; + m_restitution = def->restitution; + + m_body = body; + m_next = NULL; + + m_filter = def->filter; + + m_isSensor = def->isSensor; + + m_shape = def->shape->Clone(allocator); + + m_density = def->density; +} + +void b2Fixture::Destroy(b2BlockAllocator* allocator) +{ + // The proxy must be destroyed before calling this. + b2Assert(m_proxyId == b2BroadPhase::e_nullProxy); + + // Free the child shape. + switch (m_shape->m_type) + { + case b2Shape::e_circle: + { + b2CircleShape* s = (b2CircleShape*)m_shape; + s->~b2CircleShape(); + allocator->Free(s, sizeof(b2CircleShape)); + } + break; + + case b2Shape::e_polygon: + { + b2PolygonShape* s = (b2PolygonShape*)m_shape; + s->~b2PolygonShape(); + allocator->Free(s, sizeof(b2PolygonShape)); + } + break; + + default: + b2Assert(false); + break; + } + + m_shape = NULL; +} + +void b2Fixture::CreateProxy(b2BroadPhase* broadPhase, const b2Transform& xf) +{ + b2Assert(m_proxyId == b2BroadPhase::e_nullProxy); + + // Create proxy in the broad-phase. + m_shape->ComputeAABB(&m_aabb, xf); + m_proxyId = broadPhase->CreateProxy(m_aabb, this); +} + +void b2Fixture::DestroyProxy(b2BroadPhase* broadPhase) +{ + if (m_proxyId == b2BroadPhase::e_nullProxy) + { + return; + } + + // Destroy proxy in the broad-phase. + broadPhase->DestroyProxy(m_proxyId); + m_proxyId = b2BroadPhase::e_nullProxy; +} + +void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2) +{ + if (m_proxyId == b2BroadPhase::e_nullProxy) + { + return; + } + + // Compute an AABB that covers the swept shape (may miss some rotation effect). + b2AABB aabb1, aabb2; + m_shape->ComputeAABB(&aabb1, transform1); + m_shape->ComputeAABB(&aabb2, transform2); + + m_aabb.Combine(aabb1, aabb2); + + b2Vec2 displacement = transform2.position - transform1.position; + + broadPhase->MoveProxy(m_proxyId, m_aabb, displacement); +} + +void b2Fixture::SetFilterData(const b2Filter& filter) +{ + m_filter = filter; + + if (m_body == NULL) + { + return; + } + + // Flag associated contacts for filtering. + b2ContactEdge* edge = m_body->GetContactList(); + while (edge) + { + b2Contact* contact = edge->contact; + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); + if (fixtureA == this || fixtureB == this) + { + contact->FlagForFiltering(); + } + + edge = edge->next; + } +} + +void b2Fixture::SetSensor(bool sensor) +{ + m_isSensor = sensor; +} + diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h b/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h new file mode 100644 index 000000000..d9d325554 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h @@ -0,0 +1,326 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_FIXTURE_H +#define B2_FIXTURE_H + +#include +#include +#include + +class b2BlockAllocator; +class b2Body; +class b2BroadPhase; + +/// This holds contact filtering data. +struct b2Filter +{ + /// The collision category bits. Normally you would just set one bit. + uint16 categoryBits; + + /// The collision mask bits. This states the categories that this + /// shape would accept for collision. + uint16 maskBits; + + /// Collision groups allow a certain group of objects to never collide (negative) + /// or always collide (positive). Zero means no collision group. Non-zero group + /// filtering always wins against the mask bits. + int16 groupIndex; +}; + +/// A fixture definition is used to create a fixture. This class defines an +/// abstract fixture definition. You can reuse fixture definitions safely. +struct b2FixtureDef +{ + /// The constructor sets the default fixture definition values. + b2FixtureDef() + { + shape = NULL; + userData = NULL; + friction = 0.2f; + restitution = 0.0f; + density = 0.0f; + filter.categoryBits = 0x0001; + filter.maskBits = 0xFFFF; + filter.groupIndex = 0; + isSensor = false; + } + + virtual ~b2FixtureDef() {} + + /// The shape, this must be set. The shape will be cloned, so you + /// can create the shape on the stack. + const b2Shape* shape; + + /// Use this to store application specific fixture data. + void* userData; + + /// The friction coefficient, usually in the range [0,1]. + float32 friction; + + /// The restitution (elasticity) usually in the range [0,1]. + float32 restitution; + + /// The density, usually in kg/m^2. + float32 density; + + /// A sensor shape collects contact information but never generates a collision + /// response. + bool isSensor; + + /// Contact filtering data. + b2Filter filter; +}; + + +/// A fixture is used to attach a shape to a body for collision detection. A fixture +/// inherits its transform from its parent. Fixtures hold additional non-geometric data +/// such as friction, collision filters, etc. +/// Fixtures are created via b2Body::CreateFixture. +/// @warning you cannot reuse fixtures. +class b2Fixture +{ +public: + /// Get the type of the child shape. You can use this to down cast to the concrete shape. + /// @return the shape type. + b2Shape::Type GetType() const; + + /// Get the child shape. You can modify the child shape, however you should not change the + /// number of vertices because this will crash some collision caching mechanisms. + /// Manipulating the shape may lead to non-physical behavior. + b2Shape* GetShape(); + const b2Shape* GetShape() const; + + /// Set if this fixture is a sensor. + void SetSensor(bool sensor); + + /// Is this fixture a sensor (non-solid)? + /// @return the true if the shape is a sensor. + bool IsSensor() const; + + /// Set the contact filtering data. This will not update contacts until the next time + /// step when either parent body is active and awake. + void SetFilterData(const b2Filter& filter); + + /// Get the contact filtering data. + const b2Filter& GetFilterData() const; + + /// Get the parent body of this fixture. This is NULL if the fixture is not attached. + /// @return the parent body. + b2Body* GetBody(); + const b2Body* GetBody() const; + + /// Get the next fixture in the parent body's fixture list. + /// @return the next shape. + b2Fixture* GetNext(); + const b2Fixture* GetNext() const; + + /// Get the user data that was assigned in the fixture definition. Use this to + /// store your application specific data. + void* GetUserData() const; + + /// Set the user data. Use this to store your application specific data. + void SetUserData(void* data); + + /// Test a point for containment in this fixture. + /// @param xf the shape world transform. + /// @param p a point in world coordinates. + bool TestPoint(const b2Vec2& p) const; + + /// Cast a ray against this shape. + /// @param output the ray-cast results. + /// @param input the ray-cast input parameters. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const; + + /// Get the mass data for this fixture. The mass data is based on the density and + /// the shape. The rotational inertia is about the shape's origin. This operation + /// may be expensive. + void GetMassData(b2MassData* massData) const; + + /// Set the density of this fixture. This will _not_ automatically adjust the mass + /// of the body. You must call b2Body::ResetMassData to update the body's mass. + void SetDensity(float32 density); + + /// Get the density of this fixture. + float32 GetDensity() const; + + /// Get the coefficient of friction. + float32 GetFriction() const; + + /// Set the coefficient of friction. + void SetFriction(float32 friction); + + /// Get the coefficient of restitution. + float32 GetRestitution() const; + + /// Set the coefficient of restitution. + void SetRestitution(float32 restitution); + + /// Get the fixture's AABB. This AABB may be enlarge and/or stale. + /// If you need a more accurate AABB, compute it using the shape and + /// the body transform. + const b2AABB& GetAABB() const; + +protected: + + friend class b2Body; + friend class b2World; + friend class b2Contact; + friend class b2ContactManager; + + b2Fixture(); + ~b2Fixture(); + + // We need separation create/destroy functions from the constructor/destructor because + // the destructor cannot access the allocator (no destructor arguments allowed by C++). + void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def); + void Destroy(b2BlockAllocator* allocator); + + // These support body activation/deactivation. + void CreateProxy(b2BroadPhase* broadPhase, const b2Transform& xf); + void DestroyProxy(b2BroadPhase* broadPhase); + + void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2); + + b2AABB m_aabb; + + float32 m_density; + + b2Fixture* m_next; + b2Body* m_body; + + b2Shape* m_shape; + + float32 m_friction; + float32 m_restitution; + + int32 m_proxyId; + b2Filter m_filter; + + bool m_isSensor; + + void* m_userData; +}; + +inline b2Shape::Type b2Fixture::GetType() const +{ + return m_shape->GetType(); +} + +inline b2Shape* b2Fixture::GetShape() +{ + return m_shape; +} + +inline const b2Shape* b2Fixture::GetShape() const +{ + return m_shape; +} + +inline bool b2Fixture::IsSensor() const +{ + return m_isSensor; +} + +inline const b2Filter& b2Fixture::GetFilterData() const +{ + return m_filter; +} + +inline void* b2Fixture::GetUserData() const +{ + return m_userData; +} + +inline void b2Fixture::SetUserData(void* data) +{ + m_userData = data; +} + +inline b2Body* b2Fixture::GetBody() +{ + return m_body; +} + +inline const b2Body* b2Fixture::GetBody() const +{ + return m_body; +} + +inline b2Fixture* b2Fixture::GetNext() +{ + return m_next; +} + +inline const b2Fixture* b2Fixture::GetNext() const +{ + return m_next; +} + +inline void b2Fixture::SetDensity(float32 density) +{ + b2Assert(b2IsValid(density) && density >= 0.0f); + m_density = density; +} + +inline float32 b2Fixture::GetDensity() const +{ + return m_density; +} + +inline float32 b2Fixture::GetFriction() const +{ + return m_friction; +} + +inline void b2Fixture::SetFriction(float32 friction) +{ + m_friction = friction; +} + +inline float32 b2Fixture::GetRestitution() const +{ + return m_restitution; +} + +inline void b2Fixture::SetRestitution(float32 restitution) +{ + m_restitution = restitution; +} + +inline bool b2Fixture::TestPoint(const b2Vec2& p) const +{ + return m_shape->TestPoint(m_body->GetTransform(), p); +} + +inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const +{ + return m_shape->RayCast(output, input, m_body->GetTransform()); +} + +inline void b2Fixture::GetMassData(b2MassData* massData) const +{ + m_shape->ComputeMass(massData, m_density); +} + +inline const b2AABB& b2Fixture::GetAABB() const +{ + return m_aabb; +} + +#endif diff --git a/src/modules/physics/box2d/Source/Dynamics/b2Island.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2Island.cpp similarity index 62% rename from src/modules/physics/box2d/Source/Dynamics/b2Island.cpp rename to src/modules/physics/box2d/Box2D/Dynamics/b2Island.cpp index 4096c1ba3..009249979 100644 --- a/src/modules/physics/box2d/Source/Dynamics/b2Island.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Island.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -16,13 +16,14 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#include "b2Island.h" -#include "b2Body.h" -#include "b2World.h" -#include "Contacts/b2Contact.h" -#include "Contacts/b2ContactSolver.h" -#include "Joints/b2Joint.h" -#include "../Common/b2StackAllocator.h" +#include +#include +#include +#include +#include +#include +#include +#include /* Position Correction Notes @@ -103,6 +104,45 @@ probably default to the slower Full NGS and let the user select the faster Baumgarte method in performance critical scenarios. */ +/* +Cache Performance + +The Box2D solvers are dominated by cache misses. Data structures are designed +to increase the number of cache hits. Much of misses are due to random access +to body data. The constraint structures are iterated over linearly, which leads +to few cache misses. + +The bodies are not accessed during iteration. Instead read only data, such as +the mass values are stored with the constraints. The mutable data are the constraint +impulses and the bodies velocities/positions. The impulses are held inside the +constraint structures. The body velocities/positions are held in compact, temporary +arrays to increase the number of cache hits. Linear and angular velocity are +stored in a single array since multiple arrays lead to multiple misses. +*/ + +/* +2D Rotation + +R = [cos(theta) -sin(theta)] + [sin(theta) cos(theta) ] + +thetaDot = omega + +Let q1 = cos(theta), q2 = sin(theta). +R = [q1 -q2] + [q2 q1] + +q1Dot = -thetaDot * q2 +q2Dot = thetaDot * q1 + +q1_new = q1_old - dt * w * q2 +q2_new = q2_old + dt * w * q1 +then normalize. + +This might be faster than computing sin+cos. +However, we can compute sin+cos of the same angle fast. +*/ + b2Island::b2Island( int32 bodyCapacity, int32 contactCapacity, @@ -124,35 +164,36 @@ b2Island::b2Island( m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity * sizeof(b2Contact*)); m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*)); - m_positionIterationCount = 0; + m_velocities = (b2Velocity*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Velocity)); + m_positions = (b2Position*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Position)); } b2Island::~b2Island() { // Warning: the order should reverse the constructor order. + m_allocator->Free(m_positions); + m_allocator->Free(m_velocities); m_allocator->Free(m_joints); m_allocator->Free(m_contacts); m_allocator->Free(m_bodies); } -void b2Island::Solve(const b2TimeStep& step, const b2Vec2& gravity, bool correctPositions, bool allowSleep) +void b2Island::Solve(const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep) { // Integrate velocities and apply damping. for (int32 i = 0; i < m_bodyCount; ++i) { b2Body* b = m_bodies[i]; - if (b->IsStatic()) + if (b->GetType() != b2_dynamicBody) + { continue; + } // Integrate velocities. b->m_linearVelocity += step.dt * (gravity + b->m_invMass * b->m_force); b->m_angularVelocity += step.dt * b->m_invI * b->m_torque; - // Reset forces. - b->m_force.Set(0.0f, 0.0f); - b->m_torque = 0.0f; - // Apply damping. // ODE: dv/dt + c * v = 0 // Solution: v(t) = v0 * exp(-c * t) @@ -162,72 +203,70 @@ void b2Island::Solve(const b2TimeStep& step, const b2Vec2& gravity, bool correct // v2 = (1.0f - c * dt) * v1 b->m_linearVelocity *= b2Clamp(1.0f - step.dt * b->m_linearDamping, 0.0f, 1.0f); b->m_angularVelocity *= b2Clamp(1.0f - step.dt * b->m_angularDamping, 0.0f, 1.0f); - - // Check for large velocities. -#ifdef TARGET_FLOAT32_IS_FIXED - // Fixed point code written this way to prevent - // overflows, float code is optimized for speed - - float32 vMagnitude = b->m_linearVelocity.Length(); - if(vMagnitude > b2_maxLinearVelocity) { - b->m_linearVelocity *= b2_maxLinearVelocity/vMagnitude; - } - b->m_angularVelocity = b2Clamp(b->m_angularVelocity, - -b2_maxAngularVelocity, b2_maxAngularVelocity); - -#else - - if (b2Dot(b->m_linearVelocity, b->m_linearVelocity) > b2_maxLinearVelocitySquared) - { - b->m_linearVelocity.Normalize(); - b->m_linearVelocity *= b2_maxLinearVelocity; - } - if (b->m_angularVelocity * b->m_angularVelocity > b2_maxAngularVelocitySquared) - { - if (b->m_angularVelocity < 0.0f) - { - b->m_angularVelocity = -b2_maxAngularVelocity; - } - else - { - b->m_angularVelocity = b2_maxAngularVelocity; - } - } -#endif - } - b2ContactSolver contactSolver(step, m_contacts, m_contactCount, m_allocator); + // Partition contacts so that contacts with static bodies are solved last. + int32 i1 = -1; + for (int32 i2 = 0; i2 < m_contactCount; ++i2) + { + b2Fixture* fixtureA = m_contacts[i2]->GetFixtureA(); + b2Fixture* fixtureB = m_contacts[i2]->GetFixtureB(); + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + bool nonStatic = bodyA->GetType() != b2_staticBody && bodyB->GetType() != b2_staticBody; + if (nonStatic) + { + ++i1; + b2Swap(m_contacts[i1], m_contacts[i2]); + } + } // Initialize velocity constraints. - contactSolver.InitVelocityConstraints(step); - + b2ContactSolver contactSolver(m_contacts, m_contactCount, m_allocator, step.dtRatio); + contactSolver.WarmStart(); for (int32 i = 0; i < m_jointCount; ++i) { m_joints[i]->InitVelocityConstraints(step); } // Solve velocity constraints. - for (int32 i = 0; i < step.maxIterations; ++i) + for (int32 i = 0; i < step.velocityIterations; ++i) { - contactSolver.SolveVelocityConstraints(); - for (int32 j = 0; j < m_jointCount; ++j) { m_joints[j]->SolveVelocityConstraints(step); } + + contactSolver.SolveVelocityConstraints(); } // Post-solve (store impulses for warm starting). - contactSolver.FinalizeVelocityConstraints(); + contactSolver.StoreImpulses(); // Integrate positions. for (int32 i = 0; i < m_bodyCount; ++i) { b2Body* b = m_bodies[i]; - if (b->IsStatic()) + if (b->GetType() == b2_staticBody) + { continue; + } + + // Check for large velocities. + b2Vec2 translation = step.dt * b->m_linearVelocity; + if (b2Dot(translation, translation) > b2_maxTranslationSquared) + { + float32 ratio = b2_maxTranslation / translation.Length(); + b->m_linearVelocity *= ratio; + } + + float32 rotation = step.dt * b->m_angularVelocity; + if (rotation * rotation > b2_maxRotationSquared) + { + float32 ratio = b2_maxRotation / b2Abs(rotation); + b->m_angularVelocity *= ratio; + } // Store positions for continuous collision. b->m_sweep.c0 = b->m_sweep.c; @@ -243,31 +282,22 @@ void b2Island::Solve(const b2TimeStep& step, const b2Vec2& gravity, bool correct // Note: shapes are synchronized later. } - if (correctPositions) + // Iterate over constraints. + for (int32 i = 0; i < step.positionIterations; ++i) { - // Initialize position constraints. - // Contacts don't need initialization. + bool contactsOkay = contactSolver.SolvePositionConstraints(b2_contactBaumgarte); + + bool jointsOkay = true; for (int32 i = 0; i < m_jointCount; ++i) { - m_joints[i]->InitPositionConstraints(); + bool jointOkay = m_joints[i]->SolvePositionConstraints(b2_contactBaumgarte); + jointsOkay = jointsOkay && jointOkay; } - // Iterate over constraints. - for (m_positionIterationCount = 0; m_positionIterationCount < step.maxIterations; ++m_positionIterationCount) + if (contactsOkay && jointsOkay) { - bool contactsOkay = contactSolver.SolvePositionConstraints(b2_contactBaumgarte); - - bool jointsOkay = true; - for (int i = 0; i < m_jointCount; ++i) - { - bool jointOkay = m_joints[i]->SolvePositionConstraints(); - jointsOkay = jointsOkay && jointOkay; - } - - if (contactsOkay && jointsOkay) - { - break; - } + // Exit early if the position errors are small. + break; } } @@ -275,36 +305,28 @@ void b2Island::Solve(const b2TimeStep& step, const b2Vec2& gravity, bool correct if (allowSleep) { - float32 minSleepTime = B2_FLT_MAX; + float32 minSleepTime = b2_maxFloat; -#ifndef TARGET_FLOAT32_IS_FIXED const float32 linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance; const float32 angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance; -#endif for (int32 i = 0; i < m_bodyCount; ++i) { b2Body* b = m_bodies[i]; - if (b->m_invMass == 0.0f) + if (b->GetType() == b2_staticBody) { continue; } - if ((b->m_flags & b2Body::e_allowSleepFlag) == 0) + if ((b->m_flags & b2Body::e_autoSleepFlag) == 0) { b->m_sleepTime = 0.0f; minSleepTime = 0.0f; } - if ((b->m_flags & b2Body::e_allowSleepFlag) == 0 || -#ifdef TARGET_FLOAT32_IS_FIXED - b2Abs(b->m_angularVelocity) > b2_angularSleepTolerance || - b2Abs(b->m_linearVelocity.x) > b2_linearSleepTolerance || - b2Abs(b->m_linearVelocity.y) > b2_linearSleepTolerance) -#else + if ((b->m_flags & b2Body::e_autoSleepFlag) == 0 || b->m_angularVelocity * b->m_angularVelocity > angTolSqr || b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr) -#endif { b->m_sleepTime = 0.0f; minSleepTime = 0.0f; @@ -321,66 +343,13 @@ void b2Island::Solve(const b2TimeStep& step, const b2Vec2& gravity, bool correct for (int32 i = 0; i < m_bodyCount; ++i) { b2Body* b = m_bodies[i]; - b->m_flags |= b2Body::e_sleepFlag; - b->m_linearVelocity = b2Vec2_zero; - b->m_angularVelocity = 0.0f; + b->SetAwake(false); } } } } -void b2Island::SolveTOI(const b2TimeStep& subStep) -{ - b2ContactSolver contactSolver(subStep, m_contacts, m_contactCount, m_allocator); - - // No warm starting needed for TOI events. - - // Solve velocity constraints. - for (int32 i = 0; i < subStep.maxIterations; ++i) - { - contactSolver.SolveVelocityConstraints(); - } - - // Don't store the TOI contact forces for warm starting - // because they can be quite large. - - // Integrate positions. - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - - if (b->IsStatic()) - continue; - - // Store positions for continuous collision. - b->m_sweep.c0 = b->m_sweep.c; - b->m_sweep.a0 = b->m_sweep.a; - - // Integrate - b->m_sweep.c += subStep.dt * b->m_linearVelocity; - b->m_sweep.a += subStep.dt * b->m_angularVelocity; - - // Compute new transform - b->SynchronizeTransform(); - - // Note: shapes are synchronized later. - } - - // Solve position constraints. - const float32 k_toiBaumgarte = 0.75f; - for (int32 i = 0; i < subStep.maxIterations; ++i) - { - bool contactsOkay = contactSolver.SolvePositionConstraints(k_toiBaumgarte); - if (contactsOkay) - { - break; - } - } - - Report(contactSolver.m_constraints); -} - -void b2Island::Report(b2ContactConstraint* constraints) +void b2Island::Report(const b2ContactConstraint* constraints) { if (m_listener == NULL) { @@ -390,31 +359,16 @@ void b2Island::Report(b2ContactConstraint* constraints) for (int32 i = 0; i < m_contactCount; ++i) { b2Contact* c = m_contacts[i]; - b2ContactConstraint* cc = constraints + i; - b2ContactResult cr; - cr.shape1 = c->GetShape1(); - cr.shape2 = c->GetShape2(); - b2Body* b1 = cr.shape1->GetBody(); - int32 manifoldCount = c->GetManifoldCount(); - b2Manifold* manifolds = c->GetManifolds(); - for (int32 j = 0; j < manifoldCount; ++j) + + const b2ContactConstraint* cc = constraints + i; + + b2ContactImpulse impulse; + for (int32 j = 0; j < cc->pointCount; ++j) { - b2Manifold* manifold = manifolds + j; - cr.normal = manifold->normal; - for (int32 k = 0; k < manifold->pointCount; ++k) - { - b2ManifoldPoint* point = manifold->points + k; - b2ContactConstraintPoint* ccp = cc->points + k; - cr.position = b1->GetWorldPoint(point->localPoint1); - - // TOI constraint results are not stored, so get - // the result from the constraint. - cr.normalImpulse = ccp->normalImpulse; - cr.tangentImpulse = ccp->tangentImpulse; - cr.id = point->id; - - m_listener->Result(&cr); - } + impulse.normalImpulses[j] = cc->points[j].normalImpulse; + impulse.tangentImpulses[j] = cc->points[j].tangentImpulse; } + + m_listener->PostSolve(c, &impulse); } } diff --git a/src/modules/physics/box2d/Source/Dynamics/b2Island.h b/src/modules/physics/box2d/Box2D/Dynamics/b2Island.h similarity index 75% rename from src/modules/physics/box2d/Source/Dynamics/b2Island.h rename to src/modules/physics/box2d/Box2D/Dynamics/b2Island.h index eb62fd98e..3a5fd1131 100644 --- a/src/modules/physics/box2d/Source/Dynamics/b2Island.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Island.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -19,16 +19,31 @@ #ifndef B2_ISLAND_H #define B2_ISLAND_H -#include "../Common/b2Math.h" +#include +#include +#include class b2Contact; -class b2Body; class b2Joint; class b2StackAllocator; class b2ContactListener; struct b2ContactConstraint; -struct b2TimeStep; +/// This is an internal structure. +struct b2Position +{ + b2Vec2 x; + float32 a; +}; + +/// This is an internal structure. +struct b2Velocity +{ + b2Vec2 v; + float32 w; +}; + +/// This is an internal class. class b2Island { public: @@ -43,13 +58,12 @@ public: m_jointCount = 0; } - void Solve(const b2TimeStep& step, const b2Vec2& gravity, bool correctPositions, bool allowSleep); - - void SolveTOI(const b2TimeStep& subStep); + void Solve(const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep); void Add(b2Body* body) { b2Assert(m_bodyCount < m_bodyCapacity); + body->m_islandIndex = m_bodyCount; m_bodies[m_bodyCount++] = body; } @@ -65,7 +79,7 @@ public: m_joints[m_jointCount++] = joint; } - void Report(b2ContactConstraint* constraints); + void Report(const b2ContactConstraint* constraints); b2StackAllocator* m_allocator; b2ContactListener* m_listener; @@ -74,6 +88,9 @@ public: b2Contact** m_contacts; b2Joint** m_joints; + b2Position* m_positions; + b2Velocity* m_velocities; + int32 m_bodyCount; int32 m_jointCount; int32 m_contactCount; diff --git a/src/modules/physics/box2d/Source/Common/b2Settings.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2TimeStep.h similarity index 57% rename from src/modules/physics/box2d/Source/Common/b2Settings.cpp rename to src/modules/physics/box2d/Box2D/Dynamics/b2TimeStep.h index 060a810dc..f59245dd6 100644 --- a/src/modules/physics/box2d/Source/Common/b2Settings.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2TimeStep.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -16,36 +16,20 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#include "b2Settings.h" -#include +#ifndef B2_TIME_STEP_H +#define B2_TIME_STEP_H -b2Version b2_version = {2, 0, 1}; +#include -int32 b2_byteCount = 0; +/// This is an internal structure. +struct b2TimeStep +{ + float32 dt; // time step + float32 inv_dt; // inverse time step (0 if dt == 0). + float32 dtRatio; // dt * inv_dt0 + int32 velocityIterations; + int32 positionIterations; + bool warmStarting; +}; - - -// Memory allocators. Modify these to use your own allocator. -void* b2Alloc(int32 size) -{ - size += 4; - b2_byteCount += size; - char* bytes = (char*)malloc(size); - *(int32*)bytes = size; - return bytes + 4; -} - -void b2Free(void* mem) -{ - if (mem == NULL) - { - return; - } - - char* bytes = (char*)mem; - bytes -= 4; - int32 size = *(int32*)bytes; - b2Assert(b2_byteCount >= size); - b2_byteCount -= size; - free(bytes); -} +#endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp new file mode 100644 index 000000000..d3b9e0038 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp @@ -0,0 +1,1076 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +b2World::b2World(const b2Vec2& gravity, bool doSleep) +{ + m_destructionListener = NULL; + m_debugDraw = NULL; + + m_bodyList = NULL; + m_jointList = NULL; + + m_bodyCount = 0; + m_jointCount = 0; + + m_warmStarting = true; + m_continuousPhysics = true; + + m_allowSleep = doSleep; + m_gravity = gravity; + + m_flags = e_clearForces; + + m_inv_dt0 = 0.0f; + + m_contactManager.m_allocator = &m_blockAllocator; +} + +b2World::~b2World() +{ +} + +void b2World::SetDestructionListener(b2DestructionListener* listener) +{ + m_destructionListener = listener; +} + +void b2World::SetContactFilter(b2ContactFilter* filter) +{ + m_contactManager.m_contactFilter = filter; +} + +void b2World::SetContactListener(b2ContactListener* listener) +{ + m_contactManager.m_contactListener = listener; +} + +void b2World::SetDebugDraw(b2DebugDraw* debugDraw) +{ + m_debugDraw = debugDraw; +} + +b2Body* b2World::CreateBody(const b2BodyDef* def) +{ + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return NULL; + } + + void* mem = m_blockAllocator.Allocate(sizeof(b2Body)); + b2Body* b = new (mem) b2Body(def, this); + + // Add to world doubly linked list. + b->m_prev = NULL; + b->m_next = m_bodyList; + if (m_bodyList) + { + m_bodyList->m_prev = b; + } + m_bodyList = b; + ++m_bodyCount; + + return b; +} + +void b2World::DestroyBody(b2Body* b) +{ + b2Assert(m_bodyCount > 0); + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return; + } + + // Delete the attached joints. + b2JointEdge* je = b->m_jointList; + while (je) + { + b2JointEdge* je0 = je; + je = je->next; + + if (m_destructionListener) + { + m_destructionListener->SayGoodbye(je0->joint); + } + + DestroyJoint(je0->joint); + } + b->m_jointList = NULL; + + // Delete the attached contacts. + b2ContactEdge* ce = b->m_contactList; + while (ce) + { + b2ContactEdge* ce0 = ce; + ce = ce->next; + m_contactManager.Destroy(ce0->contact); + } + b->m_contactList = NULL; + + // Delete the attached fixtures. This destroys broad-phase proxies. + b2Fixture* f = b->m_fixtureList; + while (f) + { + b2Fixture* f0 = f; + f = f->m_next; + + if (m_destructionListener) + { + m_destructionListener->SayGoodbye(f0); + } + + f0->DestroyProxy(&m_contactManager.m_broadPhase); + f0->Destroy(&m_blockAllocator); + f0->~b2Fixture(); + m_blockAllocator.Free(f0, sizeof(b2Fixture)); + } + b->m_fixtureList = NULL; + b->m_fixtureCount = 0; + + // Remove world body list. + if (b->m_prev) + { + b->m_prev->m_next = b->m_next; + } + + if (b->m_next) + { + b->m_next->m_prev = b->m_prev; + } + + if (b == m_bodyList) + { + m_bodyList = b->m_next; + } + + --m_bodyCount; + b->~b2Body(); + m_blockAllocator.Free(b, sizeof(b2Body)); +} + +b2Joint* b2World::CreateJoint(const b2JointDef* def) +{ + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return NULL; + } + + b2Joint* j = b2Joint::Create(def, &m_blockAllocator); + + // Connect to the world list. + j->m_prev = NULL; + j->m_next = m_jointList; + if (m_jointList) + { + m_jointList->m_prev = j; + } + m_jointList = j; + ++m_jointCount; + + // Connect to the bodies' doubly linked lists. + j->m_edgeA.joint = j; + j->m_edgeA.other = j->m_bodyB; + j->m_edgeA.prev = NULL; + j->m_edgeA.next = j->m_bodyA->m_jointList; + if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA; + j->m_bodyA->m_jointList = &j->m_edgeA; + + j->m_edgeB.joint = j; + j->m_edgeB.other = j->m_bodyA; + j->m_edgeB.prev = NULL; + j->m_edgeB.next = j->m_bodyB->m_jointList; + if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB; + j->m_bodyB->m_jointList = &j->m_edgeB; + + b2Body* bodyA = def->bodyA; + b2Body* bodyB = def->bodyB; + + // If the joint prevents collisions, then flag any contacts for filtering. + if (def->collideConnected == false) + { + b2ContactEdge* edge = bodyB->GetContactList(); + while (edge) + { + if (edge->other == bodyA) + { + // Flag the contact for filtering at the next time step (where either + // body is awake). + edge->contact->FlagForFiltering(); + } + + edge = edge->next; + } + } + + // Note: creating a joint doesn't wake the bodies. + + return j; +} + +void b2World::DestroyJoint(b2Joint* j) +{ + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return; + } + + bool collideConnected = j->m_collideConnected; + + // Remove from the doubly linked list. + if (j->m_prev) + { + j->m_prev->m_next = j->m_next; + } + + if (j->m_next) + { + j->m_next->m_prev = j->m_prev; + } + + if (j == m_jointList) + { + m_jointList = j->m_next; + } + + // Disconnect from island graph. + b2Body* bodyA = j->m_bodyA; + b2Body* bodyB = j->m_bodyB; + + // Wake up connected bodies. + bodyA->SetAwake(true); + bodyB->SetAwake(true); + + // Remove from body 1. + if (j->m_edgeA.prev) + { + j->m_edgeA.prev->next = j->m_edgeA.next; + } + + if (j->m_edgeA.next) + { + j->m_edgeA.next->prev = j->m_edgeA.prev; + } + + if (&j->m_edgeA == bodyA->m_jointList) + { + bodyA->m_jointList = j->m_edgeA.next; + } + + j->m_edgeA.prev = NULL; + j->m_edgeA.next = NULL; + + // Remove from body 2 + if (j->m_edgeB.prev) + { + j->m_edgeB.prev->next = j->m_edgeB.next; + } + + if (j->m_edgeB.next) + { + j->m_edgeB.next->prev = j->m_edgeB.prev; + } + + if (&j->m_edgeB == bodyB->m_jointList) + { + bodyB->m_jointList = j->m_edgeB.next; + } + + j->m_edgeB.prev = NULL; + j->m_edgeB.next = NULL; + + b2Joint::Destroy(j, &m_blockAllocator); + + b2Assert(m_jointCount > 0); + --m_jointCount; + + // If the joint prevents collisions, then flag any contacts for filtering. + if (collideConnected == false) + { + b2ContactEdge* edge = bodyB->GetContactList(); + while (edge) + { + if (edge->other == bodyA) + { + // Flag the contact for filtering at the next time step (where either + // body is awake). + edge->contact->FlagForFiltering(); + } + + edge = edge->next; + } + } +} + +// Find islands, integrate and solve constraints, solve position constraints +void b2World::Solve(const b2TimeStep& step) +{ + // Size the island for the worst case. + b2Island island(m_bodyCount, + m_contactManager.m_contactCount, + m_jointCount, + &m_stackAllocator, + m_contactManager.m_contactListener); + + // Clear all the island flags. + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->m_flags &= ~b2Body::e_islandFlag; + } + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) + { + c->m_flags &= ~b2Contact::e_islandFlag; + } + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + j->m_islandFlag = false; + } + + // Build and simulate all awake islands. + int32 stackSize = m_bodyCount; + b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); + for (b2Body* seed = m_bodyList; seed; seed = seed->m_next) + { + if (seed->m_flags & b2Body::e_islandFlag) + { + continue; + } + + if (seed->IsAwake() == false || seed->IsActive() == false) + { + continue; + } + + // The seed can be dynamic or kinematic. + if (seed->GetType() == b2_staticBody) + { + continue; + } + + // Reset island and stack. + island.Clear(); + int32 stackCount = 0; + stack[stackCount++] = seed; + seed->m_flags |= b2Body::e_islandFlag; + + // Perform a depth first search (DFS) on the constraint graph. + while (stackCount > 0) + { + // Grab the next body off the stack and add it to the island. + b2Body* b = stack[--stackCount]; + b2Assert(b->IsActive() == true); + island.Add(b); + + // Make sure the body is awake. + b->SetAwake(true); + + // To keep islands as small as possible, we don't + // propagate islands across static bodies. + if (b->GetType() == b2_staticBody) + { + continue; + } + + // Search all contacts connected to this body. + for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next) + { + b2Contact* contact = ce->contact; + + // Has this contact already been added to an island? + if (contact->m_flags & b2Contact::e_islandFlag) + { + continue; + } + + // Is this contact solid and touching? + if (contact->IsEnabled() == false || + contact->IsTouching() == false) + { + continue; + } + + // Skip sensors. + bool sensorA = contact->m_fixtureA->m_isSensor; + bool sensorB = contact->m_fixtureB->m_isSensor; + if (sensorA || sensorB) + { + continue; + } + + island.Add(contact); + contact->m_flags |= b2Contact::e_islandFlag; + + b2Body* other = ce->other; + + // Was the other body already added to this island? + if (other->m_flags & b2Body::e_islandFlag) + { + continue; + } + + b2Assert(stackCount < stackSize); + stack[stackCount++] = other; + other->m_flags |= b2Body::e_islandFlag; + } + + // Search all joints connect to this body. + for (b2JointEdge* je = b->m_jointList; je; je = je->next) + { + if (je->joint->m_islandFlag == true) + { + continue; + } + + b2Body* other = je->other; + + // Don't simulate joints connected to inactive bodies. + if (other->IsActive() == false) + { + continue; + } + + island.Add(je->joint); + je->joint->m_islandFlag = true; + + if (other->m_flags & b2Body::e_islandFlag) + { + continue; + } + + b2Assert(stackCount < stackSize); + stack[stackCount++] = other; + other->m_flags |= b2Body::e_islandFlag; + } + } + + island.Solve(step, m_gravity, m_allowSleep); + + // Post solve cleanup. + for (int32 i = 0; i < island.m_bodyCount; ++i) + { + // Allow static bodies to participate in other islands. + b2Body* b = island.m_bodies[i]; + if (b->GetType() == b2_staticBody) + { + b->m_flags &= ~b2Body::e_islandFlag; + } + } + } + + m_stackAllocator.Free(stack); + + // Synchronize fixtures, check for out of range bodies. + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + // If a body was not in an island then it did not move. + if ((b->m_flags & b2Body::e_islandFlag) == 0) + { + continue; + } + + if (b->GetType() == b2_staticBody) + { + continue; + } + + // Update fixtures (for broad-phase). + b->SynchronizeFixtures(); + } + + // Look for new contacts. + m_contactManager.FindNewContacts(); +} + +// Advance a dynamic body to its first time of contact +// and adjust the position to ensure clearance. +void b2World::SolveTOI(b2Body* body) +{ + // Find the minimum contact. + b2Contact* toiContact = NULL; + float32 toi = 1.0f; + b2Body* toiOther = NULL; + bool found; + int32 count; + int32 iter = 0; + + bool bullet = body->IsBullet(); + + // Iterate until all contacts agree on the minimum TOI. We have + // to iterate because the TOI algorithm may skip some intermediate + // collisions when objects rotate through each other. + do + { + count = 0; + found = false; + for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) + { + if (ce->contact == toiContact) + { + continue; + } + + b2Body* other = ce->other; + b2BodyType type = other->GetType(); + + // Only bullets perform TOI with dynamic bodies. + if (bullet == true) + { + // Bullets only perform TOI with bodies that have their TOI resolved. + if ((other->m_flags & b2Body::e_toiFlag) == 0) + { + continue; + } + + // No repeated hits on non-static bodies + if (type != b2_staticBody && (ce->contact->m_flags & b2Contact::e_bulletHitFlag) != 0) + { + continue; + } + } + else if (type == b2_dynamicBody) + { + continue; + } + + // Check for a disabled contact. + b2Contact* contact = ce->contact; + if (contact->IsEnabled() == false) + { + continue; + } + + // Prevent infinite looping. + if (contact->m_toiCount > 10) + { + continue; + } + + b2Fixture* fixtureA = contact->m_fixtureA; + b2Fixture* fixtureB = contact->m_fixtureB; + + // Cull sensors. + if (fixtureA->IsSensor() || fixtureB->IsSensor()) + { + continue; + } + + b2Body* bodyA = fixtureA->m_body; + b2Body* bodyB = fixtureB->m_body; + + // Compute the time of impact in interval [0, minTOI] + b2TOIInput input; + input.proxyA.Set(fixtureA->GetShape()); + input.proxyB.Set(fixtureB->GetShape()); + input.sweepA = bodyA->m_sweep; + input.sweepB = bodyB->m_sweep; + input.tMax = toi; + + b2TOIOutput output; + b2TimeOfImpact(&output, &input); + + if (output.state == b2TOIOutput::e_touching && output.t < toi) + { + toiContact = contact; + toi = output.t; + toiOther = other; + found = true; + } + + ++count; + } + + ++iter; + } while (found && count > 1 && iter < 50); + + if (toiContact == NULL) + { + body->Advance(1.0f); + return; + } + + b2Sweep backup = body->m_sweep; + body->Advance(toi); + toiContact->Update(m_contactManager.m_contactListener); + if (toiContact->IsEnabled() == false) + { + // Contact disabled. Backup and recurse. + body->m_sweep = backup; + SolveTOI(body); + } + + ++toiContact->m_toiCount; + + // Update all the valid contacts on this body and build a contact island. + b2Contact* contacts[b2_maxTOIContacts]; + count = 0; + for (b2ContactEdge* ce = body->m_contactList; ce && count < b2_maxTOIContacts; ce = ce->next) + { + b2Body* other = ce->other; + b2BodyType type = other->GetType(); + + // Only perform correction with static bodies, so the + // body won't get pushed out of the world. + if (type == b2_dynamicBody) + { + continue; + } + + // Check for a disabled contact. + b2Contact* contact = ce->contact; + if (contact->IsEnabled() == false) + { + continue; + } + + b2Fixture* fixtureA = contact->m_fixtureA; + b2Fixture* fixtureB = contact->m_fixtureB; + + // Cull sensors. + if (fixtureA->IsSensor() || fixtureB->IsSensor()) + { + continue; + } + + // The contact likely has some new contact points. The listener + // gives the user a chance to disable the contact. + if (contact != toiContact) + { + contact->Update(m_contactManager.m_contactListener); + } + + // Did the user disable the contact? + if (contact->IsEnabled() == false) + { + // Skip this contact. + continue; + } + + if (contact->IsTouching() == false) + { + continue; + } + + contacts[count] = contact; + ++count; + } + + // Reduce the TOI body's overlap with the contact island. + b2TOISolver solver(&m_stackAllocator); + solver.Initialize(contacts, count, body); + + const float32 k_toiBaumgarte = 0.75f; + bool solved = false; + for (int32 i = 0; i < 20; ++i) + { + bool contactsOkay = solver.Solve(k_toiBaumgarte); + if (contactsOkay) + { + solved = true; + break; + } + } + + if (toiOther->GetType() != b2_staticBody) + { + toiContact->m_flags |= b2Contact::e_bulletHitFlag; + } +} + +// Sequentially solve TOIs for each body. We bring each +// body to the time of contact and perform some position correction. +// Time is not conserved. +void b2World::SolveTOI() +{ + // Prepare all contacts. + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) + { + // Enable the contact + c->m_flags |= b2Contact::e_enabledFlag; + + // Set the number of TOI events for this contact to zero. + c->m_toiCount = 0; + } + + // Initialize the TOI flag. + for (b2Body* body = m_bodyList; body; body = body->m_next) + { + // Kinematic, and static bodies will not be affected by the TOI event. + // If a body was not in an island then it did not move. + if ((body->m_flags & b2Body::e_islandFlag) == 0 || body->GetType() == b2_kinematicBody || body->GetType() == b2_staticBody) + { + body->m_flags |= b2Body::e_toiFlag; + } + else + { + body->m_flags &= ~b2Body::e_toiFlag; + } + } + + // Collide non-bullets. + for (b2Body* body = m_bodyList; body; body = body->m_next) + { + if (body->m_flags & b2Body::e_toiFlag) + { + continue; + } + + if (body->IsBullet() == true) + { + continue; + } + + SolveTOI(body); + + body->m_flags |= b2Body::e_toiFlag; + } + + // Collide bullets. + for (b2Body* body = m_bodyList; body; body = body->m_next) + { + if (body->m_flags & b2Body::e_toiFlag) + { + continue; + } + + if (body->IsBullet() == false) + { + continue; + } + + SolveTOI(body); + + body->m_flags |= b2Body::e_toiFlag; + } +} + +void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations) +{ + // If new fixtures were added, we need to find the new contacts. + if (m_flags & e_newFixture) + { + m_contactManager.FindNewContacts(); + m_flags &= ~e_newFixture; + } + + m_flags |= e_locked; + + b2TimeStep step; + step.dt = dt; + step.velocityIterations = velocityIterations; + step.positionIterations = positionIterations; + if (dt > 0.0f) + { + step.inv_dt = 1.0f / dt; + } + else + { + step.inv_dt = 0.0f; + } + + step.dtRatio = m_inv_dt0 * dt; + + step.warmStarting = m_warmStarting; + + // Update contacts. This is where some contacts are destroyed. + m_contactManager.Collide(); + + // Integrate velocities, solve velocity constraints, and integrate positions. + if (step.dt > 0.0f) + { + Solve(step); + } + + // Handle TOI events. + if (m_continuousPhysics && step.dt > 0.0f) + { + SolveTOI(); + } + + if (step.dt > 0.0f) + { + m_inv_dt0 = step.inv_dt; + } + + if (m_flags & e_clearForces) + { + ClearForces(); + } + + m_flags &= ~e_locked; +} + +void b2World::ClearForces() +{ + for (b2Body* body = m_bodyList; body; body = body->GetNext()) + { + body->m_force.SetZero(); + body->m_torque = 0.0f; + } +} + +struct b2WorldQueryWrapper +{ + bool QueryCallback(int32 proxyId) + { + b2Fixture* fixture = (b2Fixture*)broadPhase->GetUserData(proxyId); + return callback->ReportFixture(fixture); + } + + const b2BroadPhase* broadPhase; + b2QueryCallback* callback; +}; + +void b2World::QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const +{ + b2WorldQueryWrapper wrapper; + wrapper.broadPhase = &m_contactManager.m_broadPhase; + wrapper.callback = callback; + m_contactManager.m_broadPhase.Query(&wrapper, aabb); +} + +struct b2WorldRayCastWrapper +{ + float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId) + { + void* userData = broadPhase->GetUserData(proxyId); + b2Fixture* fixture = (b2Fixture*)userData; + b2RayCastOutput output; + bool hit = fixture->RayCast(&output, input); + + if (hit) + { + float32 fraction = output.fraction; + b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2; + return callback->ReportFixture(fixture, point, output.normal, fraction); + } + + return input.maxFraction; + } + + const b2BroadPhase* broadPhase; + b2RayCastCallback* callback; +}; + +void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const +{ + b2WorldRayCastWrapper wrapper; + wrapper.broadPhase = &m_contactManager.m_broadPhase; + wrapper.callback = callback; + b2RayCastInput input; + input.maxFraction = 1.0f; + input.p1 = point1; + input.p2 = point2; + m_contactManager.m_broadPhase.RayCast(&wrapper, input); +} + +void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color& color) +{ + switch (fixture->GetType()) + { + case b2Shape::e_circle: + { + b2CircleShape* circle = (b2CircleShape*)fixture->GetShape(); + + b2Vec2 center = b2Mul(xf, circle->m_p); + float32 radius = circle->m_radius; + b2Vec2 axis = xf.R.col1; + + m_debugDraw->DrawSolidCircle(center, radius, axis, color); + } + break; + + case b2Shape::e_polygon: + { + b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); + int32 vertexCount = poly->m_vertexCount; + b2Assert(vertexCount <= b2_maxPolygonVertices); + b2Vec2 vertices[b2_maxPolygonVertices]; + + for (int32 i = 0; i < vertexCount; ++i) + { + vertices[i] = b2Mul(xf, poly->m_vertices[i]); + } + + m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color); + } + break; + } +} + +void b2World::DrawJoint(b2Joint* joint) +{ + b2Body* bodyA = joint->GetBodyA(); + b2Body* bodyB = joint->GetBodyB(); + const b2Transform& xf1 = bodyA->GetTransform(); + const b2Transform& xf2 = bodyB->GetTransform(); + b2Vec2 x1 = xf1.position; + b2Vec2 x2 = xf2.position; + b2Vec2 p1 = joint->GetAnchorA(); + b2Vec2 p2 = joint->GetAnchorB(); + + b2Color color(0.5f, 0.8f, 0.8f); + + switch (joint->GetType()) + { + case e_distanceJoint: + m_debugDraw->DrawSegment(p1, p2, color); + break; + + case e_pulleyJoint: + { + b2PulleyJoint* pulley = (b2PulleyJoint*)joint; + b2Vec2 s1 = pulley->GetGroundAnchorA(); + b2Vec2 s2 = pulley->GetGroundAnchorB(); + m_debugDraw->DrawSegment(s1, p1, color); + m_debugDraw->DrawSegment(s2, p2, color); + m_debugDraw->DrawSegment(s1, s2, color); + } + break; + + case e_mouseJoint: + // don't draw this + break; + + default: + m_debugDraw->DrawSegment(x1, p1, color); + m_debugDraw->DrawSegment(p1, p2, color); + m_debugDraw->DrawSegment(x2, p2, color); + } +} + +void b2World::DrawDebugData() +{ + if (m_debugDraw == NULL) + { + return; + } + + uint32 flags = m_debugDraw->GetFlags(); + + if (flags & b2DebugDraw::e_shapeBit) + { + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + const b2Transform& xf = b->GetTransform(); + for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) + { + if (b->IsActive() == false) + { + DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f)); + } + else if (b->GetType() == b2_staticBody) + { + DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f)); + } + else if (b->GetType() == b2_kinematicBody) + { + DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f)); + } + else if (b->IsAwake() == false) + { + DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f)); + } + else + { + DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f)); + } + } + } + } + + if (flags & b2DebugDraw::e_jointBit) + { + for (b2Joint* j = m_jointList; j; j = j->GetNext()) + { + DrawJoint(j); + } + } + + if (flags & b2DebugDraw::e_pairBit) + { + b2Color color(0.3f, 0.9f, 0.9f); + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext()) + { + b2Fixture* fixtureA = c->GetFixtureA(); + b2Fixture* fixtureB = c->GetFixtureB(); + + b2Vec2 cA = fixtureA->GetAABB().GetCenter(); + b2Vec2 cB = fixtureB->GetAABB().GetCenter(); + + m_debugDraw->DrawSegment(cA, cB, color); + } + } + + if (flags & b2DebugDraw::e_aabbBit) + { + b2Color color(0.9f, 0.3f, 0.9f); + b2BroadPhase* bp = &m_contactManager.m_broadPhase; + + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + if (b->IsActive() == false) + { + continue; + } + + for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) + { + b2AABB aabb = bp->GetFatAABB(f->m_proxyId); + b2Vec2 vs[4]; + vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); + vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); + vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); + vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); + + m_debugDraw->DrawPolygon(vs, 4, color); + } + } + } + + if (flags & b2DebugDraw::e_centerOfMassBit) + { + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + b2Transform xf = b->GetTransform(); + xf.position = b->GetWorldCenter(); + m_debugDraw->DrawTransform(xf); + } + } +} + +int32 b2World::GetProxyCount() const +{ + return m_contactManager.m_broadPhase.GetProxyCount(); +} diff --git a/src/modules/physics/box2d/Source/Dynamics/b2World.h b/src/modules/physics/box2d/Box2D/Dynamics/b2World.h similarity index 57% rename from src/modules/physics/box2d/Source/Dynamics/b2World.h rename to src/modules/physics/box2d/Box2D/Dynamics/b2World.h index 02c87a631..bff14272f 100644 --- a/src/modules/physics/box2d/Source/Dynamics/b2World.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2World.h @@ -1,253 +1,285 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_WORLD_H -#define B2_WORLD_H - -#include "../Common/b2Math.h" -#include "../Common/b2BlockAllocator.h" -#include "../Common/b2StackAllocator.h" -#include "b2ContactManager.h" -#include "b2WorldCallbacks.h" - -struct b2AABB; -struct b2ShapeDef; -struct b2BodyDef; -struct b2JointDef; -class b2Body; -class b2Joint; -class b2Shape; -class b2Contact; -class b2BroadPhase; - -struct b2TimeStep -{ - float32 dt; // time step - float32 inv_dt; // inverse time step (0 if dt == 0). - float32 dtRatio; // dt * inv_dt0 - int32 maxIterations; - bool warmStarting; - bool positionCorrection; -}; - -/// The world class manages all physics entities, dynamic simulation, -/// and asynchronous queries. The world also contains efficient memory -/// management facilities. -class b2World -{ -public: - /// Construct a world object. - /// @param worldAABB a bounding box that completely encompasses all your shapes. - /// @param gravity the world gravity vector. - /// @param doSleep improve performance by not simulating inactive bodies. - b2World(const b2AABB& worldAABB, const b2Vec2& gravity, bool doSleep); - - /// Destruct the world. All physics entities are destroyed and all heap memory is released. - ~b2World(); - - /// Register a destruction listener. - void SetDestructionListener(b2DestructionListener* listener); - - /// Register a broad-phase boundary listener. - void SetBoundaryListener(b2BoundaryListener* listener); - - /// Register a contact filter to provide specific control over collision. - /// Otherwise the default filter is used (b2_defaultFilter). - void SetContactFilter(b2ContactFilter* filter); - - /// Register a contact event listener - void SetContactListener(b2ContactListener* listener); - - /// Register a routine for debug drawing. The debug draw functions are called - /// inside the b2World::Step method, so make sure your renderer is ready to - /// consume draw commands when you call Step(). - void SetDebugDraw(b2DebugDraw* debugDraw); - - /// Create a rigid body given a definition. No reference to the definition - /// is retained. - /// @warning This function is locked during callbacks. - b2Body* CreateBody(const b2BodyDef* def); - - /// Destroy a rigid body given a definition. No reference to the definition - /// is retained. This function is locked during callbacks. - /// @warning This automatically deletes all associated shapes and joints. - /// @warning This function is locked during callbacks. - void DestroyBody(b2Body* body); - - /// Create a joint to constrain bodies together. No reference to the definition - /// is retained. This may cause the connected bodies to cease colliding. - /// @warning This function is locked during callbacks. - b2Joint* CreateJoint(const b2JointDef* def); - - /// Destroy a joint. This may cause the connected bodies to begin colliding. - /// @warning This function is locked during callbacks. - void DestroyJoint(b2Joint* joint); - - /// The world provides a single static ground body with no collision shapes. - /// You can use this to simplify the creation of joints and static shapes. - b2Body* GetGroundBody(); - - /// Take a time step. This performs collision detection, integration, - /// and constraint solution. - /// @param timeStep the amount of time to simulate, this should not vary. - /// @param iterations the number of iterations to be used by the constraint solver. - void Step(float32 timeStep, int32 iterations); - - /// Query the world for all shapes that potentially overlap the - /// provided AABB. You provide a shape pointer buffer of specified - /// size. The number of shapes found is returned. - /// @param aabb the query box. - /// @param shapes a user allocated shape pointer array of size maxCount (or greater). - /// @param maxCount the capacity of the shapes array. - /// @return the number of shapes found in aabb. - int32 Query(const b2AABB& aabb, b2Shape** shapes, int32 maxCount); - - /// Get the world body list. With the returned body, use b2Body::GetNext to get - /// the next body in the world list. A NULL body indicates the end of the list. - /// @return the head of the world body list. - b2Body* GetBodyList(); - - /// Get the world joint list. With the returned joint, use b2Joint::GetNext to get - /// the next joint in the world list. A NULL joint indicates the end of the list. - /// @return the head of the world joint list. - b2Joint* GetJointList(); - - /// Re-filter a shape. This re-runs contact filtering on a shape. - void Refilter(b2Shape* shape); - - /// Enable/disable warm starting. For testing. - void SetWarmStarting(bool flag) { m_warmStarting = flag; } - - /// Enable/disable position correction. For testing. - void SetPositionCorrection(bool flag) { m_positionCorrection = flag; } - - /// Enable/disable continuous physics. For testing. - void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; } - - /// Perform validation of internal data structures. - void Validate(); - - /// Get the number of broad-phase proxies. - int32 GetProxyCount() const; - - /// Get the number of broad-phase pairs. - int32 GetPairCount() const; - - /// Get the number of bodies. - int32 GetBodyCount() const; - - /// Get the number joints. - int32 GetJointCount() const; - - /// Get the number of contacts (each may have 0 or more contact points). - int32 GetContactCount() const; - - /// Change the global gravity vector. - void SetGravity(const b2Vec2& gravity); - -public: - - friend class b2Body; - friend class b2ContactManager; - - void Solve(const b2TimeStep& step); - void SolveTOI(const b2TimeStep& step); - - void DrawJoint(b2Joint* joint); - void DrawShape(b2Shape* shape, const b2XForm& xf, const b2Color& color, bool core); - void DrawDebugData(); - - b2BlockAllocator m_blockAllocator; - b2StackAllocator m_stackAllocator; - - bool m_lock; - - b2BroadPhase* m_broadPhase; - b2ContactManager m_contactManager; - - b2Body* m_bodyList; - b2Joint* m_jointList; - - // Do not access - b2Contact* m_contactList; - - int32 m_bodyCount; - int32 m_contactCount; - int32 m_jointCount; - - b2Vec2 m_gravity; - bool m_allowSleep; - - b2Body* m_groundBody; - - b2DestructionListener* m_destructionListener; - b2BoundaryListener* m_boundaryListener; - b2ContactFilter* m_contactFilter; - b2ContactListener* m_contactListener; - b2DebugDraw* m_debugDraw; - - float32 m_inv_dt0; - - int32 m_positionIterationCount; - - // This is for debugging the solver. - bool m_positionCorrection; - - // This is for debugging the solver. - bool m_warmStarting; - - // This is for debugging the solver. - bool m_continuousPhysics; -}; - -inline b2Body* b2World::GetGroundBody() -{ - return m_groundBody; -} - -inline b2Body* b2World::GetBodyList() -{ - return m_bodyList; -} - -inline b2Joint* b2World::GetJointList() -{ - return m_jointList; -} - -inline int32 b2World::GetBodyCount() const -{ - return m_bodyCount; -} - -inline int32 b2World::GetJointCount() const -{ - return m_jointCount; -} - -inline int32 b2World::GetContactCount() const -{ - return m_contactCount; -} - -inline void b2World::SetGravity(const b2Vec2& gravity) -{ - m_gravity = gravity; -} - -#endif +/* +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_WORLD_H +#define B2_WORLD_H + +#include +#include +#include +#include +#include + +struct b2AABB; +struct b2BodyDef; +struct b2JointDef; +struct b2TimeStep; +class b2Body; +class b2Fixture; +class b2Joint; + +/// The world class manages all physics entities, dynamic simulation, +/// and asynchronous queries. The world also contains efficient memory +/// management facilities. +class b2World +{ +public: + /// Construct a world object. + /// @param gravity the world gravity vector. + /// @param doSleep improve performance by not simulating inactive bodies. + b2World(const b2Vec2& gravity, bool doSleep); + + /// Destruct the world. All physics entities are destroyed and all heap memory is released. + ~b2World(); + + /// Register a destruction listener. The listener is owned by you and must + /// remain in scope. + void SetDestructionListener(b2DestructionListener* listener); + + /// Register a contact filter to provide specific control over collision. + /// Otherwise the default filter is used (b2_defaultFilter). The listener is + /// owned by you and must remain in scope. + void SetContactFilter(b2ContactFilter* filter); + + /// Register a contact event listener. The listener is owned by you and must + /// remain in scope. + void SetContactListener(b2ContactListener* listener); + + /// Register a routine for debug drawing. The debug draw functions are called + /// inside with b2World::DrawDebugData method. The debug draw object is owned + /// by you and must remain in scope. + void SetDebugDraw(b2DebugDraw* debugDraw); + + /// Create a rigid body given a definition. No reference to the definition + /// is retained. + /// @warning This function is locked during callbacks. + b2Body* CreateBody(const b2BodyDef* def); + + /// Destroy a rigid body given a definition. No reference to the definition + /// is retained. This function is locked during callbacks. + /// @warning This automatically deletes all associated shapes and joints. + /// @warning This function is locked during callbacks. + void DestroyBody(b2Body* body); + + /// Create a joint to constrain bodies together. No reference to the definition + /// is retained. This may cause the connected bodies to cease colliding. + /// @warning This function is locked during callbacks. + b2Joint* CreateJoint(const b2JointDef* def); + + /// Destroy a joint. This may cause the connected bodies to begin colliding. + /// @warning This function is locked during callbacks. + void DestroyJoint(b2Joint* joint); + + /// Take a time step. This performs collision detection, integration, + /// and constraint solution. + /// @param timeStep the amount of time to simulate, this should not vary. + /// @param velocityIterations for the velocity constraint solver. + /// @param positionIterations for the position constraint solver. + void Step( float32 timeStep, + int32 velocityIterations, + int32 positionIterations); + + /// Call this after you are done with time steps to clear the forces. You normally + /// call this after each call to Step, unless you are performing sub-steps. By default, + /// forces will be automatically cleared, so you don't need to call this function. + /// @see SetAutoClearForces + void ClearForces(); + + /// Call this to draw shapes and other debug draw data. + void DrawDebugData(); + + /// Query the world for all fixtures that potentially overlap the + /// provided AABB. + /// @param callback a user implemented callback class. + /// @param aabb the query box. + void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const; + + /// Ray-cast the world for all fixtures in the path of the ray. Your callback + /// controls whether you get the closest point, any point, or n-points. + /// The ray-cast ignores shapes that contain the starting point. + /// @param callback a user implemented callback class. + /// @param point1 the ray starting point + /// @param point2 the ray ending point + void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const; + + /// Get the world body list. With the returned body, use b2Body::GetNext to get + /// the next body in the world list. A NULL body indicates the end of the list. + /// @return the head of the world body list. + b2Body* GetBodyList(); + + /// Get the world joint list. With the returned joint, use b2Joint::GetNext to get + /// the next joint in the world list. A NULL joint indicates the end of the list. + /// @return the head of the world joint list. + b2Joint* GetJointList(); + + /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get + /// the next contact in the world list. A NULL contact indicates the end of the list. + /// @return the head of the world contact list. + /// @warning contacts are + b2Contact* GetContactList(); + + /// Enable/disable warm starting. For testing. + void SetWarmStarting(bool flag) { m_warmStarting = flag; } + + /// Enable/disable continuous physics. For testing. + void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; } + + /// Get the number of broad-phase proxies. + int32 GetProxyCount() const; + + /// Get the number of bodies. + int32 GetBodyCount() const; + + /// Get the number of joints. + int32 GetJointCount() const; + + /// Get the number of contacts (each may have 0 or more contact points). + int32 GetContactCount() const; + + /// Change the global gravity vector. + void SetGravity(const b2Vec2& gravity); + + /// Get the global gravity vector. + b2Vec2 GetGravity() const; + + /// Is the world locked (in the middle of a time step). + bool IsLocked() const; + + /// Set flag to control automatic clearing of forces after each time step. + void SetAutoClearForces(bool flag); + + /// Get the flag that controls automatic clearing of forces after each time step. + bool GetAutoClearForces() const; + +private: + + // m_flags + enum + { + e_newFixture = 0x0001, + e_locked = 0x0002, + e_clearForces = 0x0004, + }; + + friend class b2Body; + friend class b2ContactManager; + friend class b2Controller; + + void Solve(const b2TimeStep& step); + void SolveTOI(); + void SolveTOI(b2Body* body); + + void DrawJoint(b2Joint* joint); + void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color); + + b2BlockAllocator m_blockAllocator; + b2StackAllocator m_stackAllocator; + + int32 m_flags; + + b2ContactManager m_contactManager; + + b2Body* m_bodyList; + b2Joint* m_jointList; + + int32 m_bodyCount; + int32 m_jointCount; + + b2Vec2 m_gravity; + bool m_allowSleep; + + b2Body* m_groundBody; + + b2DestructionListener* m_destructionListener; + b2DebugDraw* m_debugDraw; + + // This is used to compute the time step ratio to + // support a variable time step. + float32 m_inv_dt0; + + // This is for debugging the solver. + bool m_warmStarting; + + // This is for debugging the solver. + bool m_continuousPhysics; +}; + +inline b2Body* b2World::GetBodyList() +{ + return m_bodyList; +} + +inline b2Joint* b2World::GetJointList() +{ + return m_jointList; +} + +inline b2Contact* b2World::GetContactList() +{ + return m_contactManager.m_contactList; +} + +inline int32 b2World::GetBodyCount() const +{ + return m_bodyCount; +} + +inline int32 b2World::GetJointCount() const +{ + return m_jointCount; +} + +inline int32 b2World::GetContactCount() const +{ + return m_contactManager.m_contactCount; +} + +inline void b2World::SetGravity(const b2Vec2& gravity) +{ + m_gravity = gravity; +} + +inline b2Vec2 b2World::GetGravity() const +{ + return m_gravity; +} + +inline bool b2World::IsLocked() const +{ + return (m_flags & e_locked) == e_locked; +} + +inline void b2World::SetAutoClearForces(bool flag) +{ + if (flag) + { + m_flags |= e_clearForces; + } + else + { + m_flags &= ~e_clearForces; + } +} + +/// Get the flag that controls automatic clearing of forces after each time step. +inline bool b2World::GetAutoClearForces() const +{ + return (m_flags & e_clearForces) == e_clearForces; +} + +#endif diff --git a/src/modules/physics/box2d/Source/Dynamics/b2WorldCallbacks.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.cpp similarity index 68% rename from src/modules/physics/box2d/Source/Dynamics/b2WorldCallbacks.cpp rename to src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.cpp index 614324f63..bc5fefbdf 100644 --- a/src/modules/physics/box2d/Source/Dynamics/b2WorldCallbacks.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -16,24 +16,22 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#include "b2WorldCallbacks.h" -#include "../Collision/Shapes/b2Shape.h" - -b2ContactFilter b2_defaultFilter; +#include +#include // Return true if contact calculations should be performed between these two shapes. // If you implement your own collision filter you may want to build from this implementation. -bool b2ContactFilter::ShouldCollide(b2Shape* shape1, b2Shape* shape2) +bool b2ContactFilter::ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB) { - const b2FilterData& filter1 = shape1->GetFilterData(); - const b2FilterData& filter2 = shape2->GetFilterData(); + const b2Filter& filterA = fixtureA->GetFilterData(); + const b2Filter& filterB = fixtureB->GetFilterData(); - if (filter1.groupIndex == filter2.groupIndex && filter1.groupIndex != 0) + if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) { - return filter1.groupIndex > 0; + return filterA.groupIndex > 0; } - bool collide = (filter1.maskBits & filter2.categoryBits) != 0 && (filter1.categoryBits & filter2.maskBits) != 0; + bool collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0; return collide; } diff --git a/src/modules/physics/box2d/Source/Dynamics/b2WorldCallbacks.h b/src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.h similarity index 50% rename from src/modules/physics/box2d/Source/Dynamics/b2WorldCallbacks.h rename to src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.h index 5c03321de..82ee67ea0 100644 --- a/src/modules/physics/box2d/Source/Dynamics/b2WorldCallbacks.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -19,18 +19,19 @@ #ifndef B2_WORLD_CALLBACKS_H #define B2_WORLD_CALLBACKS_H -#include "../Common/b2Settings.h" +#include struct b2Vec2; -struct b2XForm; -class b2Shape; +struct b2Transform; +class b2Fixture; class b2Body; class b2Joint; class b2Contact; struct b2ContactPoint; struct b2ContactResult; +struct b2Manifold; -/// Joints and shapes are destroyed when their associated +/// Joints and fixtures are destroyed when their associated /// body is destroyed. Implement this listener so that you /// may nullify references to these joints and shapes. class b2DestructionListener @@ -42,24 +43,11 @@ public: /// to the destruction of one of its attached bodies. virtual void SayGoodbye(b2Joint* joint) = 0; - /// Called when any shape is about to be destroyed due + /// Called when any fixture is about to be destroyed due /// to the destruction of its parent body. - virtual void SayGoodbye(b2Shape* shape) = 0; + virtual void SayGoodbye(b2Fixture* fixture) = 0; }; - -/// This is called when a body's shape passes outside of the world boundary. -class b2BoundaryListener -{ -public: - virtual ~b2BoundaryListener() {} - - /// This is called for each body that leaves the world boundary. - /// @warning you can't modify the world inside this callback. - virtual void Violation(b2Body* body) = 0; -}; - - /// Implement this class to provide collision filtering. In other words, you can implement /// this class if you want finer control over contact creation. class b2ContactFilter @@ -69,13 +57,19 @@ public: /// Return true if contact calculations should be performed between these two shapes. /// @warning for performance reasons this is only called when the AABBs begin to overlap. - virtual bool ShouldCollide(b2Shape* shape1, b2Shape* shape2); + virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB); }; -/// The default contact filter. -extern b2ContactFilter b2_defaultFilter; +/// Contact impulses for reporting. Impulses are used instead of forces because +/// sub-step forces may approach infinity for rigid body collisions. These +/// match up one-to-one with the contact points in b2Manifold. +struct b2ContactImpulse +{ + float32 normalImpulses[b2_maxManifoldPoints]; + float32 tangentImpulses[b2_maxManifoldPoints]; +}; -/// Implement this class to get collision results. You can use these results for +/// Implement this class to get contact information. You can use these results for /// things like sounds and game logic. You can also get contact results by /// traversing the contact lists after the time step. However, you might miss /// some contacts because continuous physics leads to sub-stepping. @@ -83,27 +77,79 @@ extern b2ContactFilter b2_defaultFilter; /// single time step. /// You should strive to make your callbacks efficient because there may be /// many callbacks per time step. -/// @warning The contact separation is the last computed value. /// @warning You cannot create/destroy Box2D entities inside these callbacks. class b2ContactListener { public: virtual ~b2ContactListener() {} - /// Called when a contact point is added. This includes the geometry - /// and the forces. - virtual void Add(const b2ContactPoint* point) { } + /// Called when two fixtures begin to touch. + virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); } - /// Called when a contact point persists. This includes the geometry - /// and the forces. - virtual void Persist(const b2ContactPoint* point) { } + /// Called when two fixtures cease to touch. + virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); } - /// Called when a contact point is removed. This includes the last - /// computed geometry and forces. - virtual void Remove(const b2ContactPoint* point) { } + /// This is called after a contact is updated. This allows you to inspect a + /// contact before it goes to the solver. If you are careful, you can modify the + /// contact manifold (e.g. disable contact). + /// A copy of the old manifold is provided so that you can detect changes. + /// Note: this is called only for awake bodies. + /// Note: this is called even when the number of contact points is zero. + /// Note: this is not called for sensors. + /// Note: if you set the number of contact points to zero, you will not + /// get an EndContact callback. However, you may get a BeginContact callback + /// the next step. + virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) + { + B2_NOT_USED(contact); + B2_NOT_USED(oldManifold); + } - /// Called after a contact point is solved. - virtual void Result(const b2ContactResult* point) { } + /// This lets you inspect a contact after the solver is finished. This is useful + /// for inspecting impulses. + /// Note: the contact manifold does not include time of impact impulses, which can be + /// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly + /// in a separate data structure. + /// Note: this is only called for contacts that are touching, solid, and awake. + virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) + { + B2_NOT_USED(contact); + B2_NOT_USED(impulse); + } +}; + +/// Callback class for AABB queries. +/// See b2World::Query +class b2QueryCallback +{ +public: + virtual ~b2QueryCallback() {} + + /// Called for each fixture found in the query AABB. + /// @return false to terminate the query. + virtual bool ReportFixture(b2Fixture* fixture) = 0; +}; + +/// Callback class for ray casts. +/// See b2World::RayCast +class b2RayCastCallback +{ +public: + virtual ~b2RayCastCallback() {} + + /// Called for each fixture found in the query. You control how the ray cast + /// proceeds by returning a float: + /// return -1: ignore this fixture and continue + /// return 0: terminate the ray cast + /// return fraction: clip the ray to this point + /// return 1: don't clip the ray and continue + /// @param fixture the fixture hit by the ray + /// @param point the point of initial intersection + /// @param normal the normal vector at the point of intersection + /// @return -1 to filter, 0 to terminate, fraction to clip the ray for + /// closest hit, 1 to continue + virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, + const b2Vec2& normal, float32 fraction) = 0; }; /// Color for debug drawing. Each value has the range [0,1]. @@ -111,6 +157,7 @@ struct b2Color { b2Color() {} b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {} + void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi; } float32 r, g, b; }; @@ -127,11 +174,9 @@ public: { e_shapeBit = 0x0001, ///< draw shapes e_jointBit = 0x0002, ///< draw joint connections - e_coreShapeBit = 0x0004, ///< draw core (TOI) shapes - e_aabbBit = 0x0008, ///< draw axis aligned bounding boxes - e_obbBit = 0x0010, ///< draw oriented bounding boxes - e_pairBit = 0x0020, ///< draw broad-phase pairs - e_centerOfMassBit = 0x0040, ///< draw center of mass frame + e_aabbBit = 0x0004, ///< draw axis aligned bounding boxes + e_pairBit = 0x0008, ///< draw broad-phase pairs + e_centerOfMassBit = 0x0010, ///< draw center of mass frame }; /// Set the drawing flags. @@ -163,7 +208,7 @@ public: /// Draw a transform. Choose your own length scale. /// @param xf a transform. - virtual void DrawXForm(const b2XForm& xf) = 0; + virtual void DrawTransform(const b2Transform& xf) = 0; protected: uint32 m_drawFlags; diff --git a/src/modules/physics/box2d/Contact.h b/src/modules/physics/box2d/Contact.h index 7f1972850..c5e8aa292 100644 --- a/src/modules/physics/box2d/Contact.h +++ b/src/modules/physics/box2d/Contact.h @@ -27,7 +27,7 @@ #include "World.h" // Box2D -#include "Include/Box2D.h" +#include namespace love { diff --git a/src/modules/physics/box2d/Include/Box2D.h b/src/modules/physics/box2d/Include/Box2D.h deleted file mode 100644 index a49a3cd27..000000000 --- a/src/modules/physics/box2d/Include/Box2D.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef BOX2D_H -#define BOX2D_H - -/** -\mainpage Box2D API Documentation - -\section intro_sec Getting Started - -For tutorials please see http://www.box2d.org/manual.html - -For discussion please visit http://www.box2d.org/forum -*/ - -// These include files constitute the main Box2D API - -#include "../Source/Common/b2Settings.h" - -#include "../Source/Collision/Shapes/b2CircleShape.h" -#include "../Source/Collision/Shapes/b2PolygonShape.h" -#include "../Source/Collision/b2BroadPhase.h" -#include "../Source/Dynamics/b2WorldCallbacks.h" -#include "../Source/Dynamics/b2World.h" -#include "../Source/Dynamics/b2Body.h" - -#include "../Source/Dynamics/Contacts/b2Contact.h" - -#include "../Source/Dynamics/Joints/b2DistanceJoint.h" -#include "../Source/Dynamics/Joints/b2MouseJoint.h" -#include "../Source/Dynamics/Joints/b2PrismaticJoint.h" -#include "../Source/Dynamics/Joints/b2RevoluteJoint.h" -#include "../Source/Dynamics/Joints/b2PulleyJoint.h" -#include "../Source/Dynamics/Joints/b2GearJoint.h" - -#endif diff --git a/src/modules/physics/box2d/Joint.h b/src/modules/physics/box2d/Joint.h index b1396e3f5..6393f0dcb 100644 --- a/src/modules/physics/box2d/Joint.h +++ b/src/modules/physics/box2d/Joint.h @@ -26,7 +26,7 @@ #include // Box2D -#include "Include/Box2D.h" +#include namespace love { diff --git a/src/modules/physics/box2d/Shape.h b/src/modules/physics/box2d/Shape.h index c1902a9c3..254465167 100644 --- a/src/modules/physics/box2d/Shape.h +++ b/src/modules/physics/box2d/Shape.h @@ -27,7 +27,7 @@ #include // Box2D -#include "Include/Box2D.h" +#include namespace love { diff --git a/src/modules/physics/box2d/Source/Collision/Shapes/b2CircleShape.cpp b/src/modules/physics/box2d/Source/Collision/Shapes/b2CircleShape.cpp deleted file mode 100644 index 1a3ebe79b..000000000 --- a/src/modules/physics/box2d/Source/Collision/Shapes/b2CircleShape.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2CircleShape.h" - -b2CircleShape::b2CircleShape(const b2ShapeDef* def) -: b2Shape(def) -{ - b2Assert(def->type == e_circleShape); - const b2CircleDef* circleDef = (const b2CircleDef*)def; - - m_type = e_circleShape; - m_localPosition = circleDef->localPosition; - m_radius = circleDef->radius; -} - -void b2CircleShape::UpdateSweepRadius(const b2Vec2& center) -{ - // Update the sweep radius (maximum radius) as measured from - // a local center point. - b2Vec2 d = m_localPosition - center; - m_sweepRadius = d.Length() + m_radius - b2_toiSlop; -} - -bool b2CircleShape::TestPoint(const b2XForm& transform, const b2Vec2& p) const -{ - b2Vec2 center = transform.position + b2Mul(transform.R, m_localPosition); - b2Vec2 d = p - center; - return b2Dot(d, d) <= m_radius * m_radius; -} - -// Collision Detection in Interactive 3D Environments by Gino van den Bergen -// From Section 3.1.2 -// x = s + a * r -// norm(x) = radius -bool b2CircleShape::TestSegment(const b2XForm& transform, - float32* lambda, - b2Vec2* normal, - const b2Segment& segment, - float32 maxLambda) const -{ - b2Vec2 position = transform.position + b2Mul(transform.R, m_localPosition); - b2Vec2 s = segment.p1 - position; - float32 b = b2Dot(s, s) - m_radius * m_radius; - - // Does the segment start inside the circle? - if (b < 0.0f) - { - return false; - } - - // Solve quadratic equation. - b2Vec2 r = segment.p2 - segment.p1; - float32 c = b2Dot(s, r); - float32 rr = b2Dot(r, r); - float32 sigma = c * c - rr * b; - - // Check for negative discriminant and short segment. - if (sigma < 0.0f || rr < B2_FLT_EPSILON) - { - return false; - } - - // Find the point of intersection of the line with the circle. - float32 a = -(c + b2Sqrt(sigma)); - - // Is the intersection point on the segment? - if (0.0f <= a && a <= maxLambda * rr) - { - a /= rr; - *lambda = a; - *normal = s + a * r; - normal->Normalize(); - return true; - } - - return false; -} - -void b2CircleShape::ComputeAABB(b2AABB* aabb, const b2XForm& transform) const -{ - b2Vec2 p = transform.position + b2Mul(transform.R, m_localPosition); - aabb->lowerBound.Set(p.x - m_radius, p.y - m_radius); - aabb->upperBound.Set(p.x + m_radius, p.y + m_radius); -} - -void b2CircleShape::ComputeSweptAABB(b2AABB* aabb, const b2XForm& transform1, const b2XForm& transform2) const -{ - b2Vec2 p1 = transform1.position + b2Mul(transform1.R, m_localPosition); - b2Vec2 p2 = transform2.position + b2Mul(transform2.R, m_localPosition); - b2Vec2 lower = b2Min(p1, p2); - b2Vec2 upper = b2Max(p1, p2); - - aabb->lowerBound.Set(lower.x - m_radius, lower.y - m_radius); - aabb->upperBound.Set(upper.x + m_radius, upper.y + m_radius); -} - -void b2CircleShape::ComputeMass(b2MassData* massData) const -{ - massData->mass = m_density * b2_pi * m_radius * m_radius; - massData->center = m_localPosition; - - // inertia about the local origin - massData->I = massData->mass * (0.5f * m_radius * m_radius + b2Dot(m_localPosition, m_localPosition)); -} diff --git a/src/modules/physics/box2d/Source/Collision/Shapes/b2CircleShape.h b/src/modules/physics/box2d/Source/Collision/Shapes/b2CircleShape.h deleted file mode 100644 index f05d64276..000000000 --- a/src/modules/physics/box2d/Source/Collision/Shapes/b2CircleShape.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CIRCLE_SHAPE_H -#define B2_CIRCLE_SHAPE_H - -#include "b2Shape.h" - -/// This structure is used to build circle shapes. -struct b2CircleDef : public b2ShapeDef -{ - b2CircleDef() - { - type = e_circleShape; - localPosition.SetZero(); - radius = 1.0f; - } - - b2Vec2 localPosition; - float32 radius; -}; - -/// A circle shape. -class b2CircleShape : public b2Shape -{ -public: - /// @see b2Shape::TestPoint - bool TestPoint(const b2XForm& transform, const b2Vec2& p) const; - - /// @see b2Shape::TestSegment - bool TestSegment( const b2XForm& transform, - float32* lambda, - b2Vec2* normal, - const b2Segment& segment, - float32 maxLambda) const; - - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2XForm& transform) const; - - /// @see b2Shape::ComputeSweptAABB - void ComputeSweptAABB( b2AABB* aabb, - const b2XForm& transform1, - const b2XForm& transform2) const; - - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData) const; - - /// Get the local position of this circle in its parent body. - const b2Vec2& GetLocalPosition() const; - - /// Get the radius of this circle. - float32 GetRadius() const; - -private: - - friend class b2Shape; - - b2CircleShape(const b2ShapeDef* def); - - void UpdateSweepRadius(const b2Vec2& center); - - // Local position in parent body - b2Vec2 m_localPosition; - float32 m_radius; -}; - -inline const b2Vec2& b2CircleShape::GetLocalPosition() const -{ - return m_localPosition; -} - -inline float32 b2CircleShape::GetRadius() const -{ - return m_radius; -} - -#endif diff --git a/src/modules/physics/box2d/Source/Collision/Shapes/b2PolygonShape.cpp b/src/modules/physics/box2d/Source/Collision/Shapes/b2PolygonShape.cpp deleted file mode 100644 index 75ca1970e..000000000 --- a/src/modules/physics/box2d/Source/Collision/Shapes/b2PolygonShape.cpp +++ /dev/null @@ -1,449 +0,0 @@ - -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2PolygonShape.h" - -void b2PolygonDef::SetAsBox(float32 hx, float32 hy) -{ - vertexCount = 4; - vertices[0].Set(-hx, -hy); - vertices[1].Set( hx, -hy); - vertices[2].Set( hx, hy); - vertices[3].Set(-hx, hy); -} - -void b2PolygonDef::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle) -{ - SetAsBox(hx, hy); - b2XForm xf; - xf.position = center; - xf.R.Set(angle); - - for (int32 i = 0; i < vertexCount; ++i) - { - vertices[i] = b2Mul(xf, vertices[i]); - } -} - -static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count) -{ - b2Assert(count >= 3); - - b2Vec2 c; c.Set(0.0f, 0.0f); - float32 area = 0.0f; - - // pRef is the reference point for forming triangles. - // It's location doesn't change the result (except for rounding error). - b2Vec2 pRef(0.0f, 0.0f); -#if 0 - // This code would put the reference point inside the polygon. - for (int32 i = 0; i < count; ++i) - { - pRef += vs[i]; - } - pRef *= 1.0f / count; -#endif - - const float32 inv3 = 1.0f / 3.0f; - - for (int32 i = 0; i < count; ++i) - { - // Triangle vertices. - b2Vec2 p1 = pRef; - b2Vec2 p2 = vs[i]; - b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0]; - - b2Vec2 e1 = p2 - p1; - b2Vec2 e2 = p3 - p1; - - float32 D = b2Cross(e1, e2); - - float32 triangleArea = 0.5f * D; - area += triangleArea; - - // Area weighted centroid - c += triangleArea * inv3 * (p1 + p2 + p3); - } - - // Centroid - b2Assert(area > B2_FLT_EPSILON); - c *= 1.0f / area; - return c; -} - -// http://www.geometrictools.com/Documentation/MinimumAreaRectangle.pdf -static void ComputeOBB(b2OBB* obb, const b2Vec2* vs, int32 count) -{ - b2Assert(count <= b2_maxPolygonVertices); - b2Vec2 p[b2_maxPolygonVertices + 1]; - for (int32 i = 0; i < count; ++i) - { - p[i] = vs[i]; - } - p[count] = p[0]; - - float32 minArea = B2_FLT_MAX; - - for (int32 i = 1; i <= count; ++i) - { - b2Vec2 root = p[i-1]; - b2Vec2 ux = p[i] - root; - float32 length = ux.Normalize(); - b2Assert(length > B2_FLT_EPSILON); - b2Vec2 uy(-ux.y, ux.x); - b2Vec2 lower(B2_FLT_MAX, B2_FLT_MAX); - b2Vec2 upper(-B2_FLT_MAX, -B2_FLT_MAX); - - for (int32 j = 0; j < count; ++j) - { - b2Vec2 d = p[j] - root; - b2Vec2 r; - r.x = b2Dot(ux, d); - r.y = b2Dot(uy, d); - lower = b2Min(lower, r); - upper = b2Max(upper, r); - } - - float32 area = (upper.x - lower.x) * (upper.y - lower.y); - if (area < 0.95f * minArea) - { - minArea = area; - obb->R.col1 = ux; - obb->R.col2 = uy; - b2Vec2 center = 0.5f * (lower + upper); - obb->center = root + b2Mul(obb->R, center); - obb->extents = 0.5f * (upper - lower); - } - } - - b2Assert(minArea < B2_FLT_MAX); -} - -b2PolygonShape::b2PolygonShape(const b2ShapeDef* def) - : b2Shape(def) -{ - b2Assert(def->type == e_polygonShape); - m_type = e_polygonShape; - const b2PolygonDef* poly = (const b2PolygonDef*)def; - - // Get the vertices transformed into the body frame. - m_vertexCount = poly->vertexCount; - b2Assert(3 <= m_vertexCount && m_vertexCount <= b2_maxPolygonVertices); - - // Copy vertices. - for (int32 i = 0; i < m_vertexCount; ++i) - { - m_vertices[i] = poly->vertices[i]; - } - - // Compute normals. Ensure the edges have non-zero length. - for (int32 i = 0; i < m_vertexCount; ++i) - { - int32 i1 = i; - int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; - b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; - b2Assert(edge.LengthSquared() > B2_FLT_EPSILON * B2_FLT_EPSILON); - m_normals[i] = b2Cross(edge, 1.0f); - m_normals[i].Normalize(); - } - -#ifdef _DEBUG - // Ensure the polygon is convex. - for (int32 i = 0; i < m_vertexCount; ++i) - { - for (int32 j = 0; j < m_vertexCount; ++j) - { - // Don't check vertices on the current edge. - if (j == i || j == (i + 1) % m_vertexCount) - { - continue; - } - - // Your polygon is non-convex (it has an indentation). - // Or your polygon is too skinny. - float32 s = b2Dot(m_normals[i], m_vertices[j] - m_vertices[i]); - b2Assert(s < -b2_linearSlop); - } - } - - // Ensure the polygon is counter-clockwise. - for (int32 i = 1; i < m_vertexCount; ++i) - { - float32 cross = b2Cross(m_normals[i-1], m_normals[i]); - - // Keep asinf happy. - cross = b2Clamp(cross, -1.0f, 1.0f); - - // You have consecutive edges that are almost parallel on your polygon. - float32 angle = asinf(cross); - b2Assert(angle > b2_angularSlop); - } -#endif - - // Compute the polygon centroid. - m_centroid = ComputeCentroid(poly->vertices, poly->vertexCount); - - // Compute the oriented bounding box. - ComputeOBB(&m_obb, m_vertices, m_vertexCount); - - // Create core polygon shape by shifting edges inward. - // Also compute the min/max radius for CCD. - for (int32 i = 0; i < m_vertexCount; ++i) - { - int32 i1 = i - 1 >= 0 ? i - 1 : m_vertexCount - 1; - int32 i2 = i; - - b2Vec2 n1 = m_normals[i1]; - b2Vec2 n2 = m_normals[i2]; - b2Vec2 v = m_vertices[i] - m_centroid;; - - b2Vec2 d; - d.x = b2Dot(n1, v) - b2_toiSlop; - d.y = b2Dot(n2, v) - b2_toiSlop; - - // Shifting the edge inward by b2_toiSlop should - // not cause the plane to pass the centroid. - - // Your shape has a radius/extent less than b2_toiSlop. - b2Assert(d.x >= 0.0f); - b2Assert(d.y >= 0.0f); - b2Mat22 A; - A.col1.x = n1.x; A.col2.x = n1.y; - A.col1.y = n2.x; A.col2.y = n2.y; - m_coreVertices[i] = A.Solve(d) + m_centroid; - } -} - -void b2PolygonShape::UpdateSweepRadius(const b2Vec2& center) -{ - // Update the sweep radius (maximum radius) as measured from - // a local center point. - m_sweepRadius = 0.0f; - for (int32 i = 0; i < m_vertexCount; ++i) - { - b2Vec2 d = m_coreVertices[i] - center; - m_sweepRadius = b2Max(m_sweepRadius, d.Length()); - } -} - -bool b2PolygonShape::TestPoint(const b2XForm& xf, const b2Vec2& p) const -{ - b2Vec2 pLocal = b2MulT(xf.R, p - xf.position); - - for (int32 i = 0; i < m_vertexCount; ++i) - { - float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]); - if (dot > 0.0f) - { - return false; - } - } - - return true; -} - -bool b2PolygonShape::TestSegment( - const b2XForm& xf, - float32* lambda, - b2Vec2* normal, - const b2Segment& segment, - float32 maxLambda) const -{ - float32 lower = 0.0f, upper = maxLambda; - - b2Vec2 p1 = b2MulT(xf.R, segment.p1 - xf.position); - b2Vec2 p2 = b2MulT(xf.R, segment.p2 - xf.position); - b2Vec2 d = p2 - p1; - int32 index = -1; - - for (int32 i = 0; i < m_vertexCount; ++i) - { - // p = p1 + a * d - // dot(normal, p - v) = 0 - // dot(normal, p1 - v) + a * dot(normal, d) = 0 - float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1); - float32 denominator = b2Dot(m_normals[i], d); - - // Note: we want this predicate without division: - // lower < numerator / denominator, where denominator < 0 - // Since denominator < 0, we have to flip the inequality: - // lower < numerator / denominator <==> denominator * lower > numerator. - - if (denominator < 0.0f && numerator < lower * denominator) - { - // Increase lower. - // The segment enters this half-space. - lower = numerator / denominator; - index = i; - } - else if (denominator > 0.0f && numerator < upper * denominator) - { - // Decrease upper. - // The segment exits this half-space. - upper = numerator / denominator; - } - - if (upper < lower) - { - return false; - } - } - - b2Assert(0.0f <= lower && lower <= maxLambda); - - if (index >= 0) - { - *lambda = lower; - *normal = b2Mul(xf.R, m_normals[index]); - return true; - } - - return false; -} - -void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2XForm& xf) const -{ - b2Mat22 R = b2Mul(xf.R, m_obb.R); - b2Mat22 absR = b2Abs(R); - b2Vec2 h = b2Mul(absR, m_obb.extents); - b2Vec2 position = xf.position + b2Mul(xf.R, m_obb.center); - aabb->lowerBound = position - h; - aabb->upperBound = position + h; -} - -void b2PolygonShape::ComputeSweptAABB(b2AABB* aabb, - const b2XForm& transform1, - const b2XForm& transform2) const -{ - b2AABB aabb1, aabb2; - ComputeAABB(&aabb1, transform1); - ComputeAABB(&aabb2, transform2); - aabb->lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound); - aabb->upperBound = b2Max(aabb1.upperBound, aabb2.upperBound); -} - -void b2PolygonShape::ComputeMass(b2MassData* massData) const -{ - // Polygon mass, centroid, and inertia. - // Let rho be the polygon density in mass per unit area. - // Then: - // mass = rho * int(dA) - // centroid.x = (1/mass) * rho * int(x * dA) - // centroid.y = (1/mass) * rho * int(y * dA) - // I = rho * int((x*x + y*y) * dA) - // - // We can compute these integrals by summing all the integrals - // for each triangle of the polygon. To evaluate the integral - // for a single triangle, we make a change of variables to - // the (u,v) coordinates of the triangle: - // x = x0 + e1x * u + e2x * v - // y = y0 + e1y * u + e2y * v - // where 0 <= u && 0 <= v && u + v <= 1. - // - // We integrate u from [0,1-v] and then v from [0,1]. - // We also need to use the Jacobian of the transformation: - // D = cross(e1, e2) - // - // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) - // - // The rest of the derivation is handled by computer algebra. - - b2Assert(m_vertexCount >= 3); - - b2Vec2 center; center.Set(0.0f, 0.0f); - float32 area = 0.0f; - float32 I = 0.0f; - - // pRef is the reference point for forming triangles. - // It's location doesn't change the result (except for rounding error). - b2Vec2 pRef(0.0f, 0.0f); -#if 0 - // This code would put the reference point inside the polygon. - for (int32 i = 0; i < m_vertexCount; ++i) - { - pRef += m_vertices[i]; - } - pRef *= 1.0f / count; -#endif - - const float32 k_inv3 = 1.0f / 3.0f; - - for (int32 i = 0; i < m_vertexCount; ++i) - { - // Triangle vertices. - b2Vec2 p1 = pRef; - b2Vec2 p2 = m_vertices[i]; - b2Vec2 p3 = i + 1 < m_vertexCount ? m_vertices[i+1] : m_vertices[0]; - - b2Vec2 e1 = p2 - p1; - b2Vec2 e2 = p3 - p1; - - float32 D = b2Cross(e1, e2); - - float32 triangleArea = 0.5f * D; - area += triangleArea; - - // Area weighted centroid - center += triangleArea * k_inv3 * (p1 + p2 + p3); - - float32 px = p1.x, py = p1.y; - float32 ex1 = e1.x, ey1 = e1.y; - float32 ex2 = e2.x, ey2 = e2.y; - - float32 intx2 = k_inv3 * (0.25f * (ex1*ex1 + ex2*ex1 + ex2*ex2) + (px*ex1 + px*ex2)) + 0.5f*px*px; - float32 inty2 = k_inv3 * (0.25f * (ey1*ey1 + ey2*ey1 + ey2*ey2) + (py*ey1 + py*ey2)) + 0.5f*py*py; - - I += D * (intx2 + inty2); - } - - // Total mass - massData->mass = m_density * area; - - // Center of mass - b2Assert(area > B2_FLT_EPSILON); - center *= 1.0f / area; - massData->center = center; - - // Inertia tensor relative to the local origin. - massData->I = m_density * I; -} - -b2Vec2 b2PolygonShape::Centroid(const b2XForm& xf) const -{ - return b2Mul(xf, m_centroid); -} - -b2Vec2 b2PolygonShape::Support(const b2XForm& xf, const b2Vec2& d) const -{ - b2Vec2 dLocal = b2MulT(xf.R, d); - - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_coreVertices[0], dLocal); - for (int32 i = 1; i < m_vertexCount; ++i) - { - float32 value = b2Dot(m_coreVertices[i], dLocal); - if (value > bestValue) - { - bestIndex = i; - bestValue = value; - } - } - - return b2Mul(xf, m_coreVertices[bestIndex]); -} diff --git a/src/modules/physics/box2d/Source/Collision/Shapes/b2PolygonShape.h b/src/modules/physics/box2d/Source/Collision/Shapes/b2PolygonShape.h deleted file mode 100644 index 238614e2a..000000000 --- a/src/modules/physics/box2d/Source/Collision/Shapes/b2PolygonShape.h +++ /dev/null @@ -1,163 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_POLYGON_SHAPE_H -#define B2_POLYGON_SHAPE_H - -#include "b2Shape.h" - -/// Convex polygon. The vertices must be in CCW order for a right-handed -/// coordinate system with the z-axis coming out of the screen. -struct b2PolygonDef : public b2ShapeDef -{ - b2PolygonDef() - { - type = e_polygonShape; - vertexCount = 0; - } - - /// Build vertices to represent an axis-aligned box. - /// @param hx the half-width. - /// @param hy the half-height. - void SetAsBox(float32 hx, float32 hy); - - /// Build vertices to represent an oriented box. - /// @param hx the half-width. - /// @param hy the half-height. - /// @param center the center of the box in local coordinates. - /// @param angle the rotation of the box in local coordinates. - void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle); - - /// The polygon vertices in local coordinates. - b2Vec2 vertices[b2_maxPolygonVertices]; - - /// The number of polygon vertices. - int32 vertexCount; -}; - - -/// A convex polygon. -class b2PolygonShape : public b2Shape -{ -public: - /// @see b2Shape::TestPoint - bool TestPoint(const b2XForm& transform, const b2Vec2& p) const; - - /// @see b2Shape::TestSegment - bool TestSegment( const b2XForm& transform, - float32* lambda, - b2Vec2* normal, - const b2Segment& segment, - float32 maxLambda) const; - - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2XForm& transform) const; - - /// @see b2Shape::ComputeSweptAABB - void ComputeSweptAABB( b2AABB* aabb, - const b2XForm& transform1, - const b2XForm& transform2) const; - - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData) const; - - /// Get the oriented bounding box relative to the parent body. - const b2OBB& GetOBB() const; - - /// Get local centroid relative to the parent body. - const b2Vec2& GetCentroid() const; - - /// Get the vertex count. - int32 GetVertexCount() const; - - /// Get the vertices in local coordinates. - const b2Vec2* GetVertices() const; - - /// Get the core vertices in local coordinates. These vertices - /// represent a smaller polygon that is used for time of impact - /// computations. - const b2Vec2* GetCoreVertices() const; - - /// Get the edge normal vectors. There is one for each vertex. - const b2Vec2* GetNormals() const; - - /// Get the first vertex and apply the supplied transform. - b2Vec2 GetFirstVertex(const b2XForm& xf) const; - - /// Get the centroid and apply the supplied transform. - b2Vec2 Centroid(const b2XForm& xf) const; - - /// Get the support point in the given world direction. - /// Use the supplied transform. - b2Vec2 Support(const b2XForm& xf, const b2Vec2& d) const; - -private: - - friend class b2Shape; - - b2PolygonShape(const b2ShapeDef* def); - - void UpdateSweepRadius(const b2Vec2& center); - - // Local position of the polygon centroid. - b2Vec2 m_centroid; - - b2OBB m_obb; - - b2Vec2 m_vertices[b2_maxPolygonVertices]; - b2Vec2 m_normals[b2_maxPolygonVertices]; - b2Vec2 m_coreVertices[b2_maxPolygonVertices]; - int32 m_vertexCount; -}; - -inline b2Vec2 b2PolygonShape::GetFirstVertex(const b2XForm& xf) const -{ - return b2Mul(xf, m_coreVertices[0]); -} - -inline const b2OBB& b2PolygonShape::GetOBB() const -{ - return m_obb; -} - -inline const b2Vec2& b2PolygonShape::GetCentroid() const -{ - return m_centroid; -} - -inline int32 b2PolygonShape::GetVertexCount() const -{ - return m_vertexCount; -} - -inline const b2Vec2* b2PolygonShape::GetVertices() const -{ - return m_vertices; -} - -inline const b2Vec2* b2PolygonShape::GetCoreVertices() const -{ - return m_coreVertices; -} - -inline const b2Vec2* b2PolygonShape::GetNormals() const -{ - return m_normals; -} - -#endif diff --git a/src/modules/physics/box2d/Source/Collision/Shapes/b2Shape.cpp b/src/modules/physics/box2d/Source/Collision/Shapes/b2Shape.cpp deleted file mode 100644 index 618c7ee5c..000000000 --- a/src/modules/physics/box2d/Source/Collision/Shapes/b2Shape.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2Shape.h" -#include "b2CircleShape.h" -#include "b2PolygonShape.h" -#include "../b2Collision.h" -#include "../b2BroadPhase.h" -#include "../../Common/b2BlockAllocator.h" - -#include - -b2Shape* b2Shape::Create(const b2ShapeDef* def, b2BlockAllocator* allocator) -{ - switch (def->type) - { - case e_circleShape: - { - void* mem = allocator->Allocate(sizeof(b2CircleShape)); - return new (mem) b2CircleShape(def); - } - - case e_polygonShape: - { - void* mem = allocator->Allocate(sizeof(b2PolygonShape)); - return new (mem) b2PolygonShape(def); - } - - default: - b2Assert(false); - return NULL; - } -} - -void b2Shape::Destroy(b2Shape* s, b2BlockAllocator* allocator) -{ - switch (s->GetType()) - { - case e_circleShape: - s->~b2Shape(); - allocator->Free(s, sizeof(b2CircleShape)); - break; - - case e_polygonShape: - s->~b2Shape(); - allocator->Free(s, sizeof(b2PolygonShape)); - break; - - default: - b2Assert(false); - } -} - -b2Shape::b2Shape(const b2ShapeDef* def) -{ - m_userData = def->userData; - m_friction = def->friction; - m_restitution = def->restitution; - m_density = def->density; - m_body = NULL; - m_sweepRadius = 0.0f; - - m_next = NULL; - - m_proxyId = b2_nullProxy; - - m_filter = def->filter; - - m_isSensor = def->isSensor; -} - -b2Shape::~b2Shape() -{ - b2Assert(m_proxyId == b2_nullProxy); -} - -void b2Shape::CreateProxy(b2BroadPhase* broadPhase, const b2XForm& transform) -{ - b2Assert(m_proxyId == b2_nullProxy); - - b2AABB aabb; - ComputeAABB(&aabb, transform); - - bool inRange = broadPhase->InRange(aabb); - - // You are creating a shape outside the world box. - b2Assert(inRange); - - if (inRange) - { - m_proxyId = broadPhase->CreateProxy(aabb, this); - } - else - { - m_proxyId = b2_nullProxy; - } -} - -void b2Shape::DestroyProxy(b2BroadPhase* broadPhase) -{ - if (m_proxyId != b2_nullProxy) - { - broadPhase->DestroyProxy(m_proxyId); - m_proxyId = b2_nullProxy; - } -} - -bool b2Shape::Synchronize(b2BroadPhase* broadPhase, const b2XForm& transform1, const b2XForm& transform2) -{ - if (m_proxyId == b2_nullProxy) - { - return false; - } - - // Compute an AABB that covers the swept shape (may miss some rotation effect). - b2AABB aabb; - ComputeSweptAABB(&aabb, transform1, transform2); - - if (broadPhase->InRange(aabb)) - { - broadPhase->MoveProxy(m_proxyId, aabb); - return true; - } - else - { - return false; - } -} - -void b2Shape::RefilterProxy(b2BroadPhase* broadPhase, const b2XForm& transform) -{ - if (m_proxyId == b2_nullProxy) - { - return; - } - - broadPhase->DestroyProxy(m_proxyId); - - b2AABB aabb; - ComputeAABB(&aabb, transform); - - bool inRange = broadPhase->InRange(aabb); - - if (inRange) - { - m_proxyId = broadPhase->CreateProxy(aabb, this); - } - else - { - m_proxyId = b2_nullProxy; - } -} diff --git a/src/modules/physics/box2d/Source/Collision/Shapes/b2Shape.h b/src/modules/physics/box2d/Source/Collision/Shapes/b2Shape.h deleted file mode 100644 index fdc431e87..000000000 --- a/src/modules/physics/box2d/Source/Collision/Shapes/b2Shape.h +++ /dev/null @@ -1,286 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_SHAPE_H -#define B2_SHAPE_H - -#include "../../Common/b2Math.h" -#include "../b2Collision.h" - -class b2BlockAllocator; -class b2Body; -class b2BroadPhase; - -/// This holds the mass data computed for a shape. -struct b2MassData -{ - /// The mass of the shape, usually in kilograms. - float32 mass; - - /// The position of the shape's centroid relative to the shape's origin. - b2Vec2 center; - - /// The rotational inertia of the shape. - float32 I; -}; - -/// This holds contact filtering data. -struct b2FilterData -{ - /// The collision category bits. Normally you would just set one bit. - uint16 categoryBits; - - /// The collision mask bits. This states the categories that this - /// shape would accept for collision. - uint16 maskBits; - - /// Collision groups allow a certain group of objects to never collide (negative) - /// or always collide (positive). Zero means no collision group. Non-zero group - /// filtering always wins against the mask bits. - int16 groupIndex; -}; - -/// The various collision shape types supported by Box2D. -enum b2ShapeType -{ - e_unknownShape = -1, - e_circleShape, - e_polygonShape, - e_shapeTypeCount, -}; - -/// A shape definition is used to construct a shape. This class defines an -/// abstract shape definition. You can reuse shape definitions safely. -struct b2ShapeDef -{ - /// The constructor sets the default shape definition values. - b2ShapeDef() - { - type = e_unknownShape; - userData = NULL; - friction = 0.2f; - restitution = 0.0f; - density = 0.0f; - filter.categoryBits = 0x0001; - filter.maskBits = 0xFFFF; - filter.groupIndex = 0; - isSensor = false; - } - - virtual ~b2ShapeDef() {} - - /// Holds the shape type for down-casting. - b2ShapeType type; - - /// Use this to store application specify shape data. - void* userData; - - /// The shape's friction coefficient, usually in the range [0,1]. - float32 friction; - - /// The shape's restitution (elasticity) usually in the range [0,1]. - float32 restitution; - - /// The shape's density, usually in kg/m^2. - float32 density; - - /// A sensor shape collects contact information but never generates a collision - /// response. - bool isSensor; - - /// Contact filtering data. - b2FilterData filter; -}; - -/// A shape is used for collision detection. Shapes are created in b2World. -/// You can use shape for collision detection before they are attached to the world. -/// @warning you cannot reuse shapes. -class b2Shape -{ -public: - /// Get the type of this shape. You can use this to down cast to the concrete shape. - /// @return the shape type. - b2ShapeType GetType() const; - - /// Is this shape a sensor (non-solid)? - /// @return the true if the shape is a sensor. - bool IsSensor() const; - - /// Set the contact filtering data. You must call b2World::Refilter to correct - /// existing contacts/non-contacts. - void SetFilterData(const b2FilterData& filter); - - /// Get the contact filtering data. - const b2FilterData& GetFilterData() const; - - /// Get the parent body of this shape. This is NULL if the shape is not attached. - /// @return the parent body. - b2Body* GetBody(); - - /// Get the next shape in the parent body's shape list. - /// @return the next shape. - b2Shape* GetNext(); - - /// Get the user data that was assigned in the shape definition. Use this to - /// store your application specific data. - void* GetUserData(); - - /// Set the user data. Use this to store your application specific data. - void SetUserData(void* data); - - /// Test a point for containment in this shape. This only works for convex shapes. - /// @param xf the shape world transform. - /// @param p a point in world coordinates. - virtual bool TestPoint(const b2XForm& xf, const b2Vec2& p) const = 0; - - /// Perform a ray cast against this shape. - /// @param xf the shape world transform. - /// @param lambda returns the hit fraction. You can use this to compute the contact point - /// p = (1 - lambda) * segment.p1 + lambda * segment.p2. - /// @param normal returns the normal at the contact point. If there is no intersection, the normal - /// is not set. - /// @param segment defines the begin and end point of the ray cast. - /// @param maxLambda a number typically in the range [0,1]. - /// @return true if there was an intersection. - virtual bool TestSegment( const b2XForm& xf, - float32* lambda, - b2Vec2* normal, - const b2Segment& segment, - float32 maxLambda) const = 0; - - /// Given a transform, compute the associated axis aligned bounding box for this shape. - /// @param aabb returns the axis aligned box. - /// @param xf the world transform of the shape. - virtual void ComputeAABB(b2AABB* aabb, const b2XForm& xf) const = 0; - - /// Given two transforms, compute the associated swept axis aligned bounding box for this shape. - /// @param aabb returns the axis aligned box. - /// @param xf1 the starting shape world transform. - /// @param xf2 the ending shape world transform. - virtual void ComputeSweptAABB( b2AABB* aabb, - const b2XForm& xf1, - const b2XForm& xf2) const = 0; - - /// Compute the mass properties of this shape using its dimensions and density. - /// The inertia tensor is computed about the local origin, not the centroid. - /// @param massData returns the mass data for this shape. - virtual void ComputeMass(b2MassData* massData) const = 0; - - /// Get the maximum radius about the parent body's center of mass. - float32 GetSweepRadius() const; - - /// Get the coefficient of friction. - float32 GetFriction() const; - - /// Get the coefficient of restitution. - float32 GetRestitution() const; - - float32 m_density; - float32 m_friction; - float32 m_restitution; - bool m_isSensor; - -protected: - - friend class b2Body; - friend class b2World; - - static b2Shape* Create(const b2ShapeDef* def, b2BlockAllocator* allocator); - static void Destroy(b2Shape* shape, b2BlockAllocator* allocator); - - b2Shape(const b2ShapeDef* def); - virtual ~b2Shape(); - - void CreateProxy(b2BroadPhase* broadPhase, const b2XForm& xf); - void DestroyProxy(b2BroadPhase* broadPhase); - bool Synchronize(b2BroadPhase* broadPhase, const b2XForm& xf1, const b2XForm& xf2); - void RefilterProxy(b2BroadPhase* broadPhase, const b2XForm& xf); - - virtual void UpdateSweepRadius(const b2Vec2& center) = 0; - - b2ShapeType m_type; - b2Shape* m_next; - b2Body* m_body; - - // Sweep radius relative to the parent body's center of mass. - float32 m_sweepRadius; - - uint16 m_proxyId; - b2FilterData m_filter; - - - - void* m_userData; -}; - -inline b2ShapeType b2Shape::GetType() const -{ - return m_type; -} - -inline bool b2Shape::IsSensor() const -{ - return m_isSensor; -} - -inline void b2Shape::SetFilterData(const b2FilterData& filter) -{ - m_filter = filter; -} - -inline const b2FilterData& b2Shape::GetFilterData() const -{ - return m_filter; -} - -inline void* b2Shape::GetUserData() -{ - return m_userData; -} - -inline void b2Shape::SetUserData(void* data) -{ - m_userData = data; -} - -inline b2Body* b2Shape::GetBody() -{ - return m_body; -} - -inline b2Shape* b2Shape::GetNext() -{ - return m_next; -} - -inline float32 b2Shape::GetSweepRadius() const -{ - return m_sweepRadius; -} - -inline float32 b2Shape::GetFriction() const -{ - return m_friction; -} - -inline float32 b2Shape::GetRestitution() const -{ - return m_restitution; -} - -#endif diff --git a/src/modules/physics/box2d/Source/Collision/b2BroadPhase.cpp b/src/modules/physics/box2d/Source/Collision/b2BroadPhase.cpp deleted file mode 100644 index ab2092130..000000000 --- a/src/modules/physics/box2d/Source/Collision/b2BroadPhase.cpp +++ /dev/null @@ -1,668 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2BroadPhase.h" -#include -#include - -// Notes: -// - we use bound arrays instead of linked lists for cache coherence. -// - we use quantized integral values for fast compares. -// - we use short indices rather than pointers to save memory. -// - we use a stabbing count for fast overlap queries (less than order N). -// - we also use a time stamp on each proxy to speed up the registration of -// overlap query results. -// - where possible, we compare bound indices instead of values to reduce -// cache misses (TODO_ERIN). -// - no broadphase is perfect and neither is this one: it is not great for huge -// worlds (use a multi-SAP instead), it is not great for large objects. - -bool b2BroadPhase::s_validate = false; - -struct b2BoundValues -{ - uint16 lowerValues[2]; - uint16 upperValues[2]; -}; - -static int32 BinarySearch(b2Bound* bounds, int32 count, uint16 value) -{ - int32 low = 0; - int32 high = count - 1; - while (low <= high) - { - int32 mid = (low + high) >> 1; - if (bounds[mid].value > value) - { - high = mid - 1; - } - else if (bounds[mid].value < value) - { - low = mid + 1; - } - else - { - return (uint16)mid; - } - } - - return low; -} - -b2BroadPhase::b2BroadPhase(const b2AABB& worldAABB, b2PairCallback* callback) -{ - m_pairManager.Initialize(this, callback); - - b2Assert(worldAABB.IsValid()); - m_worldAABB = worldAABB; - m_proxyCount = 0; - - b2Vec2 d = worldAABB.upperBound - worldAABB.lowerBound; - m_quantizationFactor.x = float32(B2BROADPHASE_MAX) / d.x; - m_quantizationFactor.y = float32(B2BROADPHASE_MAX) / d.y; - - for (uint16 i = 0; i < b2_maxProxies - 1; ++i) - { - m_proxyPool[i].SetNext(i + 1); - m_proxyPool[i].timeStamp = 0; - m_proxyPool[i].overlapCount = b2_invalid; - m_proxyPool[i].userData = NULL; - } - m_proxyPool[b2_maxProxies-1].SetNext(b2_nullProxy); - m_proxyPool[b2_maxProxies-1].timeStamp = 0; - m_proxyPool[b2_maxProxies-1].overlapCount = b2_invalid; - m_proxyPool[b2_maxProxies-1].userData = NULL; - m_freeProxy = 0; - - m_timeStamp = 1; - m_queryResultCount = 0; -} - -b2BroadPhase::~b2BroadPhase() -{ -} - -// This one is only used for validation. -bool b2BroadPhase::TestOverlap(b2Proxy* p1, b2Proxy* p2) -{ - for (int32 axis = 0; axis < 2; ++axis) - { - b2Bound* bounds = m_bounds[axis]; - - b2Assert(p1->lowerBounds[axis] < 2 * m_proxyCount); - b2Assert(p1->upperBounds[axis] < 2 * m_proxyCount); - b2Assert(p2->lowerBounds[axis] < 2 * m_proxyCount); - b2Assert(p2->upperBounds[axis] < 2 * m_proxyCount); - - if (bounds[p1->lowerBounds[axis]].value > bounds[p2->upperBounds[axis]].value) - return false; - - if (bounds[p1->upperBounds[axis]].value < bounds[p2->lowerBounds[axis]].value) - return false; - } - - return true; -} - -bool b2BroadPhase::TestOverlap(const b2BoundValues& b, b2Proxy* p) -{ - for (int32 axis = 0; axis < 2; ++axis) - { - b2Bound* bounds = m_bounds[axis]; - - b2Assert(p->lowerBounds[axis] < 2 * m_proxyCount); - b2Assert(p->upperBounds[axis] < 2 * m_proxyCount); - - if (b.lowerValues[axis] > bounds[p->upperBounds[axis]].value) - return false; - - if (b.upperValues[axis] < bounds[p->lowerBounds[axis]].value) - return false; - } - - return true; -} - -void b2BroadPhase::ComputeBounds(uint16* lowerValues, uint16* upperValues, const b2AABB& aabb) -{ - b2Assert(aabb.upperBound.x > aabb.lowerBound.x); - b2Assert(aabb.upperBound.y > aabb.lowerBound.y); - - b2Vec2 minVertex = b2Clamp(aabb.lowerBound, m_worldAABB.lowerBound, m_worldAABB.upperBound); - b2Vec2 maxVertex = b2Clamp(aabb.upperBound, m_worldAABB.lowerBound, m_worldAABB.upperBound); - - // Bump lower bounds downs and upper bounds up. This ensures correct sorting of - // lower/upper bounds that would have equal values. - // TODO_ERIN implement fast float to uint16 conversion. - lowerValues[0] = (uint16)(m_quantizationFactor.x * (minVertex.x - m_worldAABB.lowerBound.x)) & (B2BROADPHASE_MAX - 1); - upperValues[0] = (uint16)(m_quantizationFactor.x * (maxVertex.x - m_worldAABB.lowerBound.x)) | 1; - - lowerValues[1] = (uint16)(m_quantizationFactor.y * (minVertex.y - m_worldAABB.lowerBound.y)) & (B2BROADPHASE_MAX - 1); - upperValues[1] = (uint16)(m_quantizationFactor.y * (maxVertex.y - m_worldAABB.lowerBound.y)) | 1; -} - -void b2BroadPhase::IncrementTimeStamp() -{ - if (m_timeStamp == B2BROADPHASE_MAX) - { - for (uint16 i = 0; i < b2_maxProxies; ++i) - { - m_proxyPool[i].timeStamp = 0; - } - m_timeStamp = 1; - } - else - { - ++m_timeStamp; - } -} - -void b2BroadPhase::IncrementOverlapCount(int32 proxyId) -{ - b2Proxy* proxy = m_proxyPool + proxyId; - if (proxy->timeStamp < m_timeStamp) - { - proxy->timeStamp = m_timeStamp; - proxy->overlapCount = 1; - } - else - { - proxy->overlapCount = 2; - b2Assert(m_queryResultCount < b2_maxProxies); - m_queryResults[m_queryResultCount] = (uint16)proxyId; - ++m_queryResultCount; - } -} - -void b2BroadPhase::Query(int32* lowerQueryOut, int32* upperQueryOut, - uint16 lowerValue, uint16 upperValue, - b2Bound* bounds, int32 boundCount, int32 axis) -{ - int32 lowerQuery = BinarySearch(bounds, boundCount, lowerValue); - int32 upperQuery = BinarySearch(bounds, boundCount, upperValue); - - // Easy case: lowerQuery <= lowerIndex(i) < upperQuery - // Solution: search query range for min bounds. - for (int32 i = lowerQuery; i < upperQuery; ++i) - { - if (bounds[i].IsLower()) - { - IncrementOverlapCount(bounds[i].proxyId); - } - } - - // Hard case: lowerIndex(i) < lowerQuery < upperIndex(i) - // Solution: use the stabbing count to search down the bound array. - if (lowerQuery > 0) - { - int32 i = lowerQuery - 1; - int32 s = bounds[i].stabbingCount; - - // Find the s overlaps. - while (s) - { - b2Assert(i >= 0); - - if (bounds[i].IsLower()) - { - b2Proxy* proxy = m_proxyPool + bounds[i].proxyId; - if (lowerQuery <= proxy->upperBounds[axis]) - { - IncrementOverlapCount(bounds[i].proxyId); - --s; - } - } - --i; - } - } - - *lowerQueryOut = lowerQuery; - *upperQueryOut = upperQuery; -} - -uint16 b2BroadPhase::CreateProxy(const b2AABB& aabb, void* userData) -{ - b2Assert(m_proxyCount < b2_maxProxies); - b2Assert(m_freeProxy != b2_nullProxy); - - uint16 proxyId = m_freeProxy; - b2Proxy* proxy = m_proxyPool + proxyId; - m_freeProxy = proxy->GetNext(); - - proxy->overlapCount = 0; - proxy->userData = userData; - - int32 boundCount = 2 * m_proxyCount; - - uint16 lowerValues[2], upperValues[2]; - ComputeBounds(lowerValues, upperValues, aabb); - - for (int32 axis = 0; axis < 2; ++axis) - { - b2Bound* bounds = m_bounds[axis]; - int32 lowerIndex, upperIndex; - Query(&lowerIndex, &upperIndex, lowerValues[axis], upperValues[axis], bounds, boundCount, axis); - - memmove(bounds + upperIndex + 2, bounds + upperIndex, (boundCount - upperIndex) * sizeof(b2Bound)); - memmove(bounds + lowerIndex + 1, bounds + lowerIndex, (upperIndex - lowerIndex) * sizeof(b2Bound)); - - // The upper index has increased because of the lower bound insertion. - ++upperIndex; - - // Copy in the new bounds. - bounds[lowerIndex].value = lowerValues[axis]; - bounds[lowerIndex].proxyId = proxyId; - bounds[upperIndex].value = upperValues[axis]; - bounds[upperIndex].proxyId = proxyId; - - bounds[lowerIndex].stabbingCount = lowerIndex == 0 ? 0 : bounds[lowerIndex-1].stabbingCount; - bounds[upperIndex].stabbingCount = bounds[upperIndex-1].stabbingCount; - - // Adjust the stabbing count between the new bounds. - for (int32 index = lowerIndex; index < upperIndex; ++index) - { - ++bounds[index].stabbingCount; - } - - // Adjust the all the affected bound indices. - for (int32 index = lowerIndex; index < boundCount + 2; ++index) - { - b2Proxy* proxy = m_proxyPool + bounds[index].proxyId; - if (bounds[index].IsLower()) - { - proxy->lowerBounds[axis] = (uint16)index; - } - else - { - proxy->upperBounds[axis] = (uint16)index; - } - } - } - - ++m_proxyCount; - - b2Assert(m_queryResultCount < b2_maxProxies); - - // Create pairs if the AABB is in range. - for (int32 i = 0; i < m_queryResultCount; ++i) - { - b2Assert(m_queryResults[i] < b2_maxProxies); - b2Assert(m_proxyPool[m_queryResults[i]].IsValid()); - - m_pairManager.AddBufferedPair(proxyId, m_queryResults[i]); - } - - m_pairManager.Commit(); - - if (s_validate) - { - Validate(); - } - - // Prepare for next query. - m_queryResultCount = 0; - IncrementTimeStamp(); - - return proxyId; -} - -void b2BroadPhase::DestroyProxy(int32 proxyId) -{ - b2Assert(0 < m_proxyCount && m_proxyCount <= b2_maxProxies); - b2Proxy* proxy = m_proxyPool + proxyId; - b2Assert(proxy->IsValid()); - - int32 boundCount = 2 * m_proxyCount; - - for (int32 axis = 0; axis < 2; ++axis) - { - b2Bound* bounds = m_bounds[axis]; - - int32 lowerIndex = proxy->lowerBounds[axis]; - int32 upperIndex = proxy->upperBounds[axis]; - uint16 lowerValue = bounds[lowerIndex].value; - uint16 upperValue = bounds[upperIndex].value; - - memmove(bounds + lowerIndex, bounds + lowerIndex + 1, (upperIndex - lowerIndex - 1) * sizeof(b2Bound)); - memmove(bounds + upperIndex-1, bounds + upperIndex + 1, (boundCount - upperIndex - 1) * sizeof(b2Bound)); - - // Fix bound indices. - for (int32 index = lowerIndex; index < boundCount - 2; ++index) - { - b2Proxy* proxy = m_proxyPool + bounds[index].proxyId; - if (bounds[index].IsLower()) - { - proxy->lowerBounds[axis] = (uint16)index; - } - else - { - proxy->upperBounds[axis] = (uint16)index; - } - } - - // Fix stabbing count. - for (int32 index = lowerIndex; index < upperIndex - 1; ++index) - { - --bounds[index].stabbingCount; - } - - // Query for pairs to be removed. lowerIndex and upperIndex are not needed. - Query(&lowerIndex, &upperIndex, lowerValue, upperValue, bounds, boundCount - 2, axis); - } - - b2Assert(m_queryResultCount < b2_maxProxies); - - for (int32 i = 0; i < m_queryResultCount; ++i) - { - b2Assert(m_proxyPool[m_queryResults[i]].IsValid()); - m_pairManager.RemoveBufferedPair(proxyId, m_queryResults[i]); - } - - m_pairManager.Commit(); - - // Prepare for next query. - m_queryResultCount = 0; - IncrementTimeStamp(); - - // Return the proxy to the pool. - proxy->userData = NULL; - proxy->overlapCount = b2_invalid; - proxy->lowerBounds[0] = b2_invalid; - proxy->lowerBounds[1] = b2_invalid; - proxy->upperBounds[0] = b2_invalid; - proxy->upperBounds[1] = b2_invalid; - - proxy->SetNext(m_freeProxy); - m_freeProxy = (uint16)proxyId; - --m_proxyCount; - - if (s_validate) - { - Validate(); - } -} - -void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb) -{ - if (proxyId == b2_nullProxy || b2_maxProxies <= proxyId) - { - b2Assert(false); - return; - } - - if (aabb.IsValid() == false) - { - b2Assert(false); - return; - } - - int32 boundCount = 2 * m_proxyCount; - - b2Proxy* proxy = m_proxyPool + proxyId; - - // Get new bound values - b2BoundValues newValues; - ComputeBounds(newValues.lowerValues, newValues.upperValues, aabb); - - // Get old bound values - b2BoundValues oldValues; - for (int32 axis = 0; axis < 2; ++axis) - { - oldValues.lowerValues[axis] = m_bounds[axis][proxy->lowerBounds[axis]].value; - oldValues.upperValues[axis] = m_bounds[axis][proxy->upperBounds[axis]].value; - } - - for (int32 axis = 0; axis < 2; ++axis) - { - b2Bound* bounds = m_bounds[axis]; - - int32 lowerIndex = proxy->lowerBounds[axis]; - int32 upperIndex = proxy->upperBounds[axis]; - - uint16 lowerValue = newValues.lowerValues[axis]; - uint16 upperValue = newValues.upperValues[axis]; - - int32 deltaLower = lowerValue - bounds[lowerIndex].value; - int32 deltaUpper = upperValue - bounds[upperIndex].value; - - bounds[lowerIndex].value = lowerValue; - bounds[upperIndex].value = upperValue; - - // - // Expanding adds overlaps - // - - // Should we move the lower bound down? - if (deltaLower < 0) - { - int32 index = lowerIndex; - while (index > 0 && lowerValue < bounds[index-1].value) - { - b2Bound* bound = bounds + index; - b2Bound* prevBound = bound - 1; - - int32 prevProxyId = prevBound->proxyId; - b2Proxy* prevProxy = m_proxyPool + prevBound->proxyId; - - ++prevBound->stabbingCount; - - if (prevBound->IsUpper() == true) - { - if (TestOverlap(newValues, prevProxy)) - { - m_pairManager.AddBufferedPair(proxyId, prevProxyId); - } - - ++prevProxy->upperBounds[axis]; - ++bound->stabbingCount; - } - else - { - ++prevProxy->lowerBounds[axis]; - --bound->stabbingCount; - } - - --proxy->lowerBounds[axis]; - b2Swap(*bound, *prevBound); - --index; - } - } - - // Should we move the upper bound up? - if (deltaUpper > 0) - { - int32 index = upperIndex; - while (index < boundCount-1 && bounds[index+1].value <= upperValue) - { - b2Bound* bound = bounds + index; - b2Bound* nextBound = bound + 1; - int32 nextProxyId = nextBound->proxyId; - b2Proxy* nextProxy = m_proxyPool + nextProxyId; - - ++nextBound->stabbingCount; - - if (nextBound->IsLower() == true) - { - if (TestOverlap(newValues, nextProxy)) - { - m_pairManager.AddBufferedPair(proxyId, nextProxyId); - } - - --nextProxy->lowerBounds[axis]; - ++bound->stabbingCount; - } - else - { - --nextProxy->upperBounds[axis]; - --bound->stabbingCount; - } - - ++proxy->upperBounds[axis]; - b2Swap(*bound, *nextBound); - ++index; - } - } - - // - // Shrinking removes overlaps - // - - // Should we move the lower bound up? - if (deltaLower > 0) - { - int32 index = lowerIndex; - while (index < boundCount-1 && bounds[index+1].value <= lowerValue) - { - b2Bound* bound = bounds + index; - b2Bound* nextBound = bound + 1; - - int32 nextProxyId = nextBound->proxyId; - b2Proxy* nextProxy = m_proxyPool + nextProxyId; - - --nextBound->stabbingCount; - - if (nextBound->IsUpper()) - { - if (TestOverlap(oldValues, nextProxy)) - { - m_pairManager.RemoveBufferedPair(proxyId, nextProxyId); - } - - --nextProxy->upperBounds[axis]; - --bound->stabbingCount; - } - else - { - --nextProxy->lowerBounds[axis]; - ++bound->stabbingCount; - } - - ++proxy->lowerBounds[axis]; - b2Swap(*bound, *nextBound); - ++index; - } - } - - // Should we move the upper bound down? - if (deltaUpper < 0) - { - int32 index = upperIndex; - while (index > 0 && upperValue < bounds[index-1].value) - { - b2Bound* bound = bounds + index; - b2Bound* prevBound = bound - 1; - - int32 prevProxyId = prevBound->proxyId; - b2Proxy* prevProxy = m_proxyPool + prevProxyId; - - --prevBound->stabbingCount; - - if (prevBound->IsLower() == true) - { - if (TestOverlap(oldValues, prevProxy)) - { - m_pairManager.RemoveBufferedPair(proxyId, prevProxyId); - } - - ++prevProxy->lowerBounds[axis]; - --bound->stabbingCount; - } - else - { - ++prevProxy->upperBounds[axis]; - ++bound->stabbingCount; - } - - --proxy->upperBounds[axis]; - b2Swap(*bound, *prevBound); - --index; - } - } - } - - if (s_validate) - { - Validate(); - } -} - -void b2BroadPhase::Commit() -{ - m_pairManager.Commit(); -} - -int32 b2BroadPhase::Query(const b2AABB& aabb, void** userData, int32 maxCount) -{ - uint16 lowerValues[2]; - uint16 upperValues[2]; - ComputeBounds(lowerValues, upperValues, aabb); - - int32 lowerIndex, upperIndex; - - Query(&lowerIndex, &upperIndex, lowerValues[0], upperValues[0], m_bounds[0], 2*m_proxyCount, 0); - Query(&lowerIndex, &upperIndex, lowerValues[1], upperValues[1], m_bounds[1], 2*m_proxyCount, 1); - - b2Assert(m_queryResultCount < b2_maxProxies); - - int32 count = 0; - for (int32 i = 0; i < m_queryResultCount && count < maxCount; ++i, ++count) - { - b2Assert(m_queryResults[i] < b2_maxProxies); - b2Proxy* proxy = m_proxyPool + m_queryResults[i]; - b2Assert(proxy->IsValid()); - userData[i] = proxy->userData; - } - - // Prepare for next query. - m_queryResultCount = 0; - IncrementTimeStamp(); - - return count; -} - -void b2BroadPhase::Validate() -{ - for (int32 axis = 0; axis < 2; ++axis) - { - b2Bound* bounds = m_bounds[axis]; - - int32 boundCount = 2 * m_proxyCount; - uint16 stabbingCount = 0; - - for (int32 i = 0; i < boundCount; ++i) - { - b2Bound* bound = bounds + i; - b2Assert(i == 0 || bounds[i-1].value <= bound->value); - b2Assert(bound->proxyId != b2_nullProxy); - b2Assert(m_proxyPool[bound->proxyId].IsValid()); - - if (bound->IsLower() == true) - { - b2Assert(m_proxyPool[bound->proxyId].lowerBounds[axis] == i); - ++stabbingCount; - } - else - { - b2Assert(m_proxyPool[bound->proxyId].upperBounds[axis] == i); - --stabbingCount; - } - - b2Assert(bound->stabbingCount == stabbingCount); - } - } -} diff --git a/src/modules/physics/box2d/Source/Collision/b2BroadPhase.h b/src/modules/physics/box2d/Source/Collision/b2BroadPhase.h deleted file mode 100644 index aa3ea1bed..000000000 --- a/src/modules/physics/box2d/Source/Collision/b2BroadPhase.h +++ /dev/null @@ -1,146 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_BROAD_PHASE_H -#define B2_BROAD_PHASE_H - -/* -This broad phase uses the Sweep and Prune algorithm as described in: -Collision Detection in Interactive 3D Environments by Gino van den Bergen -Also, some ideas, such as using integral values for fast compares comes from -Bullet (http:/www.bulletphysics.com). -*/ - -#include "../Common/b2Settings.h" -#include "b2Collision.h" -#include "b2PairManager.h" -#include - -#ifdef TARGET_FLOAT32_IS_FIXED -#define B2BROADPHASE_MAX (USHRT_MAX/2) -#else -#define B2BROADPHASE_MAX USHRT_MAX - -#endif - -const uint16 b2_invalid = B2BROADPHASE_MAX; -const uint16 b2_nullEdge = B2BROADPHASE_MAX; -struct b2BoundValues; - -struct b2Bound -{ - bool IsLower() const { return (value & 1) == 0; } - bool IsUpper() const { return (value & 1) == 1; } - - uint16 value; - uint16 proxyId; - uint16 stabbingCount; -}; - -struct b2Proxy -{ - uint16 GetNext() const { return lowerBounds[0]; } - void SetNext(uint16 next) { lowerBounds[0] = next; } - bool IsValid() const { return overlapCount != b2_invalid; } - - uint16 lowerBounds[2], upperBounds[2]; - uint16 overlapCount; - uint16 timeStamp; - void* userData; -}; - -class b2BroadPhase -{ -public: - b2BroadPhase(const b2AABB& worldAABB, b2PairCallback* callback); - ~b2BroadPhase(); - - // Use this to see if your proxy is in range. If it is not in range, - // it should be destroyed. Otherwise you may get O(m^2) pairs, where m - // is the number of proxies that are out of range. - bool InRange(const b2AABB& aabb) const; - - // Create and destroy proxies. These call Flush first. - uint16 CreateProxy(const b2AABB& aabb, void* userData); - void DestroyProxy(int32 proxyId); - - // Call MoveProxy as many times as you like, then when you are done - // call Commit to finalized the proxy pairs (for your time step). - void MoveProxy(int32 proxyId, const b2AABB& aabb); - void Commit(); - - // Get a single proxy. Returns NULL if the id is invalid. - b2Proxy* GetProxy(int32 proxyId); - - // Query an AABB for overlapping proxies, returns the user data and - // the count, up to the supplied maximum count. - int32 Query(const b2AABB& aabb, void** userData, int32 maxCount); - - void Validate(); - void ValidatePairs(); - -private: - void ComputeBounds(uint16* lowerValues, uint16* upperValues, const b2AABB& aabb); - - bool TestOverlap(b2Proxy* p1, b2Proxy* p2); - bool TestOverlap(const b2BoundValues& b, b2Proxy* p); - - void Query(int32* lowerIndex, int32* upperIndex, uint16 lowerValue, uint16 upperValue, - b2Bound* bounds, int32 boundCount, int32 axis); - void IncrementOverlapCount(int32 proxyId); - void IncrementTimeStamp(); - -public: - friend class b2PairManager; - - b2PairManager m_pairManager; - - b2Proxy m_proxyPool[b2_maxProxies]; - uint16 m_freeProxy; - - b2Bound m_bounds[2][2*b2_maxProxies]; - - uint16 m_queryResults[b2_maxProxies]; - int32 m_queryResultCount; - - b2AABB m_worldAABB; - b2Vec2 m_quantizationFactor; - int32 m_proxyCount; - uint16 m_timeStamp; - - static bool s_validate; -}; - - -inline bool b2BroadPhase::InRange(const b2AABB& aabb) const -{ - b2Vec2 d = b2Max(aabb.lowerBound - m_worldAABB.upperBound, m_worldAABB.lowerBound - aabb.upperBound); - return b2Max(d.x, d.y) < 0.0f; -} - -inline b2Proxy* b2BroadPhase::GetProxy(int32 proxyId) -{ - if (proxyId == b2_nullProxy || m_proxyPool[proxyId].IsValid() == false) - { - return NULL; - } - - return m_proxyPool + proxyId; -} - -#endif diff --git a/src/modules/physics/box2d/Source/Collision/b2CollideCircle.cpp b/src/modules/physics/box2d/Source/Collision/b2CollideCircle.cpp deleted file mode 100644 index 9384e15f4..000000000 --- a/src/modules/physics/box2d/Source/Collision/b2CollideCircle.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/* -* Copyright (c) 2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2Collision.h" -#include "Shapes/b2CircleShape.h" -#include "Shapes/b2PolygonShape.h" - -void b2CollideCircles( - b2Manifold* manifold, - const b2CircleShape* circle1, const b2XForm& xf1, - const b2CircleShape* circle2, const b2XForm& xf2) -{ - manifold->pointCount = 0; - - b2Vec2 p1 = b2Mul(xf1, circle1->GetLocalPosition()); - b2Vec2 p2 = b2Mul(xf2, circle2->GetLocalPosition()); - - b2Vec2 d = p2 - p1; - float32 distSqr = b2Dot(d, d); - float32 r1 = circle1->GetRadius(); - float32 r2 = circle2->GetRadius(); - float32 radiusSum = r1 + r2; - if (distSqr > radiusSum * radiusSum) - { - return; - } - - float32 separation; - if (distSqr < B2_FLT_EPSILON) - { - separation = -radiusSum; - manifold->normal.Set(0.0f, 1.0f); - } - else - { - float32 dist = b2Sqrt(distSqr); - separation = dist - radiusSum; - float32 a = 1.0f / dist; - manifold->normal.x = a * d.x; - manifold->normal.y = a * d.y; - } - - manifold->pointCount = 1; - manifold->points[0].id.key = 0; - manifold->points[0].separation = separation; - - p1 += r1 * manifold->normal; - p2 -= r2 * manifold->normal; - - b2Vec2 p = 0.5f * (p1 + p2); - - manifold->points[0].localPoint1 = b2MulT(xf1, p); - manifold->points[0].localPoint2 = b2MulT(xf2, p); -} - -void b2CollidePolygonAndCircle( - b2Manifold* manifold, - const b2PolygonShape* polygon, const b2XForm& xf1, - const b2CircleShape* circle, const b2XForm& xf2) -{ - manifold->pointCount = 0; - - // Compute circle position in the frame of the polygon. - b2Vec2 c = b2Mul(xf2, circle->GetLocalPosition()); - b2Vec2 cLocal = b2MulT(xf1, c); - - // Find the min separating edge. - int32 normalIndex = 0; - float32 separation = -B2_FLT_MAX; - float32 radius = circle->GetRadius(); - int32 vertexCount = polygon->GetVertexCount(); - const b2Vec2* vertices = polygon->GetVertices(); - const b2Vec2* normals = polygon->GetNormals(); - - for (int32 i = 0; i < vertexCount; ++i) - { - float32 s = b2Dot(normals[i], cLocal - vertices[i]); - - if (s > radius) - { - // Early out. - return; - } - - if (s > separation) - { - separation = s; - normalIndex = i; - } - } - - // If the center is inside the polygon ... - if (separation < B2_FLT_EPSILON) - { - manifold->pointCount = 1; - manifold->normal = b2Mul(xf1.R, normals[normalIndex]); - manifold->points[0].id.features.incidentEdge = (uint8)normalIndex; - manifold->points[0].id.features.incidentVertex = b2_nullFeature; - manifold->points[0].id.features.referenceEdge = 0; - manifold->points[0].id.features.flip = 0; - b2Vec2 position = c - radius * manifold->normal; - manifold->points[0].localPoint1 = b2MulT(xf1, position); - manifold->points[0].localPoint2 = b2MulT(xf2, position); - manifold->points[0].separation = separation - radius; - return; - } - - // Project the circle center onto the edge segment. - int32 vertIndex1 = normalIndex; - int32 vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; - b2Vec2 e = vertices[vertIndex2] - vertices[vertIndex1]; - - float32 length = e.Normalize(); - b2Assert(length > B2_FLT_EPSILON); - - // Project the center onto the edge. - float32 u = b2Dot(cLocal - vertices[vertIndex1], e); - b2Vec2 p; - if (u <= 0.0f) - { - p = vertices[vertIndex1]; - manifold->points[0].id.features.incidentEdge = b2_nullFeature; - manifold->points[0].id.features.incidentVertex = (uint8)vertIndex1; - } - else if (u >= length) - { - p = vertices[vertIndex2]; - manifold->points[0].id.features.incidentEdge = b2_nullFeature; - manifold->points[0].id.features.incidentVertex = (uint8)vertIndex2; - } - else - { - p = vertices[vertIndex1] + u * e; - manifold->points[0].id.features.incidentEdge = (uint8)normalIndex; - manifold->points[0].id.features.incidentVertex = 0; - } - - b2Vec2 d = cLocal - p; - float32 dist = d.Normalize(); - if (dist > radius) - { - return; - } - - manifold->pointCount = 1; - manifold->normal = b2Mul(xf1.R, d); - b2Vec2 position = c - radius * manifold->normal; - manifold->points[0].localPoint1 = b2MulT(xf1, position); - manifold->points[0].localPoint2 = b2MulT(xf2, position); - manifold->points[0].separation = dist - radius; - manifold->points[0].id.features.referenceEdge = 0; - manifold->points[0].id.features.flip = 0; -} diff --git a/src/modules/physics/box2d/Source/Collision/b2Collision.cpp b/src/modules/physics/box2d/Source/Collision/b2Collision.cpp deleted file mode 100644 index 7b6b59c42..000000000 --- a/src/modules/physics/box2d/Source/Collision/b2Collision.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* -* Copyright (c) 2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2Collision.h" - -// Collision Detection in Interactive 3D Environments by Gino van den Bergen -// From Section 3.4.1 -// x = mu1 * p1 + mu2 * p2 -// mu1 + mu2 = 1 && mu1 >= 0 && mu2 >= 0 -// mu1 = 1 - mu2; -// x = (1 - mu2) * p1 + mu2 * p2 -// = p1 + mu2 * (p2 - p1) -// x = s + a * r (s := start, r := end - start) -// s + a * r = p1 + mu2 * d (d := p2 - p1) -// -a * r + mu2 * d = b (b := s - p1) -// [-r d] * [a; mu2] = b -// Cramer's rule: -// denom = det[-r d] -// a = det[b d] / denom -// mu2 = det[-r b] / denom -bool b2Segment::TestSegment(float32* lambda, b2Vec2* normal, const b2Segment& segment, float32 maxLambda) const -{ - b2Vec2 s = segment.p1; - b2Vec2 r = segment.p2 - s; - b2Vec2 d = p2 - p1; - b2Vec2 n = b2Cross(d, 1.0f); - - const float32 k_slop = 100.0f * B2_FLT_EPSILON; - float32 denom = -b2Dot(r, n); - - // Cull back facing collision and ignore parallel segments. - if (denom > k_slop) - { - // Does the segment intersect the infinite line associated with this segment? - b2Vec2 b = s - p1; - float32 a = b2Dot(b, n); - - if (0.0f <= a && a <= maxLambda * denom) - { - float32 mu2 = -r.x * b.y + r.y * b.x; - - // Does the segment intersect this segment? - if (-k_slop * denom <= mu2 && mu2 <= denom * (1.0f + k_slop)) - { - a /= denom; - n.Normalize(); - *lambda = a; - *normal = n; - return true; - } - } - } - - return false; -} - - diff --git a/src/modules/physics/box2d/Source/Collision/b2Collision.h b/src/modules/physics/box2d/Source/Collision/b2Collision.h deleted file mode 100644 index a7bb64237..000000000 --- a/src/modules/physics/box2d/Source/Collision/b2Collision.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_COLLISION_H -#define B2_COLLISION_H - -#include "../Common/b2Math.h" -#include - -/// @file -/// Structures and functions used for computing contact points, distance -/// queries, and TOI queries. - -class b2Shape; -class b2CircleShape; -class b2PolygonShape; - -const uint8 b2_nullFeature = UCHAR_MAX; - -/// Contact ids to facilitate warm starting. -union b2ContactID -{ - /// The features that intersect to form the contact point - struct Features - { - uint8 referenceEdge; ///< The edge that defines the outward contact normal. - uint8 incidentEdge; ///< The edge most anti-parallel to the reference edge. - uint8 incidentVertex; ///< The vertex (0 or 1) on the incident edge that was clipped. - uint8 flip; ///< A value of 1 indicates that the reference edge is on shape2. - } features; - uint32 key; ///< Used to quickly compare contact ids. -}; - -/// A manifold point is a contact point belonging to a contact -/// manifold. It holds details related to the geometry and dynamics -/// of the contact points. -/// The point is stored in local coordinates because CCD -/// requires sub-stepping in which the separation is stale. -struct b2ManifoldPoint -{ - b2Vec2 localPoint1; ///< local position of the contact point in body1 - b2Vec2 localPoint2; ///< local position of the contact point in body2 - float32 separation; ///< the separation of the shapes along the normal vector - float32 normalImpulse; ///< the non-penetration impulse - float32 tangentImpulse; ///< the friction impulse - b2ContactID id; ///< uniquely identifies a contact point between two shapes -}; - -/// A manifold for two touching convex shapes. -struct b2Manifold -{ - b2ManifoldPoint points[b2_maxManifoldPoints]; ///< the points of contact - b2Vec2 normal; ///< the shared unit normal vector - int32 pointCount; ///< the number of manifold points -}; - -/// A line segment. -struct b2Segment -{ - /// Ray cast against this segment with another segment. - bool TestSegment(float32* lambda, b2Vec2* normal, const b2Segment& segment, float32 maxLambda) const; - - b2Vec2 p1; ///< the starting point - b2Vec2 p2; ///< the ending point -}; - -/// An axis aligned bounding box. -struct b2AABB -{ - /// Verify that the bounds are sorted. - bool IsValid() const; - - b2Vec2 lowerBound; ///< the lower vertex - b2Vec2 upperBound; ///< the upper vertex -}; - -/// An oriented bounding box. -struct b2OBB -{ - b2Mat22 R; ///< the rotation matrix - b2Vec2 center; ///< the local centroid - b2Vec2 extents; ///< the half-widths -}; - -/// Compute the collision manifold between two circles. -void b2CollideCircles(b2Manifold* manifold, - const b2CircleShape* circle1, const b2XForm& xf1, - const b2CircleShape* circle2, const b2XForm& xf2); - -/// Compute the collision manifold between a polygon and a circle. -void b2CollidePolygonAndCircle(b2Manifold* manifold, - const b2PolygonShape* polygon, const b2XForm& xf1, - const b2CircleShape* circle, const b2XForm& xf2); - -/// Compute the collision manifold between two circles. -void b2CollidePolygons(b2Manifold* manifold, - const b2PolygonShape* polygon1, const b2XForm& xf1, - const b2PolygonShape* polygon2, const b2XForm& xf2); - -/// Compute the distance between two shapes and the closest points. -/// @return the distance between the shapes or zero if they are overlapped/touching. -float32 b2Distance(b2Vec2* x1, b2Vec2* x2, - const b2Shape* shape1, const b2XForm& xf1, - const b2Shape* shape2, const b2XForm& xf2); - -/// Compute the time when two shapes begin to touch or touch at a closer distance. -/// @warning the sweeps must have the same time interval. -/// @return the fraction between [0,1] in which the shapes first touch. -/// fraction=0 means the shapes begin touching/overlapped, and fraction=1 means the shapes don't touch. -float32 b2TimeOfImpact(const b2Shape* shape1, const b2Sweep& sweep1, - const b2Shape* shape2, const b2Sweep& sweep2); - - -// ---------------- Inline Functions ------------------------------------------ - -inline bool b2AABB::IsValid() const -{ - b2Vec2 d = upperBound - lowerBound; - bool valid = d.x >= 0.0f && d.y >= 0.0f; - valid = valid && lowerBound.IsValid() && upperBound.IsValid(); - return valid; -} - -inline bool b2TestOverlap(const b2AABB& a, const b2AABB& b) -{ - b2Vec2 d1, d2; - d1 = b.lowerBound - a.upperBound; - d2 = a.lowerBound - b.upperBound; - - if (d1.x > 0.0f || d1.y > 0.0f) - return false; - - if (d2.x > 0.0f || d2.y > 0.0f) - return false; - - return true; -} - -#endif diff --git a/src/modules/physics/box2d/Source/Collision/b2Distance.cpp b/src/modules/physics/box2d/Source/Collision/b2Distance.cpp deleted file mode 100644 index a423d3f1b..000000000 --- a/src/modules/physics/box2d/Source/Collision/b2Distance.cpp +++ /dev/null @@ -1,364 +0,0 @@ -/* -* Copyright (c) 2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2Collision.h" -#include "Shapes/b2CircleShape.h" -#include "Shapes/b2PolygonShape.h" - -int32 g_GJK_Iterations = 0; - -// GJK using Voronoi regions (Christer Ericson) and region selection -// optimizations (Casey Muratori). - -// The origin is either in the region of points[1] or in the edge region. The origin is -// not in region of points[0] because that is the old point. -static int32 ProcessTwo(b2Vec2* x1, b2Vec2* x2, b2Vec2* p1s, b2Vec2* p2s, b2Vec2* points) -{ - // If in point[1] region - b2Vec2 r = -points[1]; - b2Vec2 d = points[0] - points[1]; - float32 length = d.Normalize(); - float32 lambda = b2Dot(r, d); - if (lambda <= 0.0f || length < B2_FLT_EPSILON) - { - // The simplex is reduced to a point. - *x1 = p1s[1]; - *x2 = p2s[1]; - p1s[0] = p1s[1]; - p2s[0] = p2s[1]; - points[0] = points[1]; - return 1; - } - - // Else in edge region - lambda /= length; - *x1 = p1s[1] + lambda * (p1s[0] - p1s[1]); - *x2 = p2s[1] + lambda * (p2s[0] - p2s[1]); - return 2; -} - -// Possible regions: -// - points[2] -// - edge points[0]-points[2] -// - edge points[1]-points[2] -// - inside the triangle -static int32 ProcessThree(b2Vec2* x1, b2Vec2* x2, b2Vec2* p1s, b2Vec2* p2s, b2Vec2* points) -{ - b2Vec2 a = points[0]; - b2Vec2 b = points[1]; - b2Vec2 c = points[2]; - - b2Vec2 ab = b - a; - b2Vec2 ac = c - a; - b2Vec2 bc = c - b; - - float32 sn = -b2Dot(a, ab), sd = b2Dot(b, ab); - float32 tn = -b2Dot(a, ac), td = b2Dot(c, ac); - float32 un = -b2Dot(b, bc), ud = b2Dot(c, bc); - - // In vertex c region? - if (td <= 0.0f && ud <= 0.0f) - { - // Single point - *x1 = p1s[2]; - *x2 = p2s[2]; - p1s[0] = p1s[2]; - p2s[0] = p2s[2]; - points[0] = points[2]; - return 1; - } - - // Should not be in vertex a or b region. - B2_NOT_USED(sd); - B2_NOT_USED(sn); - b2Assert(sn > 0.0f || tn > 0.0f); - b2Assert(sd > 0.0f || un > 0.0f); - - float32 n = b2Cross(ab, ac); - -#ifdef TARGET_FLOAT32_IS_FIXED - n = (n < 0.0)? -1.0 : ((n > 0.0)? 1.0 : 0.0); -#endif - - // Should not be in edge ab region. - float32 vc = n * b2Cross(a, b); - b2Assert(vc > 0.0f || sn > 0.0f || sd > 0.0f); - - // In edge bc region? - float32 va = n * b2Cross(b, c); - if (va <= 0.0f && un >= 0.0f && ud >= 0.0f && (un+ud) > 0.0f) - { - b2Assert(un + ud > 0.0f); - float32 lambda = un / (un + ud); - *x1 = p1s[1] + lambda * (p1s[2] - p1s[1]); - *x2 = p2s[1] + lambda * (p2s[2] - p2s[1]); - p1s[0] = p1s[2]; - p2s[0] = p2s[2]; - points[0] = points[2]; - return 2; - } - - // In edge ac region? - float32 vb = n * b2Cross(c, a); - if (vb <= 0.0f && tn >= 0.0f && td >= 0.0f && (tn+td) > 0.0f) - { - b2Assert(tn + td > 0.0f); - float32 lambda = tn / (tn + td); - *x1 = p1s[0] + lambda * (p1s[2] - p1s[0]); - *x2 = p2s[0] + lambda * (p2s[2] - p2s[0]); - p1s[1] = p1s[2]; - p2s[1] = p2s[2]; - points[1] = points[2]; - return 2; - } - - // Inside the triangle, compute barycentric coordinates - float32 denom = va + vb + vc; - b2Assert(denom > 0.0f); - denom = 1.0f / denom; - -#ifdef TARGET_FLOAT32_IS_FIXED - *x1 = denom * (va * p1s[0] + vb * p1s[1] + vc * p1s[2]); - *x2 = denom * (va * p2s[0] + vb * p2s[1] + vc * p2s[2]); -#else - float32 u = va * denom; - float32 v = vb * denom; - float32 w = 1.0f - u - v; - *x1 = u * p1s[0] + v * p1s[1] + w * p1s[2]; - *x2 = u * p2s[0] + v * p2s[1] + w * p2s[2]; -#endif - return 3; -} - -static bool InPoints(const b2Vec2& w, const b2Vec2* points, int32 pointCount) -{ - const float32 k_tolerance = 100.0f * B2_FLT_EPSILON; - for (int32 i = 0; i < pointCount; ++i) - { - b2Vec2 d = b2Abs(w - points[i]); - b2Vec2 m = b2Max(b2Abs(w), b2Abs(points[i])); - - if (d.x < k_tolerance * (m.x + 1.0f) && - d.y < k_tolerance * (m.y + 1.0f)) - { - return true; - } - } - - return false; -} - -template -float32 DistanceGeneric(b2Vec2* x1, b2Vec2* x2, - const T1* shape1, const b2XForm& xf1, - const T2* shape2, const b2XForm& xf2) -{ - b2Vec2 p1s[3], p2s[3]; - b2Vec2 points[3]; - int32 pointCount = 0; - - *x1 = shape1->GetFirstVertex(xf1); - *x2 = shape2->GetFirstVertex(xf2); - - float32 vSqr = 0.0f; - const int32 maxIterations = 20; - for (int32 iter = 0; iter < maxIterations; ++iter) - { - b2Vec2 v = *x2 - *x1; - b2Vec2 w1 = shape1->Support(xf1, v); - b2Vec2 w2 = shape2->Support(xf2, -v); - - vSqr = b2Dot(v, v); - b2Vec2 w = w2 - w1; - float32 vw = b2Dot(v, w); - if (vSqr - vw <= 0.01f * vSqr || InPoints(w, points, pointCount)) // or w in points - { - if (pointCount == 0) - { - *x1 = w1; - *x2 = w2; - } - g_GJK_Iterations = iter; - return b2Sqrt(vSqr); - } - - switch (pointCount) - { - case 0: - p1s[0] = w1; - p2s[0] = w2; - points[0] = w; - *x1 = p1s[0]; - *x2 = p2s[0]; - ++pointCount; - break; - - case 1: - p1s[1] = w1; - p2s[1] = w2; - points[1] = w; - pointCount = ProcessTwo(x1, x2, p1s, p2s, points); - break; - - case 2: - p1s[2] = w1; - p2s[2] = w2; - points[2] = w; - pointCount = ProcessThree(x1, x2, p1s, p2s, points); - break; - } - - // If we have three points, then the origin is in the corresponding triangle. - if (pointCount == 3) - { - g_GJK_Iterations = iter; - return 0.0f; - } - - float32 maxSqr = -B2_FLT_MAX; - for (int32 i = 0; i < pointCount; ++i) - { - maxSqr = b2Max(maxSqr, b2Dot(points[i], points[i])); - } - -#ifdef TARGET_FLOAT32_IS_FIXED - if (pointCount == 3 || vSqr <= 5.0*B2_FLT_EPSILON * maxSqr) -#else - if (pointCount == 3 || vSqr <= 100.0f * B2_FLT_EPSILON * maxSqr) -#endif - { - g_GJK_Iterations = iter; - v = *x2 - *x1; - vSqr = b2Dot(v, v); - return b2Sqrt(vSqr); - } - } - - g_GJK_Iterations = maxIterations; - return b2Sqrt(vSqr); -} - -static float32 DistanceCC( - b2Vec2* x1, b2Vec2* x2, - const b2CircleShape* circle1, const b2XForm& xf1, - const b2CircleShape* circle2, const b2XForm& xf2) -{ - b2Vec2 p1 = b2Mul(xf1, circle1->GetLocalPosition()); - b2Vec2 p2 = b2Mul(xf2, circle2->GetLocalPosition()); - - b2Vec2 d = p2 - p1; - float32 dSqr = b2Dot(d, d); - float32 r1 = circle1->GetRadius() - b2_toiSlop; - float32 r2 = circle2->GetRadius() - b2_toiSlop; - float32 r = r1 + r2; - if (dSqr > r * r) - { - float32 dLen = d.Normalize(); - float32 distance = dLen - r; - *x1 = p1 + r1 * d; - *x2 = p2 - r2 * d; - return distance; - } - else if (dSqr > B2_FLT_EPSILON * B2_FLT_EPSILON) - { - d.Normalize(); - *x1 = p1 + r1 * d; - *x2 = *x1; - return 0.0f; - } - - *x1 = p1; - *x2 = *x1; - return 0.0f; -} - -// This is used for polygon-vs-circle distance. -struct Point -{ - b2Vec2 Support(const b2XForm&, const b2Vec2&) const - { - return p; - } - - b2Vec2 GetFirstVertex(const b2XForm&) const - { - return p; - } - - b2Vec2 p; -}; - -// GJK is more robust with polygon-vs-point than polygon-vs-circle. -// So we convert polygon-vs-circle to polygon-vs-point. -static float32 DistancePC( - b2Vec2* x1, b2Vec2* x2, - const b2PolygonShape* polygon, const b2XForm& xf1, - const b2CircleShape* circle, const b2XForm& xf2) -{ - Point point; - point.p = b2Mul(xf2, circle->GetLocalPosition()); - - float32 distance = DistanceGeneric(x1, x2, polygon, xf1, &point, b2XForm_identity); - - float32 r = circle->GetRadius() - b2_toiSlop; - - if (distance > r) - { - distance -= r; - b2Vec2 d = *x2 - *x1; - d.Normalize(); - *x2 -= r * d; - } - else - { - distance = 0.0f; - *x2 = *x1; - } - - return distance; -} - -float32 b2Distance(b2Vec2* x1, b2Vec2* x2, - const b2Shape* shape1, const b2XForm& xf1, - const b2Shape* shape2, const b2XForm& xf2) -{ - b2ShapeType type1 = shape1->GetType(); - b2ShapeType type2 = shape2->GetType(); - - if (type1 == e_circleShape && type2 == e_circleShape) - { - return DistanceCC(x1, x2, (b2CircleShape*)shape1, xf1, (b2CircleShape*)shape2, xf2); - } - - if (type1 == e_polygonShape && type2 == e_circleShape) - { - return DistancePC(x1, x2, (b2PolygonShape*)shape1, xf1, (b2CircleShape*)shape2, xf2); - } - - if (type1 == e_circleShape && type2 == e_polygonShape) - { - return DistancePC(x2, x1, (b2PolygonShape*)shape2, xf2, (b2CircleShape*)shape1, xf1); - } - - if (type1 == e_polygonShape && type2 == e_polygonShape) - { - return DistanceGeneric(x1, x2, (b2PolygonShape*)shape1, xf1, (b2PolygonShape*)shape2, xf2); - } - - return 0.0f; -} diff --git a/src/modules/physics/box2d/Source/Collision/b2PairManager.cpp b/src/modules/physics/box2d/Source/Collision/b2PairManager.cpp deleted file mode 100644 index 909894491..000000000 --- a/src/modules/physics/box2d/Source/Collision/b2PairManager.cpp +++ /dev/null @@ -1,396 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2PairManager.h" -#include "b2BroadPhase.h" - -#include - -// Thomas Wang's hash, see: http://www.concentric.net/~Ttwang/tech/inthash.htm -// This assumes proxyId1 and proxyId2 are 16-bit. -inline uint32 Hash(uint32 proxyId1, uint32 proxyId2) -{ - uint32 key = (proxyId2 << 16) | proxyId1; - key = ~key + (key << 15); - key = key ^ (key >> 12); - key = key + (key << 2); - key = key ^ (key >> 4); - key = key * 2057; - key = key ^ (key >> 16); - return key; -} - -inline bool Equals(const b2Pair& pair, int32 proxyId1, int32 proxyId2) -{ - return pair.proxyId1 == proxyId1 && pair.proxyId2 == proxyId2; -} - -inline bool Equals(const b2BufferedPair& pair1, const b2BufferedPair& pair2) -{ - return pair1.proxyId1 == pair2.proxyId1 && pair1.proxyId2 == pair2.proxyId2; -} - -// For sorting. -inline bool operator < (const b2BufferedPair& pair1, const b2BufferedPair& pair2) -{ - if (pair1.proxyId1 < pair2.proxyId1) - { - return true; - } - - if (pair1.proxyId1 == pair2.proxyId1) - { - return pair1.proxyId2 < pair2.proxyId2; - } - - return false; -} - - -b2PairManager::b2PairManager() -{ - b2Assert(b2IsPowerOfTwo(b2_tableCapacity) == true); - b2Assert(b2_tableCapacity >= b2_maxPairs); - for (int32 i = 0; i < b2_tableCapacity; ++i) - { - m_hashTable[i] = b2_nullPair; - } - m_freePair = 0; - for (int32 i = 0; i < b2_maxPairs; ++i) - { - m_pairs[i].proxyId1 = b2_nullProxy; - m_pairs[i].proxyId2 = b2_nullProxy; - m_pairs[i].userData = NULL; - m_pairs[i].status = 0; - m_pairs[i].next = uint16(i + 1); - } - m_pairs[b2_maxPairs-1].next = b2_nullPair; - m_pairCount = 0; - m_pairBufferCount = 0; -} - -void b2PairManager::Initialize(b2BroadPhase* broadPhase, b2PairCallback* callback) -{ - m_broadPhase = broadPhase; - m_callback = callback; -} - -b2Pair* b2PairManager::Find(int32 proxyId1, int32 proxyId2, uint32 hash) -{ - int32 index = m_hashTable[hash]; - - while (index != b2_nullPair && Equals(m_pairs[index], proxyId1, proxyId2) == false) - { - index = m_pairs[index].next; - } - - if (index == b2_nullPair) - { - return NULL; - } - - b2Assert(index < b2_maxPairs); - - return m_pairs + index; -} - -b2Pair* b2PairManager::Find(int32 proxyId1, int32 proxyId2) -{ - if (proxyId1 > proxyId2) b2Swap(proxyId1, proxyId2); - - int32 hash = Hash(proxyId1, proxyId2) & b2_tableMask; - - return Find(proxyId1, proxyId2, hash); -} - -// Returns existing pair or creates a new one. -b2Pair* b2PairManager::AddPair(int32 proxyId1, int32 proxyId2) -{ - if (proxyId1 > proxyId2) b2Swap(proxyId1, proxyId2); - - int32 hash = Hash(proxyId1, proxyId2) & b2_tableMask; - - b2Pair* pair = Find(proxyId1, proxyId2, hash); - if (pair != NULL) - { - return pair; - } - - b2Assert(m_pairCount < b2_maxPairs && m_freePair != b2_nullPair); - - uint16 pairIndex = m_freePair; - pair = m_pairs + pairIndex; - m_freePair = pair->next; - - pair->proxyId1 = (uint16)proxyId1; - pair->proxyId2 = (uint16)proxyId2; - pair->status = 0; - pair->userData = NULL; - pair->next = m_hashTable[hash]; - - m_hashTable[hash] = pairIndex; - - ++m_pairCount; - - return pair; -} - -// Removes a pair. The pair must exist. -void* b2PairManager::RemovePair(int32 proxyId1, int32 proxyId2) -{ - b2Assert(m_pairCount > 0); - - if (proxyId1 > proxyId2) b2Swap(proxyId1, proxyId2); - - int32 hash = Hash(proxyId1, proxyId2) & b2_tableMask; - - uint16* node = &m_hashTable[hash]; - while (*node != b2_nullPair) - { - if (Equals(m_pairs[*node], proxyId1, proxyId2)) - { - uint16 index = *node; - *node = m_pairs[*node].next; - - b2Pair* pair = m_pairs + index; - void* userData = pair->userData; - - // Scrub - pair->next = m_freePair; - pair->proxyId1 = b2_nullProxy; - pair->proxyId2 = b2_nullProxy; - pair->userData = NULL; - pair->status = 0; - - m_freePair = index; - --m_pairCount; - return userData; - } - else - { - node = &m_pairs[*node].next; - } - } - - b2Assert(false); - return NULL; -} - -/* -As proxies are created and moved, many pairs are created and destroyed. Even worse, the same -pair may be added and removed multiple times in a single time step of the physics engine. To reduce -traffic in the pair manager, we try to avoid destroying pairs in the pair manager until the -end of the physics step. This is done by buffering all the RemovePair requests. AddPair -requests are processed immediately because we need the hash table entry for quick lookup. - -All user user callbacks are delayed until the buffered pairs are confirmed in Commit. -This is very important because the user callbacks may be very expensive and client logic -may be harmed if pairs are added and removed within the same time step. - -Buffer a pair for addition. -We may add a pair that is not in the pair manager or pair buffer. -We may add a pair that is already in the pair manager and pair buffer. -If the added pair is not a new pair, then it must be in the pair buffer (because RemovePair was called). -*/ -void b2PairManager::AddBufferedPair(int32 id1, int32 id2) -{ - b2Assert(id1 != b2_nullProxy && id2 != b2_nullProxy); - b2Assert(m_pairBufferCount < b2_maxPairs); - - b2Pair* pair = AddPair(id1, id2); - - // If this pair is not in the pair buffer ... - if (pair->IsBuffered() == false) - { - // This must be a newly added pair. - b2Assert(pair->IsFinal() == false); - - // Add it to the pair buffer. - pair->SetBuffered(); - m_pairBuffer[m_pairBufferCount].proxyId1 = pair->proxyId1; - m_pairBuffer[m_pairBufferCount].proxyId2 = pair->proxyId2; - ++m_pairBufferCount; - - b2Assert(m_pairBufferCount <= m_pairCount); - } - - // Confirm this pair for the subsequent call to Commit. - pair->ClearRemoved(); - - if (b2BroadPhase::s_validate) - { - ValidateBuffer(); - } -} - -// Buffer a pair for removal. -void b2PairManager::RemoveBufferedPair(int32 id1, int32 id2) -{ - b2Assert(id1 != b2_nullProxy && id2 != b2_nullProxy); - b2Assert(m_pairBufferCount < b2_maxPairs); - - b2Pair* pair = Find(id1, id2); - - if (pair == NULL) - { - // The pair never existed. This is legal (due to collision filtering). - return; - } - - // If this pair is not in the pair buffer ... - if (pair->IsBuffered() == false) - { - // This must be an old pair. - b2Assert(pair->IsFinal() == true); - - pair->SetBuffered(); - m_pairBuffer[m_pairBufferCount].proxyId1 = pair->proxyId1; - m_pairBuffer[m_pairBufferCount].proxyId2 = pair->proxyId2; - ++m_pairBufferCount; - - b2Assert(m_pairBufferCount <= m_pairCount); - } - - pair->SetRemoved(); - - if (b2BroadPhase::s_validate) - { - ValidateBuffer(); - } -} - -void b2PairManager::Commit() -{ - int32 removeCount = 0; - - b2Proxy* proxies = m_broadPhase->m_proxyPool; - - for (int32 i = 0; i < m_pairBufferCount; ++i) - { - b2Pair* pair = Find(m_pairBuffer[i].proxyId1, m_pairBuffer[i].proxyId2); - b2Assert(pair->IsBuffered()); - pair->ClearBuffered(); - - b2Assert(pair->proxyId1 < b2_maxProxies && pair->proxyId2 < b2_maxProxies); - - b2Proxy* proxy1 = proxies + pair->proxyId1; - b2Proxy* proxy2 = proxies + pair->proxyId2; - - b2Assert(proxy1->IsValid()); - b2Assert(proxy2->IsValid()); - - if (pair->IsRemoved()) - { - // It is possible a pair was added then removed before a commit. Therefore, - // we should be careful not to tell the user the pair was removed when the - // the user didn't receive a matching add. - if (pair->IsFinal() == true) - { - m_callback->PairRemoved(proxy1->userData, proxy2->userData, pair->userData); - } - - // Store the ids so we can actually remove the pair below. - m_pairBuffer[removeCount].proxyId1 = pair->proxyId1; - m_pairBuffer[removeCount].proxyId2 = pair->proxyId2; - ++removeCount; - } - else - { - b2Assert(m_broadPhase->TestOverlap(proxy1, proxy2) == true); - - if (pair->IsFinal() == false) - { - pair->userData = m_callback->PairAdded(proxy1->userData, proxy2->userData); - pair->SetFinal(); - } - } - } - - for (int32 i = 0; i < removeCount; ++i) - { - RemovePair(m_pairBuffer[i].proxyId1, m_pairBuffer[i].proxyId2); - } - - m_pairBufferCount = 0; - - if (b2BroadPhase::s_validate) - { - ValidateTable(); - } -} - -void b2PairManager::ValidateBuffer() -{ -#ifdef _DEBUG - b2Assert(m_pairBufferCount <= m_pairCount); - - std::sort(m_pairBuffer, m_pairBuffer + m_pairBufferCount); - - for (int32 i = 0; i < m_pairBufferCount; ++i) - { - if (i > 0) - { - b2Assert(Equals(m_pairBuffer[i], m_pairBuffer[i-1]) == false); - } - - b2Pair* pair = Find(m_pairBuffer[i].proxyId1, m_pairBuffer[i].proxyId2); - b2Assert(pair->IsBuffered()); - - b2Assert(pair->proxyId1 != pair->proxyId2); - b2Assert(pair->proxyId1 < b2_maxProxies); - b2Assert(pair->proxyId2 < b2_maxProxies); - - b2Proxy* proxy1 = m_broadPhase->m_proxyPool + pair->proxyId1; - b2Proxy* proxy2 = m_broadPhase->m_proxyPool + pair->proxyId2; - - b2Assert(proxy1->IsValid() == true); - b2Assert(proxy2->IsValid() == true); - } -#endif -} - -void b2PairManager::ValidateTable() -{ -#ifdef _DEBUG - for (int32 i = 0; i < b2_tableCapacity; ++i) - { - uint16 index = m_hashTable[i]; - while (index != b2_nullPair) - { - b2Pair* pair = m_pairs + index; - b2Assert(pair->IsBuffered() == false); - b2Assert(pair->IsFinal() == true); - b2Assert(pair->IsRemoved() == false); - - b2Assert(pair->proxyId1 != pair->proxyId2); - b2Assert(pair->proxyId1 < b2_maxProxies); - b2Assert(pair->proxyId2 < b2_maxProxies); - - b2Proxy* proxy1 = m_broadPhase->m_proxyPool + pair->proxyId1; - b2Proxy* proxy2 = m_broadPhase->m_proxyPool + pair->proxyId2; - - b2Assert(proxy1->IsValid() == true); - b2Assert(proxy2->IsValid() == true); - - b2Assert(m_broadPhase->TestOverlap(proxy1, proxy2) == true); - - index = pair->next; - } - } -#endif -} diff --git a/src/modules/physics/box2d/Source/Collision/b2PairManager.h b/src/modules/physics/box2d/Source/Collision/b2PairManager.h deleted file mode 100644 index 236034435..000000000 --- a/src/modules/physics/box2d/Source/Collision/b2PairManager.h +++ /dev/null @@ -1,121 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -// The pair manager is used by the broad-phase to quickly add/remove/find pairs -// of overlapping proxies. It is based closely on code provided by Pierre Terdiman. -// http://www.codercorner.com/IncrementalSAP.txt - -#ifndef B2_PAIR_MANAGER_H -#define B2_PAIR_MANAGER_H - -#include "../Common/b2Settings.h" -#include "../Common/b2Math.h" - -#include - -class b2BroadPhase; -struct b2Proxy; - -const uint16 b2_nullPair = USHRT_MAX; -const uint16 b2_nullProxy = USHRT_MAX; -const int32 b2_tableCapacity = b2_maxPairs; // must be a power of two -const int32 b2_tableMask = b2_tableCapacity - 1; - -struct b2Pair -{ - enum - { - e_pairBuffered = 0x0001, - e_pairRemoved = 0x0002, - e_pairFinal = 0x0004, - }; - - void SetBuffered() { status |= e_pairBuffered; } - void ClearBuffered() { status &= ~e_pairBuffered; } - bool IsBuffered() { return (status & e_pairBuffered) == e_pairBuffered; } - - void SetRemoved() { status |= e_pairRemoved; } - void ClearRemoved() { status &= ~e_pairRemoved; } - bool IsRemoved() { return (status & e_pairRemoved) == e_pairRemoved; } - - void SetFinal() { status |= e_pairFinal; } - bool IsFinal() { return (status & e_pairFinal) == e_pairFinal; } - - void* userData; - uint16 proxyId1; - uint16 proxyId2; - uint16 next; - uint16 status; -}; - -struct b2BufferedPair -{ - uint16 proxyId1; - uint16 proxyId2; -}; - -class b2PairCallback -{ -public: - virtual ~b2PairCallback() {} - - // This should return the new pair user data. It is ok if the - // user data is null. - virtual void* PairAdded(void* proxyUserData1, void* proxyUserData2) = 0; - - // This should free the pair's user data. In extreme circumstances, it is possible - // this will be called with null pairUserData because the pair never existed. - virtual void PairRemoved(void* proxyUserData1, void* proxyUserData2, void* pairUserData) = 0; -}; - -class b2PairManager -{ -public: - b2PairManager(); - - void Initialize(b2BroadPhase* broadPhase, b2PairCallback* callback); - - void AddBufferedPair(int32 proxyId1, int32 proxyId2); - void RemoveBufferedPair(int32 proxyId1, int32 proxyId2); - - void Commit(); - -private: - b2Pair* Find(int32 proxyId1, int32 proxyId2); - b2Pair* Find(int32 proxyId1, int32 proxyId2, uint32 hashValue); - - b2Pair* AddPair(int32 proxyId1, int32 proxyId2); - void* RemovePair(int32 proxyId1, int32 proxyId2); - - void ValidateBuffer(); - void ValidateTable(); - -public: - b2BroadPhase *m_broadPhase; - b2PairCallback *m_callback; - b2Pair m_pairs[b2_maxPairs]; - uint16 m_freePair; - int32 m_pairCount; - - b2BufferedPair m_pairBuffer[b2_maxPairs]; - int32 m_pairBufferCount; - - uint16 m_hashTable[b2_tableCapacity]; -}; - -#endif diff --git a/src/modules/physics/box2d/Source/Collision/b2TimeOfImpact.cpp b/src/modules/physics/box2d/Source/Collision/b2TimeOfImpact.cpp deleted file mode 100644 index 448c5d225..000000000 --- a/src/modules/physics/box2d/Source/Collision/b2TimeOfImpact.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* -* Copyright (c) 2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2Collision.h" -#include "Shapes/b2Shape.h" - -// This algorithm uses conservative advancement to compute the time of -// impact (TOI) of two shapes. -// Refs: Bullet, Young Kim -float32 b2TimeOfImpact(const b2Shape* shape1, const b2Sweep& sweep1, - const b2Shape* shape2, const b2Sweep& sweep2) -{ - float32 r1 = shape1->GetSweepRadius(); - float32 r2 = shape2->GetSweepRadius(); - - b2Assert(sweep1.t0 == sweep2.t0); - b2Assert(1.0f - sweep1.t0 > B2_FLT_EPSILON); - - float32 t0 = sweep1.t0; - b2Vec2 v1 = sweep1.c - sweep1.c0; - b2Vec2 v2 = sweep2.c - sweep2.c0; - float32 omega1 = sweep1.a - sweep1.a0; - float32 omega2 = sweep2.a - sweep2.a0; - - float32 alpha = 0.0f; - - b2Vec2 p1, p2; - const int32 k_maxIterations = 20; // TODO_ERIN b2Settings - int32 iter = 0; - b2Vec2 normal = b2Vec2_zero; - float32 distance = 0.0f; - float32 targetDistance = 0.0f; - for(;;) - { - float32 t = (1.0f - alpha) * t0 + alpha; - b2XForm xf1, xf2; - sweep1.GetXForm(&xf1, t); - sweep2.GetXForm(&xf2, t); - - // Get the distance between shapes. - distance = b2Distance(&p1, &p2, shape1, xf1, shape2, xf2); - - if (iter == 0) - { - // Compute a reasonable target distance to give some breathing room - // for conservative advancement. - if (distance > 2.0f * b2_toiSlop) - { - targetDistance = 1.5f * b2_toiSlop; - } - else - { - targetDistance = b2Max(0.05f * b2_toiSlop, distance - 0.5f * b2_toiSlop); - } - } - - if (distance - targetDistance < 0.05f * b2_toiSlop || iter == k_maxIterations) - { - break; - } - - normal = p2 - p1; - normal.Normalize(); - - // Compute upper bound on remaining movement. - float32 approachVelocityBound = b2Dot(normal, v1 - v2) + b2Abs(omega1) * r1 + b2Abs(omega2) * r2; - if (b2Abs(approachVelocityBound) < B2_FLT_EPSILON) - { - alpha = 1.0f; - break; - } - - // Get the conservative time increment. Don't advance all the way. - float32 dAlpha = (distance - targetDistance) / approachVelocityBound; - //float32 dt = (distance - 0.5f * b2_linearSlop) / approachVelocityBound; - float32 newAlpha = alpha + dAlpha; - - // The shapes may be moving apart or a safe distance apart. - if (newAlpha < 0.0f || 1.0f < newAlpha) - { - alpha = 1.0f; - break; - } - - // Ensure significant advancement. - if (newAlpha < (1.0f + 100.0f * B2_FLT_EPSILON) * alpha) - { - break; - } - - alpha = newAlpha; - - ++iter; - } - - return alpha; -} diff --git a/src/modules/physics/box2d/Source/Common/Fixed.h b/src/modules/physics/box2d/Source/Common/Fixed.h deleted file mode 100644 index b4d4d3be7..000000000 --- a/src/modules/physics/box2d/Source/Common/Fixed.h +++ /dev/null @@ -1,477 +0,0 @@ -/* -Copyright (c) 2006 Henry Strickland & Ryan Seto - 2007-2008 Tobias Weyand (modifications and extensions) - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. - - (* http://www.opensource.org/licenses/mit-license.php *) -*/ - -#ifndef _FIXED_H_ -#define _FIXED_H_ - -#include - -#ifdef TARGET_IS_NDS - -#include "nds.h" - -#endif - -#define FIXED_BP 16 -#define FIXED_MAX ((1<<(32-FIXED_BP-1))-1) -#define FIXED_MIN (-(1<<(32-FIXED_BP-1))) -#define FIXED_EPSILON (Fixed(0.00007f)) - -#define G_1_DIV_PI 20861 - -class Fixed { - - private: - - int g; // the guts - - const static int BP= FIXED_BP; // how many low bits are right of Binary Point - const static int BP2= BP*2; // how many low bits are right of Binary Point - const static int BPhalf= BP/2; // how many low bits are right of Binary Point - - double STEP(); // smallest step we can represent - - // for private construction via guts - enum FixedRaw { RAW }; - Fixed(FixedRaw, int guts); - - public: - - Fixed(); - Fixed(const Fixed &a); - Fixed(float a); - Fixed(double a); - Fixed(int a); - Fixed(long a); - - Fixed& operator =(const Fixed a); - Fixed& operator =(float a); - Fixed& operator =(double a); - Fixed& operator =(int a); - Fixed& operator =(long a); - - operator float(); - operator double(); - operator int(); - operator long(); - operator unsigned short(); - - operator float() const; - - Fixed operator +() const; - Fixed operator -() const; - - Fixed operator +(const Fixed a) const; - Fixed operator -(const Fixed a) const; -#if 1 - // more acurate, using long long - Fixed operator *(const Fixed a) const; -#else - // faster, but with only half as many bits right of binary point - Fixed operator *(const Fixed a) const; -#endif - Fixed operator /(const Fixed a) const; - - Fixed operator *(unsigned short a) const; - Fixed operator *(int a) const; - - Fixed operator +(float a) const; - Fixed operator -(float a) const; - Fixed operator *(float a) const; - Fixed operator /(float a) const; - - Fixed operator +(double a) const; - Fixed operator -(double a) const; - Fixed operator *(double a) const; - Fixed operator /(double a) const; - - Fixed operator >>(int a) const; - Fixed operator <<(int a) const; - - Fixed& operator +=(Fixed a); - Fixed& operator -=(Fixed a); - Fixed& operator *=(Fixed a); - Fixed& operator /=(Fixed a); - - Fixed& operator +=(int a); - Fixed& operator -=(int a); - Fixed& operator *=(int a); - Fixed& operator /=(int a); - - Fixed& operator +=(long a); - Fixed& operator -=(long a); - Fixed& operator *=(long a); - Fixed& operator /=(long a); - - Fixed& operator +=(float a); - Fixed& operator -=(float a); - Fixed& operator *=(float a); - Fixed& operator /=(float a); - - Fixed& operator +=(double a); - Fixed& operator -=(double a); - Fixed& operator *=(double a); - Fixed& operator /=(double a); - - bool operator ==(const Fixed a) const; - bool operator !=(const Fixed a) const; - bool operator <=(const Fixed a) const; - bool operator >=(const Fixed a) const; - bool operator <(const Fixed a) const; - bool operator >(const Fixed a) const; - - bool operator ==(float a) const; - bool operator !=(float a) const; - bool operator <=(float a) const; - bool operator >=(float a) const; - bool operator <(float a) const; - bool operator >(float a) const; - - bool operator ==(double a) const; - bool operator !=(double a) const; - bool operator <=(double a) const; - bool operator >=(double a) const; - bool operator <(double a) const; - bool operator >(double a) const; - - bool operator >(int a) const; - bool operator <(int a) const; - bool operator >=(int a) const; - bool operator <=(int a) const; - - Fixed abs(); - Fixed sqrt(); -#ifdef TARGET_IS_NDS - Fixed cosf(); - Fixed sinf(); - Fixed tanf(); -#endif -}; - -// -// Implementation -// - -inline double Fixed::STEP() { return 1.0 / (1<>BP; } -inline Fixed::operator long() { return g>>BP; } -//#pragma warning(disable: 4244) //HARDWIRE added pragma to prevent VS2005 compilation error -inline Fixed::operator unsigned short() { return g>>BP; } -inline Fixed::operator float() const { return g / (float)(1<> BP)); } - -#elif 0 - -// check for overflow and figure out where. Must specify -rdynamic in linker -#include -#include -#include - -inline Fixed Fixed::operator *(const Fixed a) const { - long long x = ((long long)g * (long long)a.g ); - if(x > 0x7fffffffffffLL || x < -0x7fffffffffffLL) { - printf("overflow"); - void *array[2]; - int nSize = backtrace(array, 2); - char **symbols = backtrace_symbols(array, nSize); - for(int i=0; i>BP)); -} - -#else -// faster, but with only half as many bits right of binary point -inline Fixed Fixed::operator *(const Fixed a) const { return Fixed(RAW, (g>>BPhalf) * (a.g>>BPhalf) ); } -#endif - - -#ifdef TARGET_IS_NDS -// Division using the DS's maths coprocessor -inline Fixed Fixed::operator /(const Fixed a) const -{ - //printf("%d %d\n", (long long)g << BP, a.g); - return Fixed(RAW, int( div64((long long)g << BP, a.g) ) ); -} -#else -inline Fixed Fixed::operator /(const Fixed a) const -{ - return Fixed(RAW, int( (((long long)g << BP2) / (long long)(a.g)) >> BP) ); - //return Fixed(RAW, int( (((long long)g << BP) / (long long)(a.g)) ) ); -} -#endif - -inline Fixed Fixed::operator *(unsigned short a) const { return operator*(Fixed(a)); } -inline Fixed Fixed::operator *(int a) const { return operator*(Fixed(a)); } - -inline Fixed Fixed::operator +(float a) const { return Fixed(RAW, g + Fixed(a).g); } -inline Fixed Fixed::operator -(float a) const { return Fixed(RAW, g - Fixed(a).g); } -inline Fixed Fixed::operator *(float a) const { return Fixed(RAW, (g>>BPhalf) * (Fixed(a).g>>BPhalf) ); } -//inline Fixed Fixed::operator /(float a) const { return Fixed(RAW, int( (((long long)g << BP2) / (long long)(Fixed(a).g)) >> BP) ); } -inline Fixed Fixed::operator /(float a) const { return operator/(Fixed(a)); } - -inline Fixed Fixed::operator +(double a) const { return Fixed(RAW, g + Fixed(a).g); } -inline Fixed Fixed::operator -(double a) const { return Fixed(RAW, g - Fixed(a).g); } -inline Fixed Fixed::operator *(double a) const { return Fixed(RAW, (g>>BPhalf) * (Fixed(a).g>>BPhalf) ); } -//inline Fixed Fixed::operator /(double a) const { return Fixed(RAW, int( (((long long)g << BP2) / (long long)(Fixed(a).g)) >> BP) ); } -inline Fixed Fixed::operator /(double a) const { return operator/(Fixed(a)); } - -inline Fixed Fixed::operator >>(int a) const { return Fixed(RAW, g >> a); } -inline Fixed Fixed::operator <<(int a) const { return Fixed(RAW, g << a); } - -inline Fixed& Fixed::operator +=(Fixed a) { return *this = *this + a; } -inline Fixed& Fixed::operator -=(Fixed a) { return *this = *this - a; } -inline Fixed& Fixed::operator *=(Fixed a) { return *this = *this * a; } -//inline Fixed& Fixed::operator /=(Fixed a) { return *this = *this / a; } -inline Fixed& Fixed::operator /=(Fixed a) { return *this = operator/(a); } - -inline Fixed& Fixed::operator +=(int a) { return *this = *this + (Fixed)a; } -inline Fixed& Fixed::operator -=(int a) { return *this = *this - (Fixed)a; } -inline Fixed& Fixed::operator *=(int a) { return *this = *this * (Fixed)a; } -//inline Fixed& Fixed::operator /=(int a) { return *this = *this / (Fixed)a; } -inline Fixed& Fixed::operator /=(int a) { return *this = operator/((Fixed)a); } - -inline Fixed& Fixed::operator +=(long a) { return *this = *this + (Fixed)a; } -inline Fixed& Fixed::operator -=(long a) { return *this = *this - (Fixed)a; } -inline Fixed& Fixed::operator *=(long a) { return *this = *this * (Fixed)a; } -//inline Fixed& Fixed::operator /=(long a) { return *this = *this / (Fixed)a; } -inline Fixed& Fixed::operator /=(long a) { return *this = operator/((Fixed)a); } - -inline Fixed& Fixed::operator +=(float a) { return *this = *this + a; } -inline Fixed& Fixed::operator -=(float a) { return *this = *this - a; } -inline Fixed& Fixed::operator *=(float a) { return *this = *this * a; } -//inline Fixed& Fixed::operator /=(float a) { return *this = *this / a; } -inline Fixed& Fixed::operator /=(float a) { return *this = operator/(a); } - -inline Fixed& Fixed::operator +=(double a) { return *this = *this + a; } -inline Fixed& Fixed::operator -=(double a) { return *this = *this - a; } -inline Fixed& Fixed::operator *=(double a) { return *this = *this * a; } -//inline Fixed& Fixed::operator /=(double a) { return *this = *this / a; } -inline Fixed& Fixed::operator /=(double a) { return *this = operator/(a); } - -inline Fixed operator +(int a, const Fixed b) { return Fixed(a)+b; } -inline Fixed operator -(int a, const Fixed b) { return Fixed(a)-b; } -inline Fixed operator *(int a, const Fixed b) { return Fixed(a)*b; } -inline Fixed operator /(int a, const Fixed b) { return Fixed(a)/b; }; - -inline Fixed operator +(float a, const Fixed b) { return Fixed(a)+b; } -inline Fixed operator -(float a, const Fixed b) { return Fixed(a)-b; } -inline Fixed operator *(float a, const Fixed b) { return Fixed(a)*b; } -inline Fixed operator /(float a, const Fixed b) { return Fixed(a)/b; } - -inline bool Fixed::operator ==(const Fixed a) const { return g == a.g; } -inline bool Fixed::operator !=(const Fixed a) const { return g != a.g; } -inline bool Fixed::operator <=(const Fixed a) const { return g <= a.g; } -inline bool Fixed::operator >=(const Fixed a) const { return g >= a.g; } -inline bool Fixed::operator <(const Fixed a) const { return g < a.g; } -inline bool Fixed::operator >(const Fixed a) const { return g > a.g; } - -inline bool Fixed::operator ==(float a) const { return g == Fixed(a).g; } -inline bool Fixed::operator !=(float a) const { return g != Fixed(a).g; } -inline bool Fixed::operator <=(float a) const { return g <= Fixed(a).g; } -inline bool Fixed::operator >=(float a) const { return g >= Fixed(a).g; } -inline bool Fixed::operator <(float a) const { return g < Fixed(a).g; } -inline bool Fixed::operator >(float a) const { return g > Fixed(a).g; } - -inline bool Fixed::operator ==(double a) const { return g == Fixed(a).g; } -inline bool Fixed::operator !=(double a) const { return g != Fixed(a).g; } -inline bool Fixed::operator <=(double a) const { return g <= Fixed(a).g; } -inline bool Fixed::operator >=(double a) const { return g >= Fixed(a).g; } -inline bool Fixed::operator <(double a) const { return g < Fixed(a).g; } -inline bool Fixed::operator >(double a) const { return g > Fixed(a).g; } - -inline bool Fixed::operator >(int a) const { return g > Fixed(a).g; } -inline bool Fixed::operator <(int a) const { return g < Fixed(a).g; } -inline bool Fixed::operator >=(int a) const{ return g >= Fixed(a).g; }; -inline bool Fixed::operator <=(int a) const{ return g <= Fixed(a).g; }; - -inline bool operator ==(float a, const Fixed b) { return Fixed(a) == b; } -inline bool operator !=(float a, const Fixed b) { return Fixed(a) != b; } -inline bool operator <=(float a, const Fixed b) { return Fixed(a) <= b; } -inline bool operator >=(float a, const Fixed b) { return Fixed(a) >= b; } -inline bool operator <(float a, const Fixed b) { return Fixed(a) < b; } -inline bool operator >(float a, const Fixed b) { return Fixed(a) > b; } - -inline Fixed operator +(double a, const Fixed b) { return Fixed(a)+b; } -inline Fixed operator -(double a, const Fixed b) { return Fixed(a)-b; } -inline Fixed operator *(double a, const Fixed b) { return Fixed(a)*b; } -inline Fixed operator /(double a, const Fixed b) { return Fixed(a)/b; } - -inline bool operator ==(double a, const Fixed b) { return Fixed(a) == b; } -inline bool operator !=(double a, const Fixed b) { return Fixed(a) != b; } -inline bool operator <=(double a, const Fixed b) { return Fixed(a) <= b; } -inline bool operator >=(double a, const Fixed b) { return Fixed(a) >= b; } -inline bool operator <(double a, const Fixed b) { return Fixed(a) < b; } -inline bool operator >(double a, const Fixed b) { return Fixed(a) > b; } - -inline bool operator ==(int a, const Fixed b) { return Fixed(a) == b; } -inline bool operator !=(int a, const Fixed b) { return Fixed(a) != b; } -inline bool operator <=(int a, const Fixed b) { return Fixed(a) <= b; } -inline bool operator >=(int a, const Fixed b) { return Fixed(a) >= b; } -inline bool operator <(int a, const Fixed b) { return Fixed(a) < b; } -inline bool operator >(int a, const Fixed b) { return Fixed(a) > b; } - -inline int& operator +=(int& a, const Fixed b) { a = (Fixed)a + b; return a; } -inline int& operator -=(int& a, const Fixed b) { a = (Fixed)a - b; return a; } -inline int& operator *=(int& a, const Fixed b) { a = (Fixed)a * b; return a; } -inline int& operator /=(int& a, const Fixed b) { a = (Fixed)a / b; return a; } - -inline long& operator +=(long& a, const Fixed b) { a = (Fixed)a + b; return a; } -inline long& operator -=(long& a, const Fixed b) { a = (Fixed)a - b; return a; } -inline long& operator *=(long& a, const Fixed b) { a = (Fixed)a * b; return a; } -inline long& operator /=(long& a, const Fixed b) { a = (Fixed)a / b; return a; } - -inline float& operator +=(float& a, const Fixed b) { a = a + b; return a; } -inline float& operator -=(float& a, const Fixed b) { a = a - b; return a; } -inline float& operator *=(float& a, const Fixed b) { a = a * b; return a; } -inline float& operator /=(float& a, const Fixed b) { a = a / b; return a; } - -inline double& operator +=(double& a, const Fixed b) { a = a + b; return a; } -inline double& operator -=(double& a, const Fixed b) { a = a - b; return a; } -inline double& operator *=(double& a, const Fixed b) { a = a * b; return a; } -inline double& operator /=(double& a, const Fixed b) { a = a / b; return a; } - -inline Fixed Fixed::abs() { return (g>0) ? Fixed(RAW, g) : Fixed(RAW, -g); } -inline Fixed abs(Fixed f) { return f.abs(); } - -//inline Fixed atan2(Fixed a, Fixed b) { return atan2f((float) a, (float) b); } -inline Fixed atan2(Fixed y, Fixed x) -{ - Fixed abs_y = y.abs() + FIXED_EPSILON; // avoid 0/0 - Fixed r, angle; - - if(x >= 0.0f) { - r = (x - abs_y) / (x + abs_y); - angle = 3.1415926/4.0; - } else { - r = (x + abs_y) / (abs_y - x); - angle = 3.0*3.1415926/4.0; - } - angle += Fixed(0.1963) * (r * r * r) - Fixed(0.9817) * r; - return (y < 0) ? -angle : angle; -} - -#if TARGET_IS_NDS - -static inline long nds_sqrt64(long long a) -{ - SQRT_CR = SQRT_64; - while(SQRT_CR & SQRT_BUSY); - SQRT_PARAM64 = a; - while(SQRT_CR & SQRT_BUSY); - - return SQRT_RESULT32; -} - -static inline int32 div6464(int64 num, int64 den) -{ - DIV_CR = DIV_64_64; - while(DIV_CR & DIV_BUSY); - DIV_NUMERATOR64 = num; - DIV_DENOMINATOR64 = den; - while(DIV_CR & DIV_BUSY); - - return (DIV_RESULT32); -} - -inline Fixed Fixed::sqrt() -{ - return Fixed(RAW, nds_sqrt64(((long long)(g))<>= 2 ) - { - if ( ( left & -m ) > root ) - left -= ( root += m ), root += m; - root >>= 1; - } - return Fixed(RAW, root); -} -#endif - -inline Fixed sqrt(Fixed a) { return a.sqrt(); } -inline Fixed sqrtf(Fixed a) { return a.sqrt(); } - -#endif - -#ifdef TARGET_IS_NDS -// Use the libnds lookup tables for trigonometry functions -inline Fixed Fixed::cosf() { - int idx = (((long long)g*(long long)G_1_DIV_PI)>>24)%512; - if(idx < 0) - idx += 512; - return Fixed(RAW, COS_bin[idx] << 4); -} -inline Fixed cosf(Fixed x) { return x.cosf(); } -inline Fixed Fixed::sinf() { - int idx = (((long long)g*(long long)G_1_DIV_PI)>>24)%512; - if(idx < 0) - idx += 512; - return Fixed(RAW, SIN_bin[idx] << 4); -} -inline Fixed sinf(Fixed x) { return x.sinf(); } -inline Fixed Fixed::tanf() { - int idx = (((long long)g*(long long)G_1_DIV_PI)>>24)%512; - if(idx < 0) - idx += 512; - return Fixed(RAW, TAN_bin[idx] << 4); -} -inline Fixed tanf(Fixed x) { return x.tanf(); } - - -#endif diff --git a/src/modules/physics/box2d/Source/Common/b2Math.cpp b/src/modules/physics/box2d/Source/Common/b2Math.cpp deleted file mode 100644 index 69162449a..000000000 --- a/src/modules/physics/box2d/Source/Common/b2Math.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* -* Copyright (c) 2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2Math.h" - -const b2Vec2 b2Vec2_zero(0.0f, 0.0f); -const b2Mat22 b2Mat22_identity(1.0f, 0.0f, 0.0f, 1.0f); -const b2XForm b2XForm_identity(b2Vec2_zero, b2Mat22_identity); - -void b2Sweep::GetXForm(b2XForm* xf, float32 t) const -{ - // center = p + R * localCenter - if (1.0f - t0 > B2_FLT_EPSILON) - { - float32 alpha = (t - t0) / (1.0f - t0); - xf->position = (1.0f - alpha) * c0 + alpha * c; - float32 angle = (1.0f - alpha) * a0 + alpha * a; - xf->R.Set(angle); - } - else - { - xf->position = c; - xf->R.Set(a); - } - - // Shift to origin - xf->position -= b2Mul(xf->R, localCenter); -} - -void b2Sweep::Advance(float32 t) -{ - if (t0 < t && 1.0f - t0 > B2_FLT_EPSILON) - { - float32 alpha = (t - t0) / (1.0f - t0); - c0 = (1.0f - alpha) * c0 + alpha * c; - a0 = (1.0f - alpha) * a0 + alpha * a; - t0 = t; - } -} diff --git a/src/modules/physics/box2d/Source/Common/jtypes.h b/src/modules/physics/box2d/Source/Common/jtypes.h deleted file mode 100644 index 3747ce54d..000000000 --- a/src/modules/physics/box2d/Source/Common/jtypes.h +++ /dev/null @@ -1,139 +0,0 @@ -/*--------------------------------------------------------------------------------- - $Id: jtypes.h,v 1.17 2007/07/18 05:20:45 wntrmute Exp $ - - jtypes.h -- Common types (and a few useful macros) - - Copyright (C) 2005 - Michael Noland (joat) - Jason Rogers (dovoto) - Dave Murphy (WinterMute) - Chris Double (doublec) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any - damages arising from the use of this software. - - Permission is granted to anyone to use this software for any - purpose, including commercial applications, and to alter it and - redistribute it freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you - must not claim that you wrote the original software. If you use - this software in a product, an acknowledgment in the product - documentation would be appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and - must not be misrepresented as being the original software. - 3. This notice may not be removed or altered from any source - distribution. - ----------------------------------------------------------------------------------*/ -#ifndef NDS_JTYPES_INCLUDE -#define NDS_JTYPES_INCLUDE -//--------------------------------------------------------------------------------- - - -#define PACKED __attribute__ ((packed)) -#define packed_struct struct PACKED - -//--------------------------------------------------------------------------------- -// libgba compatible section macros -//--------------------------------------------------------------------------------- -#define ITCM_CODE __attribute__((section(".itcm"), long_call)) - -#define DTCM_DATA __attribute__((section(".dtcm"))) -#define DTCM_BSS __attribute__((section(".sbss"))) -#define ALIGN(m) __attribute__((aligned (m))) - -#define PACKED __attribute__ ((packed)) -#define packed_struct struct PACKED - -//--------------------------------------------------------------------------------- -// These are linked to the bin2o macro in the Makefile -//--------------------------------------------------------------------------------- -#define GETRAW(name) (name) -#define GETRAWSIZE(name) ((int)name##_size) -#define GETRAWEND(name) ((int)name##_end) - -#ifndef TRUE -#define TRUE 1 -#define FALSE 0 -#endif - -#define BIT(n) (1 << (n)) - -// define libnds types in terms of stdint -#include - -typedef uint8_t uint8; -typedef uint16_t uint16; -typedef uint32_t uint32; -typedef uint64_t uint64; - -typedef int8_t int8; -typedef int16_t int16; -typedef int32_t int32; -typedef int64_t int64; - -//typedef float float32; -typedef double float64; - -typedef volatile uint8_t vuint8; -typedef volatile uint16_t vuint16; -typedef volatile uint32_t vuint32; -typedef volatile uint64_t vuint64; - -typedef volatile int8_t vint8; -typedef volatile int16_t vint16; -typedef volatile int32_t vint32; -typedef volatile int64_t vint64; - -typedef volatile float vfloat32; -typedef volatile float64 vfloat64; - -typedef uint8_t byte; - -typedef uint8_t u8; -typedef uint16_t u16; -typedef uint32_t u32; -typedef uint64_t u64; - -typedef int8_t s8; -typedef int16_t s16; -typedef int32_t s32; -typedef int64_t s64; - -typedef volatile u8 vu8; -typedef volatile u16 vu16; -typedef volatile u32 vu32; -typedef volatile u64 vu64; - -typedef volatile s8 vs8; -typedef volatile s16 vs16; -typedef volatile s32 vs32; -typedef volatile s64 vs64; - -typedef struct touchPosition { - int16 x; - int16 y; - int16 px; - int16 py; - int16 z1; - int16 z2; -} touchPosition; - - -#ifndef __cplusplus -/** C++ compatible bool for C - -*/ -typedef enum { false, true } bool; -#endif - -// Handy function pointer typedefs -typedef void ( * IntFn)(void); -typedef void (* VoidFunctionPointer)(void); -typedef void (* fp)(void); - -//--------------------------------------------------------------------------------- -#endif -//--------------------------------------------------------------------------------- diff --git a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2CircleContact.cpp b/src/modules/physics/box2d/Source/Dynamics/Contacts/b2CircleContact.cpp deleted file mode 100644 index 8b73cb350..000000000 --- a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2CircleContact.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2CircleContact.h" -#include "../b2Body.h" -#include "../b2WorldCallbacks.h" -#include "../../Common/b2BlockAllocator.h" - -#include -#include - -b2Contact* b2CircleContact::Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2CircleContact)); - return new (mem) b2CircleContact(shape1, shape2); -} - -void b2CircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2CircleContact*)contact)->~b2CircleContact(); - allocator->Free(contact, sizeof(b2CircleContact)); -} - -b2CircleContact::b2CircleContact(b2Shape* s1, b2Shape* s2) -: b2Contact(s1, s2) -{ - b2Assert(m_shape1->GetType() == e_circleShape); - b2Assert(m_shape2->GetType() == e_circleShape); - m_manifold.pointCount = 0; - m_manifold.points[0].normalImpulse = 0.0f; - m_manifold.points[0].tangentImpulse = 0.0f; -} - -void b2CircleContact::Evaluate(b2ContactListener* listener) -{ - b2Body* b1 = m_shape1->GetBody(); - b2Body* b2 = m_shape2->GetBody(); - - b2Manifold m0; - memcpy(&m0, &m_manifold, sizeof(b2Manifold)); - - b2CollideCircles(&m_manifold, (b2CircleShape*)m_shape1, b1->GetXForm(), (b2CircleShape*)m_shape2, b2->GetXForm()); - - b2ContactPoint cp; - cp.shape1 = m_shape1; - cp.shape2 = m_shape2; - cp.friction = m_friction; - cp.restitution = m_restitution; - - if (m_manifold.pointCount > 0) - { - m_manifoldCount = 1; - b2ManifoldPoint* mp = m_manifold.points + 0; - - if (m0.pointCount == 0) - { - mp->normalImpulse = 0.0f; - mp->tangentImpulse = 0.0f; - - if (listener) - { - cp.position = b1->GetWorldPoint(mp->localPoint1); - b2Vec2 v1 = b1->GetLinearVelocityFromLocalPoint(mp->localPoint1); - b2Vec2 v2 = b2->GetLinearVelocityFromLocalPoint(mp->localPoint2); - cp.velocity = v2 - v1; - cp.normal = m_manifold.normal; - cp.separation = mp->separation; - cp.id = mp->id; - listener->Add(&cp); - } - } - else - { - b2ManifoldPoint* mp0 = m0.points + 0; - mp->normalImpulse = mp0->normalImpulse; - mp->tangentImpulse = mp0->tangentImpulse; - - if (listener) - { - cp.position = b1->GetWorldPoint(mp->localPoint1); - b2Vec2 v1 = b1->GetLinearVelocityFromLocalPoint(mp->localPoint1); - b2Vec2 v2 = b2->GetLinearVelocityFromLocalPoint(mp->localPoint2); - cp.velocity = v2 - v1; - cp.normal = m_manifold.normal; - cp.separation = mp->separation; - cp.id = mp->id; - listener->Persist(&cp); - } - } - } - else - { - m_manifoldCount = 0; - if (m0.pointCount > 0 && listener) - { - b2ManifoldPoint* mp0 = m0.points + 0; - cp.position = b1->GetWorldPoint(mp0->localPoint1); - b2Vec2 v1 = b1->GetLinearVelocityFromLocalPoint(mp0->localPoint1); - b2Vec2 v2 = b2->GetLinearVelocityFromLocalPoint(mp0->localPoint2); - cp.velocity = v2 - v1; - cp.normal = m0.normal; - cp.separation = mp0->separation; - cp.id = mp0->id; - listener->Remove(&cp); - } - } -} diff --git a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2Contact.cpp b/src/modules/physics/box2d/Source/Dynamics/Contacts/b2Contact.cpp deleted file mode 100644 index 3de5057fa..000000000 --- a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2Contact.cpp +++ /dev/null @@ -1,172 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2Contact.h" -#include "b2CircleContact.h" -#include "b2PolyAndCircleContact.h" -#include "b2PolyContact.h" -#include "b2ContactSolver.h" -#include "../../Collision/b2Collision.h" -#include "../../Collision/Shapes/b2Shape.h" -#include "../../Common/b2BlockAllocator.h" -#include "../../Dynamics/b2World.h" -#include "../../Dynamics/b2Body.h" - -b2ContactRegister b2Contact::s_registers[e_shapeTypeCount][e_shapeTypeCount]; -bool b2Contact::s_initialized = false; - -void b2Contact::InitializeRegisters() -{ - AddType(b2CircleContact::Create, b2CircleContact::Destroy, e_circleShape, e_circleShape); - AddType(b2PolyAndCircleContact::Create, b2PolyAndCircleContact::Destroy, e_polygonShape, e_circleShape); - AddType(b2PolygonContact::Create, b2PolygonContact::Destroy, e_polygonShape, e_polygonShape); -} - -void b2Contact::AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destoryFcn, - b2ShapeType type1, b2ShapeType type2) -{ - b2Assert(e_unknownShape < type1 && type1 < e_shapeTypeCount); - b2Assert(e_unknownShape < type2 && type2 < e_shapeTypeCount); - - s_registers[type1][type2].createFcn = createFcn; - s_registers[type1][type2].destroyFcn = destoryFcn; - s_registers[type1][type2].primary = true; - - if (type1 != type2) - { - s_registers[type2][type1].createFcn = createFcn; - s_registers[type2][type1].destroyFcn = destoryFcn; - s_registers[type2][type1].primary = false; - } -} - -b2Contact* b2Contact::Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator) -{ - if (s_initialized == false) - { - InitializeRegisters(); - s_initialized = true; - } - - b2ShapeType type1 = shape1->GetType(); - b2ShapeType type2 = shape2->GetType(); - - b2Assert(e_unknownShape < type1 && type1 < e_shapeTypeCount); - b2Assert(e_unknownShape < type2 && type2 < e_shapeTypeCount); - - b2ContactCreateFcn* createFcn = s_registers[type1][type2].createFcn; - if (createFcn) - { - if (s_registers[type1][type2].primary) - { - return createFcn(shape1, shape2, allocator); - } - else - { - b2Contact* c = createFcn(shape2, shape1, allocator); - for (int32 i = 0; i < c->GetManifoldCount(); ++i) - { - b2Manifold* m = c->GetManifolds() + i; - m->normal = -m->normal; - } - return c; - } - } - else - { - return NULL; - } -} - -void b2Contact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - b2Assert(s_initialized == true); - - if (contact->GetManifoldCount() > 0) - { - contact->GetShape1()->GetBody()->WakeUp(); - contact->GetShape2()->GetBody()->WakeUp(); - } - - b2ShapeType type1 = contact->GetShape1()->GetType(); - b2ShapeType type2 = contact->GetShape2()->GetType(); - - b2Assert(e_unknownShape < type1 && type1 < e_shapeTypeCount); - b2Assert(e_unknownShape < type2 && type2 < e_shapeTypeCount); - - b2ContactDestroyFcn* destroyFcn = s_registers[type1][type2].destroyFcn; - destroyFcn(contact, allocator); -} - -b2Contact::b2Contact(b2Shape* s1, b2Shape* s2) -{ - m_flags = 0; - - if (s1->IsSensor() || s2->IsSensor()) - { - m_flags |= e_nonSolidFlag; - } - - m_shape1 = s1; - m_shape2 = s2; - - m_manifoldCount = 0; - - m_friction = b2MixFriction(m_shape1->GetFriction(), m_shape2->GetFriction()); - m_restitution = b2MixRestitution(m_shape1->GetRestitution(), m_shape2->GetRestitution()); - m_prev = NULL; - m_next = NULL; - - m_node1.contact = NULL; - m_node1.prev = NULL; - m_node1.next = NULL; - m_node1.other = NULL; - - m_node2.contact = NULL; - m_node2.prev = NULL; - m_node2.next = NULL; - m_node2.other = NULL; -} - -void b2Contact::Update(b2ContactListener* listener) -{ - int32 oldCount = GetManifoldCount(); - - Evaluate(listener); - - int32 newCount = GetManifoldCount(); - - b2Body* body1 = m_shape1->GetBody(); - b2Body* body2 = m_shape2->GetBody(); - - if (newCount == 0 && oldCount > 0) - { - body1->WakeUp(); - body2->WakeUp(); - } - - // Slow contacts don't generate TOI events. - if (body1->IsStatic() || body1->IsBullet() || body2->IsStatic() || body2->IsBullet()) - { - m_flags &= ~e_slowFlag; - } - else - { - m_flags |= e_slowFlag; - } -} diff --git a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2Contact.h b/src/modules/physics/box2d/Source/Dynamics/Contacts/b2Contact.h deleted file mode 100644 index 3d6f0dae4..000000000 --- a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2Contact.h +++ /dev/null @@ -1,183 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef CONTACT_H -#define CONTACT_H - -#include "../../Common/b2Math.h" -#include "../../Collision/b2Collision.h" -#include "../../Collision/Shapes/b2Shape.h" - -class b2Body; -class b2Contact; -class b2World; -class b2BlockAllocator; -class b2StackAllocator; -class b2ContactListener; - -typedef b2Contact* b2ContactCreateFcn(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator); -typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator); - -struct b2ContactRegister -{ - b2ContactCreateFcn* createFcn; - b2ContactDestroyFcn* destroyFcn; - bool primary; -}; - -/// A contact edge is used to connect bodies and contacts together -/// in a contact graph where each body is a node and each contact -/// is an edge. A contact edge belongs to a doubly linked list -/// maintained in each attached body. Each contact has two contact -/// nodes, one for each attached body. -struct b2ContactEdge -{ - b2Body* other; ///< provides quick access to the other body attached. - b2Contact* contact; ///< the contact - b2ContactEdge* prev; ///< the previous contact edge in the body's contact list - b2ContactEdge* next; ///< the next contact edge in the body's contact list -}; - -/// This structure is used to report contact points. -struct b2ContactPoint -{ - b2Shape* shape1; ///< the first shape - b2Shape* shape2; ///< the second shape - b2Vec2 position; ///< position in world coordinates - b2Vec2 velocity; ///< velocity of point on body2 relative to point on body1 (pre-solver) - b2Vec2 normal; ///< points from shape1 to shape2 - float32 separation; ///< the separation is negative when shapes are touching - float32 friction; ///< the combined friction coefficient - float32 restitution; ///< the combined restitution coefficient - b2ContactID id; ///< the contact id identifies the features in contact -}; - -/// This structure is used to report contact point results. -struct b2ContactResult -{ - b2Shape* shape1; ///< the first shape - b2Shape* shape2; ///< the second shape - b2Vec2 position; ///< position in world coordinates - b2Vec2 normal; ///< points from shape1 to shape2 - float32 normalImpulse; ///< the normal impulse applied to body2 - float32 tangentImpulse; ///< the tangent impulse applied to body2 - b2ContactID id; ///< the contact id identifies the features in contact -}; - -/// The class manages contact between two shapes. A contact exists for each overlapping -/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist -/// that has no contact points. -class b2Contact -{ -public: - - /// Get the manifold array. - virtual b2Manifold* GetManifolds() = 0; - - /// Get the number of manifolds. This is 0 or 1 between convex shapes. - /// This may be greater than 1 for convex-vs-concave shapes. Each - /// manifold holds up to two contact points with a shared contact normal. - int32 GetManifoldCount() const; - - /// Is this contact solid? - /// @return true if this contact should generate a response. - bool IsSolid() const; - - /// Get the next contact in the world's contact list. - b2Contact* GetNext(); - - /// Get the first shape in this contact. - b2Shape* GetShape1(); - - /// Get the second shape in this contact. - b2Shape* GetShape2(); - - //--------------- Internals Below ------------------- -public: - - // m_flags - enum - { - e_nonSolidFlag = 0x0001, - e_slowFlag = 0x0002, - e_islandFlag = 0x0004, - e_toiFlag = 0x0008, - }; - - static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn, - b2ShapeType type1, b2ShapeType type2); - static void InitializeRegisters(); - static b2Contact* Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2Contact() : m_shape1(NULL), m_shape2(NULL) {} - b2Contact(b2Shape* shape1, b2Shape* shape2); - virtual ~b2Contact() {} - - void Update(b2ContactListener* listener); - virtual void Evaluate(b2ContactListener* listener) = 0; - static b2ContactRegister s_registers[e_shapeTypeCount][e_shapeTypeCount]; - static bool s_initialized; - - uint32 m_flags; - int32 m_manifoldCount; - - // World pool and list pointers. - b2Contact* m_prev; - b2Contact* m_next; - - // Nodes for connecting bodies. - b2ContactEdge m_node1; - b2ContactEdge m_node2; - - b2Shape* m_shape1; - b2Shape* m_shape2; - - // Combined friction - float32 m_friction; - float32 m_restitution; - - float32 m_toi; -}; - -inline int32 b2Contact::GetManifoldCount() const -{ - return m_manifoldCount; -} - -inline bool b2Contact::IsSolid() const -{ - return (m_flags & e_nonSolidFlag) == 0; -} - -inline b2Contact* b2Contact::GetNext() -{ - return m_next; -} - -inline b2Shape* b2Contact::GetShape1() -{ - return m_shape1; -} - -inline b2Shape* b2Contact::GetShape2() -{ - return m_shape2; -} - -#endif diff --git a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2ContactSolver.cpp b/src/modules/physics/box2d/Source/Dynamics/Contacts/b2ContactSolver.cpp deleted file mode 100644 index bc82d2558..000000000 --- a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2ContactSolver.cpp +++ /dev/null @@ -1,360 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2ContactSolver.h" -#include "b2Contact.h" -#include "../b2Body.h" -#include "../b2World.h" -#include "../../Common/b2StackAllocator.h" - -b2ContactSolver::b2ContactSolver(const b2TimeStep& step, b2Contact** contacts, int32 contactCount, b2StackAllocator* allocator) -{ - m_step = step; - m_allocator = allocator; - - m_constraintCount = 0; - for (int32 i = 0; i < contactCount; ++i) - { - b2Assert(contacts[i]->IsSolid()); - m_constraintCount += contacts[i]->GetManifoldCount(); - } - - m_constraints = (b2ContactConstraint*)m_allocator->Allocate(m_constraintCount * sizeof(b2ContactConstraint)); - - int32 count = 0; - for (int32 i = 0; i < contactCount; ++i) - { - b2Contact* contact = contacts[i]; - - b2Body* b1 = contact->m_shape1->GetBody(); - b2Body* b2 = contact->m_shape2->GetBody(); - int32 manifoldCount = contact->GetManifoldCount(); - b2Manifold* manifolds = contact->GetManifolds(); - float32 friction = contact->m_friction; - float32 restitution = contact->m_restitution; - - b2Vec2 v1 = b1->m_linearVelocity; - b2Vec2 v2 = b2->m_linearVelocity; - float32 w1 = b1->m_angularVelocity; - float32 w2 = b2->m_angularVelocity; - - for (int32 j = 0; j < manifoldCount; ++j) - { - b2Manifold* manifold = manifolds + j; - - b2Assert(manifold->pointCount > 0); - - const b2Vec2 normal = manifold->normal; - - b2Assert(count < m_constraintCount); - b2ContactConstraint* c = m_constraints + count; - c->body1 = b1; - c->body2 = b2; - c->manifold = manifold; - c->normal = normal; - c->pointCount = manifold->pointCount; - c->friction = friction; - c->restitution = restitution; - - for (int32 k = 0; k < c->pointCount; ++k) - { - b2ManifoldPoint* cp = manifold->points + k; - b2ContactConstraintPoint* ccp = c->points + k; - - ccp->normalImpulse = cp->normalImpulse; - ccp->tangentImpulse = cp->tangentImpulse; - ccp->separation = cp->separation; - ccp->positionImpulse = 0.0f; - - ccp->localAnchor1 = cp->localPoint1; - ccp->localAnchor2 = cp->localPoint2; - ccp->r1 = b2Mul(b1->GetXForm().R, cp->localPoint1 - b1->GetLocalCenter()); - ccp->r2 = b2Mul(b2->GetXForm().R, cp->localPoint2 - b2->GetLocalCenter()); - - float32 r1Sqr = b2Dot(ccp->r1, ccp->r1); - float32 r2Sqr = b2Dot(ccp->r2, ccp->r2); - float32 rn1 = b2Dot(ccp->r1, normal); - float32 rn2 = b2Dot(ccp->r2, normal); - - float32 kNormal = b1->m_invMass + b2->m_invMass; - kNormal += b1->m_invI * (r1Sqr - rn1 * rn1) + b2->m_invI * (r2Sqr - rn2 * rn2); - - b2Assert(kNormal > B2_FLT_EPSILON); - ccp->normalMass = 1.0f / kNormal; - - float32 kEqualized = b1->m_mass * b1->m_invMass + b2->m_mass * b2->m_invMass; - kEqualized += b1->m_mass * b1->m_invI * (r1Sqr - rn1 * rn1) + b2->m_mass * b2->m_invI * (r2Sqr - rn2 * rn2); - - b2Assert(kEqualized > B2_FLT_EPSILON); - ccp->equalizedMass = 1.0f / kEqualized; - - b2Vec2 tangent = b2Cross(normal, 1.0f); - - float32 rt1 = b2Dot(ccp->r1, tangent); - float32 rt2 = b2Dot(ccp->r2, tangent); - float32 kTangent = b1->m_invMass + b2->m_invMass; - kTangent += b1->m_invI * (r1Sqr - rt1 * rt1) + b2->m_invI * (r2Sqr - rt2 * rt2); - - b2Assert(kTangent > B2_FLT_EPSILON); - ccp->tangentMass = 1.0f / kTangent; - - // Setup a velocity bias for restitution. - ccp->velocityBias = 0.0f; - if (ccp->separation > 0.0f) - { - ccp->velocityBias = -60.0f * ccp->separation; // TODO_ERIN b2TimeStep - } - - float32 vRel = b2Dot(c->normal, v2 + b2Cross(w2, ccp->r2) - v1 - b2Cross(w1, ccp->r1)); - if (vRel < -b2_velocityThreshold) - { - ccp->velocityBias += -c->restitution * vRel; - } - } - - ++count; - } - } - - b2Assert(count == m_constraintCount); -} - -b2ContactSolver::~b2ContactSolver() -{ - m_allocator->Free(m_constraints); -} - -void b2ContactSolver::InitVelocityConstraints(const b2TimeStep& step) -{ - // Warm start. - for (int32 i = 0; i < m_constraintCount; ++i) - { - b2ContactConstraint* c = m_constraints + i; - - b2Body* b1 = c->body1; - b2Body* b2 = c->body2; - float32 invMass1 = b1->m_invMass; - float32 invI1 = b1->m_invI; - float32 invMass2 = b2->m_invMass; - float32 invI2 = b2->m_invI; - b2Vec2 normal = c->normal; - b2Vec2 tangent = b2Cross(normal, 1.0f); - - if (step.warmStarting) - { - for (int32 j = 0; j < c->pointCount; ++j) - { - b2ContactConstraintPoint* ccp = c->points + j; - ccp->normalImpulse *= step.dtRatio; - ccp->tangentImpulse *= step.dtRatio; - b2Vec2 P = ccp->normalImpulse * normal + ccp->tangentImpulse * tangent; - b1->m_angularVelocity -= invI1 * b2Cross(ccp->r1, P); - b1->m_linearVelocity -= invMass1 * P; - b2->m_angularVelocity += invI2 * b2Cross(ccp->r2, P); - b2->m_linearVelocity += invMass2 * P; - } - } - else - { - for (int32 j = 0; j < c->pointCount; ++j) - { - b2ContactConstraintPoint* ccp = c->points + j; - ccp->normalImpulse = 0.0f; - ccp->tangentImpulse = 0.0f; - } - } - } -} - -void b2ContactSolver::SolveVelocityConstraints() -{ - for (int32 i = 0; i < m_constraintCount; ++i) - { - b2ContactConstraint* c = m_constraints + i; - b2Body* b1 = c->body1; - b2Body* b2 = c->body2; - float32 w1 = b1->m_angularVelocity; - float32 w2 = b2->m_angularVelocity; - b2Vec2 v1 = b1->m_linearVelocity; - b2Vec2 v2 = b2->m_linearVelocity; - float32 invMass1 = b1->m_invMass; - float32 invI1 = b1->m_invI; - float32 invMass2 = b2->m_invMass; - float32 invI2 = b2->m_invI; - b2Vec2 normal = c->normal; - b2Vec2 tangent = b2Cross(normal, 1.0f); - float32 friction = c->friction; -//#define DEFERRED_UPDATE -#ifdef DEFERRED_UPDATE - b2Vec2 b1_linearVelocity = b1->m_linearVelocity; - float32 b1_angularVelocity = b1->m_angularVelocity; - b2Vec2 b2_linearVelocity = b2->m_linearVelocity; - float32 b2_angularVelocity = b2->m_angularVelocity; -#endif - // Solve normal constraints - for (int32 j = 0; j < c->pointCount; ++j) - { - b2ContactConstraintPoint* ccp = c->points + j; - - // Relative velocity at contact - b2Vec2 dv = v2 + b2Cross(w2, ccp->r2) - v1 - b2Cross(w1, ccp->r1); - - // Compute normal impulse - float32 vn = b2Dot(dv, normal); - float32 lambda = -ccp->normalMass * (vn - ccp->velocityBias); - - // b2Clamp the accumulated impulse - float32 newImpulse = b2Max(ccp->normalImpulse + lambda, 0.0f); - lambda = newImpulse - ccp->normalImpulse; - - // Apply contact impulse - b2Vec2 P = lambda * normal; -#ifdef DEFERRED_UPDATE - b1_linearVelocity -= invMass1 * P; - b1_angularVelocity -= invI1 * b2Cross(r1, P); - - b2_linearVelocity += invMass2 * P; - b2_angularVelocity += invI2 * b2Cross(r2, P); -#else - v1 -= invMass1 * P; - w1 -= invI1 * b2Cross(ccp->r1, P); - - v2 += invMass2 * P; - w2 += invI2 * b2Cross(ccp->r2, P); -#endif - ccp->normalImpulse = newImpulse; - } - -#ifdef DEFERRED_UPDATE - b1->m_linearVelocity = b1_linearVelocity; - b1->m_angularVelocity = b1_angularVelocity; - b2->m_linearVelocity = b2_linearVelocity; - b2->m_angularVelocity = b2_angularVelocity; -#endif - // Solve tangent constraints - for (int32 j = 0; j < c->pointCount; ++j) - { - b2ContactConstraintPoint* ccp = c->points + j; - - // Relative velocity at contact - b2Vec2 dv = v2 + b2Cross(w2, ccp->r2) - v1 - b2Cross(w1, ccp->r1); - - // Compute tangent force - float32 vt = b2Dot(dv, tangent); - float32 lambda = ccp->tangentMass * (-vt); - - // b2Clamp the accumulated force - float32 maxFriction = friction * ccp->normalImpulse; - float32 newImpulse = b2Clamp(ccp->tangentImpulse + lambda, -maxFriction, maxFriction); - lambda = newImpulse - ccp->tangentImpulse; - - // Apply contact impulse - b2Vec2 P = lambda * tangent; - - v1 -= invMass1 * P; - w1 -= invI1 * b2Cross(ccp->r1, P); - - v2 += invMass2 * P; - w2 += invI2 * b2Cross(ccp->r2, P); - - ccp->tangentImpulse = newImpulse; - } - - b1->m_linearVelocity = v1; - b1->m_angularVelocity = w1; - b2->m_linearVelocity = v2; - b2->m_angularVelocity = w2; - } -} - -void b2ContactSolver::FinalizeVelocityConstraints() -{ - for (int32 i = 0; i < m_constraintCount; ++i) - { - b2ContactConstraint* c = m_constraints + i; - b2Manifold* m = c->manifold; - - for (int32 j = 0; j < c->pointCount; ++j) - { - m->points[j].normalImpulse = c->points[j].normalImpulse; - m->points[j].tangentImpulse = c->points[j].tangentImpulse; - } - } -} - -bool b2ContactSolver::SolvePositionConstraints(float32 baumgarte) -{ - float32 minSeparation = 0.0f; - - for (int32 i = 0; i < m_constraintCount; ++i) - { - b2ContactConstraint* c = m_constraints + i; - b2Body* b1 = c->body1; - b2Body* b2 = c->body2; - float32 invMass1 = b1->m_mass * b1->m_invMass; - float32 invI1 = b1->m_mass * b1->m_invI; - float32 invMass2 = b2->m_mass * b2->m_invMass; - float32 invI2 = b2->m_mass * b2->m_invI; - - b2Vec2 normal = c->normal; - - // Solver normal constraints - for (int32 j = 0; j < c->pointCount; ++j) - { - b2ContactConstraintPoint* ccp = c->points + j; - - b2Vec2 r1 = b2Mul(b1->GetXForm().R, ccp->localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetXForm().R, ccp->localAnchor2 - b2->GetLocalCenter()); - - b2Vec2 p1 = b1->m_sweep.c + r1; - b2Vec2 p2 = b2->m_sweep.c + r2; - b2Vec2 dp = p2 - p1; - - // Approximate the current separation. - float32 separation = b2Dot(dp, normal) + ccp->separation; - - // Track max constraint error. - minSeparation = b2Min(minSeparation, separation); - - // Prevent large corrections and allow slop. - float32 C = baumgarte * b2Clamp(separation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); - - // Compute normal impulse - float32 dImpulse = -ccp->equalizedMass * C; - - // b2Clamp the accumulated impulse - float32 impulse0 = ccp->positionImpulse; - ccp->positionImpulse = b2Max(impulse0 + dImpulse, 0.0f); - dImpulse = ccp->positionImpulse - impulse0; - - b2Vec2 impulse = dImpulse * normal; - - b1->m_sweep.c -= invMass1 * impulse; - b1->m_sweep.a -= invI1 * b2Cross(r1, impulse); - b1->SynchronizeTransform(); - - b2->m_sweep.c += invMass2 * impulse; - b2->m_sweep.a += invI2 * b2Cross(r2, impulse); - b2->SynchronizeTransform(); - } - } - - // We can't expect minSpeparation >= -b2_linearSlop because we don't - // push the separation above -b2_linearSlop. - return minSeparation >= -1.5f * b2_linearSlop; -} diff --git a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2PolyAndCircleContact.cpp b/src/modules/physics/box2d/Source/Dynamics/Contacts/b2PolyAndCircleContact.cpp deleted file mode 100644 index 2d0047854..000000000 --- a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2PolyAndCircleContact.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2PolyAndCircleContact.h" -#include "../b2Body.h" -#include "../b2WorldCallbacks.h" -#include "../../Common/b2BlockAllocator.h" - -#include -#include - -b2Contact* b2PolyAndCircleContact::Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2PolyAndCircleContact)); - return new (mem) b2PolyAndCircleContact(shape1, shape2); -} - -void b2PolyAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2PolyAndCircleContact*)contact)->~b2PolyAndCircleContact(); - allocator->Free(contact, sizeof(b2PolyAndCircleContact)); -} - -b2PolyAndCircleContact::b2PolyAndCircleContact(b2Shape* s1, b2Shape* s2) -: b2Contact(s1, s2) -{ - b2Assert(m_shape1->GetType() == e_polygonShape); - b2Assert(m_shape2->GetType() == e_circleShape); - m_manifold.pointCount = 0; - m_manifold.points[0].normalImpulse = 0.0f; - m_manifold.points[0].tangentImpulse = 0.0f; -} - -void b2PolyAndCircleContact::Evaluate(b2ContactListener* listener) -{ - b2Body* b1 = m_shape1->GetBody(); - b2Body* b2 = m_shape2->GetBody(); - - b2Manifold m0; - memcpy(&m0, &m_manifold, sizeof(b2Manifold)); - - b2CollidePolygonAndCircle(&m_manifold, (b2PolygonShape*)m_shape1, b1->GetXForm(), (b2CircleShape*)m_shape2, b2->GetXForm()); - - bool persisted[b2_maxManifoldPoints] = {false, false}; - - b2ContactPoint cp; - cp.shape1 = m_shape1; - cp.shape2 = m_shape2; - cp.friction = m_friction; - cp.restitution = m_restitution; - - // Match contact ids to facilitate warm starting. - if (m_manifold.pointCount > 0) - { - // Match old contact ids to new contact ids and copy the - // stored impulses to warm start the solver. - for (int32 i = 0; i < m_manifold.pointCount; ++i) - { - b2ManifoldPoint* mp = m_manifold.points + i; - mp->normalImpulse = 0.0f; - mp->tangentImpulse = 0.0f; - bool found = false; - b2ContactID id = mp->id; - - for (int32 j = 0; j < m0.pointCount; ++j) - { - if (persisted[j] == true) - { - continue; - } - - b2ManifoldPoint* mp0 = m0.points + j; - - if (mp0->id.key == id.key) - { - persisted[j] = true; - mp->normalImpulse = mp0->normalImpulse; - mp->tangentImpulse = mp0->tangentImpulse; - - // A persistent point. - found = true; - - // Report persistent point. - if (listener != NULL) - { - cp.position = b1->GetWorldPoint(mp->localPoint1); - b2Vec2 v1 = b1->GetLinearVelocityFromLocalPoint(mp->localPoint1); - b2Vec2 v2 = b2->GetLinearVelocityFromLocalPoint(mp->localPoint2); - cp.velocity = v2 - v1; - cp.normal = m_manifold.normal; - cp.separation = mp->separation; - cp.id = id; - listener->Persist(&cp); - } - break; - } - } - - // Report added point. - if (found == false && listener != NULL) - { - cp.position = b1->GetWorldPoint(mp->localPoint1); - b2Vec2 v1 = b1->GetLinearVelocityFromLocalPoint(mp->localPoint1); - b2Vec2 v2 = b2->GetLinearVelocityFromLocalPoint(mp->localPoint2); - cp.velocity = v2 - v1; - cp.normal = m_manifold.normal; - cp.separation = mp->separation; - cp.id = id; - listener->Add(&cp); - } - } - - m_manifoldCount = 1; - } - else - { - m_manifoldCount = 0; - } - - if (listener == NULL) - { - return; - } - - // Report removed points. - for (int32 i = 0; i < m0.pointCount; ++i) - { - if (persisted[i]) - { - continue; - } - - b2ManifoldPoint* mp0 = m0.points + i; - cp.position = b1->GetWorldPoint(mp0->localPoint1); - b2Vec2 v1 = b1->GetLinearVelocityFromLocalPoint(mp0->localPoint1); - b2Vec2 v2 = b2->GetLinearVelocityFromLocalPoint(mp0->localPoint2); - cp.velocity = v2 - v1; - cp.normal = m0.normal; - cp.separation = mp0->separation; - cp.id = mp0->id; - listener->Remove(&cp); - } -} diff --git a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2PolyContact.cpp b/src/modules/physics/box2d/Source/Dynamics/Contacts/b2PolyContact.cpp deleted file mode 100644 index 258882200..000000000 --- a/src/modules/physics/box2d/Source/Dynamics/Contacts/b2PolyContact.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2PolyContact.h" -#include "../b2Body.h" -#include "../b2WorldCallbacks.h" -#include "../../Common/b2BlockAllocator.h" - -#include -#include -#include - -b2Contact* b2PolygonContact::Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2PolygonContact)); - return new (mem) b2PolygonContact(shape1, shape2); -} - -void b2PolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2PolygonContact*)contact)->~b2PolygonContact(); - allocator->Free(contact, sizeof(b2PolygonContact)); -} - -b2PolygonContact::b2PolygonContact(b2Shape* s1, b2Shape* s2) - : b2Contact(s1, s2) -{ - b2Assert(m_shape1->GetType() == e_polygonShape); - b2Assert(m_shape2->GetType() == e_polygonShape); - m_manifold.pointCount = 0; -} - -void b2PolygonContact::Evaluate(b2ContactListener* listener) -{ - b2Body* b1 = m_shape1->GetBody(); - b2Body* b2 = m_shape2->GetBody(); - - b2Manifold m0; - memcpy(&m0, &m_manifold, sizeof(b2Manifold)); - - b2CollidePolygons(&m_manifold, (b2PolygonShape*)m_shape1, b1->GetXForm(), (b2PolygonShape*)m_shape2, b2->GetXForm()); - - bool persisted[b2_maxManifoldPoints] = {false, false}; - - b2ContactPoint cp; - cp.shape1 = m_shape1; - cp.shape2 = m_shape2; - cp.friction = m_friction; - cp.restitution = m_restitution; - - // Match contact ids to facilitate warm starting. - if (m_manifold.pointCount > 0) - { - // Match old contact ids to new contact ids and copy the - // stored impulses to warm start the solver. - for (int32 i = 0; i < m_manifold.pointCount; ++i) - { - b2ManifoldPoint* mp = m_manifold.points + i; - mp->normalImpulse = 0.0f; - mp->tangentImpulse = 0.0f; - bool found = false; - b2ContactID id = mp->id; - - for (int32 j = 0; j < m0.pointCount; ++j) - { - if (persisted[j] == true) - { - continue; - } - - b2ManifoldPoint* mp0 = m0.points + j; - - if (mp0->id.key == id.key) - { - persisted[j] = true; - mp->normalImpulse = mp0->normalImpulse; - mp->tangentImpulse = mp0->tangentImpulse; - - // A persistent point. - found = true; - - // Report persistent point. - if (listener != NULL) - { - cp.position = b1->GetWorldPoint(mp->localPoint1); - b2Vec2 v1 = b1->GetLinearVelocityFromLocalPoint(mp->localPoint1); - b2Vec2 v2 = b2->GetLinearVelocityFromLocalPoint(mp->localPoint2); - cp.velocity = v2 - v1; - cp.normal = m_manifold.normal; - cp.separation = mp->separation; - cp.id = id; - listener->Persist(&cp); - } - break; - } - } - - // Report added point. - if (found == false && listener != NULL) - { - cp.position = b1->GetWorldPoint(mp->localPoint1); - b2Vec2 v1 = b1->GetLinearVelocityFromLocalPoint(mp->localPoint1); - b2Vec2 v2 = b2->GetLinearVelocityFromLocalPoint(mp->localPoint2); - cp.velocity = v2 - v1; - cp.normal = m_manifold.normal; - cp.separation = mp->separation; - cp.id = id; - listener->Add(&cp); - } - } - - m_manifoldCount = 1; - } - else - { - m_manifoldCount = 0; - } - - if (listener == NULL) - { - return; - } - - // Report removed points. - for (int32 i = 0; i < m0.pointCount; ++i) - { - if (persisted[i]) - { - continue; - } - - b2ManifoldPoint* mp0 = m0.points + i; - cp.position = b1->GetWorldPoint(mp0->localPoint1); - b2Vec2 v1 = b1->GetLinearVelocityFromLocalPoint(mp0->localPoint1); - b2Vec2 v2 = b2->GetLinearVelocityFromLocalPoint(mp0->localPoint2); - cp.velocity = v2 - v1; - cp.normal = m0.normal; - cp.separation = mp0->separation; - cp.id = mp0->id; - listener->Remove(&cp); - } -} diff --git a/src/modules/physics/box2d/Source/Dynamics/Joints/b2MouseJoint.cpp b/src/modules/physics/box2d/Source/Dynamics/Joints/b2MouseJoint.cpp deleted file mode 100644 index 02bbefebc..000000000 --- a/src/modules/physics/box2d/Source/Dynamics/Joints/b2MouseJoint.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2MouseJoint.h" -#include "../b2Body.h" -#include "../b2World.h" - -// p = attached point, m = mouse point -// C = p - m -// Cdot = v -// = v + cross(w, r) -// J = [I r_skew] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) - -b2MouseJoint::b2MouseJoint(const b2MouseJointDef* def) -: b2Joint(def) -{ - m_target = def->target; - m_localAnchor = b2MulT(m_body2->GetXForm(), m_target); - - m_maxForce = B2FORCE_INV_SCALE(def->maxForce); - m_impulse.SetZero(); - - float32 mass = m_body2->m_mass; - - // Frequency - float32 omega = 2.0f * b2_pi * def->frequencyHz; - - // Damping coefficient - float32 d = 2.0f * mass * def->dampingRatio * omega; - - // Spring stiffness - float32 k = (def->timeStep * mass) * (omega * omega); - - // magic formulas - b2Assert(d + k > B2_FLT_EPSILON); - m_gamma = 1.0f / (d + k); - m_beta = k / (d + k); -} - -void b2MouseJoint::SetTarget(const b2Vec2& target) -{ - if (m_body2->IsSleeping()) - { - m_body2->WakeUp(); - } - m_target = target; -} - -void b2MouseJoint::InitVelocityConstraints(const b2TimeStep& step) -{ - b2Body* b = m_body2; - - // Compute the effective mass matrix. - b2Vec2 r = b2Mul(b->GetXForm().R, m_localAnchor - b->GetLocalCenter()); - - // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] - // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] - // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] - float32 invMass = b->m_invMass; - float32 invI = b->m_invI; - - b2Mat22 K1; - K1.col1.x = invMass; K1.col2.x = 0.0f; - K1.col1.y = 0.0f; K1.col2.y = invMass; - - b2Mat22 K2; - K2.col1.x = invI * r.y * r.y; K2.col2.x = -invI * r.x * r.y; - K2.col1.y = -invI * r.x * r.y; K2.col2.y = invI * r.x * r.x; - - b2Mat22 K = K1 + K2; - K.col1.x += m_gamma; - K.col2.y += m_gamma; - - m_mass = K.Invert(); - - m_C = b->m_sweep.c + r - m_target; - - // Cheat with some damping - b->m_angularVelocity *= 0.98f; - - // Warm starting. - b2Vec2 P = B2FORCE_SCALE(step.dt) * m_impulse; - b->m_linearVelocity += invMass * P; - b->m_angularVelocity += invI * b2Cross(r, P); -} - -void b2MouseJoint::SolveVelocityConstraints(const b2TimeStep& step) -{ - b2Body* b = m_body2; - - b2Vec2 r = b2Mul(b->GetXForm().R, m_localAnchor - b->GetLocalCenter()); - - // Cdot = v + cross(w, r) - b2Vec2 Cdot = b->m_linearVelocity + b2Cross(b->m_angularVelocity, r); - b2Vec2 force = -B2FORCE_INV_SCALE(step.inv_dt) * b2Mul(m_mass, Cdot + (m_beta * step.inv_dt) * m_C + B2FORCE_SCALE(step.dt) * (m_gamma * m_impulse)); - - b2Vec2 oldForce = m_impulse; - m_impulse += force; - float32 forceMagnitude = m_impulse.Length(); - if (forceMagnitude > m_maxForce) - { - m_impulse *= m_maxForce / forceMagnitude; - } - force = m_impulse - oldForce; - - b2Vec2 P = B2FORCE_SCALE(step.dt) * force; - b->m_linearVelocity += b->m_invMass * P; - b->m_angularVelocity += b->m_invI * b2Cross(r, P); -} - -b2Vec2 b2MouseJoint::GetAnchor1() const -{ - return m_target; -} - -b2Vec2 b2MouseJoint::GetAnchor2() const -{ - return m_body2->GetWorldPoint(m_localAnchor); -} - -b2Vec2 b2MouseJoint::GetReactionForce() const -{ - return B2FORCE_SCALE(float32(1.0))*m_impulse; -} - -float32 b2MouseJoint::GetReactionTorque() const -{ - return 0.0f; -} diff --git a/src/modules/physics/box2d/Source/Dynamics/Joints/b2PrismaticJoint.cpp b/src/modules/physics/box2d/Source/Dynamics/Joints/b2PrismaticJoint.cpp deleted file mode 100644 index 758f4409d..000000000 --- a/src/modules/physics/box2d/Source/Dynamics/Joints/b2PrismaticJoint.cpp +++ /dev/null @@ -1,478 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2PrismaticJoint.h" -#include "../b2Body.h" -#include "../b2World.h" - -// Linear constraint (point-to-line) -// d = p2 - p1 = x2 + r2 - x1 - r1 -// C = dot(ay1, d) -// Cdot = dot(d, cross(w1, ay1)) + dot(ay1, v2 + cross(w2, r2) - v1 - cross(w1, r1)) -// = -dot(ay1, v1) - dot(cross(d + r1, ay1), w1) + dot(ay1, v2) + dot(cross(r2, ay1), v2) -// J = [-ay1 -cross(d+r1,ay1) ay1 cross(r2,ay1)] -// -// Angular constraint -// C = a2 - a1 + a_initial -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] - -// Motor/Limit linear constraint -// C = dot(ax1, d) -// Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2) -// J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)] - -void b2PrismaticJointDef::Initialize(b2Body* b1, b2Body* b2, const b2Vec2& anchor, const b2Vec2& axis) -{ - body1 = b1; - body2 = b2; - localAnchor1 = body1->GetLocalPoint(anchor); - localAnchor2 = body2->GetLocalPoint(anchor); - localAxis1 = body1->GetLocalVector(axis); - referenceAngle = body2->GetAngle() - body1->GetAngle(); -} - -b2PrismaticJoint::b2PrismaticJoint(const b2PrismaticJointDef* def) -: b2Joint(def) -{ - m_localAnchor1 = def->localAnchor1; - m_localAnchor2 = def->localAnchor2; - m_localXAxis1 = def->localAxis1; - m_localYAxis1 = b2Cross(1.0f, m_localXAxis1); - m_refAngle = def->referenceAngle; - - m_linearJacobian.SetZero(); - m_linearMass = 0.0f; - m_force = 0.0f; - - m_angularMass = 0.0f; - m_torque = 0.0f; - - m_motorJacobian.SetZero(); - m_motorMass = 0.0; - m_motorForce = 0.0f; - m_limitForce = 0.0f; - m_limitPositionImpulse = 0.0f; - - m_lowerTranslation = def->lowerTranslation; - m_upperTranslation = def->upperTranslation; - m_maxMotorForce = B2FORCE_INV_SCALE(def->maxMotorForce); - m_motorSpeed = def->motorSpeed; - m_enableLimit = def->enableLimit; - m_enableMotor = def->enableMotor; -} - -void b2PrismaticJoint::InitVelocityConstraints(const b2TimeStep& step) -{ - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; - - // Compute the effective masses. - b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); - - float32 invMass1 = b1->m_invMass, invMass2 = b2->m_invMass; - float32 invI1 = b1->m_invI, invI2 = b2->m_invI; - - // Compute point to line constraint effective mass. - // J = [-ay1 -cross(d+r1,ay1) ay1 cross(r2,ay1)] - b2Vec2 ay1 = b2Mul(b1->GetXForm().R, m_localYAxis1); - b2Vec2 e = b2->m_sweep.c + r2 - b1->m_sweep.c; // e = d + r1 - - m_linearJacobian.Set(-ay1, -b2Cross(e, ay1), ay1, b2Cross(r2, ay1)); - m_linearMass = invMass1 + invI1 * m_linearJacobian.angular1 * m_linearJacobian.angular1 + - invMass2 + invI2 * m_linearJacobian.angular2 * m_linearJacobian.angular2; - b2Assert(m_linearMass > B2_FLT_EPSILON); - m_linearMass = 1.0f / m_linearMass; - - // Compute angular constraint effective mass. - m_angularMass = invI1 + invI2; - if (m_angularMass > B2_FLT_EPSILON) - { - m_angularMass = 1.0f / m_angularMass; - } - - // Compute motor and limit terms. - if (m_enableLimit || m_enableMotor) - { - // The motor and limit share a Jacobian and effective mass. - b2Vec2 ax1 = b2Mul(b1->GetXForm().R, m_localXAxis1); - m_motorJacobian.Set(-ax1, -b2Cross(e, ax1), ax1, b2Cross(r2, ax1)); - m_motorMass = invMass1 + invI1 * m_motorJacobian.angular1 * m_motorJacobian.angular1 + - invMass2 + invI2 * m_motorJacobian.angular2 * m_motorJacobian.angular2; - b2Assert(m_motorMass > B2_FLT_EPSILON); - m_motorMass = 1.0f / m_motorMass; - - if (m_enableLimit) - { - b2Vec2 d = e - r1; // p2 - p1 - float32 jointTranslation = b2Dot(ax1, d); - if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) - { - m_limitState = e_equalLimits; - } - else if (jointTranslation <= m_lowerTranslation) - { - if (m_limitState != e_atLowerLimit) - { - m_limitForce = 0.0f; - } - m_limitState = e_atLowerLimit; - } - else if (jointTranslation >= m_upperTranslation) - { - if (m_limitState != e_atUpperLimit) - { - m_limitForce = 0.0f; - } - m_limitState = e_atUpperLimit; - } - else - { - m_limitState = e_inactiveLimit; - m_limitForce = 0.0f; - } - } - } - - if (m_enableMotor == false) - { - m_motorForce = 0.0f; - } - - if (m_enableLimit == false) - { - m_limitForce = 0.0f; - } - - if (step.warmStarting) - { - b2Vec2 P1 = B2FORCE_SCALE(step.dt) * (m_force * m_linearJacobian.linear1 + (m_motorForce + m_limitForce) * m_motorJacobian.linear1); - b2Vec2 P2 = B2FORCE_SCALE(step.dt) * (m_force * m_linearJacobian.linear2 + (m_motorForce + m_limitForce) * m_motorJacobian.linear2); - float32 L1 = B2FORCE_SCALE(step.dt) * (m_force * m_linearJacobian.angular1 - m_torque + (m_motorForce + m_limitForce) * m_motorJacobian.angular1); - float32 L2 = B2FORCE_SCALE(step.dt) * (m_force * m_linearJacobian.angular2 + m_torque + (m_motorForce + m_limitForce) * m_motorJacobian.angular2); - - b1->m_linearVelocity += invMass1 * P1; - b1->m_angularVelocity += invI1 * L1; - - b2->m_linearVelocity += invMass2 * P2; - b2->m_angularVelocity += invI2 * L2; - } - else - { - m_force = 0.0f; - m_torque = 0.0f; - m_limitForce = 0.0f; - m_motorForce = 0.0f; - } - - m_limitPositionImpulse = 0.0f; -} - -void b2PrismaticJoint::SolveVelocityConstraints(const b2TimeStep& step) -{ - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; - - float32 invMass1 = b1->m_invMass, invMass2 = b2->m_invMass; - float32 invI1 = b1->m_invI, invI2 = b2->m_invI; - - // Solve linear constraint. - float32 linearCdot = m_linearJacobian.Compute(b1->m_linearVelocity, b1->m_angularVelocity, b2->m_linearVelocity, b2->m_angularVelocity); - float32 force = -B2FORCE_INV_SCALE(step.inv_dt) * m_linearMass * linearCdot; - m_force += force; - - float32 P = B2FORCE_SCALE(step.dt) * force; - b1->m_linearVelocity += (invMass1 * P) * m_linearJacobian.linear1; - b1->m_angularVelocity += invI1 * P * m_linearJacobian.angular1; - - b2->m_linearVelocity += (invMass2 * P) * m_linearJacobian.linear2; - b2->m_angularVelocity += invI2 * P * m_linearJacobian.angular2; - - // Solve angular constraint. - float32 angularCdot = b2->m_angularVelocity - b1->m_angularVelocity; - float32 torque = -B2FORCE_INV_SCALE(step.inv_dt) * m_angularMass * angularCdot; - m_torque += torque; - - float32 L = B2FORCE_SCALE(step.dt) * torque; - b1->m_angularVelocity -= invI1 * L; - b2->m_angularVelocity += invI2 * L; - - // Solve linear motor constraint. - if (m_enableMotor && m_limitState != e_equalLimits) - { - float32 motorCdot = m_motorJacobian.Compute(b1->m_linearVelocity, b1->m_angularVelocity, b2->m_linearVelocity, b2->m_angularVelocity) - m_motorSpeed; - float32 motorForce = -B2FORCE_INV_SCALE(step.inv_dt) * m_motorMass * motorCdot; - float32 oldMotorForce = m_motorForce; - m_motorForce = b2Clamp(m_motorForce + motorForce, -m_maxMotorForce, m_maxMotorForce); - motorForce = m_motorForce - oldMotorForce; - - float32 P = B2FORCE_SCALE(step.dt) * motorForce; - b1->m_linearVelocity += (invMass1 * P) * m_motorJacobian.linear1; - b1->m_angularVelocity += invI1 * P * m_motorJacobian.angular1; - - b2->m_linearVelocity += (invMass2 * P) * m_motorJacobian.linear2; - b2->m_angularVelocity += invI2 * P * m_motorJacobian.angular2; - } - - // Solve linear limit constraint. - if (m_enableLimit && m_limitState != e_inactiveLimit) - { - float32 limitCdot = m_motorJacobian.Compute(b1->m_linearVelocity, b1->m_angularVelocity, b2->m_linearVelocity, b2->m_angularVelocity); - float32 limitForce = -B2FORCE_INV_SCALE(step.inv_dt) * m_motorMass * limitCdot; - - if (m_limitState == e_equalLimits) - { - m_limitForce += limitForce; - } - else if (m_limitState == e_atLowerLimit) - { - float32 oldLimitForce = m_limitForce; - m_limitForce = b2Max(m_limitForce + limitForce, 0.0f); - limitForce = m_limitForce - oldLimitForce; - } - else if (m_limitState == e_atUpperLimit) - { - float32 oldLimitForce = m_limitForce; - m_limitForce = b2Min(m_limitForce + limitForce, 0.0f); - limitForce = m_limitForce - oldLimitForce; - } - - float32 P = B2FORCE_SCALE(step.dt) * limitForce; - - b1->m_linearVelocity += (invMass1 * P) * m_motorJacobian.linear1; - b1->m_angularVelocity += invI1 * P * m_motorJacobian.angular1; - - b2->m_linearVelocity += (invMass2 * P) * m_motorJacobian.linear2; - b2->m_angularVelocity += invI2 * P * m_motorJacobian.angular2; - } -} - -bool b2PrismaticJoint::SolvePositionConstraints() -{ - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; - - float32 invMass1 = b1->m_invMass, invMass2 = b2->m_invMass; - float32 invI1 = b1->m_invI, invI2 = b2->m_invI; - - b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); - b2Vec2 p1 = b1->m_sweep.c + r1; - b2Vec2 p2 = b2->m_sweep.c + r2; - b2Vec2 d = p2 - p1; - b2Vec2 ay1 = b2Mul(b1->GetXForm().R, m_localYAxis1); - - // Solve linear (point-to-line) constraint. - float32 linearC = b2Dot(ay1, d); - // Prevent overly large corrections. - linearC = b2Clamp(linearC, -b2_maxLinearCorrection, b2_maxLinearCorrection); - float32 linearImpulse = -m_linearMass * linearC; - - b1->m_sweep.c += (invMass1 * linearImpulse) * m_linearJacobian.linear1; - b1->m_sweep.a += invI1 * linearImpulse * m_linearJacobian.angular1; - //b1->SynchronizeTransform(); // updated by angular constraint - b2->m_sweep.c += (invMass2 * linearImpulse) * m_linearJacobian.linear2; - b2->m_sweep.a += invI2 * linearImpulse * m_linearJacobian.angular2; - //b2->SynchronizeTransform(); // updated by angular constraint - - float32 positionError = b2Abs(linearC); - - // Solve angular constraint. - float32 angularC = b2->m_sweep.a - b1->m_sweep.a - m_refAngle; - // Prevent overly large corrections. - angularC = b2Clamp(angularC, -b2_maxAngularCorrection, b2_maxAngularCorrection); - float32 angularImpulse = -m_angularMass * angularC; - - b1->m_sweep.a -= b1->m_invI * angularImpulse; - b2->m_sweep.a += b2->m_invI * angularImpulse; - - b1->SynchronizeTransform(); - b2->SynchronizeTransform(); - - float32 angularError = b2Abs(angularC); - - // Solve linear limit constraint. - if (m_enableLimit && m_limitState != e_inactiveLimit) - { - b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); - b2Vec2 p1 = b1->m_sweep.c + r1; - b2Vec2 p2 = b2->m_sweep.c + r2; - b2Vec2 d = p2 - p1; - b2Vec2 ax1 = b2Mul(b1->GetXForm().R, m_localXAxis1); - - float32 translation = b2Dot(ax1, d); - float32 limitImpulse = 0.0f; - - if (m_limitState == e_equalLimits) - { - // Prevent large angular corrections - float32 limitC = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection); - limitImpulse = -m_motorMass * limitC; - positionError = b2Max(positionError, b2Abs(angularC)); - } - else if (m_limitState == e_atLowerLimit) - { - float32 limitC = translation - m_lowerTranslation; - positionError = b2Max(positionError, -limitC); - - // Prevent large linear corrections and allow some slop. - limitC = b2Clamp(limitC + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); - limitImpulse = -m_motorMass * limitC; - float32 oldLimitImpulse = m_limitPositionImpulse; - m_limitPositionImpulse = b2Max(m_limitPositionImpulse + limitImpulse, 0.0f); - limitImpulse = m_limitPositionImpulse - oldLimitImpulse; - } - else if (m_limitState == e_atUpperLimit) - { - float32 limitC = translation - m_upperTranslation; - positionError = b2Max(positionError, limitC); - - // Prevent large linear corrections and allow some slop. - limitC = b2Clamp(limitC - b2_linearSlop, 0.0f, b2_maxLinearCorrection); - limitImpulse = -m_motorMass * limitC; - float32 oldLimitImpulse = m_limitPositionImpulse; - m_limitPositionImpulse = b2Min(m_limitPositionImpulse + limitImpulse, 0.0f); - limitImpulse = m_limitPositionImpulse - oldLimitImpulse; - } - - b1->m_sweep.c += (invMass1 * limitImpulse) * m_motorJacobian.linear1; - b1->m_sweep.a += invI1 * limitImpulse * m_motorJacobian.angular1; - b2->m_sweep.c += (invMass2 * limitImpulse) * m_motorJacobian.linear2; - b2->m_sweep.a += invI2 * limitImpulse * m_motorJacobian.angular2; - - b1->SynchronizeTransform(); - b2->SynchronizeTransform(); - } - - return positionError <= b2_linearSlop && angularError <= b2_angularSlop; -} - -b2Vec2 b2PrismaticJoint::GetAnchor1() const -{ - return m_body1->GetWorldPoint(m_localAnchor1); -} - -b2Vec2 b2PrismaticJoint::GetAnchor2() const -{ - return m_body2->GetWorldPoint(m_localAnchor2); -} - -b2Vec2 b2PrismaticJoint::GetReactionForce() const -{ - b2Vec2 ax1 = b2Mul(m_body1->GetXForm().R, m_localXAxis1); - b2Vec2 ay1 = b2Mul(m_body1->GetXForm().R, m_localYAxis1); - - return B2FORCE_SCALE(float32(1.0))*(m_limitForce * ax1 + m_force * ay1); -} - -float32 b2PrismaticJoint::GetReactionTorque() const -{ - return B2FORCE_SCALE(m_torque); -} - -float32 b2PrismaticJoint::GetJointTranslation() const -{ - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; - - b2Vec2 p1 = b1->GetWorldPoint(m_localAnchor1); - b2Vec2 p2 = b2->GetWorldPoint(m_localAnchor2); - b2Vec2 d = p2 - p1; - b2Vec2 axis = b1->GetWorldVector(m_localXAxis1); - - float32 translation = b2Dot(d, axis); - return translation; -} - -float32 b2PrismaticJoint::GetJointSpeed() const -{ - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; - - b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); - b2Vec2 p1 = b1->m_sweep.c + r1; - b2Vec2 p2 = b2->m_sweep.c + r2; - b2Vec2 d = p2 - p1; - b2Vec2 axis = b1->GetWorldVector(m_localXAxis1); - - b2Vec2 v1 = b1->m_linearVelocity; - b2Vec2 v2 = b2->m_linearVelocity; - float32 w1 = b1->m_angularVelocity; - float32 w2 = b2->m_angularVelocity; - - float32 speed = b2Dot(d, b2Cross(w1, axis)) + b2Dot(axis, v2 + b2Cross(w2, r2) - v1 - b2Cross(w1, r1)); - return speed; -} - -bool b2PrismaticJoint::IsLimitEnabled() const -{ - return m_enableLimit; -} - -void b2PrismaticJoint::EnableLimit(bool flag) -{ - m_enableLimit = flag; -} - -float32 b2PrismaticJoint::GetLowerLimit() const -{ - return m_lowerTranslation; -} - -float32 b2PrismaticJoint::GetUpperLimit() const -{ - return m_upperTranslation; -} - -void b2PrismaticJoint::SetLimits(float32 lower, float32 upper) -{ - b2Assert(lower <= upper); - m_lowerTranslation = lower; - m_upperTranslation = upper; -} - -bool b2PrismaticJoint::IsMotorEnabled() const -{ - return m_enableMotor; -} - -void b2PrismaticJoint::EnableMotor(bool flag) -{ - m_enableMotor = flag; -} - -void b2PrismaticJoint::SetMotorSpeed(float32 speed) -{ - m_motorSpeed = speed; -} - -void b2PrismaticJoint::SetMaxMotorForce(float32 force) -{ - m_maxMotorForce = B2FORCE_SCALE(float32(1.0))*force; -} - -float32 b2PrismaticJoint::GetMotorForce() const -{ - return m_motorForce; -} - - - diff --git a/src/modules/physics/box2d/Source/Dynamics/Joints/b2RevoluteJoint.cpp b/src/modules/physics/box2d/Source/Dynamics/Joints/b2RevoluteJoint.cpp deleted file mode 100644 index e83d59942..000000000 --- a/src/modules/physics/box2d/Source/Dynamics/Joints/b2RevoluteJoint.cpp +++ /dev/null @@ -1,399 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2RevoluteJoint.h" -#include "../b2Body.h" -#include "../b2World.h" - -#include "../b2Island.h" - -// Point-to-point constraint -// C = p2 - p1 -// Cdot = v2 - v1 -// = v2 + cross(w2, r2) - v1 - cross(w1, r1) -// J = [-I -r1_skew I r2_skew ] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) - -// Motor constraint -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] -// K = invI1 + invI2 - -void b2RevoluteJointDef::Initialize(b2Body* b1, b2Body* b2, const b2Vec2& anchor) -{ - body1 = b1; - body2 = b2; - localAnchor1 = body1->GetLocalPoint(anchor); - localAnchor2 = body2->GetLocalPoint(anchor); - referenceAngle = body2->GetAngle() - body1->GetAngle(); -} - -b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def) -: b2Joint(def) -{ - m_localAnchor1 = def->localAnchor1; - m_localAnchor2 = def->localAnchor2; - m_referenceAngle = def->referenceAngle; - - m_pivotForce.Set(0.0f, 0.0f); - m_motorForce = 0.0f; - m_limitForce = 0.0f; - m_limitPositionImpulse = 0.0f; - - m_lowerAngle = def->lowerAngle; - m_upperAngle = def->upperAngle; - m_maxMotorTorque = def->maxMotorTorque; - m_motorSpeed = def->motorSpeed; - m_enableLimit = def->enableLimit; - m_enableMotor = def->enableMotor; -} - -void b2RevoluteJoint::InitVelocityConstraints(const b2TimeStep& step) -{ - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; - - // Compute the effective mass matrix. - b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); - - // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] - // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] - // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] - float32 invMass1 = b1->m_invMass, invMass2 = b2->m_invMass; - float32 invI1 = b1->m_invI, invI2 = b2->m_invI; - - b2Mat22 K1; - K1.col1.x = invMass1 + invMass2; K1.col2.x = 0.0f; - K1.col1.y = 0.0f; K1.col2.y = invMass1 + invMass2; - - b2Mat22 K2; - K2.col1.x = invI1 * r1.y * r1.y; K2.col2.x = -invI1 * r1.x * r1.y; - K2.col1.y = -invI1 * r1.x * r1.y; K2.col2.y = invI1 * r1.x * r1.x; - - b2Mat22 K3; - K3.col1.x = invI2 * r2.y * r2.y; K3.col2.x = -invI2 * r2.x * r2.y; - K3.col1.y = -invI2 * r2.x * r2.y; K3.col2.y = invI2 * r2.x * r2.x; - - b2Mat22 K = K1 + K2 + K3; - m_pivotMass = K.Invert(); - - m_motorMass = 1.0f / (invI1 + invI2); - - if (m_enableMotor == false) - { - m_motorForce = 0.0f; - } - - if (m_enableLimit) - { - float32 jointAngle = b2->m_sweep.a - b1->m_sweep.a - m_referenceAngle; - if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop) - { - m_limitState = e_equalLimits; - } - else if (jointAngle <= m_lowerAngle) - { - if (m_limitState != e_atLowerLimit) - { - m_limitForce = 0.0f; - } - m_limitState = e_atLowerLimit; - } - else if (jointAngle >= m_upperAngle) - { - if (m_limitState != e_atUpperLimit) - { - m_limitForce = 0.0f; - } - m_limitState = e_atUpperLimit; - } - else - { - m_limitState = e_inactiveLimit; - m_limitForce = 0.0f; - } - } - else - { - m_limitForce = 0.0f; - } - - if (step.warmStarting) - { - b1->m_linearVelocity -= B2FORCE_SCALE(step.dt) * invMass1 * m_pivotForce; - b1->m_angularVelocity -= B2FORCE_SCALE(step.dt) * invI1 * (b2Cross(r1, m_pivotForce) + B2FORCE_INV_SCALE(m_motorForce + m_limitForce)); - - b2->m_linearVelocity += B2FORCE_SCALE(step.dt) * invMass2 * m_pivotForce; - b2->m_angularVelocity += B2FORCE_SCALE(step.dt) * invI2 * (b2Cross(r2, m_pivotForce) + B2FORCE_INV_SCALE(m_motorForce + m_limitForce)); - } - else - { - m_pivotForce.SetZero(); - m_motorForce = 0.0f; - m_limitForce = 0.0f; - } - - m_limitPositionImpulse = 0.0f; -} - -void b2RevoluteJoint::SolveVelocityConstraints(const b2TimeStep& step) -{ - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; - - b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); - - // Solve point-to-point constraint - b2Vec2 pivotCdot = b2->m_linearVelocity + b2Cross(b2->m_angularVelocity, r2) - b1->m_linearVelocity - b2Cross(b1->m_angularVelocity, r1); - b2Vec2 pivotForce = -B2FORCE_INV_SCALE(step.inv_dt) * b2Mul(m_pivotMass, pivotCdot); - m_pivotForce += pivotForce; - - b2Vec2 P = B2FORCE_SCALE(step.dt) * pivotForce; - b1->m_linearVelocity -= b1->m_invMass * P; - b1->m_angularVelocity -= b1->m_invI * b2Cross(r1, P); - - b2->m_linearVelocity += b2->m_invMass * P; - b2->m_angularVelocity += b2->m_invI * b2Cross(r2, P); - - if (m_enableMotor && m_limitState != e_equalLimits) - { - float32 motorCdot = b2->m_angularVelocity - b1->m_angularVelocity - m_motorSpeed; - float32 motorForce = -step.inv_dt * m_motorMass * motorCdot; - float32 oldMotorForce = m_motorForce; - m_motorForce = b2Clamp(m_motorForce + motorForce, -m_maxMotorTorque, m_maxMotorTorque); - motorForce = m_motorForce - oldMotorForce; - - float32 P = step.dt * motorForce; - b1->m_angularVelocity -= b1->m_invI * P; - b2->m_angularVelocity += b2->m_invI * P; - } - - if (m_enableLimit && m_limitState != e_inactiveLimit) - { - float32 limitCdot = b2->m_angularVelocity - b1->m_angularVelocity; - float32 limitForce = -step.inv_dt * m_motorMass * limitCdot; - - if (m_limitState == e_equalLimits) - { - m_limitForce += limitForce; - } - else if (m_limitState == e_atLowerLimit) - { - float32 oldLimitForce = m_limitForce; - m_limitForce = b2Max(m_limitForce + limitForce, 0.0f); - limitForce = m_limitForce - oldLimitForce; - } - else if (m_limitState == e_atUpperLimit) - { - float32 oldLimitForce = m_limitForce; - m_limitForce = b2Min(m_limitForce + limitForce, 0.0f); - limitForce = m_limitForce - oldLimitForce; - } - - float32 P = step.dt * limitForce; - b1->m_angularVelocity -= b1->m_invI * P; - b2->m_angularVelocity += b2->m_invI * P; - } -} - -bool b2RevoluteJoint::SolvePositionConstraints() -{ - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; - - float32 positionError = 0.0f; - - // Solve point-to-point position error. - b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter()); - - b2Vec2 p1 = b1->m_sweep.c + r1; - b2Vec2 p2 = b2->m_sweep.c + r2; - b2Vec2 ptpC = p2 - p1; - - positionError = ptpC.Length(); - - // Prevent overly large corrections. - //b2Vec2 dpMax(b2_maxLinearCorrection, b2_maxLinearCorrection); - //ptpC = b2Clamp(ptpC, -dpMax, dpMax); - - float32 invMass1 = b1->m_invMass, invMass2 = b2->m_invMass; - float32 invI1 = b1->m_invI, invI2 = b2->m_invI; - - b2Mat22 K1; - K1.col1.x = invMass1 + invMass2; K1.col2.x = 0.0f; - K1.col1.y = 0.0f; K1.col2.y = invMass1 + invMass2; - - b2Mat22 K2; - K2.col1.x = invI1 * r1.y * r1.y; K2.col2.x = -invI1 * r1.x * r1.y; - K2.col1.y = -invI1 * r1.x * r1.y; K2.col2.y = invI1 * r1.x * r1.x; - - b2Mat22 K3; - K3.col1.x = invI2 * r2.y * r2.y; K3.col2.x = -invI2 * r2.x * r2.y; - K3.col1.y = -invI2 * r2.x * r2.y; K3.col2.y = invI2 * r2.x * r2.x; - - b2Mat22 K = K1 + K2 + K3; - b2Vec2 impulse = K.Solve(-ptpC); - - b1->m_sweep.c -= b1->m_invMass * impulse; - b1->m_sweep.a -= b1->m_invI * b2Cross(r1, impulse); - - b2->m_sweep.c += b2->m_invMass * impulse; - b2->m_sweep.a += b2->m_invI * b2Cross(r2, impulse); - - b1->SynchronizeTransform(); - b2->SynchronizeTransform(); - - // Handle limits. - float32 angularError = 0.0f; - - if (m_enableLimit && m_limitState != e_inactiveLimit) - { - float32 angle = b2->m_sweep.a - b1->m_sweep.a - m_referenceAngle; - float32 limitImpulse = 0.0f; - - if (m_limitState == e_equalLimits) - { - // Prevent large angular corrections - float32 limitC = b2Clamp(angle, -b2_maxAngularCorrection, b2_maxAngularCorrection); - limitImpulse = -m_motorMass * limitC; - angularError = b2Abs(limitC); - } - else if (m_limitState == e_atLowerLimit) - { - float32 limitC = angle - m_lowerAngle; - angularError = b2Max(0.0f, -limitC); - - // Prevent large angular corrections and allow some slop. - limitC = b2Clamp(limitC + b2_angularSlop, -b2_maxAngularCorrection, 0.0f); - limitImpulse = -m_motorMass * limitC; - float32 oldLimitImpulse = m_limitPositionImpulse; - m_limitPositionImpulse = b2Max(m_limitPositionImpulse + limitImpulse, 0.0f); - limitImpulse = m_limitPositionImpulse - oldLimitImpulse; - } - else if (m_limitState == e_atUpperLimit) - { - float32 limitC = angle - m_upperAngle; - angularError = b2Max(0.0f, limitC); - - // Prevent large angular corrections and allow some slop. - limitC = b2Clamp(limitC - b2_angularSlop, 0.0f, b2_maxAngularCorrection); - limitImpulse = -m_motorMass * limitC; - float32 oldLimitImpulse = m_limitPositionImpulse; - m_limitPositionImpulse = b2Min(m_limitPositionImpulse + limitImpulse, 0.0f); - limitImpulse = m_limitPositionImpulse - oldLimitImpulse; - } - - b1->m_sweep.a -= b1->m_invI * limitImpulse; - b2->m_sweep.a += b2->m_invI * limitImpulse; - - b1->SynchronizeTransform(); - b2->SynchronizeTransform(); - } - - return positionError <= b2_linearSlop && angularError <= b2_angularSlop; -} - -b2Vec2 b2RevoluteJoint::GetAnchor1() const -{ - return m_body1->GetWorldPoint(m_localAnchor1); -} - -b2Vec2 b2RevoluteJoint::GetAnchor2() const -{ - return m_body2->GetWorldPoint(m_localAnchor2); -} - -b2Vec2 b2RevoluteJoint::GetReactionForce() const -{ - return B2FORCE_SCALE(float32(1.0))*m_pivotForce; -} - -float32 b2RevoluteJoint::GetReactionTorque() const -{ - return m_limitForce; -} - -float32 b2RevoluteJoint::GetJointAngle() const -{ - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; - return b2->m_sweep.a - b1->m_sweep.a - m_referenceAngle; -} - -float32 b2RevoluteJoint::GetJointSpeed() const -{ - b2Body* b1 = m_body1; - b2Body* b2 = m_body2; - return b2->m_angularVelocity - b1->m_angularVelocity; -} - -bool b2RevoluteJoint::IsMotorEnabled() const -{ - return m_enableMotor; -} - -void b2RevoluteJoint::EnableMotor(bool flag) -{ - m_enableMotor = flag; -} - -float32 b2RevoluteJoint::GetMotorTorque() const -{ - return m_motorForce; -} - -void b2RevoluteJoint::SetMotorSpeed(float32 speed) -{ - m_motorSpeed = speed; -} - -void b2RevoluteJoint::SetMaxMotorTorque(float32 torque) -{ - m_maxMotorTorque = torque; -} - -bool b2RevoluteJoint::IsLimitEnabled() const -{ - return m_enableLimit; -} - -void b2RevoluteJoint::EnableLimit(bool flag) -{ - m_enableLimit = flag; -} - -float32 b2RevoluteJoint::GetLowerLimit() const -{ - return m_lowerAngle; -} - -float32 b2RevoluteJoint::GetUpperLimit() const -{ - return m_upperAngle; -} - -void b2RevoluteJoint::SetLimits(float32 lower, float32 upper) -{ - b2Assert(lower <= upper); - m_lowerAngle = lower; - m_upperAngle = upper; -} diff --git a/src/modules/physics/box2d/Source/Dynamics/b2Body.cpp b/src/modules/physics/box2d/Source/Dynamics/b2Body.cpp deleted file mode 100644 index d2b206a0a..000000000 --- a/src/modules/physics/box2d/Source/Dynamics/b2Body.cpp +++ /dev/null @@ -1,394 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2Body.h" -#include "b2World.h" -#include "Joints/b2Joint.h" -#include "../Collision/Shapes/b2Shape.h" - -b2Body::b2Body(const b2BodyDef* bd, b2World* world) -{ - b2Assert(world->m_lock == false); - - m_flags = 0; - - if (bd->isBullet) - { - m_flags |= e_bulletFlag; - } - if (bd->fixedRotation) - { - m_flags |= e_fixedRotationFlag; - } - if (bd->allowSleep) - { - m_flags |= e_allowSleepFlag; - } - if (bd->isSleeping) - { - m_flags |= e_sleepFlag; - } - - m_world = world; - - m_xf.position = bd->position; - m_xf.R.Set(bd->angle); - - m_sweep.localCenter = bd->massData.center; - m_sweep.t0 = 1.0f; - m_sweep.a0 = m_sweep.a = bd->angle; - m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - - m_jointList = NULL; - m_contactList = NULL; - m_prev = NULL; - m_next = NULL; - - m_linearDamping = bd->linearDamping; - m_angularDamping = bd->angularDamping; - - m_force.Set(0.0f, 0.0f); - m_torque = 0.0f; - - m_linearVelocity.SetZero(); - m_angularVelocity = 0.0f; - - m_sleepTime = 0.0f; - - m_invMass = 0.0f; - m_I = 0.0f; - m_invI = 0.0f; - - m_mass = bd->massData.mass; - - if (m_mass > 0.0f) - { - m_invMass = 1.0f / m_mass; - } - - if ((m_flags & b2Body::e_fixedRotationFlag) == 0) - { - m_I = bd->massData.I; - } - - if (m_I > 0.0f) - { - m_invI = 1.0f / m_I; - } - - if (m_invMass == 0.0f && m_invI == 0.0f) - { - m_type = e_staticType; - } - else - { - m_type = e_dynamicType; - } - - m_userData = bd->userData; - - m_shapeList = NULL; - m_shapeCount = 0; -} - -b2Body::~b2Body() -{ - b2Assert(m_world->m_lock == false); - // shapes and joints are destroyed in b2World::Destroy -} - -b2Shape* b2Body::CreateShape(b2ShapeDef* def) -{ - b2Assert(m_world->m_lock == false); - if (m_world->m_lock == true) - { - return NULL; - } - - b2Shape* s = b2Shape::Create(def, &m_world->m_blockAllocator); - - s->m_next = m_shapeList; - m_shapeList = s; - ++m_shapeCount; - - s->m_body = this; - - // Add the shape to the world's broad-phase. - s->CreateProxy(m_world->m_broadPhase, m_xf); - - // Compute the sweep radius for CCD. - s->UpdateSweepRadius(m_sweep.localCenter); - - return s; -} - -void b2Body::DestroyShape(b2Shape* s) -{ - b2Assert(m_world->m_lock == false); - if (m_world->m_lock == true) - { - return; - } - - b2Assert(s->GetBody() == this); - s->DestroyProxy(m_world->m_broadPhase); - - b2Assert(m_shapeCount > 0); - b2Shape** node = &m_shapeList; - bool found = false; - while (*node != NULL) - { - if (*node == s) - { - *node = s->m_next; - found = true; - break; - } - - node = &(*node)->m_next; - } - - // You tried to remove a shape that is not attached to this body. - b2Assert(found); - - s->m_body = NULL; - s->m_next = NULL; - - --m_shapeCount; - - b2Shape::Destroy(s, &m_world->m_blockAllocator); -} - -// TODO_ERIN adjust linear velocity and torque to account for movement of center. -void b2Body::SetMass(const b2MassData* massData) -{ - b2Assert(m_world->m_lock == false); - if (m_world->m_lock == true) - { - return; - } - - m_invMass = 0.0f; - m_I = 0.0f; - m_invI = 0.0f; - - m_mass = massData->mass; - - if (m_mass > 0.0f) - { - m_invMass = 1.0f / m_mass; - } - - if ((m_flags & b2Body::e_fixedRotationFlag) == 0) - { - m_I = massData->I; - } - - if (m_I > 0.0f) - { - m_invI = 1.0f / m_I; - } - - // Move center of mass. - m_sweep.localCenter = massData->center; - m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - - // Update the sweep radii of all child shapes. - for (b2Shape* s = m_shapeList; s; s = s->m_next) - { - s->UpdateSweepRadius(m_sweep.localCenter); - } - - int16 oldType = m_type; - if (m_invMass == 0.0f && m_invI == 0.0f) - { - m_type = e_staticType; - } - else - { - m_type = e_dynamicType; - } - - // If the body type changed, we need to refilter the broad-phase proxies. - if (oldType != m_type) - { - for (b2Shape* s = m_shapeList; s; s = s->m_next) - { - s->RefilterProxy(m_world->m_broadPhase, m_xf); - } - } -} - -// TODO_ERIN adjust linear velocity and torque to account for movement of center. -void b2Body::SetMassFromShapes() -{ - b2Assert(m_world->m_lock == false); - if (m_world->m_lock == true) - { - return; - } - - // Compute mass data from shapes. Each shape has its own density. - m_mass = 0.0f; - m_invMass = 0.0f; - m_I = 0.0f; - m_invI = 0.0f; - - b2Vec2 center = b2Vec2_zero; - for (b2Shape* s = m_shapeList; s; s = s->m_next) - { - b2MassData massData; - s->ComputeMass(&massData); - m_mass += massData.mass; - center += massData.mass * massData.center; - m_I += massData.I; - } - - // Compute center of mass, and shift the origin to the COM. - if (m_mass > 0.0f) - { - m_invMass = 1.0f / m_mass; - center *= m_invMass; - } - - if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) - { - // Center the inertia about the center of mass. - m_I -= m_mass * b2Dot(center, center); - b2Assert(m_I > 0.0f); - m_invI = 1.0f / m_I; - } - else - { - m_I = 0.0f; - m_invI = 0.0f; - } - - // Move center of mass. - m_sweep.localCenter = center; - m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - - // Update the sweep radii of all child shapes. - for (b2Shape* s = m_shapeList; s; s = s->m_next) - { - s->UpdateSweepRadius(m_sweep.localCenter); - } - - int16 oldType = m_type; - if (m_invMass == 0.0f && m_invI == 0.0f) - { - m_type = e_staticType; - } - else - { - m_type = e_dynamicType; - } - - // If the body type changed, we need to refilter the broad-phase proxies. - if (oldType != m_type) - { - for (b2Shape* s = m_shapeList; s; s = s->m_next) - { - s->RefilterProxy(m_world->m_broadPhase, m_xf); - } - } -} - -bool b2Body::SetXForm(const b2Vec2& position, float32 angle) -{ - b2Assert(m_world->m_lock == false); - if (m_world->m_lock == true) - { - return true; - } - - if (IsFrozen()) - { - return false; - } - - m_xf.R.Set(angle); - m_xf.position = position; - - m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - m_sweep.a0 = m_sweep.a = angle; - - bool freeze = false; - for (b2Shape* s = m_shapeList; s; s = s->m_next) - { - bool inRange = s->Synchronize(m_world->m_broadPhase, m_xf, m_xf); - - if (inRange == false) - { - freeze = true; - break; - } - } - - if (freeze == true) - { - m_flags |= e_frozenFlag; - m_linearVelocity.SetZero(); - m_angularVelocity = 0.0f; - for (b2Shape* s = m_shapeList; s; s = s->m_next) - { - s->DestroyProxy(m_world->m_broadPhase); - } - - // Failure - return false; - } - - // Success - m_world->m_broadPhase->Commit(); - return true; -} - -bool b2Body::SynchronizeShapes() -{ - b2XForm xf1; - xf1.R.Set(m_sweep.a0); - xf1.position = m_sweep.c0 - b2Mul(xf1.R, m_sweep.localCenter); - - bool inRange = true; - for (b2Shape* s = m_shapeList; s; s = s->m_next) - { - inRange = s->Synchronize(m_world->m_broadPhase, xf1, m_xf); - if (inRange == false) - { - break; - } - } - - if (inRange == false) - { - m_flags |= e_frozenFlag; - m_linearVelocity.SetZero(); - m_angularVelocity = 0.0f; - for (b2Shape* s = m_shapeList; s; s = s->m_next) - { - s->DestroyProxy(m_world->m_broadPhase); - } - - // Failure - return false; - } - - // Success - return true; -} diff --git a/src/modules/physics/box2d/Source/Dynamics/b2Body.h b/src/modules/physics/box2d/Source/Dynamics/b2Body.h deleted file mode 100644 index f2efda73a..000000000 --- a/src/modules/physics/box2d/Source/Dynamics/b2Body.h +++ /dev/null @@ -1,587 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_BODY_H -#define B2_BODY_H - -#include "../Common/b2Math.h" -#include "../Collision/Shapes/b2Shape.h" -#include "Joints/b2Joint.h" - -#include - -class b2Joint; -class b2Contact; -class b2World; -struct b2JointEdge; -struct b2ContactEdge; - -/// A body definition holds all the data needed to construct a rigid body. -/// You can safely re-use body definitions. -struct b2BodyDef -{ - /// This constructor sets the body definition default values. - b2BodyDef() - { - massData.center.SetZero(); - massData.mass = 0.0f; - massData.I = 0.0f; - userData = NULL; - position.Set(0.0f, 0.0f); - angle = 0.0f; - linearDamping = 0.0f; - angularDamping = 0.0f; - allowSleep = true; - isSleeping = false; - fixedRotation = false; - isBullet = false; - } - - /// You can use this to initialized the mass properties of the body. - /// If you prefer, you can set the mass properties after the shapes - /// have been added using b2Body::SetMassFromShapes. - b2MassData massData; - - /// Use this to store application specific body data. - void* userData; - - /// The world position of the body. Avoid creating bodies at the origin - /// since this can lead to many overlapping shapes. - b2Vec2 position; - - /// The world angle of the body in radians. - float32 angle; - - /// Linear damping is use to reduce the linear velocity. The damping parameter - /// can be larger than 1.0f but the damping effect becomes sensitive to the - /// time step when the damping parameter is large. - float32 linearDamping; - - /// Angular damping is use to reduce the angular velocity. The damping parameter - /// can be larger than 1.0f but the damping effect becomes sensitive to the - /// time step when the damping parameter is large. - float32 angularDamping; - - /// Set this flag to false if this body should never fall asleep. Note that - /// this increases CPU usage. - bool allowSleep; - - /// Is this body initially sleeping? - bool isSleeping; - - /// Should this body be prevented from rotating? Useful for characters. - bool fixedRotation; - - /// Is this a fast moving body that should be prevented from tunneling through - /// other moving bodies? Note that all bodies are prevented from tunneling through - /// static bodies. - /// @warning You should use this flag sparingly since it increases processing time. - bool isBullet; -}; - -/// A rigid body. -class b2Body -{ -public: - /// Creates a shape and attach it to this body. - /// @param shapeDef the shape definition. - /// @warning This function is locked during callbacks. - b2Shape* CreateShape(b2ShapeDef* shapeDef); - - /// Destroy a shape. This removes the shape from the broad-phase and - /// therefore destroys any contacts associated with this shape. All shapes - /// attached to a body are implicitly destroyed when the body is destroyed. - /// @param shape the shape to be removed. - /// @warning This function is locked during callbacks. - void DestroyShape(b2Shape* shape); - - /// Set the mass properties. Note that this changes the center of mass position. - /// If you are not sure how to compute mass properties, use SetMassFromShapes. - /// The inertia tensor is assumed to be relative to the center of mass. - /// @param massData the mass properties. - void SetMass(const b2MassData* massData); - - /// Compute the mass properties from the attached shapes. You typically call this - /// after adding all the shapes. If you add or remove shapes later, you may want - /// to call this again. Note that this changes the center of mass position. - void SetMassFromShapes(); - - /// Set the position of the body's origin and rotation (radians). - /// This breaks any contacts and wakes the other bodies. - /// @param position the new world position of the body's origin (not necessarily - /// the center of mass). - /// @param angle the new world rotation angle of the body in radians. - /// @return false if the movement put a shape outside the world. In this case the - /// body is automatically frozen. - bool SetXForm(const b2Vec2& position, float32 angle); - - /// Get the body transform for the body's origin. - /// @return the world transform of the body's origin. - const b2XForm& GetXForm() const; - - /// Get the world body origin position. - /// @return the world position of the body's origin. - const b2Vec2& GetPosition() const; - - /// Get the angle in radians. - /// @return the current world rotation angle in radians. - float32 GetAngle() const; - - /// Get the world position of the center of mass. - const b2Vec2& GetWorldCenter() const; - - /// Get the local position of the center of mass. - const b2Vec2& GetLocalCenter() const; - - /// Set the linear velocity of the center of mass. - /// @param v the new linear velocity of the center of mass. - void SetLinearVelocity(const b2Vec2& v); - - /// Get the linear velocity of the center of mass. - /// @return the linear velocity of the center of mass. - b2Vec2 GetLinearVelocity() const; - - /// Set the angular velocity. - /// @param omega the new angular velocity in radians/second. - void SetAngularVelocity(float32 omega); - - /// Get the angular velocity. - /// @return the angular velocity in radians/second. - float32 GetAngularVelocity() const; - - /// Apply a force at a world point. If the force is not - /// applied at the center of mass, it will generate a torque and - /// affect the angular velocity. This wakes up the body. - /// @param force the world force vector, usually in Newtons (N). - /// @param point the world position of the point of application. - void ApplyForce(const b2Vec2& force, const b2Vec2& point); - - /// Apply a torque. This affects the angular velocity - /// without affecting the linear velocity of the center of mass. - /// This wakes up the body. - /// @param torque about the z-axis (out of the screen), usually in N-m. - void ApplyTorque(float32 torque); - - /// Apply an impulse at a point. This immediately modifies the velocity. - /// It also modifies the angular velocity if the point of application - /// is not at the center of mass. This wakes up the body. - /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s. - /// @param point the world position of the point of application. - void ApplyImpulse(const b2Vec2& impulse, const b2Vec2& point); - - /// Get the total mass of the body. - /// @return the mass, usually in kilograms (kg). - float32 GetMass() const; - - /// Get the central rotational inertia of the body. - /// @return the rotational inertia, usually in kg-m^2. - float32 GetInertia() const; - - /// Get the world coordinates of a point given the local coordinates. - /// @param localPoint a point on the body measured relative the the body's origin. - /// @return the same point expressed in world coordinates. - b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const; - - /// Get the world coordinates of a vector given the local coordinates. - /// @param localVector a vector fixed in the body. - /// @return the same vector expressed in world coordinates. - b2Vec2 GetWorldVector(const b2Vec2& localVector) const; - - /// Gets a local point relative to the body's origin given a world point. - /// @param a point in world coordinates. - /// @return the corresponding local point relative to the body's origin. - b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const; - - /// Gets a local vector given a world vector. - /// @param a vector in world coordinates. - /// @return the corresponding local vector. - b2Vec2 GetLocalVector(const b2Vec2& worldVector) const; - - /// Get the world linear velocity of a world point attached to this body. - /// @param a point in world coordinates. - /// @return the world velocity of a point. - b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const; - - /// Get the world velocity of a local point. - /// @param a point in local coordinates. - /// @return the world velocity of a point. - b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const; - - /// Is this body treated like a bullet for continuous collision detection? - bool IsBullet() const; - - /// Should this body be treated like a bullet for continuous collision detection? - void SetBullet(bool flag); - - /// Is this body static (immovable)? - bool IsStatic() const; - - /// Is this body dynamic (movable)? - bool IsDynamic() const; - - /// Is this body frozen? - bool IsFrozen() const; - - /// Is this body sleeping (not simulating). - bool IsSleeping() const; - - /// You can disable sleeping on this body. - void AllowSleeping(bool flag); - - /// Wake up this body so it will begin simulating. - void WakeUp(); - - /// Put this body to sleep so it will stop simulating. - /// This also sets the velocity to zero. - void PutToSleep(); - - /// Get the list of all shapes attached to this body. - b2Shape* GetShapeList(); - - /// Get the list of all joints attached to this body. - b2JointEdge* GetJointList(); - - /// Get the next body in the world's body list. - b2Body* GetNext(); - - /// Get the user data pointer that was provided in the body definition. - void* GetUserData(); - - /// Set the user data. Use this to store your application specific data. - void SetUserData(void* data); - - /// Get the parent world of this body. - b2World* GetWorld(); - -public: - - friend class b2World; - friend class b2Island; - friend class b2ContactManager; - friend class b2ContactSolver; - - friend class b2DistanceJoint; - friend class b2GearJoint; - friend class b2MouseJoint; - friend class b2PrismaticJoint; - friend class b2PulleyJoint; - friend class b2RevoluteJoint; - - // m_flags - enum - { - e_frozenFlag = 0x0002, - e_islandFlag = 0x0004, - e_sleepFlag = 0x0008, - e_allowSleepFlag = 0x0010, - e_bulletFlag = 0x0020, - e_fixedRotationFlag = 0x0040, - }; - - // m_type - enum - { - e_staticType, - e_dynamicType, - e_maxTypes, - }; - - b2Body(const b2BodyDef* bd, b2World* world); - ~b2Body(); - - bool SynchronizeShapes(); - - void SynchronizeTransform(); - - // This is used to prevent connected bodies from colliding. - // It may lie, depending on the collideConnected flag. - bool IsConnected(const b2Body* other) const; - - void Advance(float32 t); - - uint16 m_flags; - int16 m_type; - - b2XForm m_xf; // the body origin transform - - b2Sweep m_sweep; // the swept motion for CCD - - b2Vec2 m_linearVelocity; - float32 m_angularVelocity; - - b2Vec2 m_force; - float32 m_torque; - - b2World* m_world; - b2Body* m_prev; - b2Body* m_next; - - b2Shape* m_shapeList; - int32 m_shapeCount; - - b2JointEdge* m_jointList; - b2ContactEdge* m_contactList; - - float32 m_mass, m_invMass; - float32 m_I, m_invI; - - float32 m_linearDamping; - float32 m_angularDamping; - - float32 m_sleepTime; - - void* m_userData; -}; - -inline const b2XForm& b2Body::GetXForm() const -{ - return m_xf; -} - -inline const b2Vec2& b2Body::GetPosition() const -{ - return m_xf.position; -} - -inline float32 b2Body::GetAngle() const -{ - return m_sweep.a; -} - -inline const b2Vec2& b2Body::GetWorldCenter() const -{ - return m_sweep.c; -} - -inline const b2Vec2& b2Body::GetLocalCenter() const -{ - return m_sweep.localCenter; -} - -inline void b2Body::SetLinearVelocity(const b2Vec2& v) -{ - m_linearVelocity = v; -} - -inline b2Vec2 b2Body::GetLinearVelocity() const -{ - return m_linearVelocity; -} - -inline void b2Body::SetAngularVelocity(float32 w) -{ - m_angularVelocity = w; -} - -inline float32 b2Body::GetAngularVelocity() const -{ - return m_angularVelocity; -} - -inline float32 b2Body::GetMass() const -{ - return m_mass; -} - -inline float32 b2Body::GetInertia() const -{ - return m_I; -} - -inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const -{ - return b2Mul(m_xf, localPoint); -} - -inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const -{ - return b2Mul(m_xf.R, localVector); -} - -inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const -{ - return b2MulT(m_xf, worldPoint); -} - -inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const -{ - return b2MulT(m_xf.R, worldVector); -} - -inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const -{ - return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_sweep.c); -} - -inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const -{ - return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint)); -} - -inline bool b2Body::IsBullet() const -{ - return (m_flags & e_bulletFlag) == e_bulletFlag; -} - -inline void b2Body::SetBullet(bool flag) -{ - if (flag) - { - m_flags |= e_bulletFlag; - } - else - { - m_flags &= ~e_bulletFlag; - } -} - -inline bool b2Body::IsStatic() const -{ - return m_type == e_staticType; -} - -inline bool b2Body::IsDynamic() const -{ - return m_type == e_dynamicType; -} - -inline bool b2Body::IsFrozen() const -{ - return (m_flags & e_frozenFlag) == e_frozenFlag; -} - -inline bool b2Body::IsSleeping() const -{ - return (m_flags & e_sleepFlag) == e_sleepFlag; -} - -inline void b2Body::AllowSleeping(bool flag) -{ - if (flag) - { - m_flags |= e_allowSleepFlag; - } - else - { - m_flags &= ~e_allowSleepFlag; - WakeUp(); - } -} - -inline void b2Body::WakeUp() -{ - m_flags &= ~e_sleepFlag; - m_sleepTime = 0.0f; -} - -inline void b2Body::PutToSleep() -{ - m_flags |= e_sleepFlag; - m_sleepTime = 0.0f; - m_linearVelocity.SetZero(); - m_angularVelocity = 0.0f; - m_force.SetZero(); - m_torque = 0.0f; -} - -inline b2Shape* b2Body::GetShapeList() -{ - return m_shapeList; -} - -inline b2JointEdge* b2Body::GetJointList() -{ - return m_jointList; -} - -inline b2Body* b2Body::GetNext() -{ - return m_next; -} - -inline void* b2Body::GetUserData() -{ - return m_userData; -} - -inline void b2Body::SetUserData(void* data) -{ - m_userData = data; -} - -inline bool b2Body::IsConnected(const b2Body* other) const -{ - for (b2JointEdge* jn = m_jointList; jn; jn = jn->next) - { - if (jn->other == other) - return jn->joint->m_collideConnected == false; - } - - return false; -} - -inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point) -{ - if (IsSleeping()) - { - WakeUp(); - } - m_force += force; - m_torque += b2Cross(point - m_sweep.c, force); -} - -inline void b2Body::ApplyTorque(float32 torque) -{ - if (IsSleeping()) - { - WakeUp(); - } - m_torque += torque; -} - -inline void b2Body::ApplyImpulse(const b2Vec2& impulse, const b2Vec2& point) -{ - if (IsSleeping()) - { - WakeUp(); - } - m_linearVelocity += m_invMass * impulse; - m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse); -} - -inline void b2Body::SynchronizeTransform() -{ - m_xf.R.Set(m_sweep.a); - m_xf.position = m_sweep.c - b2Mul(m_xf.R, m_sweep.localCenter); -} - -inline void b2Body::Advance(float32 t) -{ - // Advance to the new safe time. - m_sweep.Advance(t); - m_sweep.c = m_sweep.c0; - m_sweep.a = m_sweep.a0; - SynchronizeTransform(); -} - -inline b2World* b2Body::GetWorld() -{ - return m_world; -} - -#endif diff --git a/src/modules/physics/box2d/Source/Dynamics/b2ContactManager.cpp b/src/modules/physics/box2d/Source/Dynamics/b2ContactManager.cpp deleted file mode 100644 index 4fc73c2fd..000000000 --- a/src/modules/physics/box2d/Source/Dynamics/b2ContactManager.cpp +++ /dev/null @@ -1,240 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2ContactManager.h" -#include "b2World.h" -#include "b2Body.h" - -// This is a callback from the broadphase when two AABB proxies begin -// to overlap. We create a b2Contact to manage the narrow phase. -void* b2ContactManager::PairAdded(void* proxyUserData1, void* proxyUserData2) -{ - b2Shape* shape1 = (b2Shape*)proxyUserData1; - b2Shape* shape2 = (b2Shape*)proxyUserData2; - - b2Body* body1 = shape1->GetBody(); - b2Body* body2 = shape2->GetBody(); - - if (body1->IsStatic() && body2->IsStatic()) - { - return &m_nullContact; - } - - if (shape1->GetBody() == shape2->GetBody()) - { - return &m_nullContact; - } - - if (body2->IsConnected(body1)) - { - return &m_nullContact; - } - - if (m_world->m_contactFilter != NULL && m_world->m_contactFilter->ShouldCollide(shape1, shape2) == false) - { - return &m_nullContact; - } - - // Call the factory. - b2Contact* c = b2Contact::Create(shape1, shape2, &m_world->m_blockAllocator); - - if (c == NULL) - { - return &m_nullContact; - } - - // Contact creation may swap shapes. - shape1 = c->GetShape1(); - shape2 = c->GetShape2(); - body1 = shape1->GetBody(); - body2 = shape2->GetBody(); - - // Insert into the world. - c->m_prev = NULL; - c->m_next = m_world->m_contactList; - if (m_world->m_contactList != NULL) - { - m_world->m_contactList->m_prev = c; - } - m_world->m_contactList = c; - - // Connect to island graph. - - // Connect to body 1 - c->m_node1.contact = c; - c->m_node1.other = body2; - - c->m_node1.prev = NULL; - c->m_node1.next = body1->m_contactList; - if (body1->m_contactList != NULL) - { - body1->m_contactList->prev = &c->m_node1; - } - body1->m_contactList = &c->m_node1; - - // Connect to body 2 - c->m_node2.contact = c; - c->m_node2.other = body1; - - c->m_node2.prev = NULL; - c->m_node2.next = body2->m_contactList; - if (body2->m_contactList != NULL) - { - body2->m_contactList->prev = &c->m_node2; - } - body2->m_contactList = &c->m_node2; - - ++m_world->m_contactCount; - return c; -} - -// This is a callback from the broadphase when two AABB proxies cease -// to overlap. We retire the b2Contact. -void b2ContactManager::PairRemoved(void* proxyUserData1, void* proxyUserData2, void* pairUserData) -{ - B2_NOT_USED(proxyUserData1); - B2_NOT_USED(proxyUserData2); - - if (pairUserData == NULL) - { - return; - } - - b2Contact* c = (b2Contact*)pairUserData; - if (c == &m_nullContact) - { - return; - } - - // An attached body is being destroyed, we must destroy this contact - // immediately to avoid orphaned shape pointers. - Destroy(c); -} - -void b2ContactManager::Destroy(b2Contact* c) -{ - b2Shape* shape1 = c->GetShape1(); - b2Shape* shape2 = c->GetShape2(); - - // Inform the user that this contact is ending. - int32 manifoldCount = c->GetManifoldCount(); - if (manifoldCount > 0 && m_world->m_contactListener) - { - b2Body* b1 = shape1->GetBody(); - b2Body* b2 = shape2->GetBody(); - - b2Manifold* manifolds = c->GetManifolds(); - b2ContactPoint cp; - cp.shape1 = c->GetShape1(); - cp.shape2 = c->GetShape2(); - cp.friction = c->m_friction; - cp.restitution = c->m_restitution; - - for (int32 i = 0; i < manifoldCount; ++i) - { - b2Manifold* manifold = manifolds + i; - cp.normal = manifold->normal; - - for (int32 j = 0; j < manifold->pointCount; ++j) - { - b2ManifoldPoint* mp = manifold->points + j; - cp.position = b1->GetWorldPoint(mp->localPoint1); - b2Vec2 v1 = b1->GetLinearVelocityFromLocalPoint(mp->localPoint1); - b2Vec2 v2 = b2->GetLinearVelocityFromLocalPoint(mp->localPoint2); - cp.velocity = v2 - v1; - cp.separation = mp->separation; - cp.id = mp->id; - m_world->m_contactListener->Remove(&cp); - } - } - } - - // Remove from the world. - if (c->m_prev) - { - c->m_prev->m_next = c->m_next; - } - - if (c->m_next) - { - c->m_next->m_prev = c->m_prev; - } - - if (c == m_world->m_contactList) - { - m_world->m_contactList = c->m_next; - } - - b2Body* body1 = shape1->GetBody(); - b2Body* body2 = shape2->GetBody(); - - // Remove from body 1 - if (c->m_node1.prev) - { - c->m_node1.prev->next = c->m_node1.next; - } - - if (c->m_node1.next) - { - c->m_node1.next->prev = c->m_node1.prev; - } - - if (&c->m_node1 == body1->m_contactList) - { - body1->m_contactList = c->m_node1.next; - } - - // Remove from body 2 - if (c->m_node2.prev) - { - c->m_node2.prev->next = c->m_node2.next; - } - - if (c->m_node2.next) - { - c->m_node2.next->prev = c->m_node2.prev; - } - - if (&c->m_node2 == body2->m_contactList) - { - body2->m_contactList = c->m_node2.next; - } - - // Call the factory. - b2Contact::Destroy(c, &m_world->m_blockAllocator); - --m_world->m_contactCount; -} - -// This is the top level collision call for the time step. Here -// all the narrow phase collision is processed for the world -// contact list. -void b2ContactManager::Collide() -{ - // Update awake contacts. - for (b2Contact* c = m_world->m_contactList; c; c = c->GetNext()) - { - b2Body* body1 = c->GetShape1()->GetBody(); - b2Body* body2 = c->GetShape2()->GetBody(); - if (body1->IsSleeping() && body2->IsSleeping()) - { - continue; - } - - c->Update(m_world->m_contactListener); - } -} diff --git a/src/modules/physics/box2d/Source/Dynamics/b2World.cpp b/src/modules/physics/box2d/Source/Dynamics/b2World.cpp deleted file mode 100644 index ab752807c..000000000 --- a/src/modules/physics/box2d/Source/Dynamics/b2World.cpp +++ /dev/null @@ -1,1064 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "b2World.h" -#include "b2Body.h" -#include "b2Island.h" -#include "Joints/b2PulleyJoint.h" -#include "Contacts/b2Contact.h" -#include "Contacts/b2ContactSolver.h" -#include "../Collision/b2Collision.h" -#include "../Collision/Shapes/b2CircleShape.h" -#include "../Collision/Shapes/b2PolygonShape.h" -#include - -b2World::b2World(const b2AABB& worldAABB, const b2Vec2& gravity, bool doSleep) -{ - m_destructionListener = NULL; - m_boundaryListener = NULL; - m_contactFilter = &b2_defaultFilter; - m_contactListener = NULL; - m_debugDraw = NULL; - - m_bodyList = NULL; - m_contactList = NULL; - m_jointList = NULL; - - m_bodyCount = 0; - m_contactCount = 0; - m_jointCount = 0; - - m_positionCorrection = true; - m_warmStarting = true; - m_continuousPhysics = true; - - m_allowSleep = doSleep; - m_gravity = gravity; - - m_lock = false; - - m_inv_dt0 = 0.0f; - - m_contactManager.m_world = this; - void* mem = b2Alloc(sizeof(b2BroadPhase)); - m_broadPhase = new (mem) b2BroadPhase(worldAABB, &m_contactManager); - - b2BodyDef bd; - m_groundBody = CreateBody(&bd); -} - -b2World::~b2World() -{ - DestroyBody(m_groundBody); - m_broadPhase->~b2BroadPhase(); - b2Free(m_broadPhase); -} - -void b2World::SetDestructionListener(b2DestructionListener* listener) -{ - m_destructionListener = listener; -} - -void b2World::SetBoundaryListener(b2BoundaryListener* listener) -{ - m_boundaryListener = listener; -} - -void b2World::SetContactFilter(b2ContactFilter* filter) -{ - m_contactFilter = filter; -} - -void b2World::SetContactListener(b2ContactListener* listener) -{ - m_contactListener = listener; -} - -void b2World::SetDebugDraw(b2DebugDraw* debugDraw) -{ - m_debugDraw = debugDraw; -} - -b2Body* b2World::CreateBody(const b2BodyDef* def) -{ - b2Assert(m_lock == false); - if (m_lock == true) - { - return NULL; - } - - void* mem = m_blockAllocator.Allocate(sizeof(b2Body)); - b2Body* b = new (mem) b2Body(def, this); - - // Add to world doubly linked list. - b->m_prev = NULL; - b->m_next = m_bodyList; - if (m_bodyList) - { - m_bodyList->m_prev = b; - } - m_bodyList = b; - ++m_bodyCount; - - return b; -} - -void b2World::DestroyBody(b2Body* b) -{ - b2Assert(m_bodyCount > 0); - b2Assert(m_lock == false); - if (m_lock == true) - { - return; - } - - // Delete the attached joints. - b2JointEdge* jn = b->m_jointList; - while (jn) - { - b2JointEdge* jn0 = jn; - jn = jn->next; - - if (m_destructionListener) - { - m_destructionListener->SayGoodbye(jn0->joint); - } - - DestroyJoint(jn0->joint); - } - - // Delete the attached shapes. This destroys broad-phase - // proxies and pairs, leading to the destruction of contacts. - b2Shape* s = b->m_shapeList; - while (s) - { - b2Shape* s0 = s; - s = s->m_next; - - if (m_destructionListener) - { - m_destructionListener->SayGoodbye(s0); - } - - s0->DestroyProxy(m_broadPhase); - b2Shape::Destroy(s0, &m_blockAllocator); - } - - // Remove world body list. - if (b->m_prev) - { - b->m_prev->m_next = b->m_next; - } - - if (b->m_next) - { - b->m_next->m_prev = b->m_prev; - } - - if (b == m_bodyList) - { - m_bodyList = b->m_next; - } - - --m_bodyCount; - b->~b2Body(); - m_blockAllocator.Free(b, sizeof(b2Body)); -} - -b2Joint* b2World::CreateJoint(const b2JointDef* def) -{ - b2Assert(m_lock == false); - - b2Joint* j = b2Joint::Create(def, &m_blockAllocator); - - // Connect to the world list. - j->m_prev = NULL; - j->m_next = m_jointList; - if (m_jointList) - { - m_jointList->m_prev = j; - } - m_jointList = j; - ++m_jointCount; - - // Connect to the bodies' doubly linked lists. - j->m_node1.joint = j; - j->m_node1.other = j->m_body2; - j->m_node1.prev = NULL; - j->m_node1.next = j->m_body1->m_jointList; - if (j->m_body1->m_jointList) j->m_body1->m_jointList->prev = &j->m_node1; - j->m_body1->m_jointList = &j->m_node1; - - j->m_node2.joint = j; - j->m_node2.other = j->m_body1; - j->m_node2.prev = NULL; - j->m_node2.next = j->m_body2->m_jointList; - if (j->m_body2->m_jointList) j->m_body2->m_jointList->prev = &j->m_node2; - j->m_body2->m_jointList = &j->m_node2; - - // If the joint prevents collisions, then reset collision filtering. - if (def->collideConnected == false) - { - // Reset the proxies on the body with the minimum number of shapes. - b2Body* b = def->body1->m_shapeCount < def->body2->m_shapeCount ? def->body1 : def->body2; - for (b2Shape* s = b->m_shapeList; s; s = s->m_next) - { - s->RefilterProxy(m_broadPhase, b->GetXForm()); - } - } - - return j; -} - -void b2World::DestroyJoint(b2Joint* j) -{ - b2Assert(m_lock == false); - - bool collideConnected = j->m_collideConnected; - - // Remove from the doubly linked list. - if (j->m_prev) - { - j->m_prev->m_next = j->m_next; - } - - if (j->m_next) - { - j->m_next->m_prev = j->m_prev; - } - - if (j == m_jointList) - { - m_jointList = j->m_next; - } - - // Disconnect from island graph. - b2Body* body1 = j->m_body1; - b2Body* body2 = j->m_body2; - - // Wake up connected bodies. - body1->WakeUp(); - body2->WakeUp(); - - // Remove from body 1. - if (j->m_node1.prev) - { - j->m_node1.prev->next = j->m_node1.next; - } - - if (j->m_node1.next) - { - j->m_node1.next->prev = j->m_node1.prev; - } - - if (&j->m_node1 == body1->m_jointList) - { - body1->m_jointList = j->m_node1.next; - } - - j->m_node1.prev = NULL; - j->m_node1.next = NULL; - - // Remove from body 2 - if (j->m_node2.prev) - { - j->m_node2.prev->next = j->m_node2.next; - } - - if (j->m_node2.next) - { - j->m_node2.next->prev = j->m_node2.prev; - } - - if (&j->m_node2 == body2->m_jointList) - { - body2->m_jointList = j->m_node2.next; - } - - j->m_node2.prev = NULL; - j->m_node2.next = NULL; - - b2Joint::Destroy(j, &m_blockAllocator); - - b2Assert(m_jointCount > 0); - --m_jointCount; - - // If the joint prevents collisions, then reset collision filtering. - if (collideConnected == false) - { - // Reset the proxies on the body with the minimum number of shapes. - b2Body* b = body1->m_shapeCount < body2->m_shapeCount ? body1 : body2; - for (b2Shape* s = b->m_shapeList; s; s = s->m_next) - { - s->RefilterProxy(m_broadPhase, b->GetXForm()); - } - } -} - -void b2World::Refilter(b2Shape* shape) -{ - shape->RefilterProxy(m_broadPhase, shape->GetBody()->GetXForm()); -} - -// Find islands, integrate and solve constraints, solve position constraints -void b2World::Solve(const b2TimeStep& step) -{ - m_positionIterationCount = 0; - - // Size the island for the worst case. - b2Island island(m_bodyCount, m_contactCount, m_jointCount, &m_stackAllocator, m_contactListener); - - // Clear all the island flags. - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_flags &= ~b2Body::e_islandFlag; - } - for (b2Contact* c = m_contactList; c; c = c->m_next) - { - c->m_flags &= ~b2Contact::e_islandFlag; - } - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - j->m_islandFlag = false; - } - - // Build and simulate all awake islands. - int32 stackSize = m_bodyCount; - b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); - for (b2Body* seed = m_bodyList; seed; seed = seed->m_next) - { - if (seed->m_flags & (b2Body::e_islandFlag | b2Body::e_sleepFlag | b2Body::e_frozenFlag)) - { - continue; - } - - if (seed->IsStatic()) - { - continue; - } - - // Reset island and stack. - island.Clear(); - int32 stackCount = 0; - stack[stackCount++] = seed; - seed->m_flags |= b2Body::e_islandFlag; - - // Perform a depth first search (DFS) on the constraint graph. - while (stackCount > 0) - { - // Grab the next body off the stack and add it to the island. - b2Body* b = stack[--stackCount]; - island.Add(b); - - // Make sure the body is awake. - b->m_flags &= ~b2Body::e_sleepFlag; - - // To keep islands as small as possible, we don't - // propagate islands across static bodies. - if (b->IsStatic()) - { - continue; - } - - // Search all contacts connected to this body. - for (b2ContactEdge* cn = b->m_contactList; cn; cn = cn->next) - { - // Has this contact already been added to an island? - if (cn->contact->m_flags & (b2Contact::e_islandFlag | b2Contact::e_nonSolidFlag)) - { - continue; - } - - // Is this contact touching? - if (cn->contact->GetManifoldCount() == 0) - { - continue; - } - - island.Add(cn->contact); - cn->contact->m_flags |= b2Contact::e_islandFlag; - - b2Body* other = cn->other; - - // Was the other body already added to this island? - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } - - b2Assert(stackCount < stackSize); - stack[stackCount++] = other; - other->m_flags |= b2Body::e_islandFlag; - } - - // Search all joints connect to this body. - for (b2JointEdge* jn = b->m_jointList; jn; jn = jn->next) - { - if (jn->joint->m_islandFlag == true) - { - continue; - } - - island.Add(jn->joint); - jn->joint->m_islandFlag = true; - - b2Body* other = jn->other; - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } - - b2Assert(stackCount < stackSize); - stack[stackCount++] = other; - other->m_flags |= b2Body::e_islandFlag; - } - } - - island.Solve(step, m_gravity, m_positionCorrection, m_allowSleep); - m_positionIterationCount = b2Max(m_positionIterationCount, island.m_positionIterationCount); - - // Post solve cleanup. - for (int32 i = 0; i < island.m_bodyCount; ++i) - { - // Allow static bodies to participate in other islands. - b2Body* b = island.m_bodies[i]; - if (b->IsStatic()) - { - b->m_flags &= ~b2Body::e_islandFlag; - } - } - } - - m_stackAllocator.Free(stack); - - // Synchronize shapes, check for out of range bodies. - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - if (b->m_flags & (b2Body::e_sleepFlag | b2Body::e_frozenFlag)) - { - continue; - } - - if (b->IsStatic()) - { - continue; - } - - // Update shapes (for broad-phase). If the shapes go out of - // the world AABB then shapes and contacts may be destroyed, - // including contacts that are - bool inRange = b->SynchronizeShapes(); - - // Did the body's shapes leave the world? - if (inRange == false && m_boundaryListener != NULL) - { - m_boundaryListener->Violation(b); - } - } - - // Commit shape proxy movements to the broad-phase so that new contacts are created. - // Also, some contacts can be destroyed. - m_broadPhase->Commit(); -} - -// Find TOI contacts and solve them. -void b2World::SolveTOI(const b2TimeStep& step) -{ - // Reserve an island and a stack for TOI island solution. - b2Island island(m_bodyCount, b2_maxTOIContactsPerIsland, 0, &m_stackAllocator, m_contactListener); - int32 stackSize = m_bodyCount; - b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); - - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_flags &= ~b2Body::e_islandFlag; - b->m_sweep.t0 = 0.0f; - } - - for (b2Contact* c = m_contactList; c; c = c->m_next) - { - // Invalidate TOI - c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); - } - - // Find TOI events and solve them. - for (;;) - { - // Find the first TOI. - b2Contact* minContact = NULL; - float32 minTOI = 1.0f; - - for (b2Contact* c = m_contactList; c; c = c->m_next) - { - if (c->m_flags & (b2Contact::e_slowFlag | b2Contact::e_nonSolidFlag)) - { - continue; - } - - // TODO_ERIN keep a counter on the contact, only respond to M TOIs per contact. - - float32 toi = 1.0f; - if (c->m_flags & b2Contact::e_toiFlag) - { - // This contact has a valid cached TOI. - toi = c->m_toi; - } - else - { - // Compute the TOI for this contact. - b2Shape* s1 = c->GetShape1(); - b2Shape* s2 = c->GetShape2(); - b2Body* b1 = s1->GetBody(); - b2Body* b2 = s2->GetBody(); - - if ((b1->IsStatic() || b1->IsSleeping()) && (b2->IsStatic() || b2->IsSleeping())) - { - continue; - } - - // Put the sweeps onto the same time interval. - float32 t0 = b1->m_sweep.t0; - - if (b1->m_sweep.t0 < b2->m_sweep.t0) - { - t0 = b2->m_sweep.t0; - b1->m_sweep.Advance(t0); - } - else if (b2->m_sweep.t0 < b1->m_sweep.t0) - { - t0 = b1->m_sweep.t0; - b2->m_sweep.Advance(t0); - } - - b2Assert(t0 < 1.0f); - - // Compute the time of impact. - toi = b2TimeOfImpact(c->m_shape1, b1->m_sweep, c->m_shape2, b2->m_sweep); - - b2Assert(0.0f <= toi && toi <= 1.0f); - - if (toi > 0.0f && toi < 1.0f) - { - toi = b2Min((1.0f - toi) * t0 + toi, 1.0f); - } - - - c->m_toi = toi; - c->m_flags |= b2Contact::e_toiFlag; - } - - if (B2_FLT_EPSILON < toi && toi < minTOI) - { - // This is the minimum TOI found so far. - minContact = c; - minTOI = toi; - } - } - - if (minContact == NULL || 1.0f - 100.0f * B2_FLT_EPSILON < minTOI) - { - // No more TOI events. Done! - break; - } - - // Advance the bodies to the TOI. - b2Shape* s1 = minContact->GetShape1(); - b2Shape* s2 = minContact->GetShape2(); - b2Body* b1 = s1->GetBody(); - b2Body* b2 = s2->GetBody(); - b1->Advance(minTOI); - b2->Advance(minTOI); - - // The TOI contact likely has some new contact points. - minContact->Update(m_contactListener); - minContact->m_flags &= ~b2Contact::e_toiFlag; - - if (minContact->GetManifoldCount() == 0) - { - // This shouldn't happen. Numerical error? - //b2Assert(false); - continue; - } - - // Build the TOI island. We need a dynamic seed. - b2Body* seed = b1; - if (seed->IsStatic()) - { - seed = b2; - } - - // Reset island and stack. - island.Clear(); - int32 stackCount = 0; - stack[stackCount++] = seed; - seed->m_flags |= b2Body::e_islandFlag; - - // Perform a depth first search (DFS) on the contact graph. - while (stackCount > 0) - { - // Grab the next body off the stack and add it to the island. - b2Body* b = stack[--stackCount]; - island.Add(b); - - // Make sure the body is awake. - b->m_flags &= ~b2Body::e_sleepFlag; - - // To keep islands as small as possible, we don't - // propagate islands across static bodies. - if (b->IsStatic()) - { - continue; - } - - // Search all contacts connected to this body. - for (b2ContactEdge* cn = b->m_contactList; cn; cn = cn->next) - { - // Does the TOI island still have space for contacts? - if (island.m_contactCount == island.m_contactCapacity) - { - continue; - } - - // Has this contact already been added to an island? Skip slow or non-solid contacts. - if (cn->contact->m_flags & (b2Contact::e_islandFlag | b2Contact::e_slowFlag | b2Contact::e_nonSolidFlag)) - { - continue; - } - - // Is this contact touching? For performance we are not updating this contact. - if (cn->contact->GetManifoldCount() == 0) - { - continue; - } - - island.Add(cn->contact); - cn->contact->m_flags |= b2Contact::e_islandFlag; - - // Update other body. - b2Body* other = cn->other; - - // Was the other body already added to this island? - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } - - // March forward, this can do no harm since this is the min TOI. - if (other->IsStatic() == false) - { - other->Advance(minTOI); - other->WakeUp(); - } - - b2Assert(stackCount < stackSize); - stack[stackCount++] = other; - other->m_flags |= b2Body::e_islandFlag; - } - } - - b2TimeStep subStep; - subStep.dt = (1.0f - minTOI) * step.dt; - b2Assert(subStep.dt > B2_FLT_EPSILON); - subStep.inv_dt = 1.0f / subStep.dt; - subStep.maxIterations = step.maxIterations; - - island.SolveTOI(subStep); - - // Post solve cleanup. - for (int32 i = 0; i < island.m_bodyCount; ++i) - { - // Allow bodies to participate in future TOI islands. - b2Body* b = island.m_bodies[i]; - b->m_flags &= ~b2Body::e_islandFlag; - - if (b->m_flags & (b2Body::e_sleepFlag | b2Body::e_frozenFlag)) - { - continue; - } - - if (b->IsStatic()) - { - continue; - } - - // Update shapes (for broad-phase). If the shapes go out of - // the world AABB then shapes and contacts may be destroyed, - // including contacts that are - bool inRange = b->SynchronizeShapes(); - - // Did the body's shapes leave the world? - if (inRange == false && m_boundaryListener != NULL) - { - m_boundaryListener->Violation(b); - } - - // Invalidate all contact TOIs associated with this body. Some of these - // may not be in the island because they were not touching. - for (b2ContactEdge* cn = b->m_contactList; cn; cn = cn->next) - { - cn->contact->m_flags &= ~b2Contact::e_toiFlag; - } - } - - for (int32 i = 0; i < island.m_contactCount; ++i) - { - // Allow contacts to participate in future TOI islands. - b2Contact* c = island.m_contacts[i]; - c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); - } - - // Commit shape proxy movements to the broad-phase so that new contacts are created. - // Also, some contacts can be destroyed. - m_broadPhase->Commit(); - } - - m_stackAllocator.Free(stack); -} - -void b2World::Step(float32 dt, int32 iterations) -{ - m_lock = true; - - b2TimeStep step; - step.dt = dt; - step.maxIterations = iterations; - if (dt > 0.0f) - { - step.inv_dt = 1.0f / dt; - } - else - { - step.inv_dt = 0.0f; - } - - step.dtRatio = m_inv_dt0 * dt; - - step.positionCorrection = m_positionCorrection; - step.warmStarting = m_warmStarting; - - // Update contacts. - m_contactManager.Collide(); - - // Integrate velocities, solve velocity constraints, and integrate positions. - if (step.dt > 0.0f) - { - Solve(step); - } - - // Handle TOI events. - if (m_continuousPhysics && step.dt > 0.0f) - { - SolveTOI(step); - } - - // Draw debug information. - DrawDebugData(); - - m_inv_dt0 = step.inv_dt; - m_lock = false; -} - -int32 b2World::Query(const b2AABB& aabb, b2Shape** shapes, int32 maxCount) -{ - void** results = (void**)m_stackAllocator.Allocate(maxCount * sizeof(void*)); - - int32 count = m_broadPhase->Query(aabb, results, maxCount); - - for (int32 i = 0; i < count; ++i) - { - shapes[i] = (b2Shape*)results[i]; - } - - m_stackAllocator.Free(results); - return count; -} - -void b2World::DrawShape(b2Shape* shape, const b2XForm& xf, const b2Color& color, bool core) -{ - b2Color coreColor(0.9f, 0.6f, 0.6f); - - switch (shape->GetType()) - { - case e_circleShape: - { - b2CircleShape* circle = (b2CircleShape*)shape; - - b2Vec2 center = b2Mul(xf, circle->GetLocalPosition()); - float32 radius = circle->GetRadius(); - b2Vec2 axis = xf.R.col1; - - m_debugDraw->DrawSolidCircle(center, radius, axis, color); - - if (core) - { - m_debugDraw->DrawCircle(center, radius - b2_toiSlop, coreColor); - } - } - break; - - case e_polygonShape: - { - b2PolygonShape* poly = (b2PolygonShape*)shape; - int32 vertexCount = poly->GetVertexCount(); - const b2Vec2* localVertices = poly->GetVertices(); - - b2Assert(vertexCount <= b2_maxPolygonVertices); - b2Vec2 vertices[b2_maxPolygonVertices]; - - for (int32 i = 0; i < vertexCount; ++i) - { - vertices[i] = b2Mul(xf, localVertices[i]); - } - - m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color); - - if (core) - { - const b2Vec2* localCoreVertices = poly->GetCoreVertices(); - for (int32 i = 0; i < vertexCount; ++i) - { - vertices[i] = b2Mul(xf, localCoreVertices[i]); - } - m_debugDraw->DrawPolygon(vertices, vertexCount, coreColor); - } - } - break; - } -} - -void b2World::DrawJoint(b2Joint* joint) -{ - b2Body* b1 = joint->GetBody1(); - b2Body* b2 = joint->GetBody2(); - const b2XForm& xf1 = b1->GetXForm(); - const b2XForm& xf2 = b2->GetXForm(); - b2Vec2 x1 = xf1.position; - b2Vec2 x2 = xf2.position; - b2Vec2 p1 = joint->GetAnchor1(); - b2Vec2 p2 = joint->GetAnchor2(); - - b2Color color(0.5f, 0.8f, 0.8f); - - switch (joint->GetType()) - { - case e_distanceJoint: - m_debugDraw->DrawSegment(p1, p2, color); - break; - - case e_pulleyJoint: - { - b2PulleyJoint* pulley = (b2PulleyJoint*)joint; - b2Vec2 s1 = pulley->GetGroundAnchor1(); - b2Vec2 s2 = pulley->GetGroundAnchor2(); - m_debugDraw->DrawSegment(s1, p1, color); - m_debugDraw->DrawSegment(s2, p2, color); - m_debugDraw->DrawSegment(s1, s2, color); - } - break; - - case e_mouseJoint: - // don't draw this - break; - - default: - m_debugDraw->DrawSegment(x1, p1, color); - m_debugDraw->DrawSegment(p1, p2, color); - m_debugDraw->DrawSegment(x2, p2, color); - } -} - -void b2World::DrawDebugData() -{ - if (m_debugDraw == NULL) - { - return; - } - - uint32 flags = m_debugDraw->GetFlags(); - - if (flags & b2DebugDraw::e_shapeBit) - { - bool core = (flags & b2DebugDraw::e_coreShapeBit) == b2DebugDraw::e_coreShapeBit; - - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - const b2XForm& xf = b->GetXForm(); - for (b2Shape* s = b->GetShapeList(); s; s = s->GetNext()) - { - if (b->IsStatic()) - { - DrawShape(s, xf, b2Color(0.5f, 0.9f, 0.5f), core); - } - else if (b->IsSleeping()) - { - DrawShape(s, xf, b2Color(0.5f, 0.5f, 0.9f), core); - } - else - { - DrawShape(s, xf, b2Color(0.9f, 0.9f, 0.9f), core); - } - } - } - } - - if (flags & b2DebugDraw::e_jointBit) - { - for (b2Joint* j = m_jointList; j; j = j->GetNext()) - { - if (j->GetType() != e_mouseJoint) - { - DrawJoint(j); - } - } - } - - if (flags & b2DebugDraw::e_pairBit) - { - b2BroadPhase* bp = m_broadPhase; - b2Vec2 invQ; - invQ.Set(1.0f / bp->m_quantizationFactor.x, 1.0f / bp->m_quantizationFactor.y); - b2Color color(0.9f, 0.9f, 0.3f); - - for (int32 i = 0; i < b2_tableCapacity; ++i) - { - uint16 index = bp->m_pairManager.m_hashTable[i]; - while (index != b2_nullPair) - { - b2Pair* pair = bp->m_pairManager.m_pairs + index; - b2Proxy* p1 = bp->m_proxyPool + pair->proxyId1; - b2Proxy* p2 = bp->m_proxyPool + pair->proxyId2; - - b2AABB b1, b2; - b1.lowerBound.x = bp->m_worldAABB.lowerBound.x + invQ.x * bp->m_bounds[0][p1->lowerBounds[0]].value; - b1.lowerBound.y = bp->m_worldAABB.lowerBound.y + invQ.y * bp->m_bounds[1][p1->lowerBounds[1]].value; - b1.upperBound.x = bp->m_worldAABB.lowerBound.x + invQ.x * bp->m_bounds[0][p1->upperBounds[0]].value; - b1.upperBound.y = bp->m_worldAABB.lowerBound.y + invQ.y * bp->m_bounds[1][p1->upperBounds[1]].value; - b2.lowerBound.x = bp->m_worldAABB.lowerBound.x + invQ.x * bp->m_bounds[0][p2->lowerBounds[0]].value; - b2.lowerBound.y = bp->m_worldAABB.lowerBound.y + invQ.y * bp->m_bounds[1][p2->lowerBounds[1]].value; - b2.upperBound.x = bp->m_worldAABB.lowerBound.x + invQ.x * bp->m_bounds[0][p2->upperBounds[0]].value; - b2.upperBound.y = bp->m_worldAABB.lowerBound.y + invQ.y * bp->m_bounds[1][p2->upperBounds[1]].value; - - b2Vec2 x1 = 0.5f * (b1.lowerBound + b1.upperBound); - b2Vec2 x2 = 0.5f * (b2.lowerBound + b2.upperBound); - - m_debugDraw->DrawSegment(x1, x2, color); - - index = pair->next; - } - } - } - - if (flags & b2DebugDraw::e_aabbBit) - { - b2BroadPhase* bp = m_broadPhase; - b2Vec2 worldLower = bp->m_worldAABB.lowerBound; - b2Vec2 worldUpper = bp->m_worldAABB.upperBound; - - b2Vec2 invQ; - invQ.Set(1.0f / bp->m_quantizationFactor.x, 1.0f / bp->m_quantizationFactor.y); - b2Color color(0.9f, 0.3f, 0.9f); - for (int32 i = 0; i < b2_maxProxies; ++i) - { - b2Proxy* p = bp->m_proxyPool + i; - if (p->IsValid() == false) - { - continue; - } - - b2AABB b; - b.lowerBound.x = worldLower.x + invQ.x * bp->m_bounds[0][p->lowerBounds[0]].value; - b.lowerBound.y = worldLower.y + invQ.y * bp->m_bounds[1][p->lowerBounds[1]].value; - b.upperBound.x = worldLower.x + invQ.x * bp->m_bounds[0][p->upperBounds[0]].value; - b.upperBound.y = worldLower.y + invQ.y * bp->m_bounds[1][p->upperBounds[1]].value; - - b2Vec2 vs[4]; - vs[0].Set(b.lowerBound.x, b.lowerBound.y); - vs[1].Set(b.upperBound.x, b.lowerBound.y); - vs[2].Set(b.upperBound.x, b.upperBound.y); - vs[3].Set(b.lowerBound.x, b.upperBound.y); - - m_debugDraw->DrawPolygon(vs, 4, color); - } - - b2Vec2 vs[4]; - vs[0].Set(worldLower.x, worldLower.y); - vs[1].Set(worldUpper.x, worldLower.y); - vs[2].Set(worldUpper.x, worldUpper.y); - vs[3].Set(worldLower.x, worldUpper.y); - m_debugDraw->DrawPolygon(vs, 4, b2Color(0.3f, 0.9f, 0.9f)); - } - - if (flags & b2DebugDraw::e_obbBit) - { - b2Color color(0.5f, 0.3f, 0.5f); - - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - const b2XForm& xf = b->GetXForm(); - for (b2Shape* s = b->GetShapeList(); s; s = s->GetNext()) - { - if (s->GetType() != e_polygonShape) - { - continue; - } - - b2PolygonShape* poly = (b2PolygonShape*)s; - const b2OBB& obb = poly->GetOBB(); - b2Vec2 h = obb.extents; - b2Vec2 vs[4]; - vs[0].Set(-h.x, -h.y); - vs[1].Set( h.x, -h.y); - vs[2].Set( h.x, h.y); - vs[3].Set(-h.x, h.y); - - for (int32 i = 0; i < 4; ++i) - { - vs[i] = obb.center + b2Mul(obb.R, vs[i]); - vs[i] = b2Mul(xf, vs[i]); - } - - m_debugDraw->DrawPolygon(vs, 4, color); - } - } - } - - if (flags & b2DebugDraw::e_centerOfMassBit) - { - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - b2XForm xf = b->GetXForm(); - xf.position = b->GetWorldCenter(); - m_debugDraw->DrawXForm(xf); - } - } -} - -void b2World::Validate() -{ - m_broadPhase->Validate(); -} - -int32 b2World::GetProxyCount() const -{ - return m_broadPhase->m_proxyCount; -} - -int32 b2World::GetPairCount() const -{ - return m_broadPhase->m_pairManager.m_pairCount; -} diff --git a/src/modules/physics/box2d/World.h b/src/modules/physics/box2d/World.h index af3f84ce5..7cdfc8ba2 100644 --- a/src/modules/physics/box2d/World.h +++ b/src/modules/physics/box2d/World.h @@ -30,7 +30,7 @@ #include // Box2D -#include "Include/Box2D.h" +#include namespace love { From e32a373dc9952bfbaa8106e5123c539c0445d876 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 13 Mar 2011 08:04:43 -0400 Subject: [PATCH 03/78] add new joint enums (no implementation yet) --HG-- branch : box2d-update --- src/modules/physics/Joint.cpp | 3 +++ src/modules/physics/Joint.h | 3 +++ 2 files changed, 6 insertions(+) diff --git a/src/modules/physics/Joint.cpp b/src/modules/physics/Joint.cpp index 99b90041c..add6b33bf 100644 --- a/src/modules/physics/Joint.cpp +++ b/src/modules/physics/Joint.cpp @@ -46,6 +46,9 @@ namespace physics {"mouse", Joint::JOINT_MOUSE}, {"pulley", Joint::JOINT_PULLEY}, {"gear", Joint::JOINT_GEAR}, + {"friction", Joint::JOINT_FRICTION}, + {"line", Joint::JOINT_LINE}, + {"weld", Joint::JOINT_WELD}, }; StringMap Joint::types(Joint::typeEntries, sizeof(Joint::typeEntries)); diff --git a/src/modules/physics/Joint.h b/src/modules/physics/Joint.h index f5e49aa4a..efa89bec3 100644 --- a/src/modules/physics/Joint.h +++ b/src/modules/physics/Joint.h @@ -42,6 +42,9 @@ namespace physics JOINT_MOUSE, JOINT_PULLEY, JOINT_GEAR, + JOINT_FRICTION, + JOINT_LINE, + JOINT_WELD, JOINT_MAX_ENUM }; From c3d69746c1a8a234f3a084a9a814d3550f604053 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 13 Mar 2011 09:33:32 -0400 Subject: [PATCH 04/78] making a stab at updating Shapes --HG-- branch : box2d-update --- .../macosx/love.xcodeproj/project.pbxproj | 6 + src/modules/physics/box2d/CircleShape.cpp | 45 ++-- src/modules/physics/box2d/CircleShape.h | 21 +- src/modules/physics/box2d/Fixture.cpp | 9 + src/modules/physics/box2d/Fixture.h | 197 ++++++++++++++ src/modules/physics/box2d/Physics.cpp | 57 ++-- src/modules/physics/box2d/Physics.h | 21 +- src/modules/physics/box2d/PolygonShape.cpp | 12 +- src/modules/physics/box2d/PolygonShape.h | 2 +- src/modules/physics/box2d/Shape.cpp | 244 +----------------- src/modules/physics/box2d/Shape.h | 140 +--------- .../physics/box2d/wrap_CircleShape.cpp | 49 +--- src/modules/physics/box2d/wrap_CircleShape.h | 3 +- .../physics/box2d/wrap_PolygonShape.cpp | 22 -- src/modules/physics/box2d/wrap_Shape.cpp | 196 -------------- src/modules/physics/box2d/wrap_Shape.h | 22 -- 16 files changed, 300 insertions(+), 746 deletions(-) create mode 100644 src/modules/physics/box2d/Fixture.cpp create mode 100644 src/modules/physics/box2d/Fixture.h diff --git a/platform/macosx/love.xcodeproj/project.pbxproj b/platform/macosx/love.xcodeproj/project.pbxproj index eee5e9af9..933c8eeaa 100644 --- a/platform/macosx/love.xcodeproj/project.pbxproj +++ b/platform/macosx/love.xcodeproj/project.pbxproj @@ -184,6 +184,7 @@ A986EC84132CE6DB00F048C8 /* b2PulleyJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC0D132CE6D800F048C8 /* b2PulleyJoint.cpp */; }; A986EC85132CE6DB00F048C8 /* b2RevoluteJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC0F132CE6D800F048C8 /* b2RevoluteJoint.cpp */; }; A986EC86132CE6DB00F048C8 /* b2WeldJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC11132CE6D800F048C8 /* b2WeldJoint.cpp */; }; + A986ECAF132CEBB000F048C8 /* Fixture.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986ECAD132CEB9300F048C8 /* Fixture.cpp */; }; A98D914410507C97008E03F2 /* EncodedImageData.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A98D914310507C97008E03F2 /* EncodedImageData.cpp */; }; A9B4BA9C1045937F001DBC80 /* ParticleSystem.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9B4BA9A1045937F001DBC80 /* ParticleSystem.cpp */; }; A9B4BA9D1045937F001DBC80 /* wrap_ParticleSystem.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9B4BA9B1045937F001DBC80 /* wrap_ParticleSystem.cpp */; }; @@ -598,6 +599,8 @@ A986EC11132CE6D800F048C8 /* b2WeldJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2WeldJoint.cpp; sourceTree = ""; }; A986EC12132CE6D800F048C8 /* b2WeldJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2WeldJoint.h; sourceTree = ""; }; A986ECAC132CE82F00F048C8 /* Box2D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Box2D.h; sourceTree = ""; }; + A986ECAD132CEB9300F048C8 /* Fixture.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Fixture.cpp; sourceTree = ""; }; + A986ECAE132CEB9B00F048C8 /* Fixture.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Fixture.h; sourceTree = ""; }; A98D913E10507BF9008E03F2 /* EncodedImageData.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EncodedImageData.h; sourceTree = ""; }; A98D914310507C97008E03F2 /* EncodedImageData.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = EncodedImageData.cpp; sourceTree = ""; }; A9B1AE451197293000D496EB /* love_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = love_Prefix.pch; sourceTree = ""; }; @@ -1144,6 +1147,8 @@ A93E6AF010420AC7007D418B /* Contact.h */, A93E6AF110420AC7007D418B /* DistanceJoint.cpp */, A93E6AF210420AC7007D418B /* DistanceJoint.h */, + A986ECAD132CEB9300F048C8 /* Fixture.cpp */, + A986ECAE132CEB9B00F048C8 /* Fixture.h */, A93E6AF310420AC7007D418B /* GearJoint.cpp */, A93E6AF410420AC7007D418B /* GearJoint.h */, A93E6AF510420AC7007D418B /* graham */, @@ -1672,6 +1677,7 @@ A986EC84132CE6DB00F048C8 /* b2PulleyJoint.cpp in Sources */, A986EC85132CE6DB00F048C8 /* b2RevoluteJoint.cpp in Sources */, A986EC86132CE6DB00F048C8 /* b2WeldJoint.cpp in Sources */, + A986ECAF132CEBB000F048C8 /* Fixture.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/src/modules/physics/box2d/CircleShape.cpp b/src/modules/physics/box2d/CircleShape.cpp index 2c1546756..3fa88e1d0 100644 --- a/src/modules/physics/box2d/CircleShape.cpp +++ b/src/modules/physics/box2d/CircleShape.cpp @@ -30,41 +30,28 @@ namespace physics { namespace box2d { - CircleShape::CircleShape(Body * body, b2CircleDef * def) - : Shape(body) + CircleShape::CircleShape(b2CircleShape * c) { - def->localPosition = body->world->scaleDown(def->localPosition); - def->radius = body->world->scaleDown(def->radius); - radius = def->radius; - this->localPosition = def->localPosition; - - def->userData = (void*)data; - shape = body->body->CreateShape(def); + shape = c; } CircleShape::~CircleShape() { + shape = NULL; } - - float CircleShape::getRadius() const - { - return body->world->scaleUp(radius); - } - - void CircleShape::getLocalCenter(float & x, float & y) const - { - x = localPosition.x; - y = localPosition.y; - body->world->scaleUp(x, y); - } - - void CircleShape::getWorldCenter(float & x, float & y) const - { - b2Vec2 worldCenter = body->body->GetWorldPoint(localPosition); - worldCenter = body->world->scaleUp(worldCenter); - x = worldCenter.x; - y = worldCenter.y; - } + + float CircleShape::getRadius() const + { + return shape->m_radius; + } + + /** + * Gets the radius for the circle. + **/ + void CircleShape::setRadius(float r) + { + shape->m_radius = r; + } } // box2d } // physics diff --git a/src/modules/physics/box2d/CircleShape.h b/src/modules/physics/box2d/CircleShape.h index 7b00e5db8..a48becb06 100644 --- a/src/modules/physics/box2d/CircleShape.h +++ b/src/modules/physics/box2d/CircleShape.h @@ -41,15 +41,6 @@ namespace box2d **/ class CircleShape : public Shape { - private: - - // The radius of the circle. We need to store this because - // Box2D has no built-in method for getting the radius. - float radius; - - // Local offset. - b2Vec2 localPosition; - public: /** @@ -58,7 +49,7 @@ namespace box2d * @param body The parent body. * @param def The CircleShape definition. **/ - CircleShape(Body * body, b2CircleDef * def); + CircleShape(b2CircleShape * c); virtual ~CircleShape(); @@ -66,11 +57,11 @@ namespace box2d * Gets the radius for the circle. **/ float getRadius() const; - - // There is no support for setting the radius. - - void getLocalCenter(float & x, float & y) const; - void getWorldCenter(float & x, float & y) const; + + /** + * Gets the radius for the circle. + **/ + void setRadius(float r); }; } // box2d diff --git a/src/modules/physics/box2d/Fixture.cpp b/src/modules/physics/box2d/Fixture.cpp new file mode 100644 index 000000000..fca250b11 --- /dev/null +++ b/src/modules/physics/box2d/Fixture.cpp @@ -0,0 +1,9 @@ +// +// Fixture.cpp +// love +// +// Created by Bill Meltsner on 3/13/11. +// Copyright 2011 Bill Meltsner. All rights reserved. +// + +#include "Fixture.h" diff --git a/src/modules/physics/box2d/Fixture.h b/src/modules/physics/box2d/Fixture.h new file mode 100644 index 000000000..76760b5d7 --- /dev/null +++ b/src/modules/physics/box2d/Fixture.h @@ -0,0 +1,197 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BOX2D_FIXTURE_H +#define LOVE_PHYSICS_BOX2D_FIXTURE_H + +// LOVE +#include +#include +#include +#include +#include + +// Box2D +#include + +namespace love +{ +namespace physics +{ +namespace box2d +{ + /** + * This struct is stored in a void pointer + * in the Box2D Fixture class. For now, all we + * need is a Lua reference to arbitrary data, + * but we might need more later. + **/ + struct fixtureudata + { + // Reference to arbitrary data. + Reference * ref; + }; + + /** + * A Fixture is used to attach a shape to a body for collision detection. + * A Fixture inherits its transform from its parent. Fixtures hold + * additional non-geometric data such as friction, collision filters, + * etc. + **/ + class Fixture : public Object + { + protected: + + b2Fixture * fixture; + fixtureudata * data; + + public: + + /** + * Creates a Fixture. + **/ + Fixture(Body * body, Shape * shape); + + virtual ~Fixture(); + + /** + * Gets the type of the Fixture's Shape. Useful for + * debug drawing. + **/ + Shape::Type getType() const; + + /** + * Sets the friction of the Fixture. + * @param friction The new friction. + **/ + void setFriction(float friction); + + /** + * Sets the restitution for the Fixture. + * @param restitution The restitution. + **/ + void setRestitution(float restitution); + + /** + * Sets the density of the Fixture. + * @param density The density of the Fixture. + **/ + void setDensity(float density); + + /** + * Set whether this Fixture should be a sensor or not. + * @param sensor True if sensor, false if not. + **/ + void setSensor(bool sensor); + + /** + * Gets the friction of the Fixture. + * @returns The friction. + **/ + float getFriction() const; + + /** + * Gets the restitution of the Fixture. + * @return The restitution of the Fixture. + **/ + float getRestitution() const; + + /** + * Gets the density of the Fixture. + * @return The density. + **/ + float getDensity() const; + + /** + * Checks whether this Fixture acts as a sensor. + * @return True if sensor, false otherwise. + **/ + bool isSensor() const; + + /** + * Get the body attatched to this Fixture. + * @return The parent Body. + **/ + Body * getBody() const; + + /** + * Checks if a point is inside the Fixture. + * @param x The x-component of the Fixture. + * @param y The y-component of the Fixture. + **/ + bool testPoint(float x, float y) const; + + /** + * Tests whether a line segment intersects a Fixture. + **/ + int testSegment(lua_State * L); + + /** + * Sets the filter data. An integer array is used even though the + * first two elements are unsigned shorts. The elements are: + * category (16-bits), mask (16-bits) and group (32-bits/int). + **/ + void setFilterData(int * v); + + /** + * Gets the filter data. An integer array is used even though the + * first two elements are unsigned shorts. The elements are: + * category (16-bits), mask (16-bits) and group (32-bits/int). + **/ + void getFilterData(int * v); + + void setGroupIndex(int index); + int getGroupIndex() const; + + int setCategory(lua_State * L); + int setMask(lua_State * L); + int getCategory(lua_State * L); + int getMask(lua_State * L); + uint16 getBits(lua_State * L); + int pushBits(lua_State * L, uint16 bits); + + /** + * This function stores an in-C reference to + * arbitrary Lua data in the Box2D Fixture object. + * + * The data set here will be passed to the collision + * handler when collisions occur. + **/ + int setData(lua_State * L); + + /** + * Gets the data set with setData. If no + * data is set, nil is returned. + **/ + int getData(lua_State * L); + + /** + * Gets the bounding box for this Fixture. + * The function returns eight values which can be + * passed directly to love.graphics.polygon. + **/ + int getBoundingBox(lua_State * L); + }; + +} // box2d +} // physics +} // love + +#endif // LOVE_PHYSICS_BOX2D_FIXTURE_H diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 92f6b1de1..7829a1ec9 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -78,41 +78,40 @@ namespace box2d return new CircleShape(body, &def); } - PolygonShape * Physics::newRectangleShape(Body * body, float w, float h) + PolygonShape * Physics::newRectangleShape(float w, float h) { return newRectangleShape(body, 0, 0, w, h, 0); } - PolygonShape * Physics::newRectangleShape(Body * body, float x, float y, float w, float h) + PolygonShape * Physics::newRectangleShape(float x, float y, float w, float h) { return newRectangleShape(body, x, y, w, h, 0); } - PolygonShape * Physics::newRectangleShape(Body * body, float x, float y, float w, float h, float angle) + PolygonShape * Physics::newRectangleShape(float x, float y, float w, float h, float angle) { - b2PolygonDef def; - def.friction = 0.5f; - def.restitution = 0.1f; - def.density = 1.0f; - def.SetAsBox(w/2.0f, h/2.0f, b2Vec2(x, y), angle); - return new PolygonShape(body, &def); + b2PolygonShape s; + s.SetAsBox(w/2.0f, h/2.0f, b2Vec2(x, y), angle); + return new PolygonShape(&s); + } + + PolygonShape * Physics::newEdgeShape(float x1, float y1, float x2, float y2) + { + b2PolygonShape s; + s.SetAsEdge(b2vec2(x1, y1), b2vec2(x2, y2)); + return new PolygonShape(&s); } int Physics::newPolygonShape(lua_State * L) { int argc = lua_gettop(L); - int vcount = (int)(argc-1)/2; - // 1 body + 3 vertices - love::luax_assert_argc(L, 1 + (2 * 3)); + int vcount = (int)argc/2; + // 3 vertices + love::luax_assert_argc(L, 2 * 3); - Body * b = luax_checkbody(L, 1); + b2PolygonShape s; - b2PolygonDef def; - def.friction = 0.5f; - def.restitution = 0.1f; - def.density = 1.0f; - - std::vector points(def.vertexCount); + std::vector points(s.m_vertexCount); std::vector convex_hull; for(int i = 0;ivertexCount; i++) - def->vertices[i] = body->world->scaleDown(def->vertices[i]); - - def->userData = (void*)data; - shape = body->body->CreateShape(def); + shape = p; } PolygonShape::~PolygonShape() @@ -48,11 +43,10 @@ namespace box2d { love::luax_assert_argc(L, 0); b2PolygonShape * p = (b2PolygonShape *)shape; - const b2Vec2 * vertices = p->GetVertices(); int count = p->GetVertexCount(); for(int i = 0;iworld->scaleUp(body->body->GetWorldPoint(vertices[i])); + b2Vec2 v = p->GetVertex(i); lua_pushnumber(L, v.x); lua_pushnumber(L, v.y); } diff --git a/src/modules/physics/box2d/PolygonShape.h b/src/modules/physics/box2d/PolygonShape.h index 7c02c9fed..91969031d 100644 --- a/src/modules/physics/box2d/PolygonShape.h +++ b/src/modules/physics/box2d/PolygonShape.h @@ -47,7 +47,7 @@ namespace box2d * @param body The parent Body. * @param def The polygon definition. **/ - PolygonShape(Body * body, b2PolygonDef * def); + PolygonShape(b2PolygonShape * p); virtual ~PolygonShape(); diff --git a/src/modules/physics/box2d/Shape.cpp b/src/modules/physics/box2d/Shape.cpp index 32dcb3304..c3d30854c 100644 --- a/src/modules/physics/box2d/Shape.cpp +++ b/src/modules/physics/box2d/Shape.cpp @@ -33,265 +33,29 @@ namespace physics { namespace box2d { - Shape::Shape(Body * body) - : body(body), shape(NULL) + Shape::Shape() + : shape(NULL) { - body->retain(); - data = new shapeudata(); - data->ref = 0; } Shape::~Shape() { - if(data->ref != 0) - delete data->ref; - - delete data; - data = 0; - - if (shape) - body->body->DestroyShape(shape); shape = 0; - - body->release(); } Shape::Type Shape::getType() const { switch(shape->GetType()) { - case e_circleShape: + case b2Shape::e_circle: return SHAPE_CIRCLE; - case e_polygonShape: + case b2Shape::e_polygon: return SHAPE_POLYGON; default: return SHAPE_INVALID; } } - void Shape::setFriction(float friction) - { - shape->m_friction = friction; - } - - void Shape::setRestitution(float restitution) - { - shape->m_restitution = restitution; - } - - void Shape::setDensity(float density) - { - shape->m_density = density; - } - - void Shape::setSensor(bool sensor) - { - shape->m_isSensor = sensor; - } - - float Shape::getFriction() const - { - return shape->GetFriction(); - } - - float Shape::getRestitution() const - { - return shape->GetRestitution(); - } - - float Shape::getDensity() const - { - return shape->m_density; - } - - bool Shape::isSensor() const - { - return shape->IsSensor(); - } - - Body * Shape::getBody() const - { - return body; - } - - bool Shape::testPoint(float x, float y) const - { - return shape->TestPoint(shape->GetBody()->GetXForm(), body->getWorld()->scaleDown(b2Vec2(x, y))); - } - - int Shape::testSegment(lua_State * L) - { - love::luax_assert_argc(L, 4, 4); - - b2Segment s; - - s.p1.x = (float)lua_tonumber(L, 1); - s.p1.y = (float)lua_tonumber(L, 2); - s.p2.x = (float)lua_tonumber(L, 3); - s.p2.y = (float)lua_tonumber(L, 4); - - s.p1 = body->getWorld()->scaleDown(s.p1); - s.p2 = body->getWorld()->scaleDown(s.p2); - - float lambda; - b2Vec2 normal; - - if(shape->TestSegment(shape->GetBody()->GetXForm(), &lambda, &normal, s, 1.0f)) - { - lua_pushnumber(L, lambda); - normal = body->getWorld()->scaleUp(normal); - lua_pushnumber(L, normal.x); - lua_pushnumber(L, normal.y); - return 3; - } - - return 0; - } - - void Shape::setFilterData(int * v) - { - b2FilterData f; - f.categoryBits = (unsigned short)v[0]; - f.maskBits = (unsigned short)v[1]; - f.groupIndex = v[2]; - shape->SetFilterData(f); - shape->GetBody()->GetWorld()->Refilter(shape); - } - - void Shape::getFilterData(int * v) - { - b2FilterData f = shape->GetFilterData(); - v[0] = (int)f.categoryBits; - v[1] = (int)f.maskBits; - v[2] = f.groupIndex; - } - - int Shape::setCategory(lua_State * L) - { - b2FilterData f = shape->GetFilterData(); - f.categoryBits = (uint16)getBits(L); - shape->SetFilterData(f); - shape->GetBody()->GetWorld()->Refilter(shape); - return 0; - } - - int Shape::setMask(lua_State * L) - { - b2FilterData f = shape->GetFilterData(); - f.maskBits = ~(uint16)getBits(L); - shape->SetFilterData(f); - shape->GetBody()->GetWorld()->Refilter(shape); - return 0; - } - - void Shape::setGroupIndex(int index) - { - b2FilterData f = shape->GetFilterData(); - f.groupIndex = (uint16)index; - shape->SetFilterData(f); - shape->GetBody()->GetWorld()->Refilter(shape); - } - - int Shape::getGroupIndex() const - { - b2FilterData f = shape->GetFilterData(); - return f.groupIndex; - } - - int Shape::getCategory(lua_State * L) - { - return pushBits(L, shape->GetFilterData().categoryBits); - } - - int Shape::getMask(lua_State * L) - { - return pushBits(L, ~(shape->GetFilterData().maskBits)); - } - - uint16 Shape::getBits(lua_State * L) - { - // Get number of args. - int argc = lua_gettop(L); - - // The new bitset. - std::bitset<16> b; - - for(int i = 1;i<=argc;i++) - { - size_t bpos = (size_t)(lua_tointeger(L, i)-1); - if(bpos > 16) - return luaL_error(L, "Values must be in range 1-16."); - b.set(bpos, true); - } - - return (uint16)b.to_ulong(); - } - - int Shape::pushBits(lua_State * L, uint16 bits) - { - // Create a bitset. - std::bitset<16> b((int)bits); - - // Push all set bits. - for(int i = 0;i<16;i++) - if(b.test(i)) - lua_pushinteger(L, i+1); - - // Count number of set bits. - return (int)b.count(); - } - - int Shape::setData(lua_State * L) - { - love::luax_assert_argc(L, 1, 1); - - if(data->ref != 0) - { - delete data->ref; - data->ref = 0; - } - - data->ref = new Reference(L); - return 0; - } - - int Shape::getData(lua_State * L) - { - love::luax_assert_argc(L, 0, 0); - if(data->ref != 0) - data->ref->push(); - else - lua_pushnil(L); - - return 1; - } - - int Shape::getBoundingBox(lua_State * L) - { - love::luax_assert_argc(L, 0, 0); - b2AABB bb; - shape->ComputeAABB(&bb, shape->GetBody()->GetXForm()); - bb = body->getWorld()->scaleUp(bb); - - // Top left. - lua_pushnumber(L, bb.lowerBound.x); - lua_pushnumber(L, bb.upperBound.y); - - // Bottom left. - lua_pushnumber(L, bb.lowerBound.x); - lua_pushnumber(L, bb.lowerBound.y); - - // Bottom right. - lua_pushnumber(L, bb.upperBound.x); - lua_pushnumber(L, bb.lowerBound.y); - - // Top right. - lua_pushnumber(L, bb.upperBound.x); - lua_pushnumber(L, bb.upperBound.y); - - return 8; - } - } // box2d } // physics } // love diff --git a/src/modules/physics/box2d/Shape.h b/src/modules/physics/box2d/Shape.h index 254465167..bb77239f3 100644 --- a/src/modules/physics/box2d/Shape.h +++ b/src/modules/physics/box2d/Shape.h @@ -35,20 +35,9 @@ namespace physics { namespace box2d { - /** - * This struct is stored in a void pointer - * in the Box2D Shape class. For now, all we - * need is a Lua reference to arbitrary data, - * but we might need more later. - **/ - struct shapeudata - { - // Reference to arbitrary data. - Reference * ref; - }; /** - * A Shape is geometry attached to a Body. + * A Shape is geometry, attached to a Body via a Fixture. * A Body has position and orientation, and * a Shape's geometry will be affected by the parent * body's transformation. @@ -57,26 +46,15 @@ namespace box2d { protected: - // A pointer to the parent Body. If the Body - // is destroyed, all child shapes are destroyed as well. - // This ensures that all child shapes are always destroyed - // *before* the parent Body. - Body * body; - // The Box2D shape. b2Shape * shape; - // Our shape data, to be stored in - // the Box2D shape. - shapeudata * data; - public: /** - * Creates a Shape attatched to the specified - * Body. + * Creates a Shape. **/ - Shape(Body * body); + Shape(); virtual ~Shape(); @@ -85,118 +63,6 @@ namespace box2d * debug drawing. **/ Type getType() const; - - /** - * Sets the friction of the Shape. - * @param friction The new friction. - **/ - void setFriction(float friction); - - /** - * Sets the restitution for the Shape. - * @param restitution The restitution. - **/ - void setRestitution(float restitution); - - /** - * Sets the density of the Shape. - * @param density The density of the Shape. - **/ - void setDensity(float density); - - /** - * Set whether this shape should be a sensor or not. - * @param sensor True if sensor, false if not. - **/ - void setSensor(bool sensor); - - /** - * Gets the friction of the Shape. - * @returns The friction. - **/ - float getFriction() const; - - /** - * Gets the restitution of the Shape. - * @return The restitution of the Shape. - **/ - float getRestitution() const; - - /** - * Gets the density of the Shape. - * @return The density. - **/ - float getDensity() const; - - /** - * Checks whether this Shape acts as a sensor. - * @return True if sensor, false otherwise. - **/ - bool isSensor() const; - - /** - * Get the body attatched to this Shape. - * @return The parent Body. - **/ - Body * getBody() const; - - /** - * Checks if a point is inside the Shape. - * @param x The x-component of the Shape. - * @param y The y-component of the Shape. - **/ - bool testPoint(float x, float y) const; - - /** - * Tests whether a line segment intersects a Shape. - **/ - int testSegment(lua_State * L); - - /** - * Sets the filter data. An integer array is used even though the - * first two elements are unsigned shorts. The elements are: - * category (16-bits), mask (16-bits) and group (32-bits/int). - **/ - void setFilterData(int * v); - - /** - * Gets the filter data. An integer array is used even though the - * first two elements are unsigned shorts. The elements are: - * category (16-bits), mask (16-bits) and group (32-bits/int). - **/ - void getFilterData(int * v); - - void setGroupIndex(int index); - int getGroupIndex() const; - - int setCategory(lua_State * L); - int setMask(lua_State * L); - int getCategory(lua_State * L); - int getMask(lua_State * L); - uint16 getBits(lua_State * L); - int pushBits(lua_State * L, uint16 bits); - - /** - * This function stores an in-C reference to - * arbitrary Lua data in the Box2D shape object. - * - * The data set here will be passed to the collision - * handler when collisions occur. - **/ - int setData(lua_State * L); - - /** - * Gets the data set with setData. If no - * data is set, nil is returned. - **/ - int getData(lua_State * L); - - /** - * Gets the bounding box for this Shape. - * The function returns eight values which can be - * passed directly to love.graphics.polygon. - **/ - int getBoundingBox(lua_State * L); }; } // box2d diff --git a/src/modules/physics/box2d/wrap_CircleShape.cpp b/src/modules/physics/box2d/wrap_CircleShape.cpp index 157b905d2..a17bef0d9 100644 --- a/src/modules/physics/box2d/wrap_CircleShape.cpp +++ b/src/modules/physics/box2d/wrap_CircleShape.cpp @@ -38,54 +38,19 @@ namespace box2d return 1; } - int w_CircleShape_getLocalCenter(lua_State * L) - { - CircleShape * c = luax_checkcircleshape(L, 1); - float x, y; - c->getLocalCenter(x, y); - lua_pushnumber(L, x); - lua_pushnumber(L, y); - return 2; - } - - int w_CircleShape_getWorldCenter(lua_State * L) - { - CircleShape * c = luax_checkcircleshape(L, 1); - float x, y; - c->getWorldCenter(x, y); - lua_pushnumber(L, x); - lua_pushnumber(L, y); - return 2; + int w_CircleShape_setRadius(lua_State * L) + { + CircleShape * c = luax_checkcircleshape(L, 1); + float r = (float)luaL_checknumber(L, 2); + c->setRadius(r); + return 0; } static const luaL_Reg functions[] = { { "getRadius", w_CircleShape_getRadius }, - { "getLocalCenter", w_CircleShape_getLocalCenter }, - { "getWorldCenter", w_CircleShape_getWorldCenter }, + { "setRadius", w_CircleShape_setRadius }, // From Shape. { "getType", w_Shape_getType }, - { "setFriction", w_Shape_setFriction }, - { "setRestitution", w_Shape_setRestitution }, - { "setDensity", w_Shape_setDensity }, - { "setSensor", w_Shape_setSensor }, - { "getFriction", w_Shape_getFriction }, - { "getRestitution", w_Shape_getRestitution }, - { "getDensity", w_Shape_getDensity }, - { "getBody", w_Shape_getBody }, - { "isSensor", w_Shape_isSensor }, - { "testPoint", w_Shape_testPoint }, - { "testSegment", w_Shape_testSegment }, - { "setFilterData", w_Shape_setFilterData }, - { "getFilterData", w_Shape_getFilterData }, - { "setCategory", w_Shape_setCategory }, - { "getCategory", w_Shape_getCategory }, - { "setMask", w_Shape_setMask }, - { "getMask", w_Shape_getMask }, - { "setData", w_Shape_setData }, - { "getData", w_Shape_getData }, - { "getBoundingBox", w_Shape_getBoundingBox }, - { "getGroupIndex", w_Shape_getGroupIndex }, - { "setGroupIndex", w_Shape_setGroupIndex }, { "destroy", w_Shape_destroy }, { 0, 0 } }; diff --git a/src/modules/physics/box2d/wrap_CircleShape.h b/src/modules/physics/box2d/wrap_CircleShape.h index 17925391f..4cd879b51 100644 --- a/src/modules/physics/box2d/wrap_CircleShape.h +++ b/src/modules/physics/box2d/wrap_CircleShape.h @@ -34,8 +34,7 @@ namespace box2d { CircleShape * luax_checkcircleshape(lua_State * L, int idx); int w_CircleShape_getRadius(lua_State * L); - int w_CircleShape_getLocalCenter(lua_State * L); - int w_CircleShape_getWorldCenter(lua_State * L); + int w_CircleShape_setRadius(lua_State * L); int luaopen_circleshape(lua_State * L); } // box2d diff --git a/src/modules/physics/box2d/wrap_PolygonShape.cpp b/src/modules/physics/box2d/wrap_PolygonShape.cpp index af5e0d8e2..8b8a5cc28 100644 --- a/src/modules/physics/box2d/wrap_PolygonShape.cpp +++ b/src/modules/physics/box2d/wrap_PolygonShape.cpp @@ -42,28 +42,6 @@ namespace box2d { "getPoints", w_PolygonShape_getPoints }, // From Shape. { "getType", w_Shape_getType }, - { "setFriction", w_Shape_setFriction }, - { "setRestitution", w_Shape_setRestitution }, - { "setDensity", w_Shape_setDensity }, - { "setSensor", w_Shape_setSensor }, - { "getFriction", w_Shape_getFriction }, - { "getRestitution", w_Shape_getRestitution }, - { "getDensity", w_Shape_getDensity }, - { "getBody", w_Shape_getBody }, - { "isSensor", w_Shape_isSensor }, - { "testPoint", w_Shape_testPoint }, - { "testSegment", w_Shape_testSegment }, - { "setFilterData", w_Shape_setFilterData }, - { "getFilterData", w_Shape_getFilterData }, - { "setCategory", w_Shape_setCategory }, - { "getCategory", w_Shape_getCategory }, - { "setMask", w_Shape_setMask }, - { "getMask", w_Shape_getMask }, - { "setData", w_Shape_setData }, - { "getData", w_Shape_getData }, - { "getBoundingBox", w_Shape_getBoundingBox }, - { "getGroupIndex", w_Shape_getGroupIndex }, - { "setGroupIndex", w_Shape_setGroupIndex }, { "destroy", w_Shape_destroy }, { 0, 0 } }; diff --git a/src/modules/physics/box2d/wrap_Shape.cpp b/src/modules/physics/box2d/wrap_Shape.cpp index 758a4c6ad..510b75b16 100644 --- a/src/modules/physics/box2d/wrap_Shape.cpp +++ b/src/modules/physics/box2d/wrap_Shape.cpp @@ -41,180 +41,6 @@ namespace box2d return 1; } - int w_Shape_setFriction(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - float arg1 = (float)luaL_checknumber(L, 2); - t->setFriction(arg1); - return 0; - } - - int w_Shape_setRestitution(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - float arg1 = (float)luaL_checknumber(L, 2); - t->setRestitution(arg1); - return 0; - } - - int w_Shape_setDensity(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - float arg1 = (float)luaL_checknumber(L, 2); - t->setDensity(arg1); - return 0; - } - - int w_Shape_setSensor(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - bool arg1 = luax_toboolean(L, 2); - t->setSensor(arg1); - return 0; - } - - int w_Shape_getFriction(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - lua_pushnumber(L, t->getFriction()); - return 1; - } - - int w_Shape_getRestitution(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - lua_pushnumber(L, t->getRestitution()); - return 1; - } - - int w_Shape_getDensity(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - lua_pushnumber(L, t->getDensity()); - return 1; - } - - int w_Shape_isSensor(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - luax_pushboolean(L, t->isSensor()); - return 1; - } - - int w_Shape_getBody(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - Body * body = t->getBody(); - if(body == 0) - return 0; - body->retain(); - luax_newtype(L, "Body", PHYSICS_BODY_T, (void*)body); - return 1; - } - - int w_Shape_testPoint(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - float x = (float)luaL_checknumber(L, 2); - float y = (float)luaL_checknumber(L, 3); - luax_pushboolean(L, t->testPoint(x, y)); - return 1; - } - - int w_Shape_testSegment(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - lua_remove(L, 1); - return t->testSegment(L); - } - - int w_Shape_setFilterData(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - int v[3]; - v[0] = luaL_checkint(L, 2); - v[1] = luaL_checkint(L, 3); - v[2] = luaL_checkint(L, 4); - t->setFilterData(v); - return 0; - } - - int w_Shape_getFilterData(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - int v[3]; - t->getFilterData(v); - lua_pushinteger(L, v[0]); - lua_pushinteger(L, v[1]); - lua_pushinteger(L, v[2]); - return 3; - } - - int w_Shape_setCategory(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - lua_remove(L, 1); - return t->setCategory(L); - } - - int w_Shape_getCategory(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - lua_remove(L, 1); - return t->getCategory(L); - } - - int w_Shape_setMask(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - lua_remove(L, 1); - return t->setMask(L); - } - - int w_Shape_getMask(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - lua_remove(L, 1); - return t->getMask(L); - } - - int w_Shape_setData(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - lua_remove(L, 1); - return t->setData(L); - } - - int w_Shape_getData(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - lua_remove(L, 1); - return t->getData(L); - } - - int w_Shape_getBoundingBox(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - lua_remove(L, 1); - return t->getBoundingBox(L); - } - - int w_Shape_getGroupIndex(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - int i = t->getGroupIndex(); - lua_pushinteger(L, i); - return 1; - } - - int w_Shape_setGroupIndex(lua_State * L) - { - Shape * t = luax_checkshape(L, 1); - int i = luaL_checkint(L, 2); - t->setGroupIndex(i); - return 0; - } - int w_Shape_destroy(lua_State * L) { Proxy * p = (Proxy *)lua_touserdata(L, 1); @@ -227,28 +53,6 @@ namespace box2d static const luaL_Reg functions[] = { { "getType", w_Shape_getType }, - { "setFriction", w_Shape_setFriction }, - { "setRestitution", w_Shape_setRestitution }, - { "setDensity", w_Shape_setDensity }, - { "setSensor", w_Shape_setSensor }, - { "getFriction", w_Shape_getFriction }, - { "getRestitution", w_Shape_getRestitution }, - { "getDensity", w_Shape_getDensity }, - { "getBody", w_Shape_getBody }, - { "isSensor", w_Shape_isSensor }, - { "testPoint", w_Shape_testPoint }, - { "testSegment", w_Shape_testSegment }, - { "setFilterData", w_Shape_setFilterData }, - { "getFilterData", w_Shape_getFilterData }, - { "setCategory", w_Shape_setCategory }, - { "getCategory", w_Shape_getCategory }, - { "setMask", w_Shape_setMask }, - { "getMask", w_Shape_getMask }, - { "setData", w_Shape_setData }, - { "getData", w_Shape_getData }, - { "getBoundingBox", w_Shape_getBoundingBox }, - { "getGroupIndex", w_Shape_getGroupIndex }, - { "setGroupIndex", w_Shape_setGroupIndex }, { "destroy", w_Shape_destroy }, { 0, 0 } }; diff --git a/src/modules/physics/box2d/wrap_Shape.h b/src/modules/physics/box2d/wrap_Shape.h index 24d7ff21a..02950111d 100644 --- a/src/modules/physics/box2d/wrap_Shape.h +++ b/src/modules/physics/box2d/wrap_Shape.h @@ -33,28 +33,6 @@ namespace box2d { Shape * luax_checkshape(lua_State * L, int idx); int w_Shape_getType(lua_State * L); - int w_Shape_setFriction(lua_State * L); - int w_Shape_setRestitution(lua_State * L); - int w_Shape_setDensity(lua_State * L); - int w_Shape_setSensor(lua_State * L); - int w_Shape_getFriction(lua_State * L); - int w_Shape_getRestitution(lua_State * L); - int w_Shape_getDensity(lua_State * L); - int w_Shape_isSensor(lua_State * L); - int w_Shape_getBody(lua_State * L); - int w_Shape_testPoint(lua_State * L); - int w_Shape_testSegment(lua_State * L); - int w_Shape_setFilterData(lua_State * L); - int w_Shape_getFilterData(lua_State * L); - int w_Shape_setCategory(lua_State * L); - int w_Shape_getCategory(lua_State * L); - int w_Shape_setMask(lua_State * L); - int w_Shape_getMask(lua_State * L); - int w_Shape_setData(lua_State * L); - int w_Shape_getData(lua_State * L); - int w_Shape_getBoundingBox(lua_State * L); - int w_Shape_getGroupIndex(lua_State * L); - int w_Shape_setGroupIndex(lua_State * L); int w_Shape_destroy(lua_State * L); int luaopen_shape(lua_State * L); From be146c5f61dedafa73177960a59e38ffb8746a2d Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 13 Mar 2011 10:09:17 -0400 Subject: [PATCH 05/78] some more Shape fixes --HG-- branch : box2d-update --- src/modules/physics/box2d/wrap_Physics.cpp | 51 +++++++++++++--------- src/modules/physics/box2d/wrap_Physics.h | 3 +- 2 files changed, 32 insertions(+), 22 deletions(-) diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index e94bf1e2b..cd5d79cf8 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -63,22 +63,21 @@ namespace box2d int w_newCircleShape(lua_State * L) { - Body * body = luax_checktype(L, 1, "Body", PHYSICS_BODY_T); int top = lua_gettop(L); - if(top == 2) + if(top == 1) { - float radius = (float)luaL_checknumber(L, 2); - CircleShape * shape = instance->newCircleShape(body, radius); + float radius = (float)luaL_checknumber(L, 1); + CircleShape * shape = instance->newCircleShape(radius); luax_newtype(L, "CircleShape", PHYSICS_CIRCLE_SHAPE_T, (void*)shape); return 1; } - else if(top == 4) + else if(top == 3) { - float x = (float)luaL_checknumber(L, 2); - float y = (float)luaL_checknumber(L, 3); - float radius = (float)luaL_checknumber(L, 4); - CircleShape * shape = instance->newCircleShape(body, x, y, radius); + float x = (float)luaL_checknumber(L, 1); + float y = (float)luaL_checknumber(L, 2); + float radius = (float)luaL_checknumber(L, 3); + CircleShape * shape = instance->newCircleShape(x, y, radius); luax_newtype(L, "CircleShape", PHYSICS_CIRCLE_SHAPE_T, (void*)shape); return 1; } @@ -88,31 +87,41 @@ namespace box2d int w_newRectangleShape(lua_State * L) { - Body * body = luax_checktype(L, 1, "Body", PHYSICS_BODY_T); int top = lua_gettop(L); - if(top == 3) + if(top == 2) { - float w = (float)luaL_checknumber(L, 2); - float h = (float)luaL_checknumber(L, 3); - PolygonShape * shape = instance->newRectangleShape(body, w, h); + float w = (float)luaL_checknumber(L, 1); + float h = (float)luaL_checknumber(L, 2); + PolygonShape * shape = instance->newRectangleShape(w, h); luax_newtype(L, "PolygonShape", PHYSICS_POLYGON_SHAPE_T, (void*)shape); return 1; } - else if(top == 5 || top == 6) + else if(top == 4 || top == 5) { - float x = (float)luaL_checknumber(L, 2); - float y = (float)luaL_checknumber(L, 3); - float w = (float)luaL_checknumber(L, 4); - float h = (float)luaL_checknumber(L, 5); - float angle = (float)luaL_optnumber(L, 6, 0); - PolygonShape * shape = instance->newRectangleShape(body, x, y, w, h, angle); + float x = (float)luaL_checknumber(L, 1); + float y = (float)luaL_checknumber(L, 2); + float w = (float)luaL_checknumber(L, 3); + float h = (float)luaL_checknumber(L, 4); + float angle = (float)luaL_optnumber(L, 5, 0); + PolygonShape * shape = instance->newRectangleShape(x, y, w, h, angle); luax_newtype(L, "PolygonShape", PHYSICS_POLYGON_SHAPE_T, (void*)shape); return 1; } else return luaL_error(L, "Incorrect number of parameters"); } + + int w_newEdgeShape(lua_State * L) + { + float x1 = (float)luaL_checknumber(L, 1); + float y1 = (float)luaL_checknumber(L, 2); + float x2 = (float)luaL_checknumber(L, 3); + float y2 = (float)luaL_checknumber(L, 4); + PolygonShape * shape = instance->newEdgeShape(x1, y1, x2, y2); + luax_newtype(L, "PolygonShape", PHYSICS_POLYGON_SHAPE_T, (void*)shape); + return 1; + } int w_newPolygonShape(lua_State * L) { diff --git a/src/modules/physics/box2d/wrap_Physics.h b/src/modules/physics/box2d/wrap_Physics.h index 46cbb55ff..5385a6e7b 100644 --- a/src/modules/physics/box2d/wrap_Physics.h +++ b/src/modules/physics/box2d/wrap_Physics.h @@ -48,7 +48,8 @@ namespace box2d int w_newBody(lua_State * L); int w_newCircleShape(lua_State * L); int w_newRectangleShape(lua_State * L); - int w_newPolygonShape(lua_State * L);; + int w_newEdgeShape(lua_State * L); + int w_newPolygonShape(lua_State * L); int w_newDistanceJoint(lua_State * L); int w_newMouseJoint(lua_State * L); int w_newRevoluteJoint(lua_State * L); From b4fae893fd54227bf20696a34d0a7a9d9cfa7f36 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 13 Mar 2011 13:16:02 -0400 Subject: [PATCH 06/78] updating the Joints --HG-- branch : box2d-update --- src/modules/physics/box2d/DistanceJoint.cpp | 12 ++--- src/modules/physics/box2d/GearJoint.cpp | 8 +-- src/modules/physics/box2d/Joint.cpp | 25 +++------ src/modules/physics/box2d/Joint.h | 14 +---- src/modules/physics/box2d/MouseJoint.cpp | 12 ++--- src/modules/physics/box2d/Physics.cpp | 2 +- src/modules/physics/box2d/PrismaticJoint.cpp | 7 +-- src/modules/physics/box2d/PrismaticJoint.h | 5 -- src/modules/physics/box2d/PulleyJoint.cpp | 51 ++----------------- src/modules/physics/box2d/PulleyJoint.h | 23 --------- src/modules/physics/box2d/RevoluteJoint.cpp | 7 +-- src/modules/physics/box2d/RevoluteJoint.h | 5 -- src/modules/physics/box2d/World.cpp | 8 +++ src/modules/physics/box2d/World.h | 9 ++++ .../physics/box2d/wrap_PrismaticJoint.cpp | 8 --- .../physics/box2d/wrap_PrismaticJoint.h | 1 - .../physics/box2d/wrap_PulleyJoint.cpp | 44 ---------------- src/modules/physics/box2d/wrap_PulleyJoint.h | 5 -- .../physics/box2d/wrap_RevoluteJoint.cpp | 8 --- .../physics/box2d/wrap_RevoluteJoint.h | 1 - 20 files changed, 50 insertions(+), 205 deletions(-) diff --git a/src/modules/physics/box2d/DistanceJoint.cpp b/src/modules/physics/box2d/DistanceJoint.cpp index 3089139e4..d05ee3883 100644 --- a/src/modules/physics/box2d/DistanceJoint.cpp +++ b/src/modules/physics/box2d/DistanceJoint.cpp @@ -46,32 +46,32 @@ namespace box2d void DistanceJoint::setLength(float length) { - joint->m_length = world->scaleDown(length); + joint->SetLength(world->scaleDown(length)); } float DistanceJoint::getLength() const { - return world->scaleUp(joint->m_length); + return world->scaleUp(joint->GetLength()); } void DistanceJoint::setFrequency(float hz) { - joint->m_frequencyHz = hz; + joint->SetFrequency(hz); } float DistanceJoint::getFrequency() const { - return joint->m_frequencyHz; + return joint->GetFrequency(); } void DistanceJoint::setDampingRatio(float d) { - joint->m_dampingRatio = d; + joint->SetDampingRatio(d); } float DistanceJoint::getDampingRatio() const { - return joint->m_dampingRatio; + return joint->GetDampingRatio(); } diff --git a/src/modules/physics/box2d/GearJoint.cpp b/src/modules/physics/box2d/GearJoint.cpp index 6dba58348..aad347f45 100644 --- a/src/modules/physics/box2d/GearJoint.cpp +++ b/src/modules/physics/box2d/GearJoint.cpp @@ -36,8 +36,8 @@ namespace box2d b2GearJointDef def; def.joint1 = joint1->joint; def.joint2 = joint2->joint; - def.body1 = joint1->body2->body; - def.body2 = joint2->body2->body; + def.bodyA = joint1->body2->body; + def.bodyB = joint2->body2->body; def.ratio = ratio; joint = (b2GearJoint*)createJoint(&def); @@ -51,12 +51,12 @@ namespace box2d void GearJoint::setRatio(float ratio) { - joint->m_ratio = ratio; + joint->SetRatio(ratio); } float GearJoint::getRatio() const { - return joint->m_ratio; + return joint->GetRatio(); } } // box2d diff --git a/src/modules/physics/box2d/Joint.cpp b/src/modules/physics/box2d/Joint.cpp index 4e7f0368e..a32f97372 100644 --- a/src/modules/physics/box2d/Joint.cpp +++ b/src/modules/physics/box2d/Joint.cpp @@ -79,34 +79,25 @@ namespace box2d int Joint::getAnchors(lua_State * L) { - lua_pushnumber(L, world->scaleUp(joint->GetAnchor1().x)); - lua_pushnumber(L, world->scaleUp(joint->GetAnchor1().y)); - lua_pushnumber(L, world->scaleUp(joint->GetAnchor2().x)); - lua_pushnumber(L, world->scaleUp(joint->GetAnchor2().y)); + lua_pushnumber(L, world->scaleUp(joint->GetAnchorA().x)); + lua_pushnumber(L, world->scaleUp(joint->GetAnchorA().y)); + lua_pushnumber(L, world->scaleUp(joint->GetAnchorB().x)); + lua_pushnumber(L, world->scaleUp(joint->GetAnchorB().y)); return 4; } int Joint::getReactionForce(lua_State * L) { - b2Vec2 v = joint->GetReactionForce(); + float dt = (float)luaL_checknumber(L, 2); + b2Vec2 v = joint->GetReactionForce(dt); lua_pushnumber(L, v.x); lua_pushnumber(L, v.y); return 2; } - float Joint::getReactionTorque() + float Joint::getReactionTorque(float dt) { - return joint->GetReactionTorque(); - } - - void Joint::setCollideConnected(bool collide) - { - joint->m_collideConnected = collide; - } - - bool Joint::getCollideConnected() const - { - return joint->m_collideConnected; + return joint->GetReactionTorque(dt); } b2Joint * Joint::createJoint(b2JointDef * def) diff --git a/src/modules/physics/box2d/Joint.h b/src/modules/physics/box2d/Joint.h index 6393f0dcb..f05beb735 100644 --- a/src/modules/physics/box2d/Joint.h +++ b/src/modules/physics/box2d/Joint.h @@ -97,19 +97,7 @@ namespace box2d /** * Gets the reaction torque on body2. **/ - float getReactionTorque(); - - /** - * Sets whether connected bodies should collide - * or not. Default is false. - **/ - void setCollideConnected(bool collide); - - /** - * Gets whether connected bodies should collide - * or not. - **/ - bool getCollideConnected() const; + float getReactionTorque(float dt); protected: diff --git a/src/modules/physics/box2d/MouseJoint.cpp b/src/modules/physics/box2d/MouseJoint.cpp index e35f37445..e3f239b8b 100644 --- a/src/modules/physics/box2d/MouseJoint.cpp +++ b/src/modules/physics/box2d/MouseJoint.cpp @@ -35,8 +35,8 @@ namespace box2d { b2MouseJointDef def; - def.body1 = body1->world->world->GetGroundBody(); - def.body2 = body1->body; + def.bodyA = body1->world->getGroundBody(); + def.bodyB = body1->body; def.maxForce = 1000.0f * body1->body->GetMass(); def.target = body1->world->scaleDown(b2Vec2(x,y)); joint = (b2MouseJoint*)createJoint(&def); @@ -55,19 +55,19 @@ namespace box2d int MouseJoint::getTarget(lua_State * L) { - lua_pushnumber(L, world->scaleUp(joint->m_target.x)); - lua_pushnumber(L, world->scaleUp(joint->m_target.y)); + lua_pushnumber(L, world->scaleUp(joint->GetTarget().x)); + lua_pushnumber(L, world->scaleUp(joint->GetTarget().y)); return 2; } void MouseJoint::setMaxForce(float force) { - joint->m_maxForce = force; + joint->SetMaxForce(force); } float MouseJoint::getMaxForce() const { - return joint->m_maxForce; + return joint->GetMaxForce(); } } // box2d diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 7829a1ec9..f76d9c9d1 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -131,7 +131,7 @@ namespace box2d if(count < 3) return luaL_error(L, "Polygon degenerated to less than three points."); - b2vec2 vecs[] = new b2vec2[count]; + b2Vec2 vecs[] = new b2vec2[count]; for (int i = 0; i < count; i++) { vecs[i].Set(convex_hull[i].x, convex_hull[i].y); diff --git a/src/modules/physics/box2d/PrismaticJoint.cpp b/src/modules/physics/box2d/PrismaticJoint.cpp index b613cbe6f..f97eba491 100644 --- a/src/modules/physics/box2d/PrismaticJoint.cpp +++ b/src/modules/physics/box2d/PrismaticJoint.cpp @@ -72,12 +72,7 @@ namespace box2d { joint->SetMaxMotorForce(force); } - - float PrismaticJoint::getMaxMotorForce() const - { - return joint->m_maxMotorForce; - } - + void PrismaticJoint::setMotorSpeed(float speed) { joint->SetMotorSpeed(speed); diff --git a/src/modules/physics/box2d/PrismaticJoint.h b/src/modules/physics/box2d/PrismaticJoint.h index 01baf40e1..6a0fb3b1b 100644 --- a/src/modules/physics/box2d/PrismaticJoint.h +++ b/src/modules/physics/box2d/PrismaticJoint.h @@ -75,11 +75,6 @@ namespace box2d **/ void setMaxMotorForce(float force); - /** - * Get the current motor force, usually in N. - **/ - float getMaxMotorForce() const; - /** * Set the motor speed, usually in meters per second. **/ diff --git a/src/modules/physics/box2d/PulleyJoint.cpp b/src/modules/physics/box2d/PulleyJoint.cpp index e4193902b..d45c850da 100644 --- a/src/modules/physics/box2d/PulleyJoint.cpp +++ b/src/modules/physics/box2d/PulleyJoint.cpp @@ -48,49 +48,13 @@ namespace box2d int PulleyJoint::getGroundAnchors(lua_State * L) { - lua_pushnumber(L, world->scaleUp(joint->GetGroundAnchor1().x)); - lua_pushnumber(L, world->scaleUp(joint->GetGroundAnchor1().y)); - lua_pushnumber(L, world->scaleUp(joint->GetGroundAnchor2().x)); - lua_pushnumber(L, world->scaleUp(joint->GetGroundAnchor2().y)); + lua_pushnumber(L, world->scaleUp(joint->GetGroundAnchorA().x)); + lua_pushnumber(L, world->scaleUp(joint->GetGroundAnchorA().y)); + lua_pushnumber(L, world->scaleUp(joint->GetGroundAnchorB().x)); + lua_pushnumber(L, world->scaleUp(joint->GetGroundAnchorB().y)); return 4; } - void PulleyJoint::setMaxLengths(float maxlength1, float maxlength2) - { - // Apply Box2D's maximum lengths too. They know better. - - if (maxlength1 > 0) - { - joint->m_maxLength1 = b2Min(world->scaleDown(maxlength1), joint->m_constant - joint->m_ratio * b2_minPulleyLength); - } - - if (maxlength2 > 0) - { - joint->m_maxLength2 = b2Min(world->scaleDown(maxlength2), (joint->m_constant - b2_minPulleyLength) / joint->m_ratio); - } - } - - int PulleyJoint::getMaxLengths(lua_State * L) - { - lua_pushnumber(L, world->scaleUp(joint->m_maxLength1)); - lua_pushnumber(L, world->scaleUp(joint->m_maxLength2)); - return 2; - } - - void PulleyJoint::setConstant(float constant) - { - joint->m_constant = world->scaleDown(constant); - - // Update the max lengths, as does Box2D - joint->m_maxLength1 = joint->m_constant - joint->m_ratio * b2_minPulleyLength; - joint->m_maxLength2 = (joint->m_constant - b2_minPulleyLength) / joint->m_ratio; - } - - float PulleyJoint::getConstant() const - { - return world->scaleUp(joint->m_constant); - } - float PulleyJoint::getLength1() const { return world->scaleUp(joint->GetLength1()); @@ -101,14 +65,9 @@ namespace box2d return world->scaleUp(joint->GetLength2()); } - void PulleyJoint::setRatio(float ratio) - { - joint->m_ratio = ratio; - } - float PulleyJoint::getRatio() const { - return joint->m_ratio; + return joint->GetRatio(); } } // box2d diff --git a/src/modules/physics/box2d/PulleyJoint.h b/src/modules/physics/box2d/PulleyJoint.h index 8e5154c66..9e16e8c33 100644 --- a/src/modules/physics/box2d/PulleyJoint.h +++ b/src/modules/physics/box2d/PulleyJoint.h @@ -56,29 +56,6 @@ namespace box2d **/ int getGroundAnchors(lua_State * L); - /** - * Sets the max rope lengths (a value of zero keeps it - * unchanged). Beware that Box2D also imposes a maximum, - * so the smallest of these is actually set. - **/ - void setMaxLengths(float maxlength1, float maxlength2); - - /** - * Gets the max rope lengths. - **/ - int getMaxLengths(lua_State * L); - - /** - * Sets the total length of the rope and updates the - * MaxLengths values accordingly. - **/ - void setConstant(float length); - - /** - * Gets the total length of the rope. - **/ - float getConstant() const; - /** * Gets the current length of the segment attached to body1. **/ diff --git a/src/modules/physics/box2d/RevoluteJoint.cpp b/src/modules/physics/box2d/RevoluteJoint.cpp index a3003f900..01276ca80 100644 --- a/src/modules/physics/box2d/RevoluteJoint.cpp +++ b/src/modules/physics/box2d/RevoluteJoint.cpp @@ -70,12 +70,7 @@ namespace box2d { joint->SetMaxMotorTorque(torque); } - - float RevoluteJoint::getMaxMotorTorque() const - { - return joint->m_maxMotorTorque; - } - + void RevoluteJoint::setMotorSpeed(float speed) { joint->SetMotorSpeed(speed); diff --git a/src/modules/physics/box2d/RevoluteJoint.h b/src/modules/physics/box2d/RevoluteJoint.h index 1d9685299..359caa7fb 100644 --- a/src/modules/physics/box2d/RevoluteJoint.h +++ b/src/modules/physics/box2d/RevoluteJoint.h @@ -75,11 +75,6 @@ namespace box2d **/ void setMaxMotorTorque(float torque); - /** - * Gets the maximum motor torque, usually in N-m. - **/ - float getMaxMotorTorque() const; - /** * Sets the motor speed in degrees per second. **/ diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index 87594530f..bcb8582a7 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -100,6 +100,8 @@ namespace box2d { world = new b2World(scaleDown(aabb), b2Vec2(0,0), true); world->SetContactListener(this); + b2BodyDef def; + groundBody = world->CreateBody(def); } World::World(b2AABB aabb, b2Vec2 gravity, bool sleep, int meter) @@ -111,6 +113,7 @@ namespace box2d World::~World() { + world->DestroyBody(groundBody); delete world; } @@ -272,6 +275,11 @@ namespace box2d t.upperBound = scaleUp(aabb.upperBound); return t; } + + b2Body * World::getGroundBody() + { + return groundBody; + } } // box2d } // physics diff --git a/src/modules/physics/box2d/World.h b/src/modules/physics/box2d/World.h index 7cdfc8ba2..68ed12af1 100644 --- a/src/modules/physics/box2d/World.h +++ b/src/modules/physics/box2d/World.h @@ -77,6 +77,9 @@ namespace box2d // Pointer to the Box2D world. b2World * world; + + // Ground body + b2Body * groundBody; // Contact callbacks. ContactCallback add, persist, remove, result; @@ -241,6 +244,12 @@ namespace box2d * @return The scaled AABB. **/ b2AABB scaleUp(const b2AABB & aabb); + + /** + * Gets the ground body. + * @return The ground body. + **/ + b2Body * getGroundBody(); }; diff --git a/src/modules/physics/box2d/wrap_PrismaticJoint.cpp b/src/modules/physics/box2d/wrap_PrismaticJoint.cpp index 86b335508..80146caac 100644 --- a/src/modules/physics/box2d/wrap_PrismaticJoint.cpp +++ b/src/modules/physics/box2d/wrap_PrismaticJoint.cpp @@ -68,13 +68,6 @@ namespace box2d return 0; } - int w_PrismaticJoint_getMaxMotorForce(lua_State * L) - { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); - lua_pushnumber(L, t->getMaxMotorForce()); - return 1; - } - int w_PrismaticJoint_setMotorSpeed(lua_State * L) { PrismaticJoint * t = luax_checkprismaticjoint(L, 1); @@ -164,7 +157,6 @@ namespace box2d { "setMotorEnabled", w_PrismaticJoint_setMotorEnabled }, { "isMotorEnabled", w_PrismaticJoint_isMotorEnabled }, { "setMaxMotorForce", w_PrismaticJoint_setMaxMotorForce }, - { "getMaxMotorForce", w_PrismaticJoint_getMaxMotorForce }, { "setMotorSpeed", w_PrismaticJoint_setMotorSpeed }, { "getMotorSpeed", w_PrismaticJoint_getMotorSpeed }, { "getMotorForce", w_PrismaticJoint_getMotorForce }, diff --git a/src/modules/physics/box2d/wrap_PrismaticJoint.h b/src/modules/physics/box2d/wrap_PrismaticJoint.h index 1044d1aec..d420e26cb 100644 --- a/src/modules/physics/box2d/wrap_PrismaticJoint.h +++ b/src/modules/physics/box2d/wrap_PrismaticJoint.h @@ -38,7 +38,6 @@ namespace box2d int w_PrismaticJoint_setMotorEnabled(lua_State * L); int w_PrismaticJoint_isMotorEnabled(lua_State * L); int w_PrismaticJoint_setMaxMotorForce(lua_State * L); - int w_PrismaticJoint_getMaxMotorForce(lua_State * L); int w_PrismaticJoint_setMotorSpeed(lua_State * L); int w_PrismaticJoint_getMotorSpeed(lua_State * L); int w_PrismaticJoint_getMotorForce(lua_State * L); diff --git a/src/modules/physics/box2d/wrap_PulleyJoint.cpp b/src/modules/physics/box2d/wrap_PulleyJoint.cpp index ac45af23f..aa68acda3 100644 --- a/src/modules/physics/box2d/wrap_PulleyJoint.cpp +++ b/src/modules/physics/box2d/wrap_PulleyJoint.cpp @@ -37,37 +37,6 @@ namespace box2d lua_remove(L, 1); return t->getGroundAnchors(L); } - - int w_PulleyJoint_setMaxLengths(lua_State * L) - { - PulleyJoint * t = luax_checkpulleyjoint(L, 1); - float arg1 = (float)luaL_optnumber(L, 2, 0.0); - float arg2 = (float)luaL_optnumber(L, 3, 0.0); - t->setMaxLengths(arg1, arg2); - return 0; - } - - int w_PulleyJoint_getMaxLengths(lua_State * L) - { - PulleyJoint * t = luax_checkpulleyjoint(L, 1); - lua_remove(L, 1); - return t->getMaxLengths(L); - } - - int w_PulleyJoint_setConstant(lua_State * L) - { - PulleyJoint * t = luax_checkpulleyjoint(L, 1); - float arg1 = (float)luaL_checknumber(L, 2); - t->setConstant(arg1); - return 0; - } - - int w_PulleyJoint_getConstant(lua_State * L) - { - PulleyJoint * t = luax_checkpulleyjoint(L, 1); - lua_pushnumber(L, t->getConstant()); - return 1; - } int w_PulleyJoint_getLength1(lua_State * L) { @@ -83,14 +52,6 @@ namespace box2d return 1; } - int w_PulleyJoint_setRatio(lua_State * L) - { - PulleyJoint * t = luax_checkpulleyjoint(L, 1); - float arg1 = (float)luaL_checknumber(L, 2); - t->setRatio(arg1); - return 0; - } - int w_PulleyJoint_getRatio(lua_State * L) { PulleyJoint * t = luax_checkpulleyjoint(L, 1); @@ -100,13 +61,8 @@ namespace box2d static const luaL_Reg functions[] = { { "getGroundAnchors", w_PulleyJoint_getGroundAnchors }, - { "setMaxLengths", w_PulleyJoint_setMaxLengths }, - { "getMaxLengths", w_PulleyJoint_getMaxLengths }, - { "setConstant", w_PulleyJoint_setConstant }, - { "getConstant", w_PulleyJoint_getConstant }, { "getLength1", w_PulleyJoint_getLength1 }, { "getLength2", w_PulleyJoint_getLength2 }, - { "setRatio", w_PulleyJoint_setRatio }, { "getRatio", w_PulleyJoint_getRatio }, // From Joint. { "getType", w_Joint_getType }, diff --git a/src/modules/physics/box2d/wrap_PulleyJoint.h b/src/modules/physics/box2d/wrap_PulleyJoint.h index 3ccd33995..6001a5f85 100644 --- a/src/modules/physics/box2d/wrap_PulleyJoint.h +++ b/src/modules/physics/box2d/wrap_PulleyJoint.h @@ -34,13 +34,8 @@ namespace box2d { PulleyJoint * luax_checkpulleyjoint(lua_State * L, int idx); int w_PulleyJoint_getGroundAnchors(lua_State * L); - int w_PulleyJoint_setMaxLengths(lua_State * L); - int w_PulleyJoint_getMaxLengths(lua_State * L); - int w_PulleyJoint_setConstant(lua_State * L); - int w_PulleyJoint_getConstant(lua_State * L); int w_PulleyJoint_getLength1(lua_State * L); int w_PulleyJoint_getLength2(lua_State * L); - int w_PulleyJoint_setRatio(lua_State * L); int w_PulleyJoint_getRatio(lua_State * L); int luaopen_pulleyjoint(lua_State * L); diff --git a/src/modules/physics/box2d/wrap_RevoluteJoint.cpp b/src/modules/physics/box2d/wrap_RevoluteJoint.cpp index 58e2ab6ee..6545d125e 100644 --- a/src/modules/physics/box2d/wrap_RevoluteJoint.cpp +++ b/src/modules/physics/box2d/wrap_RevoluteJoint.cpp @@ -68,13 +68,6 @@ namespace box2d return 0; } - int w_RevoluteJoint_getMaxMotorTorque(lua_State * L) - { - RevoluteJoint * t = luax_checkrevolutejoint(L, 1); - lua_pushnumber(L, t->getMaxMotorTorque()); - return 1; - } - int w_RevoluteJoint_setMotorSpeed(lua_State * L) { RevoluteJoint * t = luax_checkrevolutejoint(L, 1); @@ -164,7 +157,6 @@ namespace box2d { "setMotorEnabled", w_RevoluteJoint_setMotorEnabled }, { "isMotorEnabled", w_RevoluteJoint_isMotorEnabled }, { "setMaxMotorTorque", w_RevoluteJoint_setMaxMotorTorque }, - { "getMaxMotorTorque", w_RevoluteJoint_getMaxMotorTorque }, { "setMotorSpeed", w_RevoluteJoint_setMotorSpeed }, { "getMotorSpeed", w_RevoluteJoint_getMotorSpeed }, { "getMotorTorque", w_RevoluteJoint_getMotorTorque }, diff --git a/src/modules/physics/box2d/wrap_RevoluteJoint.h b/src/modules/physics/box2d/wrap_RevoluteJoint.h index 89c856b62..ad03ce4e1 100644 --- a/src/modules/physics/box2d/wrap_RevoluteJoint.h +++ b/src/modules/physics/box2d/wrap_RevoluteJoint.h @@ -38,7 +38,6 @@ namespace box2d int w_RevoluteJoint_setMotorEnabled(lua_State * L); int w_RevoluteJoint_isMotorEnabled(lua_State * L); int w_RevoluteJoint_setMaxMotorTorque(lua_State * L); - int w_RevoluteJoint_getMaxMotorTorque(lua_State * L); int w_RevoluteJoint_setMotorSpeed(lua_State * L); int w_RevoluteJoint_getMotorSpeed(lua_State * L); int w_RevoluteJoint_getMotorTorque(lua_State * L); From b3434997bfe26cab7bc6cfbff35759b380fa6c9d Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 2 Jul 2011 11:46:42 -0500 Subject: [PATCH 07/78] more joint updates to better match the API --HG-- branch : box2d-update --- src/modules/physics/box2d/Joint.cpp | 5 +++ src/modules/physics/box2d/Joint.h | 2 ++ src/modules/physics/box2d/MouseJoint.cpp | 20 +++++++++++ src/modules/physics/box2d/MouseJoint.h | 22 ++++++++++++ src/modules/physics/box2d/PrismaticJoint.h | 6 ++-- src/modules/physics/box2d/PulleyJoint.h | 5 --- src/modules/physics/box2d/RevoluteJoint.cpp | 6 ++-- src/modules/physics/box2d/RevoluteJoint.h | 6 ++-- .../physics/box2d/wrap_DistanceJoint.cpp | 4 +-- src/modules/physics/box2d/wrap_MouseJoint.cpp | 34 +++++++++++++++++++ src/modules/physics/box2d/wrap_MouseJoint.h | 4 +++ .../physics/box2d/wrap_PrismaticJoint.cpp | 18 +++++----- .../physics/box2d/wrap_PrismaticJoint.h | 6 ++-- .../physics/box2d/wrap_RevoluteJoint.cpp | 18 +++++----- .../physics/box2d/wrap_RevoluteJoint.h | 6 ++-- 15 files changed, 122 insertions(+), 40 deletions(-) diff --git a/src/modules/physics/box2d/Joint.cpp b/src/modules/physics/box2d/Joint.cpp index a32f97372..14f617489 100644 --- a/src/modules/physics/box2d/Joint.cpp +++ b/src/modules/physics/box2d/Joint.cpp @@ -111,6 +111,11 @@ namespace box2d if (joint != NULL) world->world->DestroyJoint(joint); } + + bool Joint::isActive() const + { + return joint->IsActive(); + } } // box2d } // physics diff --git a/src/modules/physics/box2d/Joint.h b/src/modules/physics/box2d/Joint.h index f05beb735..ea6fe9b09 100644 --- a/src/modules/physics/box2d/Joint.h +++ b/src/modules/physics/box2d/Joint.h @@ -98,6 +98,8 @@ namespace box2d * Gets the reaction torque on body2. **/ float getReactionTorque(float dt); + + bool isActive() const; protected: diff --git a/src/modules/physics/box2d/MouseJoint.cpp b/src/modules/physics/box2d/MouseJoint.cpp index e3f239b8b..5fee8b23f 100644 --- a/src/modules/physics/box2d/MouseJoint.cpp +++ b/src/modules/physics/box2d/MouseJoint.cpp @@ -69,6 +69,26 @@ namespace box2d { return joint->GetMaxForce(); } + + void MouseJoint::setFrequency(float hz) + { + joint->SetFrequency(hz); + } + + float MouseJoint::getFrequency() const + { + return joint->GetFrequency(); + } + + void MouseJoint::setDampingRatio(float d) + { + joint->SetDampingRatio(d); + } + + float MouseJoint::getDampingRatio() const + { + return joint->GetDampingRatio(); + } } // box2d } // physics diff --git a/src/modules/physics/box2d/MouseJoint.h b/src/modules/physics/box2d/MouseJoint.h index 083b23b91..6b1429001 100644 --- a/src/modules/physics/box2d/MouseJoint.h +++ b/src/modules/physics/box2d/MouseJoint.h @@ -74,6 +74,28 @@ namespace box2d * to move the candidate body. **/ float getMaxForce() const; + + /** + * Sets the response speed. + **/ + void setFrequency(float hz); + + /** + * Gets the response speed. + **/ + float getFrequency() const; + + /** + * Sets the damping ratio. + * 0 = no damping, 1 = critical damping. + **/ + void setDampingRatio(float d); + + /** + * Gets the damping ratio. + * 0 = no damping, 1 = critical damping. + **/ + float getDampingRatio() const; }; } // box2d diff --git a/src/modules/physics/box2d/PrismaticJoint.h b/src/modules/physics/box2d/PrismaticJoint.h index 6a0fb3b1b..b7f96ed3d 100644 --- a/src/modules/physics/box2d/PrismaticJoint.h +++ b/src/modules/physics/box2d/PrismaticJoint.h @@ -63,7 +63,7 @@ namespace box2d /** * Enable/disable the joint motor. **/ - void setMotorEnabled(bool motor); + void enableMotor(bool motor); /** * Checks whether the motor is enabled. @@ -93,12 +93,12 @@ namespace box2d /** * Enable/disable the joint limit. **/ - void setLimitsEnabled(bool limit); + void enableLimit(bool limit); /** * Checks whether limits are enabled. **/ - bool isLimitsEnabled() const; + bool isLimitEnabled() const; /** * Sets the upper limit, usually in meters. diff --git a/src/modules/physics/box2d/PulleyJoint.h b/src/modules/physics/box2d/PulleyJoint.h index 9e16e8c33..a352c738a 100644 --- a/src/modules/physics/box2d/PulleyJoint.h +++ b/src/modules/physics/box2d/PulleyJoint.h @@ -66,11 +66,6 @@ namespace box2d **/ float getLength2() const; - /** - * Sets the pulley ratio. - **/ - void setRatio(float ratio); - /** * Gets the pulley ratio. **/ diff --git a/src/modules/physics/box2d/RevoluteJoint.cpp b/src/modules/physics/box2d/RevoluteJoint.cpp index 01276ca80..d725efa6e 100644 --- a/src/modules/physics/box2d/RevoluteJoint.cpp +++ b/src/modules/physics/box2d/RevoluteJoint.cpp @@ -56,7 +56,7 @@ namespace box2d return joint->GetJointSpeed(); } - void RevoluteJoint::setMotorEnabled(bool motor) + void RevoluteJoint::enableMotor(bool motor) { return joint->EnableMotor(motor); } @@ -86,12 +86,12 @@ namespace box2d return joint->GetMotorTorque(); } - void RevoluteJoint::setLimitsEnabled(bool limit) + void RevoluteJoint::enableLimit(bool limit) { joint->EnableLimit(limit); } - bool RevoluteJoint::isLimitsEnabled() const + bool RevoluteJoint::isLimitEnabled() const { return joint->IsLimitEnabled(); } diff --git a/src/modules/physics/box2d/RevoluteJoint.h b/src/modules/physics/box2d/RevoluteJoint.h index 359caa7fb..51acf26fe 100644 --- a/src/modules/physics/box2d/RevoluteJoint.h +++ b/src/modules/physics/box2d/RevoluteJoint.h @@ -63,7 +63,7 @@ namespace box2d /** * Enable/disable the joint motor. **/ - void setMotorEnabled(bool motor); + void enableMotor(bool motor); /** * Checks whether the motor is enabled. @@ -93,12 +93,12 @@ namespace box2d /** * Enable/disable the joint limit. **/ - void setLimitsEnabled(bool limit); + void enableLimit(bool limit); /** * Checks whether limits are enabled. **/ - bool isLimitsEnabled() const; + bool isLimitEnabled() const; /** * Sets the upper limit in degrees. diff --git a/src/modules/physics/box2d/wrap_DistanceJoint.cpp b/src/modules/physics/box2d/wrap_DistanceJoint.cpp index ac36b536b..94eeaa28c 100644 --- a/src/modules/physics/box2d/wrap_DistanceJoint.cpp +++ b/src/modules/physics/box2d/wrap_DistanceJoint.cpp @@ -81,8 +81,8 @@ namespace box2d { "getLength", w_DistanceJoint_getLength }, { "setFrequency", w_DistanceJoint_setFrequency }, { "getFrequency", w_DistanceJoint_getFrequency }, - { "setDamping", w_DistanceJoint_setDampingRatio }, - { "getDamping", w_DistanceJoint_getDampingRatio }, + { "setDampingRatio", w_DistanceJoint_setDampingRatio }, + { "getDampingRatio", w_DistanceJoint_getDampingRatio }, // From Joint. { "getType", w_Joint_getType }, { "getAnchors", w_Joint_getAnchors }, diff --git a/src/modules/physics/box2d/wrap_MouseJoint.cpp b/src/modules/physics/box2d/wrap_MouseJoint.cpp index 49b292e8a..8739b35f9 100644 --- a/src/modules/physics/box2d/wrap_MouseJoint.cpp +++ b/src/modules/physics/box2d/wrap_MouseJoint.cpp @@ -61,12 +61,46 @@ namespace box2d lua_pushnumber(L, t->getMaxForce()); return 1; } + + int w_MouseJoint_setFrequency(lua_State * L) + { + MouseJoint * t = luax_checkmousejoint(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setFrequency(arg1); + return 0; + } + + int w_MouseJoint_getFrequency(lua_State * L) + { + MouseJoint * t = luax_checkmousejoint(L, 1); + lua_pushnumber(L, t->getFrequency()); + return 1; + } + + int w_MouseJoint_setDampingRatio(lua_State * L) + { + MouseJoint * t = luax_checkmousejoint(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setDampingRatio(arg1); + return 0; + } + + int w_MouseJoint_getDampingRatio(lua_State * L) + { + MouseJoint * t = luax_checkmousejoint(L, 1); + lua_pushnumber(L, t->getDampingRatio()); + return 1; + } static const luaL_Reg functions[] = { { "setTarget", w_MouseJoint_setTarget }, { "getTarget", w_MouseJoint_getTarget }, { "setMaxForce", w_MouseJoint_setMaxForce }, { "getMaxForce", w_MouseJoint_getMaxForce }, + { "setFrequency", w_MouseJoint_setFrequency }, + { "getFrequency", w_MouseJoint_getFrequency }, + { "setDampingRatio", w_MouseJoint_setDampingRatio }, + { "getDampingRatio", w_MouseJoint_getDampingRatio }, // From Joint. { "getType", w_Joint_getType }, { "getAnchors", w_Joint_getAnchors }, diff --git a/src/modules/physics/box2d/wrap_MouseJoint.h b/src/modules/physics/box2d/wrap_MouseJoint.h index 0d261e678..6b99311f4 100644 --- a/src/modules/physics/box2d/wrap_MouseJoint.h +++ b/src/modules/physics/box2d/wrap_MouseJoint.h @@ -37,6 +37,10 @@ namespace box2d int w_MouseJoint_getTarget(lua_State * L); int w_MouseJoint_setMaxForce(lua_State * L); int w_MouseJoint_getMaxForce(lua_State * L); + int w_MouseJoint_setFrequency(lua_State * L); + int w_MouseJoint_getFrequency(lua_State * L); + int w_MouseJoint_setDampingRatio(lua_State * L); + int w_MouseJoint_getDampingRatio(lua_State * L); int luaopen_mousejoint(lua_State * L); } // box2d diff --git a/src/modules/physics/box2d/wrap_PrismaticJoint.cpp b/src/modules/physics/box2d/wrap_PrismaticJoint.cpp index 80146caac..2981af5f2 100644 --- a/src/modules/physics/box2d/wrap_PrismaticJoint.cpp +++ b/src/modules/physics/box2d/wrap_PrismaticJoint.cpp @@ -45,11 +45,11 @@ namespace box2d return 1; } - int w_PrismaticJoint_setMotorEnabled(lua_State * L) + int w_PrismaticJoint_enableMotor(lua_State * L) { PrismaticJoint * t = luax_checkprismaticjoint(L, 1); bool arg1 = luax_toboolean(L, 2); - t->setMotorEnabled(arg1); + t->enableMotor(arg1); return 0; } @@ -90,18 +90,18 @@ namespace box2d return 1; } - int w_PrismaticJoint_setLimitsEnabled(lua_State * L) + int w_PrismaticJoint_enableLimit(lua_State * L) { PrismaticJoint * t = luax_checkprismaticjoint(L, 1); bool arg1 = luax_toboolean(L, 2); - t->setLimitsEnabled(arg1); + t->enableLimit(arg1); return 0; } - int w_PrismaticJoint_isLimitsEnabled(lua_State * L) + int w_PrismaticJoint_isLimitEnabled(lua_State * L) { PrismaticJoint * t = luax_checkprismaticjoint(L, 1); - luax_pushboolean(L, t->isLimitsEnabled()); + luax_pushboolean(L, t->isLimitEnabled()); return 1; } @@ -154,14 +154,14 @@ namespace box2d static const luaL_Reg functions[] = { { "getJointTranslation", w_PrismaticJoint_getJointTranslation }, { "getJointSpeed", w_PrismaticJoint_getJointSpeed }, - { "setMotorEnabled", w_PrismaticJoint_setMotorEnabled }, + { "enableMotor", w_PrismaticJoint_enableMotor }, { "isMotorEnabled", w_PrismaticJoint_isMotorEnabled }, { "setMaxMotorForce", w_PrismaticJoint_setMaxMotorForce }, { "setMotorSpeed", w_PrismaticJoint_setMotorSpeed }, { "getMotorSpeed", w_PrismaticJoint_getMotorSpeed }, { "getMotorForce", w_PrismaticJoint_getMotorForce }, - { "setLimitsEnabled", w_PrismaticJoint_setLimitsEnabled }, - { "isLimitsEnabled", w_PrismaticJoint_isLimitsEnabled }, + { "enableLimit", w_PrismaticJoint_enableLimit }, + { "isLimitEnabled", w_PrismaticJoint_isLimitEnabled }, { "setUpperLimit", w_PrismaticJoint_setUpperLimit }, { "setLowerLimit", w_PrismaticJoint_setLowerLimit }, { "setLimits", w_PrismaticJoint_setLimits }, diff --git a/src/modules/physics/box2d/wrap_PrismaticJoint.h b/src/modules/physics/box2d/wrap_PrismaticJoint.h index d420e26cb..203edaea7 100644 --- a/src/modules/physics/box2d/wrap_PrismaticJoint.h +++ b/src/modules/physics/box2d/wrap_PrismaticJoint.h @@ -35,14 +35,14 @@ namespace box2d PrismaticJoint * luax_checkprismaticjoint(lua_State * L, int idx); int w_PrismaticJoint_getJointTranslation(lua_State * L); int w_PrismaticJoint_getJointSpeed(lua_State * L); - int w_PrismaticJoint_setMotorEnabled(lua_State * L); + int w_PrismaticJoint_enableMotor(lua_State * L); int w_PrismaticJoint_isMotorEnabled(lua_State * L); int w_PrismaticJoint_setMaxMotorForce(lua_State * L); int w_PrismaticJoint_setMotorSpeed(lua_State * L); int w_PrismaticJoint_getMotorSpeed(lua_State * L); int w_PrismaticJoint_getMotorForce(lua_State * L); - int w_PrismaticJoint_setLimitsEnabled(lua_State * L); - int w_PrismaticJoint_isLimitsEnabled(lua_State * L); + int w_PrismaticJoint_enableLimit(lua_State * L); + int w_PrismaticJoint_isLimitEnabled(lua_State * L); int w_PrismaticJoint_setUpperLimit(lua_State * L); int w_PrismaticJoint_setLowerLimit(lua_State * L); int w_PrismaticJoint_setLimits(lua_State * L); diff --git a/src/modules/physics/box2d/wrap_RevoluteJoint.cpp b/src/modules/physics/box2d/wrap_RevoluteJoint.cpp index 6545d125e..3e87b5b4e 100644 --- a/src/modules/physics/box2d/wrap_RevoluteJoint.cpp +++ b/src/modules/physics/box2d/wrap_RevoluteJoint.cpp @@ -45,11 +45,11 @@ namespace box2d return 1; } - int w_RevoluteJoint_setMotorEnabled(lua_State * L) + int w_RevoluteJoint_enableMotor(lua_State * L) { RevoluteJoint * t = luax_checkrevolutejoint(L, 1); bool arg1 = luax_toboolean(L, 2); - t->setMotorEnabled(arg1); + t->enableMotor(arg1); return 0; } @@ -90,18 +90,18 @@ namespace box2d return 1; } - int w_RevoluteJoint_setLimitsEnabled(lua_State * L) + int w_RevoluteJoint_enableLimit(lua_State * L) { RevoluteJoint * t = luax_checkrevolutejoint(L, 1); bool arg1 = luax_toboolean(L, 2); - t->setLimitsEnabled(arg1); + t->enableLimit(arg1); return 0; } - int w_RevoluteJoint_isLimitsEnabled(lua_State * L) + int w_RevoluteJoint_isLimitEnabled(lua_State * L) { RevoluteJoint * t = luax_checkrevolutejoint(L, 1); - luax_pushboolean(L, t->isLimitsEnabled()); + luax_pushboolean(L, t->isLimitEnabled()); return 1; } @@ -154,14 +154,14 @@ namespace box2d static const luaL_Reg functions[] = { { "getJointAngle", w_RevoluteJoint_getJointAngle }, { "getJointSpeed", w_RevoluteJoint_getJointSpeed }, - { "setMotorEnabled", w_RevoluteJoint_setMotorEnabled }, + { "enableMotor", w_RevoluteJoint_enableMotor }, { "isMotorEnabled", w_RevoluteJoint_isMotorEnabled }, { "setMaxMotorTorque", w_RevoluteJoint_setMaxMotorTorque }, { "setMotorSpeed", w_RevoluteJoint_setMotorSpeed }, { "getMotorSpeed", w_RevoluteJoint_getMotorSpeed }, { "getMotorTorque", w_RevoluteJoint_getMotorTorque }, - { "setLimitsEnabled", w_RevoluteJoint_setLimitsEnabled }, - { "isLimitsEnabled", w_RevoluteJoint_isLimitsEnabled }, + { "enableLimit", w_RevoluteJoint_enableLimit }, + { "isLimitEnabled", w_RevoluteJoint_isLimitEnabled }, { "setUpperLimit", w_RevoluteJoint_setUpperLimit }, { "setLowerLimit", w_RevoluteJoint_setLowerLimit }, { "setLimits", w_RevoluteJoint_setLimits }, diff --git a/src/modules/physics/box2d/wrap_RevoluteJoint.h b/src/modules/physics/box2d/wrap_RevoluteJoint.h index ad03ce4e1..1e13aec3a 100644 --- a/src/modules/physics/box2d/wrap_RevoluteJoint.h +++ b/src/modules/physics/box2d/wrap_RevoluteJoint.h @@ -35,14 +35,14 @@ namespace box2d RevoluteJoint * luax_checkrevolutejoint(lua_State * L, int idx); int w_RevoluteJoint_getJointAngle(lua_State * L); int w_RevoluteJoint_getJointSpeed(lua_State * L); - int w_RevoluteJoint_setMotorEnabled(lua_State * L); + int w_RevoluteJoint_enableMotor(lua_State * L); int w_RevoluteJoint_isMotorEnabled(lua_State * L); int w_RevoluteJoint_setMaxMotorTorque(lua_State * L); int w_RevoluteJoint_setMotorSpeed(lua_State * L); int w_RevoluteJoint_getMotorSpeed(lua_State * L); int w_RevoluteJoint_getMotorTorque(lua_State * L); - int w_RevoluteJoint_setLimitsEnabled(lua_State * L); - int w_RevoluteJoint_isLimitsEnabled(lua_State * L); + int w_RevoluteJoint_enableLimit(lua_State * L); + int w_RevoluteJoint_isLimitEnabled(lua_State * L); int w_RevoluteJoint_setUpperLimit(lua_State * L); int w_RevoluteJoint_setLowerLimit(lua_State * L); int w_RevoluteJoint_setLimits(lua_State * L); From 915e3e9d8636aa751b324ef9c71c960c870befc2 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 3 Sep 2011 15:39:32 -0400 Subject: [PATCH 08/78] Updated to Box2D 2.2, added new joints, some other updates to match the API changes (still plenty more to go though) --HG-- branch : box2d-update --- .../macosx/love.xcodeproj/project.pbxproj | 133 +++- src/common/types.h | 12 + src/modules/physics/Joint.cpp | 3 +- src/modules/physics/Joint.h | 3 +- src/modules/physics/box2d/Box2D/Box2D.h | 11 +- .../Box2D/Collision/Shapes/b2ChainShape.cpp | 171 +++++ .../Box2D/Collision/Shapes/b2ChainShape.h | 117 +++ .../Box2D/Collision/Shapes/b2CircleShape.cpp | 23 +- .../Box2D/Collision/Shapes/b2CircleShape.h | 10 +- .../Box2D/Collision/Shapes/b2EdgeShape.cpp | 139 ++++ .../Box2D/Collision/Shapes/b2EdgeShape.h | 70 ++ .../Box2D/Collision/Shapes/b2PolygonShape.cpp | 245 +++--- .../Box2D/Collision/Shapes/b2PolygonShape.h | 56 +- .../box2d/Box2D/Collision/Shapes/b2Shape.h | 26 +- .../box2d/Box2D/Collision/b2BroadPhase.cpp | 8 +- .../box2d/Box2D/Collision/b2BroadPhase.h | 33 +- .../box2d/Box2D/Collision/b2CollideCircle.cpp | 2 +- .../box2d/Box2D/Collision/b2CollideEdge.cpp | 698 +++++++++++++++++ .../Box2D/Collision/b2CollidePolygon.cpp | 53 +- .../box2d/Box2D/Collision/b2Collision.cpp | 31 +- .../box2d/Box2D/Collision/b2Collision.h | 74 +- .../box2d/Box2D/Collision/b2Distance.cpp | 40 +- .../box2d/Box2D/Collision/b2Distance.h | 6 +- .../box2d/Box2D/Collision/b2DynamicTree.cpp | 642 +++++++++++++--- .../box2d/Box2D/Collision/b2DynamicTree.h | 96 ++- .../box2d/Box2D/Collision/b2TimeOfImpact.cpp | 42 +- .../box2d/Box2D/Collision/b2TimeOfImpact.h | 3 +- .../box2d/Box2D/Common/b2BlockAllocator.cpp | 18 +- .../box2d/Box2D/Common/b2BlockAllocator.h | 13 +- .../physics/box2d/Box2D/Common/b2Draw.cpp | 44 ++ .../physics/box2d/Box2D/Common/b2Draw.h | 81 ++ .../box2d/Box2D/Common/b2GrowableStack.h | 85 +++ .../physics/box2d/Box2D/Common/b2Math.cpp | 14 +- .../physics/box2d/Box2D/Common/b2Math.h | 289 ++++--- .../physics/box2d/Box2D/Common/b2Settings.cpp | 4 +- .../physics/box2d/Box2D/Common/b2Settings.h | 28 +- .../box2d/Box2D/Common/b2StackAllocator.cpp | 2 +- .../box2d/Box2D/Common/b2StackAllocator.h | 2 +- .../physics/box2d/Box2D/Common/b2Timer.cpp | 100 +++ .../b2TOISolver.h => Common/b2Timer.h} | 44 +- .../Contacts/b2ChainAndCircleContact.cpp | 54 ++ .../Contacts/b2ChainAndCircleContact.h | 39 + .../Contacts/b2ChainAndPolygonContact.cpp | 54 ++ .../Contacts/b2ChainAndPolygonContact.h | 39 + .../Dynamics/Contacts/b2CircleContact.cpp | 7 +- .../Box2D/Dynamics/Contacts/b2CircleContact.h | 5 +- .../Box2D/Dynamics/Contacts/b2Contact.cpp | 38 +- .../box2d/Box2D/Dynamics/Contacts/b2Contact.h | 105 ++- .../Dynamics/Contacts/b2ContactSolver.cpp | 715 +++++++++++------ .../Box2D/Dynamics/Contacts/b2ContactSolver.h | 54 +- .../Contacts/b2EdgeAndCircleContact.cpp | 50 ++ .../Contacts/b2EdgeAndCircleContact.h | 39 + .../Contacts/b2EdgeAndPolygonContact.cpp | 50 ++ .../Contacts/b2EdgeAndPolygonContact.h | 39 + .../Contacts/b2PolygonAndCircleContact.cpp | 10 +- .../Contacts/b2PolygonAndCircleContact.h | 4 +- .../Dynamics/Contacts/b2PolygonContact.cpp | 7 +- .../Dynamics/Contacts/b2PolygonContact.h | 5 +- .../Box2D/Dynamics/Contacts/b2TOISolver.cpp | 231 ------ .../Box2D/Dynamics/Joints/b2DistanceJoint.cpp | 139 ++-- .../Box2D/Dynamics/Joints/b2DistanceJoint.h | 37 +- .../Box2D/Dynamics/Joints/b2FrictionJoint.cpp | 114 +-- .../Box2D/Dynamics/Joints/b2FrictionJoint.h | 27 +- .../Box2D/Dynamics/Joints/b2GearJoint.cpp | 359 ++++++--- .../box2d/Box2D/Dynamics/Joints/b2GearJoint.h | 58 +- .../box2d/Box2D/Dynamics/Joints/b2Joint.cpp | 26 +- .../box2d/Box2D/Dynamics/Joints/b2Joint.h | 58 +- .../Box2D/Dynamics/Joints/b2LineJoint.cpp | 591 --------------- .../box2d/Box2D/Dynamics/Joints/b2LineJoint.h | 170 ----- .../Box2D/Dynamics/Joints/b2MouseJoint.cpp | 106 +-- .../Box2D/Dynamics/Joints/b2MouseJoint.h | 31 +- .../Dynamics/Joints/b2PrismaticJoint.cpp | 397 +++++----- .../Box2D/Dynamics/Joints/b2PrismaticJoint.h | 55 +- .../Box2D/Dynamics/Joints/b2PulleyJoint.cpp | 439 ++++------- .../Box2D/Dynamics/Joints/b2PulleyJoint.h | 74 +- .../Box2D/Dynamics/Joints/b2RevoluteJoint.cpp | 321 ++++---- .../Box2D/Dynamics/Joints/b2RevoluteJoint.h | 47 +- .../Box2D/Dynamics/Joints/b2RopeJoint.cpp | 226 ++++++ .../box2d/Box2D/Dynamics/Joints/b2RopeJoint.h | 104 +++ .../Box2D/Dynamics/Joints/b2WeldJoint.cpp | 172 +++-- .../box2d/Box2D/Dynamics/Joints/b2WeldJoint.h | 22 +- .../Box2D/Dynamics/Joints/b2WheelJoint.cpp | 404 ++++++++++ .../Box2D/Dynamics/Joints/b2WheelJoint.h | 199 +++++ .../physics/box2d/Box2D/Dynamics/b2Body.cpp | 74 +- .../physics/box2d/Box2D/Dynamics/b2Body.h | 77 +- .../box2d/Box2D/Dynamics/b2ContactManager.cpp | 45 +- .../box2d/Box2D/Dynamics/b2ContactManager.h | 2 +- .../box2d/Box2D/Dynamics/b2Fixture.cpp | 127 +++- .../physics/box2d/Box2D/Dynamics/b2Fixture.h | 48 +- .../physics/box2d/Box2D/Dynamics/b2Island.cpp | 381 +++++++--- .../physics/box2d/Box2D/Dynamics/b2Island.h | 30 +- .../physics/box2d/Box2D/Dynamics/b2TimeStep.h | 55 +- .../physics/box2d/Box2D/Dynamics/b2World.cpp | 717 +++++++++++------- .../physics/box2d/Box2D/Dynamics/b2World.h | 86 ++- .../box2d/Box2D/Dynamics/b2WorldCallbacks.cpp | 27 +- .../box2d/Box2D/Dynamics/b2WorldCallbacks.h | 66 +- .../physics/box2d/Box2D/Rope/b2Rope.cpp | 259 +++++++ src/modules/physics/box2d/Box2D/Rope/b2Rope.h | 115 +++ src/modules/physics/box2d/FrictionJoint.cpp | 72 ++ src/modules/physics/box2d/FrictionJoint.h | 78 ++ src/modules/physics/box2d/Joint.cpp | 13 + src/modules/physics/box2d/Joint.h | 2 + src/modules/physics/box2d/Physics.cpp | 5 + src/modules/physics/box2d/Physics.h | 8 + src/modules/physics/box2d/PrismaticJoint.cpp | 16 +- src/modules/physics/box2d/PrismaticJoint.h | 3 +- src/modules/physics/box2d/WeldJoint.cpp | 51 ++ src/modules/physics/box2d/WeldJoint.h | 58 ++ src/modules/physics/box2d/WheelJoint.cpp | 116 +++ src/modules/physics/box2d/WheelJoint.h | 127 ++++ .../physics/box2d/wrap_DistanceJoint.cpp | 1 - .../physics/box2d/wrap_FrictionJoint.cpp | 86 +++ .../physics/box2d/wrap_FrictionJoint.h | 46 ++ src/modules/physics/box2d/wrap_GearJoint.cpp | 1 - src/modules/physics/box2d/wrap_Joint.cpp | 9 - src/modules/physics/box2d/wrap_Joint.h | 1 - src/modules/physics/box2d/wrap_MouseJoint.cpp | 1 - src/modules/physics/box2d/wrap_Physics.cpp | 13 + src/modules/physics/box2d/wrap_Physics.h | 2 + .../physics/box2d/wrap_PrismaticJoint.cpp | 1 - .../physics/box2d/wrap_PulleyJoint.cpp | 1 - .../physics/box2d/wrap_RevoluteJoint.cpp | 1 - src/modules/physics/box2d/wrap_WeldJoint.cpp | 52 ++ src/modules/physics/box2d/wrap_WeldJoint.h | 42 + src/modules/physics/box2d/wrap_WheelJoint.cpp | 188 +++++ src/modules/physics/box2d/wrap_WheelJoint.h | 58 ++ 126 files changed, 8581 insertions(+), 3772 deletions(-) mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Box2D.h create mode 100755 src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.cpp create mode 100755 src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.h create mode 100755 src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.cpp create mode 100755 src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/Shapes/b2Shape.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/b2CollideCircle.cpp create mode 100755 src/modules/physics/box2d/Box2D/Collision/b2CollideEdge.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/b2CollidePolygon.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/b2Collision.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/b2Collision.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/b2Distance.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.h create mode 100755 src/modules/physics/box2d/Box2D/Common/b2Draw.cpp create mode 100755 src/modules/physics/box2d/Box2D/Common/b2Draw.h create mode 100755 src/modules/physics/box2d/Box2D/Common/b2GrowableStack.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Common/b2Math.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Common/b2Math.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Common/b2Settings.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Common/b2Settings.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Common/b2StackAllocator.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Common/b2StackAllocator.h create mode 100755 src/modules/physics/box2d/Box2D/Common/b2Timer.cpp rename src/modules/physics/box2d/Box2D/{Dynamics/Contacts/b2TOISolver.h => Common/b2Timer.h} (54%) mode change 100644 => 100755 create mode 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp create mode 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h create mode 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp create mode 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.h create mode 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp create mode 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h create mode 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp create mode 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.h delete mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.h delete mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.cpp delete mode 100644 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h create mode 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.cpp create mode 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h create mode 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.cpp create mode 100755 src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/b2Body.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/b2Island.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/b2Island.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/b2TimeStep.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/b2World.h mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.cpp mode change 100644 => 100755 src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.h create mode 100755 src/modules/physics/box2d/Box2D/Rope/b2Rope.cpp create mode 100755 src/modules/physics/box2d/Box2D/Rope/b2Rope.h create mode 100644 src/modules/physics/box2d/FrictionJoint.cpp create mode 100644 src/modules/physics/box2d/FrictionJoint.h create mode 100644 src/modules/physics/box2d/WeldJoint.cpp create mode 100644 src/modules/physics/box2d/WeldJoint.h create mode 100644 src/modules/physics/box2d/WheelJoint.cpp create mode 100644 src/modules/physics/box2d/WheelJoint.h create mode 100644 src/modules/physics/box2d/wrap_FrictionJoint.cpp create mode 100644 src/modules/physics/box2d/wrap_FrictionJoint.h create mode 100644 src/modules/physics/box2d/wrap_WeldJoint.cpp create mode 100644 src/modules/physics/box2d/wrap_WeldJoint.h create mode 100644 src/modules/physics/box2d/wrap_WheelJoint.cpp create mode 100644 src/modules/physics/box2d/wrap_WheelJoint.h diff --git a/platform/macosx/love.xcodeproj/project.pbxproj b/platform/macosx/love.xcodeproj/project.pbxproj index 933c8eeaa..77cba2653 100644 --- a/platform/macosx/love.xcodeproj/project.pbxproj +++ b/platform/macosx/love.xcodeproj/project.pbxproj @@ -147,6 +147,22 @@ A968F0D91083A9FC00A895AA /* Mouse.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0D81083A9FC00A895AA /* Mouse.cpp */; }; A968F0DD1083AA6600A895AA /* Shape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0DB1083AA6600A895AA /* Shape.cpp */; }; A968F0DE1083AA6600A895AA /* Joint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0DC1083AA6600A895AA /* Joint.cpp */; }; + A96F416014127E340067FE9A /* b2RopeJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F415C14127E310067FE9A /* b2RopeJoint.cpp */; }; + A96F416114127E340067FE9A /* b2WheelJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F415E14127E320067FE9A /* b2WheelJoint.cpp */; }; + A96F416514127E720067FE9A /* b2Rope.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F416314127E720067FE9A /* b2Rope.cpp */; }; + A96F416B14127E9C0067FE9A /* b2Draw.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F416614127E9C0067FE9A /* b2Draw.cpp */; }; + A96F416C14127E9C0067FE9A /* b2Timer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F416914127E9C0067FE9A /* b2Timer.cpp */; }; + A96F416E14127EB20067FE9A /* b2CollideEdge.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F416D14127EB20067FE9A /* b2CollideEdge.cpp */; }; + A96F417114127EC00067FE9A /* b2ChainShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F416F14127EC00067FE9A /* b2ChainShape.cpp */; }; + A96F417614127EE70067FE9A /* b2ChainAndCircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F417214127EE70067FE9A /* b2ChainAndCircleContact.cpp */; }; + A96F417714127EE70067FE9A /* b2ChainAndPolygonContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F417414127EE70067FE9A /* b2ChainAndPolygonContact.cpp */; }; + A96F417C14127EFD0067FE9A /* b2EdgeAndCircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F417814127EFD0067FE9A /* b2EdgeAndCircleContact.cpp */; }; + A96F417D14127EFD0067FE9A /* b2EdgeAndPolygonContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F417A14127EFD0067FE9A /* b2EdgeAndPolygonContact.cpp */; }; + A96F418014127FC20067FE9A /* b2EdgeShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F417E14127FC20067FE9A /* b2EdgeShape.cpp */; }; + A96F41831412AFE20067FE9A /* wrap_WeldJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F41811412AFB70067FE9A /* wrap_WeldJoint.cpp */; }; + A96F41861412AFF80067FE9A /* WeldJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F41841412AFEB0067FE9A /* WeldJoint.cpp */; }; + A96F41891412B36D0067FE9A /* wrap_WheelJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F41871412B35B0067FE9A /* wrap_WheelJoint.cpp */; }; + A96F418C1412B3AD0067FE9A /* WheelJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F418A1412B3A30067FE9A /* WheelJoint.cpp */; }; A986DEB5113249A800810279 /* Thread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986DEB1113249A800810279 /* Thread.cpp */; }; A986DEB6113249A800810279 /* wrap_Thread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986DEB3113249A800810279 /* wrap_Thread.cpp */; }; A986EC64132CE6DB00F048C8 /* b2BroadPhase.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBC8132CE6D800F048C8 /* b2BroadPhase.cpp */; }; @@ -173,12 +189,10 @@ A986EC79132CE6DB00F048C8 /* b2ContactSolver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBF6132CE6D800F048C8 /* b2ContactSolver.cpp */; }; A986EC7A132CE6DB00F048C8 /* b2PolygonAndCircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBF8132CE6D800F048C8 /* b2PolygonAndCircleContact.cpp */; }; A986EC7B132CE6DB00F048C8 /* b2PolygonContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBFA132CE6D800F048C8 /* b2PolygonContact.cpp */; }; - A986EC7C132CE6DB00F048C8 /* b2TOISolver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBFC132CE6D800F048C8 /* b2TOISolver.cpp */; }; A986EC7D132CE6DB00F048C8 /* b2DistanceJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBFF132CE6D800F048C8 /* b2DistanceJoint.cpp */; }; A986EC7E132CE6DB00F048C8 /* b2FrictionJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC01132CE6D800F048C8 /* b2FrictionJoint.cpp */; }; A986EC7F132CE6DB00F048C8 /* b2GearJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC03132CE6D800F048C8 /* b2GearJoint.cpp */; }; A986EC80132CE6DB00F048C8 /* b2Joint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC05132CE6D800F048C8 /* b2Joint.cpp */; }; - A986EC81132CE6DB00F048C8 /* b2LineJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC07132CE6D800F048C8 /* b2LineJoint.cpp */; }; A986EC82132CE6DB00F048C8 /* b2MouseJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC09132CE6D800F048C8 /* b2MouseJoint.cpp */; }; A986EC83132CE6DB00F048C8 /* b2PrismaticJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC0B132CE6D800F048C8 /* b2PrismaticJoint.cpp */; }; A986EC84132CE6DB00F048C8 /* b2PulleyJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC0D132CE6D800F048C8 /* b2PulleyJoint.cpp */; }; @@ -188,6 +202,8 @@ A98D914410507C97008E03F2 /* EncodedImageData.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A98D914310507C97008E03F2 /* EncodedImageData.cpp */; }; A9B4BA9C1045937F001DBC80 /* ParticleSystem.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9B4BA9A1045937F001DBC80 /* ParticleSystem.cpp */; }; A9B4BA9D1045937F001DBC80 /* wrap_ParticleSystem.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9B4BA9B1045937F001DBC80 /* wrap_ParticleSystem.cpp */; }; + A9B6432C13BF83AB00DC3C7E /* FrictionJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9B6432A13BF833900DC3C7E /* FrictionJoint.cpp */; }; + A9B6432F13BF87F100DC3C7E /* wrap_FrictionJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9B6432D13BF87E400DC3C7E /* wrap_FrictionJoint.cpp */; }; A9BD60741226C988007DEC63 /* Framebuffer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9BD60701226C988007DEC63 /* Framebuffer.cpp */; }; A9BD60751226C988007DEC63 /* wrap_Framebuffer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9BD60721226C988007DEC63 /* wrap_Framebuffer.cpp */; }; A9CF0E8610B9EB1000E6F37E /* utf8.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9CF0E8510B9EB1000E6F37E /* utf8.cpp */; }; @@ -523,6 +539,38 @@ A968F0D81083A9FC00A895AA /* Mouse.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Mouse.cpp; sourceTree = ""; }; A968F0DB1083AA6600A895AA /* Shape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Shape.cpp; sourceTree = ""; }; A968F0DC1083AA6600A895AA /* Joint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Joint.cpp; sourceTree = ""; }; + A96F415C14127E310067FE9A /* b2RopeJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2RopeJoint.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Joints/b2RopeJoint.cpp; sourceTree = ""; }; + A96F415D14127E320067FE9A /* b2RopeJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2RopeJoint.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Joints/b2RopeJoint.h; sourceTree = ""; }; + A96F415E14127E320067FE9A /* b2WheelJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2WheelJoint.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Joints/b2WheelJoint.cpp; sourceTree = ""; }; + A96F415F14127E320067FE9A /* b2WheelJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2WheelJoint.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Joints/b2WheelJoint.h; sourceTree = ""; }; + A96F416314127E720067FE9A /* b2Rope.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Rope.cpp; sourceTree = ""; }; + A96F416414127E720067FE9A /* b2Rope.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Rope.h; sourceTree = ""; }; + A96F416614127E9C0067FE9A /* b2Draw.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2Draw.cpp; path = ../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Common/b2Draw.cpp; sourceTree = ""; }; + A96F416714127E9C0067FE9A /* b2Draw.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2Draw.h; path = ../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Common/b2Draw.h; sourceTree = ""; }; + A96F416814127E9C0067FE9A /* b2GrowableStack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2GrowableStack.h; path = ../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Common/b2GrowableStack.h; sourceTree = ""; }; + A96F416914127E9C0067FE9A /* b2Timer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2Timer.cpp; path = ../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Common/b2Timer.cpp; sourceTree = ""; }; + A96F416A14127E9C0067FE9A /* b2Timer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2Timer.h; path = ../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Common/b2Timer.h; sourceTree = ""; }; + A96F416D14127EB20067FE9A /* b2CollideEdge.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2CollideEdge.cpp; path = ../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Collision/b2CollideEdge.cpp; sourceTree = ""; }; + A96F416F14127EC00067FE9A /* b2ChainShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2ChainShape.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Collision/Shapes/b2ChainShape.cpp; sourceTree = ""; }; + A96F417014127EC00067FE9A /* b2ChainShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2ChainShape.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Collision/Shapes/b2ChainShape.h; sourceTree = ""; }; + A96F417214127EE70067FE9A /* b2ChainAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2ChainAndCircleContact.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp; sourceTree = ""; }; + A96F417314127EE70067FE9A /* b2ChainAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2ChainAndCircleContact.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h; sourceTree = ""; }; + A96F417414127EE70067FE9A /* b2ChainAndPolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2ChainAndPolygonContact.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp; sourceTree = ""; }; + A96F417514127EE70067FE9A /* b2ChainAndPolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2ChainAndPolygonContact.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h; sourceTree = ""; }; + A96F417814127EFD0067FE9A /* b2EdgeAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2EdgeAndCircleContact.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp; sourceTree = ""; }; + A96F417914127EFD0067FE9A /* b2EdgeAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2EdgeAndCircleContact.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h; sourceTree = ""; }; + A96F417A14127EFD0067FE9A /* b2EdgeAndPolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2EdgeAndPolygonContact.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp; sourceTree = ""; }; + A96F417B14127EFD0067FE9A /* b2EdgeAndPolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2EdgeAndPolygonContact.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h; sourceTree = ""; }; + A96F417E14127FC20067FE9A /* b2EdgeShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2EdgeShape.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Collision/Shapes/b2EdgeShape.cpp; sourceTree = ""; }; + A96F417F14127FC20067FE9A /* b2EdgeShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2EdgeShape.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Collision/Shapes/b2EdgeShape.h; sourceTree = ""; }; + A96F41811412AFB70067FE9A /* wrap_WeldJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_WeldJoint.cpp; sourceTree = ""; }; + A96F41821412AFC60067FE9A /* wrap_WeldJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_WeldJoint.h; sourceTree = ""; }; + A96F41841412AFEB0067FE9A /* WeldJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WeldJoint.cpp; sourceTree = ""; }; + A96F41851412AFEE0067FE9A /* WeldJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WeldJoint.h; sourceTree = ""; }; + A96F41871412B35B0067FE9A /* wrap_WheelJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_WheelJoint.cpp; sourceTree = ""; }; + A96F41881412B3610067FE9A /* wrap_WheelJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_WheelJoint.h; sourceTree = ""; }; + A96F418A1412B3A30067FE9A /* WheelJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WheelJoint.cpp; sourceTree = ""; }; + A96F418B1412B3A80067FE9A /* WheelJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WheelJoint.h; sourceTree = ""; }; A97E3842132A9EDE00198A2F /* love-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "love-Info.plist"; sourceTree = ""; }; A986DEB1113249A800810279 /* Thread.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Thread.cpp; sourceTree = ""; }; A986DEB2113249A800810279 /* Thread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Thread.h; sourceTree = ""; }; @@ -576,8 +624,6 @@ A986EBF9132CE6D800F048C8 /* b2PolygonAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PolygonAndCircleContact.h; sourceTree = ""; }; A986EBFA132CE6D800F048C8 /* b2PolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PolygonContact.cpp; sourceTree = ""; }; A986EBFB132CE6D800F048C8 /* b2PolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PolygonContact.h; sourceTree = ""; }; - A986EBFC132CE6D800F048C8 /* b2TOISolver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2TOISolver.cpp; sourceTree = ""; }; - A986EBFD132CE6D800F048C8 /* b2TOISolver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2TOISolver.h; sourceTree = ""; }; A986EBFF132CE6D800F048C8 /* b2DistanceJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2DistanceJoint.cpp; sourceTree = ""; }; A986EC00132CE6D800F048C8 /* b2DistanceJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2DistanceJoint.h; sourceTree = ""; }; A986EC01132CE6D800F048C8 /* b2FrictionJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2FrictionJoint.cpp; sourceTree = ""; }; @@ -586,8 +632,6 @@ A986EC04132CE6D800F048C8 /* b2GearJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2GearJoint.h; sourceTree = ""; }; A986EC05132CE6D800F048C8 /* b2Joint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Joint.cpp; sourceTree = ""; }; A986EC06132CE6D800F048C8 /* b2Joint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Joint.h; sourceTree = ""; }; - A986EC07132CE6D800F048C8 /* b2LineJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2LineJoint.cpp; sourceTree = ""; }; - A986EC08132CE6D800F048C8 /* b2LineJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2LineJoint.h; sourceTree = ""; }; A986EC09132CE6D800F048C8 /* b2MouseJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2MouseJoint.cpp; sourceTree = ""; }; A986EC0A132CE6D800F048C8 /* b2MouseJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2MouseJoint.h; sourceTree = ""; }; A986EC0B132CE6D800F048C8 /* b2PrismaticJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PrismaticJoint.cpp; sourceTree = ""; }; @@ -608,6 +652,10 @@ A9B4BA991045937F001DBC80 /* wrap_ParticleSystem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_ParticleSystem.h; sourceTree = ""; }; A9B4BA9A1045937F001DBC80 /* ParticleSystem.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ParticleSystem.cpp; sourceTree = ""; }; A9B4BA9B1045937F001DBC80 /* wrap_ParticleSystem.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_ParticleSystem.cpp; sourceTree = ""; }; + A9B6432A13BF833900DC3C7E /* FrictionJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = FrictionJoint.cpp; sourceTree = ""; }; + A9B6432B13BF837800DC3C7E /* FrictionJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FrictionJoint.h; sourceTree = ""; }; + A9B6432D13BF87E400DC3C7E /* wrap_FrictionJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_FrictionJoint.cpp; sourceTree = ""; }; + A9B6432E13BF87EA00DC3C7E /* wrap_FrictionJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_FrictionJoint.h; sourceTree = ""; }; A9BD60701226C988007DEC63 /* Framebuffer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Framebuffer.cpp; sourceTree = ""; }; A9BD60711226C988007DEC63 /* Framebuffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Framebuffer.h; sourceTree = ""; }; A9BD60721226C988007DEC63 /* wrap_Framebuffer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_Framebuffer.cpp; sourceTree = ""; }; @@ -1149,6 +1197,8 @@ A93E6AF210420AC7007D418B /* DistanceJoint.h */, A986ECAD132CEB9300F048C8 /* Fixture.cpp */, A986ECAE132CEB9B00F048C8 /* Fixture.h */, + A9B6432A13BF833900DC3C7E /* FrictionJoint.cpp */, + A9B6432B13BF837800DC3C7E /* FrictionJoint.h */, A93E6AF310420AC7007D418B /* GearJoint.cpp */, A93E6AF410420AC7007D418B /* GearJoint.h */, A93E6AF510420AC7007D418B /* graham */, @@ -1168,6 +1218,10 @@ A93E6B0710420AC8007D418B /* RevoluteJoint.h */, A93E6B0810420AC8007D418B /* Shape.cpp */, A93E6B0910420AC8007D418B /* Shape.h */, + A96F41841412AFEB0067FE9A /* WeldJoint.cpp */, + A96F41851412AFEE0067FE9A /* WeldJoint.h */, + A96F418A1412B3A30067FE9A /* WheelJoint.cpp */, + A96F418B1412B3A80067FE9A /* WheelJoint.h */, A93E6B4E10420ACA007D418B /* World.cpp */, A93E6B4F10420ACA007D418B /* World.h */, A93E6B5010420ACA007D418B /* wrap_Body.cpp */, @@ -1178,6 +1232,8 @@ A93E6B5510420ACA007D418B /* wrap_Contact.h */, A93E6B5610420ACA007D418B /* wrap_DistanceJoint.cpp */, A93E6B5710420ACA007D418B /* wrap_DistanceJoint.h */, + A9B6432D13BF87E400DC3C7E /* wrap_FrictionJoint.cpp */, + A9B6432E13BF87EA00DC3C7E /* wrap_FrictionJoint.h */, A93E6B5810420ACA007D418B /* wrap_GearJoint.cpp */, A93E6B5910420ACA007D418B /* wrap_GearJoint.h */, A93E6B5A10420ACA007D418B /* wrap_Joint.cpp */, @@ -1196,6 +1252,10 @@ A93E6B6710420ACA007D418B /* wrap_RevoluteJoint.h */, A93E6B6810420ACA007D418B /* wrap_Shape.cpp */, A93E6B6910420ACA007D418B /* wrap_Shape.h */, + A96F41811412AFB70067FE9A /* wrap_WeldJoint.cpp */, + A96F41821412AFC60067FE9A /* wrap_WeldJoint.h */, + A96F41871412B35B0067FE9A /* wrap_WheelJoint.cpp */, + A96F41881412B3610067FE9A /* wrap_WheelJoint.h */, A93E6B6A10420ACA007D418B /* wrap_World.cpp */, A93E6B6B10420ACB007D418B /* wrap_World.h */, ); @@ -1300,6 +1360,16 @@ path = utf8; sourceTree = ""; }; + A96F416214127E720067FE9A /* Rope */ = { + isa = PBXGroup; + children = ( + A96F416314127E720067FE9A /* b2Rope.cpp */, + A96F416414127E720067FE9A /* b2Rope.h */, + ); + name = Rope; + path = ../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Rope; + sourceTree = ""; + }; A986DEAF113249A700810279 /* thread */ = { isa = PBXGroup; children = ( @@ -1327,6 +1397,7 @@ A986EBC7132CE6D800F048C8 /* Collision */, A986EBDA132CE6D800F048C8 /* Common */, A986EBE3132CE6D800F048C8 /* Dynamics */, + A96F416214127E720067FE9A /* Rope */, ); path = Box2D; sourceTree = ""; @@ -1337,6 +1408,7 @@ A986EBC8132CE6D800F048C8 /* b2BroadPhase.cpp */, A986EBC9132CE6D800F048C8 /* b2BroadPhase.h */, A986EBCA132CE6D800F048C8 /* b2CollideCircle.cpp */, + A96F416D14127EB20067FE9A /* b2CollideEdge.cpp */, A986EBCB132CE6D800F048C8 /* b2CollidePolygon.cpp */, A986EBCC132CE6D800F048C8 /* b2Collision.cpp */, A986EBCD132CE6D800F048C8 /* b2Collision.h */, @@ -1354,8 +1426,12 @@ A986EBD4132CE6D800F048C8 /* Shapes */ = { isa = PBXGroup; children = ( + A96F416F14127EC00067FE9A /* b2ChainShape.cpp */, + A96F417014127EC00067FE9A /* b2ChainShape.h */, A986EBD5132CE6D800F048C8 /* b2CircleShape.cpp */, A986EBD6132CE6D800F048C8 /* b2CircleShape.h */, + A96F417E14127FC20067FE9A /* b2EdgeShape.cpp */, + A96F417F14127FC20067FE9A /* b2EdgeShape.h */, A986EBD7132CE6D800F048C8 /* b2PolygonShape.cpp */, A986EBD8132CE6D800F048C8 /* b2PolygonShape.h */, A986EBD9132CE6D800F048C8 /* b2Shape.h */, @@ -1368,12 +1444,17 @@ children = ( A986EBDB132CE6D800F048C8 /* b2BlockAllocator.cpp */, A986EBDC132CE6D800F048C8 /* b2BlockAllocator.h */, + A96F416614127E9C0067FE9A /* b2Draw.cpp */, + A96F416714127E9C0067FE9A /* b2Draw.h */, + A96F416814127E9C0067FE9A /* b2GrowableStack.h */, A986EBDD132CE6D800F048C8 /* b2Math.cpp */, A986EBDE132CE6D800F048C8 /* b2Math.h */, A986EBDF132CE6D800F048C8 /* b2Settings.cpp */, A986EBE0132CE6D800F048C8 /* b2Settings.h */, A986EBE1132CE6D800F048C8 /* b2StackAllocator.cpp */, A986EBE2132CE6D800F048C8 /* b2StackAllocator.h */, + A96F416914127E9C0067FE9A /* b2Timer.cpp */, + A96F416A14127E9C0067FE9A /* b2Timer.h */, ); path = Common; sourceTree = ""; @@ -1403,18 +1484,24 @@ A986EBF1132CE6D800F048C8 /* Contacts */ = { isa = PBXGroup; children = ( + A96F417214127EE70067FE9A /* b2ChainAndCircleContact.cpp */, + A96F417314127EE70067FE9A /* b2ChainAndCircleContact.h */, + A96F417414127EE70067FE9A /* b2ChainAndPolygonContact.cpp */, + A96F417514127EE70067FE9A /* b2ChainAndPolygonContact.h */, A986EBF2132CE6D800F048C8 /* b2CircleContact.cpp */, A986EBF3132CE6D800F048C8 /* b2CircleContact.h */, A986EBF4132CE6D800F048C8 /* b2Contact.cpp */, A986EBF5132CE6D800F048C8 /* b2Contact.h */, A986EBF6132CE6D800F048C8 /* b2ContactSolver.cpp */, A986EBF7132CE6D800F048C8 /* b2ContactSolver.h */, + A96F417814127EFD0067FE9A /* b2EdgeAndCircleContact.cpp */, + A96F417914127EFD0067FE9A /* b2EdgeAndCircleContact.h */, + A96F417A14127EFD0067FE9A /* b2EdgeAndPolygonContact.cpp */, + A96F417B14127EFD0067FE9A /* b2EdgeAndPolygonContact.h */, A986EBF8132CE6D800F048C8 /* b2PolygonAndCircleContact.cpp */, A986EBF9132CE6D800F048C8 /* b2PolygonAndCircleContact.h */, A986EBFA132CE6D800F048C8 /* b2PolygonContact.cpp */, A986EBFB132CE6D800F048C8 /* b2PolygonContact.h */, - A986EBFC132CE6D800F048C8 /* b2TOISolver.cpp */, - A986EBFD132CE6D800F048C8 /* b2TOISolver.h */, ); path = Contacts; sourceTree = ""; @@ -1430,8 +1517,6 @@ A986EC04132CE6D800F048C8 /* b2GearJoint.h */, A986EC05132CE6D800F048C8 /* b2Joint.cpp */, A986EC06132CE6D800F048C8 /* b2Joint.h */, - A986EC07132CE6D800F048C8 /* b2LineJoint.cpp */, - A986EC08132CE6D800F048C8 /* b2LineJoint.h */, A986EC09132CE6D800F048C8 /* b2MouseJoint.cpp */, A986EC0A132CE6D800F048C8 /* b2MouseJoint.h */, A986EC0B132CE6D800F048C8 /* b2PrismaticJoint.cpp */, @@ -1440,8 +1525,12 @@ A986EC0E132CE6D800F048C8 /* b2PulleyJoint.h */, A986EC0F132CE6D800F048C8 /* b2RevoluteJoint.cpp */, A986EC10132CE6D800F048C8 /* b2RevoluteJoint.h */, + A96F415C14127E310067FE9A /* b2RopeJoint.cpp */, + A96F415D14127E320067FE9A /* b2RopeJoint.h */, A986EC11132CE6D800F048C8 /* b2WeldJoint.cpp */, A986EC12132CE6D800F048C8 /* b2WeldJoint.h */, + A96F415E14127E320067FE9A /* b2WheelJoint.cpp */, + A96F415F14127E320067FE9A /* b2WheelJoint.h */, ); path = Joints; sourceTree = ""; @@ -1473,6 +1562,9 @@ /* Begin PBXProject section */ 29B97313FDCFA39411CA2CEA /* Project object */ = { isa = PBXProject; + attributes = { + LastUpgradeCheck = 0410; + }; buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "love" */; compatibilityVersion = "Xcode 3.1"; developmentRegion = English; @@ -1666,18 +1758,34 @@ A986EC79132CE6DB00F048C8 /* b2ContactSolver.cpp in Sources */, A986EC7A132CE6DB00F048C8 /* b2PolygonAndCircleContact.cpp in Sources */, A986EC7B132CE6DB00F048C8 /* b2PolygonContact.cpp in Sources */, - A986EC7C132CE6DB00F048C8 /* b2TOISolver.cpp in Sources */, A986EC7D132CE6DB00F048C8 /* b2DistanceJoint.cpp in Sources */, A986EC7E132CE6DB00F048C8 /* b2FrictionJoint.cpp in Sources */, A986EC7F132CE6DB00F048C8 /* b2GearJoint.cpp in Sources */, A986EC80132CE6DB00F048C8 /* b2Joint.cpp in Sources */, - A986EC81132CE6DB00F048C8 /* b2LineJoint.cpp in Sources */, A986EC82132CE6DB00F048C8 /* b2MouseJoint.cpp in Sources */, A986EC83132CE6DB00F048C8 /* b2PrismaticJoint.cpp in Sources */, A986EC84132CE6DB00F048C8 /* b2PulleyJoint.cpp in Sources */, A986EC85132CE6DB00F048C8 /* b2RevoluteJoint.cpp in Sources */, A986EC86132CE6DB00F048C8 /* b2WeldJoint.cpp in Sources */, A986ECAF132CEBB000F048C8 /* Fixture.cpp in Sources */, + A9B6432C13BF83AB00DC3C7E /* FrictionJoint.cpp in Sources */, + A9B6432F13BF87F100DC3C7E /* wrap_FrictionJoint.cpp in Sources */, + A96F416014127E340067FE9A /* b2RopeJoint.cpp in Sources */, + A96F416114127E340067FE9A /* b2WheelJoint.cpp in Sources */, + A96F416514127E720067FE9A /* b2Rope.cpp in Sources */, + A96F416B14127E9C0067FE9A /* b2Draw.cpp in Sources */, + A96F416C14127E9C0067FE9A /* b2Timer.cpp in Sources */, + A96F416E14127EB20067FE9A /* b2CollideEdge.cpp in Sources */, + A96F417114127EC00067FE9A /* b2ChainShape.cpp in Sources */, + A96F417614127EE70067FE9A /* b2ChainAndCircleContact.cpp in Sources */, + A96F417714127EE70067FE9A /* b2ChainAndPolygonContact.cpp in Sources */, + A96F417C14127EFD0067FE9A /* b2EdgeAndCircleContact.cpp in Sources */, + A96F417D14127EFD0067FE9A /* b2EdgeAndPolygonContact.cpp in Sources */, + A96F418014127FC20067FE9A /* b2EdgeShape.cpp in Sources */, + A96F41831412AFE20067FE9A /* wrap_WeldJoint.cpp in Sources */, + A96F41861412AFF80067FE9A /* WeldJoint.cpp in Sources */, + A96F41891412B36D0067FE9A /* wrap_WheelJoint.cpp in Sources */, + A96F418C1412B3AD0067FE9A /* WheelJoint.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1743,6 +1851,7 @@ ); ONLY_ACTIVE_ARCH = NO; PRODUCT_NAME = love; + SDKROOT = macosx; }; name = Release; }; diff --git a/src/common/types.h b/src/common/types.h index 7009baa14..567d93744 100644 --- a/src/common/types.h +++ b/src/common/types.h @@ -72,6 +72,8 @@ namespace love PHYSICS_SHAPE_ID, PHYSICS_CIRCLE_SHAPE_ID, PHYSICS_POLYGON_SHAPE_ID, + PHYSICS_EDGE_SHAPE_ID, + PHYSICS_CHAIN_SHAPE_ID, PHYSICS_JOINT_ID, PHYSICS_MOUSE_JOINT_ID, PHYSICS_DISTANCE_JOINT_ID, @@ -79,6 +81,10 @@ namespace love PHYSICS_REVOLUTE_JOINT_ID, PHYSICS_PULLEY_JOINT_ID, PHYSICS_GEAR_JOINT_ID, + PHYSICS_FRICTION_JOINT_ID, + PHYSICS_WELD_JOINT_ID, + PHYSICS_ROPE_JOINT_ID, + PHYSICS_WHEEL_JOINT_ID, // Thread THREAD_THREAD_ID, @@ -137,6 +143,8 @@ namespace love const bits PHYSICS_SHAPE_T = (bits(1) << PHYSICS_SHAPE_ID) | OBJECT_T; const bits PHYSICS_CIRCLE_SHAPE_T = (bits(1) << PHYSICS_CIRCLE_SHAPE_ID) | PHYSICS_SHAPE_T; const bits PHYSICS_POLYGON_SHAPE_T = (bits(1) << PHYSICS_POLYGON_SHAPE_ID) | PHYSICS_SHAPE_T; + const bits PHYSICS_EDGE_SHAPE_T = (bits(1) << PHYSICS_EDGE_SHAPE_ID) | PHYSICS_SHAPE_T; + const bits PHYSICS_CHAIN_SHAPE_T = (bits(1) << PHYSICS_CHAIN_SHAPE_ID) | PHYSICS_SHAPE_T; const bits PHYSICS_JOINT_T = (bits(1) << PHYSICS_JOINT_ID) | OBJECT_T; const bits PHYSICS_MOUSE_JOINT_T = (bits(1) << PHYSICS_MOUSE_JOINT_ID) | PHYSICS_JOINT_T; const bits PHYSICS_DISTANCE_JOINT_T = (bits(1) << PHYSICS_DISTANCE_JOINT_ID) | PHYSICS_JOINT_T; @@ -144,6 +152,10 @@ namespace love const bits PHYSICS_REVOLUTE_JOINT_T = (bits(1) << PHYSICS_REVOLUTE_JOINT_ID) | PHYSICS_JOINT_T; const bits PHYSICS_PULLEY_JOINT_T = (bits(1) << PHYSICS_PULLEY_JOINT_ID) | PHYSICS_JOINT_T; const bits PHYSICS_GEAR_JOINT_T = (bits(1) << PHYSICS_GEAR_JOINT_ID) | PHYSICS_JOINT_T; + const bits PHYSICS_FRICTION_JOINT_T = (bits(1) << PHYSICS_FRICTION_JOINT_ID) | PHYSICS_JOINT_T; + const bits PHYSICS_WELD_JOINT_T = (bits(1) << PHYSICS_WELD_JOINT_ID) | PHYSICS_JOINT_T; + const bits PHYSICS_ROPE_JOINT_T = (bits(1) << PHYSICS_ROPE_JOINT_ID) | PHYSICS_JOINT_T; + const bits PHYSICS_WHEEL_JOINT_T = (bits(1) << PHYSICS_WHEEL_JOINT_ID) | PHYSICS_JOINT_T; // Thread. const bits THREAD_THREAD_T = (bits(1) << THREAD_THREAD_ID) | OBJECT_T; diff --git a/src/modules/physics/Joint.cpp b/src/modules/physics/Joint.cpp index add6b33bf..f25b61e7d 100644 --- a/src/modules/physics/Joint.cpp +++ b/src/modules/physics/Joint.cpp @@ -47,8 +47,9 @@ namespace physics {"pulley", Joint::JOINT_PULLEY}, {"gear", Joint::JOINT_GEAR}, {"friction", Joint::JOINT_FRICTION}, - {"line", Joint::JOINT_LINE}, {"weld", Joint::JOINT_WELD}, + {"wheel", Joint::JOINT_WHEEL}, + {"rope", Joint::JOINT_ROPE}, }; StringMap Joint::types(Joint::typeEntries, sizeof(Joint::typeEntries)); diff --git a/src/modules/physics/Joint.h b/src/modules/physics/Joint.h index efa89bec3..a37d29350 100644 --- a/src/modules/physics/Joint.h +++ b/src/modules/physics/Joint.h @@ -43,8 +43,9 @@ namespace physics JOINT_PULLEY, JOINT_GEAR, JOINT_FRICTION, - JOINT_LINE, JOINT_WELD, + JOINT_WHEEL, + JOINT_ROPE, JOINT_MAX_ENUM }; diff --git a/src/modules/physics/box2d/Box2D/Box2D.h b/src/modules/physics/box2d/Box2D/Box2D.h old mode 100644 new mode 100755 index dc5701f51..817cd1ccf --- a/src/modules/physics/box2d/Box2D/Box2D.h +++ b/src/modules/physics/box2d/Box2D/Box2D.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -32,8 +32,12 @@ For discussion please visit http://box2d.org/forum // These include files constitute the main Box2D API #include +#include +#include #include +#include +#include #include #include @@ -52,11 +56,14 @@ For discussion please visit http://box2d.org/forum #include #include #include -#include +#include #include #include #include #include +#include #include +#include + #endif diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.cpp b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.cpp new file mode 100755 index 000000000..f7bbe06b6 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.cpp @@ -0,0 +1,171 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +using namespace std; + +b2ChainShape::~b2ChainShape() +{ + b2Free(m_vertices); + m_vertices = NULL; + m_count = 0; +} + +void b2ChainShape::CreateLoop(const b2Vec2* vertices, int32 count) +{ + b2Assert(m_vertices == NULL && m_count == 0); + b2Assert(count >= 3); + m_count = count + 1; + m_vertices = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + memcpy(m_vertices, vertices, count * sizeof(b2Vec2)); + m_vertices[count] = m_vertices[0]; + m_prevVertex = m_vertices[m_count - 2]; + m_nextVertex = m_vertices[1]; + m_hasPrevVertex = true; + m_hasNextVertex = true; +} + +void b2ChainShape::CreateChain(const b2Vec2* vertices, int32 count) +{ + b2Assert(m_vertices == NULL && m_count == 0); + b2Assert(count >= 2); + m_count = count; + m_vertices = (b2Vec2*)b2Alloc(count * sizeof(b2Vec2)); + memcpy(m_vertices, vertices, m_count * sizeof(b2Vec2)); + m_hasPrevVertex = false; + m_hasNextVertex = false; +} + +void b2ChainShape::SetPrevVertex(const b2Vec2& prevVertex) +{ + m_prevVertex = prevVertex; + m_hasPrevVertex = true; +} + +void b2ChainShape::SetNextVertex(const b2Vec2& nextVertex) +{ + m_nextVertex = nextVertex; + m_hasNextVertex = true; +} + +b2Shape* b2ChainShape::Clone(b2BlockAllocator* allocator) const +{ + void* mem = allocator->Allocate(sizeof(b2ChainShape)); + b2ChainShape* clone = new (mem) b2ChainShape; + clone->CreateChain(m_vertices, m_count); + clone->m_prevVertex = m_prevVertex; + clone->m_nextVertex = m_nextVertex; + clone->m_hasPrevVertex = m_hasPrevVertex; + clone->m_hasNextVertex = m_hasNextVertex; + return clone; +} + +int32 b2ChainShape::GetChildCount() const +{ + // edge count = vertex count - 1 + return m_count - 1; +} + +void b2ChainShape::GetChildEdge(b2EdgeShape* edge, int32 index) const +{ + b2Assert(0 <= index && index < m_count - 1); + edge->m_type = b2Shape::e_edge; + edge->m_radius = m_radius; + + edge->m_vertex1 = m_vertices[index + 0]; + edge->m_vertex2 = m_vertices[index + 1]; + + if (index > 0) + { + edge->m_vertex0 = m_vertices[index - 1]; + edge->m_hasVertex0 = true; + } + else + { + edge->m_vertex0 = m_prevVertex; + edge->m_hasVertex0 = m_hasPrevVertex; + } + + if (index < m_count - 2) + { + edge->m_vertex3 = m_vertices[index + 2]; + edge->m_hasVertex3 = true; + } + else + { + edge->m_vertex3 = m_nextVertex; + edge->m_hasVertex3 = m_hasNextVertex; + } +} + +bool b2ChainShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const +{ + B2_NOT_USED(xf); + B2_NOT_USED(p); + return false; +} + +bool b2ChainShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& xf, int32 childIndex) const +{ + b2Assert(childIndex < m_count); + + b2EdgeShape edgeShape; + + int32 i1 = childIndex; + int32 i2 = childIndex + 1; + if (i2 == m_count) + { + i2 = 0; + } + + edgeShape.m_vertex1 = m_vertices[i1]; + edgeShape.m_vertex2 = m_vertices[i2]; + + return edgeShape.RayCast(output, input, xf, 0); +} + +void b2ChainShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const +{ + b2Assert(childIndex < m_count); + + int32 i1 = childIndex; + int32 i2 = childIndex + 1; + if (i2 == m_count) + { + i2 = 0; + } + + b2Vec2 v1 = b2Mul(xf, m_vertices[i1]); + b2Vec2 v2 = b2Mul(xf, m_vertices[i2]); + + aabb->lowerBound = b2Min(v1, v2); + aabb->upperBound = b2Max(v1, v2); +} + +void b2ChainShape::ComputeMass(b2MassData* massData, float32 density) const +{ + B2_NOT_USED(density); + + massData->mass = 0.0f; + massData->center.SetZero(); + massData->I = 0.0f; +} diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.h b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.h new file mode 100755 index 000000000..34593e2b8 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.h @@ -0,0 +1,117 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CHAIN_SHAPE_H +#define B2_CHAIN_SHAPE_H + +#include + +class b2EdgeShape; + +/// A chain shape is a free form sequence of line segments. +/// The chain has two-sided collision, so you can use inside and outside collision. +/// Therefore, you may use any winding order. +/// Since there may be many vertices, they are allocated using b2Alloc. +/// Connectivity information is used to create smooth collisions. +/// WARNING: The chain will not collide properly if there are self-intersections. +class b2ChainShape : public b2Shape +{ +public: + b2ChainShape(); + + /// The destructor frees the vertices using b2Free. + ~b2ChainShape(); + + /// Create a loop. This automatically adjusts connectivity. + /// @param vertices an array of vertices, these are copied + /// @param count the vertex count + void CreateLoop(const b2Vec2* vertices, int32 count); + + /// Create a chain with isolated end vertices. + /// @param vertices an array of vertices, these are copied + /// @param count the vertex count + void CreateChain(const b2Vec2* vertices, int32 count); + + /// Establish connectivity to a vertex that precedes the first vertex. + /// Don't call this for loops. + void SetPrevVertex(const b2Vec2& prevVertex); + + /// Establish connectivity to a vertex that follows the last vertex. + /// Don't call this for loops. + void SetNextVertex(const b2Vec2& nextVertex); + + /// Implement b2Shape. Vertices are cloned using b2Alloc. + b2Shape* Clone(b2BlockAllocator* allocator) const; + + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; + + /// Get a child edge. + void GetChildEdge(b2EdgeShape* edge, int32 index) const; + + /// This always return false. + /// @see b2Shape::TestPoint + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; + + /// Chains have zero mass. + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; + + /// Get the number of vertices. + int32 GetVertexCount() const { return m_count; } + + /// Get the vertices (read-only). + const b2Vec2& GetVertex(int32 index) const + { + b2Assert(0 <= index && index < m_count); + return m_vertices[index]; + } + + /// Get the vertices (read-only). + const b2Vec2* GetVertices() const { return m_vertices; } + +protected: + + /// The vertices. Owned by this class. + b2Vec2* m_vertices; + + /// The vertex count. + int32 m_count; + + b2Vec2 m_prevVertex, m_nextVertex; + bool m_hasPrevVertex, m_hasNextVertex; +}; + +inline b2ChainShape::b2ChainShape() +{ + m_type = e_chain; + m_radius = b2_polygonRadius; + m_vertices = NULL; + m_count = 0; + m_hasPrevVertex = NULL; + m_hasNextVertex = NULL; +} + +#endif diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.cpp b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.cpp old mode 100644 new mode 100755 index a950b0be5..c03d662df --- a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.cpp +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -18,6 +18,7 @@ #include #include +using namespace std; b2Shape* b2CircleShape::Clone(b2BlockAllocator* allocator) const { @@ -27,9 +28,14 @@ b2Shape* b2CircleShape::Clone(b2BlockAllocator* allocator) const return clone; } +int32 b2CircleShape::GetChildCount() const +{ + return 1; +} + bool b2CircleShape::TestPoint(const b2Transform& transform, const b2Vec2& p) const { - b2Vec2 center = transform.position + b2Mul(transform.R, m_p); + b2Vec2 center = transform.p + b2Mul(transform.q, m_p); b2Vec2 d = p - center; return b2Dot(d, d) <= m_radius * m_radius; } @@ -38,9 +44,12 @@ bool b2CircleShape::TestPoint(const b2Transform& transform, const b2Vec2& p) con // From Section 3.1.2 // x = s + a * r // norm(x) = radius -bool b2CircleShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const +bool b2CircleShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const { - b2Vec2 position = transform.position + b2Mul(transform.R, m_p); + B2_NOT_USED(childIndex); + + b2Vec2 position = transform.p + b2Mul(transform.q, m_p); b2Vec2 s = input.p1 - position; float32 b = b2Dot(s, s) - m_radius * m_radius; @@ -72,9 +81,11 @@ bool b2CircleShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input return false; } -void b2CircleShape::ComputeAABB(b2AABB* aabb, const b2Transform& transform) const +void b2CircleShape::ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const { - b2Vec2 p = transform.position + b2Mul(transform.R, m_p); + B2_NOT_USED(childIndex); + + b2Vec2 p = transform.p + b2Mul(transform.q, m_p); aabb->lowerBound.Set(p.x - m_radius, p.y - m_radius); aabb->upperBound.Set(p.x + m_radius, p.y + m_radius); } diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.h b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.h old mode 100644 new mode 100755 index bb31da898..6c1fd543a --- a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.h +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -30,14 +30,18 @@ public: /// Implement b2Shape. b2Shape* Clone(b2BlockAllocator* allocator) const; + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; + /// Implement b2Shape. bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const; + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform) const; + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; /// @see b2Shape::ComputeMass void ComputeMass(b2MassData* massData, float32 density) const; diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.cpp b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.cpp new file mode 100755 index 000000000..e204160b0 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.cpp @@ -0,0 +1,139 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +using namespace std; + +void b2EdgeShape::Set(const b2Vec2& v1, const b2Vec2& v2) +{ + m_vertex1 = v1; + m_vertex2 = v2; + m_hasVertex0 = false; + m_hasVertex3 = false; +} + +b2Shape* b2EdgeShape::Clone(b2BlockAllocator* allocator) const +{ + void* mem = allocator->Allocate(sizeof(b2EdgeShape)); + b2EdgeShape* clone = new (mem) b2EdgeShape; + *clone = *this; + return clone; +} + +int32 b2EdgeShape::GetChildCount() const +{ + return 1; +} + +bool b2EdgeShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const +{ + B2_NOT_USED(xf); + B2_NOT_USED(p); + return false; +} + +// p = p1 + t * d +// v = v1 + s * e +// p1 + t * d = v1 + s * e +// s * e - t * d = p1 - v1 +bool b2EdgeShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& xf, int32 childIndex) const +{ + B2_NOT_USED(childIndex); + + // Put the ray into the edge's frame of reference. + b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); + b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); + b2Vec2 d = p2 - p1; + + b2Vec2 v1 = m_vertex1; + b2Vec2 v2 = m_vertex2; + b2Vec2 e = v2 - v1; + b2Vec2 normal(e.y, -e.x); + normal.Normalize(); + + // q = p1 + t * d + // dot(normal, q - v1) = 0 + // dot(normal, p1 - v1) + t * dot(normal, d) = 0 + float32 numerator = b2Dot(normal, v1 - p1); + float32 denominator = b2Dot(normal, d); + + if (denominator == 0.0f) + { + return false; + } + + float32 t = numerator / denominator; + if (t < 0.0f || input.maxFraction < t) + { + return false; + } + + b2Vec2 q = p1 + t * d; + + // q = v1 + s * r + // s = dot(q - v1, r) / dot(r, r) + b2Vec2 r = v2 - v1; + float32 rr = b2Dot(r, r); + if (rr == 0.0f) + { + return false; + } + + float32 s = b2Dot(q - v1, r) / rr; + if (s < 0.0f || 1.0f < s) + { + return false; + } + + output->fraction = t; + if (numerator > 0.0f) + { + output->normal = -normal; + } + else + { + output->normal = normal; + } + return true; +} + +void b2EdgeShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const +{ + B2_NOT_USED(childIndex); + + b2Vec2 v1 = b2Mul(xf, m_vertex1); + b2Vec2 v2 = b2Mul(xf, m_vertex2); + + b2Vec2 lower = b2Min(v1, v2); + b2Vec2 upper = b2Max(v1, v2); + + b2Vec2 r(m_radius, m_radius); + aabb->lowerBound = lower - r; + aabb->upperBound = upper + r; +} + +void b2EdgeShape::ComputeMass(b2MassData* massData, float32 density) const +{ + B2_NOT_USED(density); + + massData->mass = 0.0f; + massData->center = 0.5f * (m_vertex1 + m_vertex2); + massData->I = 0.0f; +} diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.h b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.h new file mode 100755 index 000000000..780eb2c5c --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.h @@ -0,0 +1,70 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_EDGE_SHAPE_H +#define B2_EDGE_SHAPE_H + +#include + +/// A line segment (edge) shape. These can be connected in chains or loops +/// to other edge shapes. The connectivity information is used to ensure +/// correct contact normals. +class b2EdgeShape : public b2Shape +{ +public: + b2EdgeShape(); + + /// Set this as an isolated edge. + void Set(const b2Vec2& v1, const b2Vec2& v2); + + /// Implement b2Shape. + b2Shape* Clone(b2BlockAllocator* allocator) const; + + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; + + /// @see b2Shape::TestPoint + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; + + /// These are the edge vertices + b2Vec2 m_vertex1, m_vertex2; + + /// Optional adjacent vertices. These are used for smooth collision. + b2Vec2 m_vertex0, m_vertex3; + bool m_hasVertex0, m_hasVertex3; +}; + +inline b2EdgeShape::b2EdgeShape() +{ + m_type = e_edge; + m_radius = b2_polygonRadius; + m_hasVertex0 = false; + m_hasVertex3 = false; +} + +#endif diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp old mode 100644 new mode 100755 index 429e64704..8be813338 --- a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -55,41 +55,29 @@ void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, floa m_centroid = center; b2Transform xf; - xf.position = center; - xf.R.Set(angle); + xf.p = center; + xf.q.Set(angle); // Transform vertices and normals. for (int32 i = 0; i < m_vertexCount; ++i) { m_vertices[i] = b2Mul(xf, m_vertices[i]); - m_normals[i] = b2Mul(xf.R, m_normals[i]); + m_normals[i] = b2Mul(xf.q, m_normals[i]); } } -void b2PolygonShape::SetAsEdge(const b2Vec2& v1, const b2Vec2& v2) +int32 b2PolygonShape::GetChildCount() const { - m_vertexCount = 2; - m_vertices[0] = v1; - m_vertices[1] = v2; - m_centroid = 0.5f * (v1 + v2); - m_normals[0] = b2Cross(v2 - v1, 1.0f); - m_normals[0].Normalize(); - m_normals[1] = -m_normals[0]; + return 1; } static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count) { - b2Assert(count >= 2); + b2Assert(count >= 3); b2Vec2 c; c.Set(0.0f, 0.0f); float32 area = 0.0f; - if (count == 2) - { - c = 0.5f * (vs[0] + vs[1]); - return c; - } - // pRef is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). b2Vec2 pRef(0.0f, 0.0f); @@ -131,7 +119,7 @@ static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count) void b2PolygonShape::Set(const b2Vec2* vertices, int32 count) { - b2Assert(2 <= count && count <= b2_maxPolygonVertices); + b2Assert(3 <= count && count <= b2_maxPolygonVertices); m_vertexCount = count; // Copy vertices. @@ -170,10 +158,10 @@ void b2PolygonShape::Set(const b2Vec2* vertices, int32 count) b2Vec2 r = m_vertices[j] - m_vertices[i1]; - // Your polygon is non-convex (it has an indentation) or - // has colinear edges. + // If this crashes, your polygon is non-convex, has colinear edges, + // or the winding order is wrong. float32 s = b2Cross(edge, r); - b2Assert(s > 0.0f); + b2Assert(s > 0.0f && "ERROR: Please ensure your polygon is convex and has a CCW winding order"); } } #endif @@ -184,7 +172,7 @@ void b2PolygonShape::Set(const b2Vec2* vertices, int32 count) bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const { - b2Vec2 pLocal = b2MulT(xf.R, p - xf.position); + b2Vec2 pLocal = b2MulT(xf.q, p - xf.p); for (int32 i = 0; i < m_vertexCount; ++i) { @@ -198,131 +186,82 @@ bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const return true; } -bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& xf) const +bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& xf, int32 childIndex) const { + B2_NOT_USED(childIndex); + // Put the ray into the polygon's frame of reference. - b2Vec2 p1 = b2MulT(xf.R, input.p1 - xf.position); - b2Vec2 p2 = b2MulT(xf.R, input.p2 - xf.position); + b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); + b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); b2Vec2 d = p2 - p1; - if (m_vertexCount == 2) - { - b2Vec2 v1 = m_vertices[0]; - b2Vec2 v2 = m_vertices[1]; - b2Vec2 normal = m_normals[0]; + float32 lower = 0.0f, upper = input.maxFraction; - // q = p1 + t * d - // dot(normal, q - v1) = 0 - // dot(normal, p1 - v1) + t * dot(normal, d) = 0 - float32 numerator = b2Dot(normal, v1 - p1); - float32 denominator = b2Dot(normal, d); + int32 index = -1; + + for (int32 i = 0; i < m_vertexCount; ++i) + { + // p = p1 + a * d + // dot(normal, p - v) = 0 + // dot(normal, p1 - v) + a * dot(normal, d) = 0 + float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1); + float32 denominator = b2Dot(m_normals[i], d); if (denominator == 0.0f) - { - return false; - } - - float32 t = numerator / denominator; - if (t < 0.0f || 1.0f < t) - { - return false; - } - - b2Vec2 q = p1 + t * d; - - // q = v1 + s * r - // s = dot(q - v1, r) / dot(r, r) - b2Vec2 r = v2 - v1; - float32 rr = b2Dot(r, r); - if (rr == 0.0f) - { - return false; - } - - float32 s = b2Dot(q - v1, r) / rr; - if (s < 0.0f || 1.0f < s) - { - return false; - } - - output->fraction = t; - if (numerator > 0.0f) - { - output->normal = -normal; - } - else - { - output->normal = normal; - } - return true; - } - else - { - float32 lower = 0.0f, upper = input.maxFraction; - - int32 index = -1; - - for (int32 i = 0; i < m_vertexCount; ++i) - { - // p = p1 + a * d - // dot(normal, p - v) = 0 - // dot(normal, p1 - v) + a * dot(normal, d) = 0 - float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1); - float32 denominator = b2Dot(m_normals[i], d); - - if (denominator == 0.0f) - { - if (numerator < 0.0f) - { - return false; - } - } - else - { - // Note: we want this predicate without division: - // lower < numerator / denominator, where denominator < 0 - // Since denominator < 0, we have to flip the inequality: - // lower < numerator / denominator <==> denominator * lower > numerator. - if (denominator < 0.0f && numerator < lower * denominator) - { - // Increase lower. - // The segment enters this half-space. - lower = numerator / denominator; - index = i; - } - else if (denominator > 0.0f && numerator < upper * denominator) - { - // Decrease upper. - // The segment exits this half-space. - upper = numerator / denominator; - } - } - - // The use of epsilon here causes the assert on lower to trip - // in some cases. Apparently the use of epsilon was to make edge - // shapes work, but now those are handled separately. - //if (upper < lower - b2_epsilon) - if (upper < lower) + { + if (numerator < 0.0f) { return false; } } - - b2Assert(0.0f <= lower && lower <= input.maxFraction); - - if (index >= 0) + else { - output->fraction = lower; - output->normal = b2Mul(xf.R, m_normals[index]); - return true; + // Note: we want this predicate without division: + // lower < numerator / denominator, where denominator < 0 + // Since denominator < 0, we have to flip the inequality: + // lower < numerator / denominator <==> denominator * lower > numerator. + if (denominator < 0.0f && numerator < lower * denominator) + { + // Increase lower. + // The segment enters this half-space. + lower = numerator / denominator; + index = i; + } + else if (denominator > 0.0f && numerator < upper * denominator) + { + // Decrease upper. + // The segment exits this half-space. + upper = numerator / denominator; + } } + + // The use of epsilon here causes the assert on lower to trip + // in some cases. Apparently the use of epsilon was to make edge + // shapes work, but now those are handled separately. + //if (upper < lower - b2_epsilon) + if (upper < lower) + { + return false; + } + } + + b2Assert(0.0f <= lower && lower <= input.maxFraction); + + if (index >= 0) + { + output->fraction = lower; + output->normal = b2Mul(xf.q, m_normals[index]); + return true; } return false; } -void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf) const +void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const { + B2_NOT_USED(childIndex); + b2Vec2 lower = b2Mul(xf, m_vertices[0]); b2Vec2 upper = lower; @@ -364,44 +303,30 @@ void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const // // The rest of the derivation is handled by computer algebra. - b2Assert(m_vertexCount >= 2); - - // A line segment has zero mass. - if (m_vertexCount == 2) - { - massData->center = 0.5f * (m_vertices[0] + m_vertices[1]); - massData->mass = 0.0f; - massData->I = 0.0f; - return; - } + b2Assert(m_vertexCount >= 3); b2Vec2 center; center.Set(0.0f, 0.0f); float32 area = 0.0f; float32 I = 0.0f; - // pRef is the reference point for forming triangles. + // s is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). - b2Vec2 pRef(0.0f, 0.0f); -#if 0 + b2Vec2 s(0.0f, 0.0f); + // This code would put the reference point inside the polygon. for (int32 i = 0; i < m_vertexCount; ++i) { - pRef += m_vertices[i]; + s += m_vertices[i]; } - pRef *= 1.0f / count; -#endif + s *= 1.0f / m_vertexCount; const float32 k_inv3 = 1.0f / 3.0f; for (int32 i = 0; i < m_vertexCount; ++i) { // Triangle vertices. - b2Vec2 p1 = pRef; - b2Vec2 p2 = m_vertices[i]; - b2Vec2 p3 = i + 1 < m_vertexCount ? m_vertices[i+1] : m_vertices[0]; - - b2Vec2 e1 = p2 - p1; - b2Vec2 e2 = p3 - p1; + b2Vec2 e1 = m_vertices[i] - s; + b2Vec2 e2 = i + 1 < m_vertexCount ? m_vertices[i+1] - s : m_vertices[0] - s; float32 D = b2Cross(e1, e2); @@ -409,16 +334,15 @@ void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const area += triangleArea; // Area weighted centroid - center += triangleArea * k_inv3 * (p1 + p2 + p3); + center += triangleArea * k_inv3 * (e1 + e2); - float32 px = p1.x, py = p1.y; float32 ex1 = e1.x, ey1 = e1.y; float32 ex2 = e2.x, ey2 = e2.y; - float32 intx2 = k_inv3 * (0.25f * (ex1*ex1 + ex2*ex1 + ex2*ex2) + (px*ex1 + px*ex2)) + 0.5f*px*px; - float32 inty2 = k_inv3 * (0.25f * (ey1*ey1 + ey2*ey1 + ey2*ey2) + (py*ey1 + py*ey2)) + 0.5f*py*py; + float32 intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2; + float32 inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2; - I += D * (intx2 + inty2); + I += (0.25f * k_inv3 * D) * (intx2 + inty2); } // Total mass @@ -427,8 +351,11 @@ void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const // Center of mass b2Assert(area > b2_epsilon); center *= 1.0f / area; - massData->center = center; + massData->center = center + s; - // Inertia tensor relative to the local origin. + // Inertia tensor relative to the local origin (point s). massData->I = density * I; + + // Shift to center of mass then to original body origin. + massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center)); } diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.h b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.h old mode 100644 new mode 100755 index 564d4b083..fd11bd162 --- a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.h +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -23,6 +23,8 @@ /// A convex polygon. It is assumed that the interior of the polygon is to /// the left of each edge. +/// Polygons have a maximum number of vertices equal to b2_maxPolygonVertices. +/// In most cases you should not need many vertices for a convex polygon. class b2PolygonShape : public b2Shape { public: @@ -31,8 +33,12 @@ public: /// Implement b2Shape. b2Shape* Clone(b2BlockAllocator* allocator) const; + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; + /// Copy vertices. This assumes the vertices define a convex polygon. /// It is assumed that the exterior is the the right of each edge. + /// The count must be in the range [3, b2_maxPolygonVertices]. void Set(const b2Vec2* vertices, int32 vertexCount); /// Build vertices to represent an axis-aligned box. @@ -47,27 +53,19 @@ public: /// @param angle the rotation of the box in local coordinates. void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle); - /// Set this as a single edge. - void SetAsEdge(const b2Vec2& v1, const b2Vec2& v2); - /// @see b2Shape::TestPoint bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const; + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform) const; + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; /// @see b2Shape::ComputeMass void ComputeMass(b2MassData* massData, float32 density) const; - /// Get the supporting vertex index in the given direction. - int32 GetSupport(const b2Vec2& d) const; - - /// Get the supporting vertex in the given direction. - const b2Vec2& GetSupportVertex(const b2Vec2& d) const; - /// Get the vertex count. int32 GetVertexCount() const { return m_vertexCount; } @@ -88,40 +86,6 @@ inline b2PolygonShape::b2PolygonShape() m_centroid.SetZero(); } -inline int32 b2PolygonShape::GetSupport(const b2Vec2& d) const -{ - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_vertices[0], d); - for (int32 i = 1; i < m_vertexCount; ++i) - { - float32 value = b2Dot(m_vertices[i], d); - if (value > bestValue) - { - bestIndex = i; - bestValue = value; - } - } - - return bestIndex; -} - -inline const b2Vec2& b2PolygonShape::GetSupportVertex(const b2Vec2& d) const -{ - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_vertices[0], d); - for (int32 i = 1; i < m_vertexCount; ++i) - { - float32 value = b2Dot(m_vertices[i], d); - if (value > bestValue) - { - bestIndex = i; - bestValue = value; - } - } - - return m_vertices[bestIndex]; -} - inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const { b2Assert(0 <= index && index < m_vertexCount); diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2Shape.h b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2Shape.h old mode 100644 new mode 100755 index 9082c0ef9..fd7de2626 --- a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2Shape.h +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2Shape.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -38,20 +38,20 @@ struct b2MassData /// A shape is used for collision detection. You can create a shape however you like. /// Shapes used for simulation in b2World are created automatically when a b2Fixture -/// is created. +/// is created. Shapes may encapsulate a one or more child shapes. class b2Shape { public: enum Type { - e_unknown= -1, e_circle = 0, - e_polygon = 1, - e_typeCount = 2, + e_edge = 1, + e_polygon = 2, + e_chain = 3, + e_typeCount = 4 }; - b2Shape() { m_type = e_unknown; } virtual ~b2Shape() {} /// Clone the concrete shape using the provided allocator. @@ -61,21 +61,27 @@ public: /// @return the shape type. Type GetType() const; + /// Get the number of child primitives. + virtual int32 GetChildCount() const = 0; + /// Test a point for containment in this shape. This only works for convex shapes. /// @param xf the shape world transform. /// @param p a point in world coordinates. virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0; - /// Cast a ray against this shape. + /// Cast a ray against a child shape. /// @param output the ray-cast results. /// @param input the ray-cast input parameters. /// @param transform the transform to be applied to the shape. - virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const = 0; + /// @param childIndex the child shape index + virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const = 0; - /// Given a transform, compute the associated axis aligned bounding box for this shape. + /// Given a transform, compute the associated axis aligned bounding box for a child shape. /// @param aabb returns the axis aligned box. /// @param xf the world transform of the shape. - virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf) const = 0; + /// @param childIndex the child shape + virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const = 0; /// Compute the mass properties of this shape using its dimensions and density. /// The inertia tensor is computed about the local origin. diff --git a/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.cpp b/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.cpp old mode 100644 new mode 100755 index 12c79678d..2aa62f948 --- a/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.cpp +++ b/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -18,6 +18,7 @@ #include #include +using namespace std; b2BroadPhase::b2BroadPhase() { @@ -62,6 +63,11 @@ void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& di } } +void b2BroadPhase::TouchProxy(int32 proxyId) +{ + BufferMove(proxyId); +} + void b2BroadPhase::BufferMove(int32 proxyId) { if (m_moveCount == m_moveCapacity) diff --git a/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.h b/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.h old mode 100644 new mode 100755 index bff188e88..c7398c97a --- a/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.h +++ b/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -40,7 +40,7 @@ public: enum { - e_nullProxy = -1, + e_nullProxy = -1 }; b2BroadPhase(); @@ -57,6 +57,9 @@ public: /// call UpdatePairs to finalized the proxy pairs (for your time step). void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement); + /// Call to trigger a re-processing of it's pairs on the next call to UpdatePairs. + void TouchProxy(int32 proxyId); + /// Get the fat AABB for a proxy. const b2AABB& GetFatAABB(int32 proxyId) const; @@ -88,8 +91,14 @@ public: template void RayCast(T* callback, const b2RayCastInput& input) const; - /// Compute the height of the embedded tree. - int32 ComputeHeight() const; + /// Get the height of the embedded tree. + int32 GetTreeHeight() const; + + /// Get the balance of the embedded tree. + int32 GetTreeBalance() const; + + /// Get the quality metric of the embedded tree. + float32 GetTreeQuality() const; private: @@ -153,9 +162,19 @@ inline int32 b2BroadPhase::GetProxyCount() const return m_proxyCount; } -inline int32 b2BroadPhase::ComputeHeight() const +inline int32 b2BroadPhase::GetTreeHeight() const { - return m_tree.ComputeHeight(); + return m_tree.GetHeight(); +} + +inline int32 b2BroadPhase::GetTreeBalance() const +{ + return m_tree.GetMaxBalance(); +} + +inline float32 b2BroadPhase::GetTreeQuality() const +{ + return m_tree.GetAreaRatio(); } template @@ -211,7 +230,7 @@ void b2BroadPhase::UpdatePairs(T* callback) } // Try to keep the tree balanced. - m_tree.Rebalance(4); + //m_tree.Rebalance(4); } template diff --git a/src/modules/physics/box2d/Box2D/Collision/b2CollideCircle.cpp b/src/modules/physics/box2d/Box2D/Collision/b2CollideCircle.cpp old mode 100644 new mode 100755 index 6edf89d7b..0ad58f000 --- a/src/modules/physics/box2d/Box2D/Collision/b2CollideCircle.cpp +++ b/src/modules/physics/box2d/Box2D/Collision/b2CollideCircle.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2007-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages diff --git a/src/modules/physics/box2d/Box2D/Collision/b2CollideEdge.cpp b/src/modules/physics/box2d/Box2D/Collision/b2CollideEdge.cpp new file mode 100755 index 000000000..281967183 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Collision/b2CollideEdge.cpp @@ -0,0 +1,698 @@ +/* + * Copyright (c) 2007-2009 Erin Catto http://www.box2d.org + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + */ + +#include +#include +#include +#include + + +// Compute contact points for edge versus circle. +// This accounts for edge connectivity. +void b2CollideEdgeAndCircle(b2Manifold* manifold, + const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB) +{ + manifold->pointCount = 0; + + // Compute circle in frame of edge + b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p)); + + b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2; + b2Vec2 e = B - A; + + // Barycentric coordinates + float32 u = b2Dot(e, B - Q); + float32 v = b2Dot(e, Q - A); + + float32 radius = edgeA->m_radius + circleB->m_radius; + + b2ContactFeature cf; + cf.indexB = 0; + cf.typeB = b2ContactFeature::e_vertex; + + // Region A + if (v <= 0.0f) + { + b2Vec2 P = A; + b2Vec2 d = Q - P; + float32 dd = b2Dot(d, d); + if (dd > radius * radius) + { + return; + } + + // Is there an edge connected to A? + if (edgeA->m_hasVertex0) + { + b2Vec2 A1 = edgeA->m_vertex0; + b2Vec2 B1 = A; + b2Vec2 e1 = B1 - A1; + float32 u1 = b2Dot(e1, B1 - Q); + + // Is the circle in Region AB of the previous edge? + if (u1 > 0.0f) + { + return; + } + } + + cf.indexA = 0; + cf.typeA = b2ContactFeature::e_vertex; + manifold->pointCount = 1; + manifold->type = b2Manifold::e_circles; + manifold->localNormal.SetZero(); + manifold->localPoint = P; + manifold->points[0].id.key = 0; + manifold->points[0].id.cf = cf; + manifold->points[0].localPoint = circleB->m_p; + return; + } + + // Region B + if (u <= 0.0f) + { + b2Vec2 P = B; + b2Vec2 d = Q - P; + float32 dd = b2Dot(d, d); + if (dd > radius * radius) + { + return; + } + + // Is there an edge connected to B? + if (edgeA->m_hasVertex3) + { + b2Vec2 B2 = edgeA->m_vertex3; + b2Vec2 A2 = B; + b2Vec2 e2 = B2 - A2; + float32 v2 = b2Dot(e2, Q - A2); + + // Is the circle in Region AB of the next edge? + if (v2 > 0.0f) + { + return; + } + } + + cf.indexA = 1; + cf.typeA = b2ContactFeature::e_vertex; + manifold->pointCount = 1; + manifold->type = b2Manifold::e_circles; + manifold->localNormal.SetZero(); + manifold->localPoint = P; + manifold->points[0].id.key = 0; + manifold->points[0].id.cf = cf; + manifold->points[0].localPoint = circleB->m_p; + return; + } + + // Region AB + float32 den = b2Dot(e, e); + b2Assert(den > 0.0f); + b2Vec2 P = (1.0f / den) * (u * A + v * B); + b2Vec2 d = Q - P; + float32 dd = b2Dot(d, d); + if (dd > radius * radius) + { + return; + } + + b2Vec2 n(-e.y, e.x); + if (b2Dot(n, Q - A) < 0.0f) + { + n.Set(-n.x, -n.y); + } + n.Normalize(); + + cf.indexA = 0; + cf.typeA = b2ContactFeature::e_face; + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = n; + manifold->localPoint = A; + manifold->points[0].id.key = 0; + manifold->points[0].id.cf = cf; + manifold->points[0].localPoint = circleB->m_p; +} + +// This structure is used to keep track of the best separating axis. +struct b2EPAxis +{ + enum Type + { + e_unknown, + e_edgeA, + e_edgeB + }; + + Type type; + int32 index; + float32 separation; +}; + +// This holds polygon B expressed in frame A. +struct b2TempPolygon +{ + b2Vec2 vertices[b2_maxPolygonVertices]; + b2Vec2 normals[b2_maxPolygonVertices]; + int32 count; +}; + +// Reference face used for clipping +struct b2ReferenceFace +{ + int32 i1, i2; + + b2Vec2 v1, v2; + + b2Vec2 normal; + + b2Vec2 sideNormal1; + float32 sideOffset1; + + b2Vec2 sideNormal2; + float32 sideOffset2; +}; + +// This class collides and edge and a polygon, taking into account edge adjacency. +struct b2EPCollider +{ + void Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB); + b2EPAxis ComputeEdgeSeparation(); + b2EPAxis ComputePolygonSeparation(); + + enum VertexType + { + e_isolated, + e_concave, + e_convex + }; + + b2TempPolygon m_polygonB; + + b2Transform m_xf; + b2Vec2 m_centroidB; + b2Vec2 m_v0, m_v1, m_v2, m_v3; + b2Vec2 m_normal0, m_normal1, m_normal2; + b2Vec2 m_normal; + VertexType m_type1, m_type2; + b2Vec2 m_lowerLimit, m_upperLimit; + float32 m_radius; + bool m_front; +}; + +// Algorithm: +// 1. Classify v1 and v2 +// 2. Classify polygon centroid as front or back +// 3. Flip normal if necessary +// 4. Initialize normal range to [-pi, pi] about face normal +// 5. Adjust normal range according to adjacent edges +// 6. Visit each separating axes, only accept axes within the range +// 7. Return if _any_ axis indicates separation +// 8. Clip +void b2EPCollider::Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB) +{ + m_xf = b2MulT(xfA, xfB); + + m_centroidB = b2Mul(m_xf, polygonB->m_centroid); + + m_v0 = edgeA->m_vertex0; + m_v1 = edgeA->m_vertex1; + m_v2 = edgeA->m_vertex2; + m_v3 = edgeA->m_vertex3; + + bool hasVertex0 = edgeA->m_hasVertex0; + bool hasVertex3 = edgeA->m_hasVertex3; + + b2Vec2 edge1 = m_v2 - m_v1; + edge1.Normalize(); + m_normal1.Set(edge1.y, -edge1.x); + float32 offset1 = b2Dot(m_normal1, m_centroidB - m_v1); + float32 offset0 = 0.0f, offset2 = 0.0f; + bool convex1 = false, convex2 = false; + + // Is there a preceding edge? + if (hasVertex0) + { + b2Vec2 edge0 = m_v1 - m_v0; + edge0.Normalize(); + m_normal0.Set(edge0.y, -edge0.x); + convex1 = b2Cross(edge0, edge1) >= 0.0f; + offset0 = b2Dot(m_normal0, m_centroidB - m_v0); + } + + // Is there a following edge? + if (hasVertex3) + { + b2Vec2 edge2 = m_v3 - m_v2; + edge2.Normalize(); + m_normal2.Set(edge2.y, -edge2.x); + convex2 = b2Cross(edge1, edge2) > 0.0f; + offset2 = b2Dot(m_normal2, m_centroidB - m_v2); + } + + // Determine front or back collision. Determine collision normal limits. + if (hasVertex0 && hasVertex3) + { + if (convex1 && convex2) + { + m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal0; + m_upperLimit = m_normal2; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = -m_normal1; + } + } + else if (convex1) + { + m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f); + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal0; + m_upperLimit = m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal2; + m_upperLimit = -m_normal1; + } + } + else if (convex2) + { + m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f); + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = m_normal2; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = -m_normal0; + } + } + else + { + m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal2; + m_upperLimit = -m_normal0; + } + } + } + else if (hasVertex0) + { + if (convex1) + { + m_front = offset0 >= 0.0f || offset1 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal0; + m_upperLimit = -m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = -m_normal1; + } + } + else + { + m_front = offset0 >= 0.0f && offset1 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = -m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = -m_normal0; + } + } + } + else if (hasVertex3) + { + if (convex2) + { + m_front = offset1 >= 0.0f || offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = m_normal2; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = m_normal1; + } + } + else + { + m_front = offset1 >= 0.0f && offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal2; + m_upperLimit = m_normal1; + } + } + } + else + { + m_front = offset1 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = -m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = m_normal1; + } + } + + // Get polygonB in frameA + m_polygonB.count = polygonB->m_vertexCount; + for (int32 i = 0; i < polygonB->m_vertexCount; ++i) + { + m_polygonB.vertices[i] = b2Mul(m_xf, polygonB->m_vertices[i]); + m_polygonB.normals[i] = b2Mul(m_xf.q, polygonB->m_normals[i]); + } + + m_radius = 2.0f * b2_polygonRadius; + + manifold->pointCount = 0; + + b2EPAxis edgeAxis = ComputeEdgeSeparation(); + + // If no valid normal can be found than this edge should not collide. + if (edgeAxis.type == b2EPAxis::e_unknown) + { + return; + } + + if (edgeAxis.separation > m_radius) + { + return; + } + + b2EPAxis polygonAxis = ComputePolygonSeparation(); + if (polygonAxis.type != b2EPAxis::e_unknown && polygonAxis.separation > m_radius) + { + return; + } + + // Use hysteresis for jitter reduction. + const float32 k_relativeTol = 0.98f; + const float32 k_absoluteTol = 0.001f; + + b2EPAxis primaryAxis; + if (polygonAxis.type == b2EPAxis::e_unknown) + { + primaryAxis = edgeAxis; + } + else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) + { + primaryAxis = polygonAxis; + } + else + { + primaryAxis = edgeAxis; + } + + b2ClipVertex ie[2]; + b2ReferenceFace rf; + if (primaryAxis.type == b2EPAxis::e_edgeA) + { + manifold->type = b2Manifold::e_faceA; + + // Search for the polygon normal that is most anti-parallel to the edge normal. + int32 bestIndex = 0; + float32 bestValue = b2Dot(m_normal, m_polygonB.normals[0]); + for (int32 i = 1; i < m_polygonB.count; ++i) + { + float32 value = b2Dot(m_normal, m_polygonB.normals[i]); + if (value < bestValue) + { + bestValue = value; + bestIndex = i; + } + } + + int32 i1 = bestIndex; + int32 i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0; + + ie[0].v = m_polygonB.vertices[i1]; + ie[0].id.cf.indexA = 0; + ie[0].id.cf.indexB = i1; + ie[0].id.cf.typeA = b2ContactFeature::e_face; + ie[0].id.cf.typeB = b2ContactFeature::e_vertex; + + ie[1].v = m_polygonB.vertices[i2]; + ie[1].id.cf.indexA = 0; + ie[1].id.cf.indexB = i2; + ie[1].id.cf.typeA = b2ContactFeature::e_face; + ie[1].id.cf.typeB = b2ContactFeature::e_vertex; + + if (m_front) + { + rf.i1 = 0; + rf.i2 = 1; + rf.v1 = m_v1; + rf.v2 = m_v2; + rf.normal = m_normal1; + } + else + { + rf.i1 = 1; + rf.i2 = 0; + rf.v1 = m_v2; + rf.v2 = m_v1; + rf.normal = -m_normal1; + } + } + else + { + manifold->type = b2Manifold::e_faceB; + + ie[0].v = m_v1; + ie[0].id.cf.indexA = 0; + ie[0].id.cf.indexB = primaryAxis.index; + ie[0].id.cf.typeA = b2ContactFeature::e_vertex; + ie[0].id.cf.typeB = b2ContactFeature::e_face; + + ie[1].v = m_v2; + ie[1].id.cf.indexA = 0; + ie[1].id.cf.indexB = primaryAxis.index; + ie[1].id.cf.typeA = b2ContactFeature::e_vertex; + ie[1].id.cf.typeB = b2ContactFeature::e_face; + + rf.i1 = primaryAxis.index; + rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0; + rf.v1 = m_polygonB.vertices[rf.i1]; + rf.v2 = m_polygonB.vertices[rf.i2]; + rf.normal = m_polygonB.normals[rf.i1]; + } + + rf.sideNormal1.Set(rf.normal.y, -rf.normal.x); + rf.sideNormal2 = -rf.sideNormal1; + rf.sideOffset1 = b2Dot(rf.sideNormal1, rf.v1); + rf.sideOffset2 = b2Dot(rf.sideNormal2, rf.v2); + + // Clip incident edge against extruded edge1 side edges. + b2ClipVertex clipPoints1[2]; + b2ClipVertex clipPoints2[2]; + int32 np; + + // Clip to box side 1 + np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); + + if (np < b2_maxManifoldPoints) + { + return; + } + + // Clip to negative box side 1 + np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); + + if (np < b2_maxManifoldPoints) + { + return; + } + + // Now clipPoints2 contains the clipped points. + if (primaryAxis.type == b2EPAxis::e_edgeA) + { + manifold->localNormal = rf.normal; + manifold->localPoint = rf.v1; + } + else + { + manifold->localNormal = polygonB->m_normals[rf.i1]; + manifold->localPoint = polygonB->m_vertices[rf.i1]; + } + + int32 pointCount = 0; + for (int32 i = 0; i < b2_maxManifoldPoints; ++i) + { + float32 separation; + + separation = b2Dot(rf.normal, clipPoints2[i].v - rf.v1); + + if (separation <= m_radius) + { + b2ManifoldPoint* cp = manifold->points + pointCount; + + if (primaryAxis.type == b2EPAxis::e_edgeA) + { + cp->localPoint = b2MulT(m_xf, clipPoints2[i].v); + cp->id = clipPoints2[i].id; + } + else + { + cp->localPoint = clipPoints2[i].v; + cp->id.cf.typeA = clipPoints2[i].id.cf.typeB; + cp->id.cf.typeB = clipPoints2[i].id.cf.typeA; + cp->id.cf.indexA = clipPoints2[i].id.cf.indexB; + cp->id.cf.indexB = clipPoints2[i].id.cf.indexA; + } + + ++pointCount; + } + } + + manifold->pointCount = pointCount; +} + +b2EPAxis b2EPCollider::ComputeEdgeSeparation() +{ + b2EPAxis axis; + axis.type = b2EPAxis::e_edgeA; + axis.index = m_front ? 0 : 1; + axis.separation = FLT_MAX; + + for (int32 i = 0; i < m_polygonB.count; ++i) + { + float32 s = b2Dot(m_normal, m_polygonB.vertices[i] - m_v1); + if (s < axis.separation) + { + axis.separation = s; + } + } + + return axis; +} + +b2EPAxis b2EPCollider::ComputePolygonSeparation() +{ + b2EPAxis axis; + axis.type = b2EPAxis::e_unknown; + axis.index = -1; + axis.separation = -FLT_MAX; + + b2Vec2 perp(-m_normal.y, m_normal.x); + + for (int32 i = 0; i < m_polygonB.count; ++i) + { + b2Vec2 n = -m_polygonB.normals[i]; + + float32 s1 = b2Dot(n, m_polygonB.vertices[i] - m_v1); + float32 s2 = b2Dot(n, m_polygonB.vertices[i] - m_v2); + float32 s = b2Min(s1, s2); + + if (s > m_radius) + { + // No collision + axis.type = b2EPAxis::e_edgeB; + axis.index = i; + axis.separation = s; + return axis; + } + + // Adjacency + if (b2Dot(n, perp) >= 0.0f) + { + if (b2Dot(n - m_upperLimit, m_normal) < -b2_angularSlop) + { + continue; + } + } + else + { + if (b2Dot(n - m_lowerLimit, m_normal) < -b2_angularSlop) + { + continue; + } + } + + if (s > axis.separation) + { + axis.type = b2EPAxis::e_edgeB; + axis.index = i; + axis.separation = s; + } + } + + return axis; +} + +void b2CollideEdgeAndPolygon( b2Manifold* manifold, + const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB) +{ + b2EPCollider collider; + collider.Collide(manifold, edgeA, xfA, polygonB, xfB); +} diff --git a/src/modules/physics/box2d/Box2D/Collision/b2CollidePolygon.cpp b/src/modules/physics/box2d/Box2D/Collision/b2CollidePolygon.cpp old mode 100644 new mode 100755 index b37b7ba92..2f0946b92 --- a/src/modules/physics/box2d/Box2D/Collision/b2CollidePolygon.cpp +++ b/src/modules/physics/box2d/Box2D/Collision/b2CollidePolygon.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -23,18 +23,17 @@ static float32 b2EdgeSeparation(const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, const b2PolygonShape* poly2, const b2Transform& xf2) { - int32 count1 = poly1->m_vertexCount; const b2Vec2* vertices1 = poly1->m_vertices; const b2Vec2* normals1 = poly1->m_normals; int32 count2 = poly2->m_vertexCount; const b2Vec2* vertices2 = poly2->m_vertices; - b2Assert(0 <= edge1 && edge1 < count1); + b2Assert(0 <= edge1 && edge1 < poly1->m_vertexCount); // Convert normal from poly1's frame into poly2's frame. - b2Vec2 normal1World = b2Mul(xf1.R, normals1[edge1]); - b2Vec2 normal1 = b2MulT(xf2.R, normal1World); + b2Vec2 normal1World = b2Mul(xf1.q, normals1[edge1]); + b2Vec2 normal1 = b2MulT(xf2.q, normal1World); // Find support vertex on poly2 for -normal. int32 index = 0; @@ -66,7 +65,7 @@ static float32 b2FindMaxSeparation(int32* edgeIndex, // Vector pointing from the centroid of poly1 to the centroid of poly2. b2Vec2 d = b2Mul(xf2, poly2->m_centroid) - b2Mul(xf1, poly1->m_centroid); - b2Vec2 dLocal1 = b2MulT(xf1.R, d); + b2Vec2 dLocal1 = b2MulT(xf1.q, d); // Find edge normal on poly1 that has the largest projection onto d. int32 edge = 0; @@ -143,17 +142,16 @@ static void b2FindIncidentEdge(b2ClipVertex c[2], const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, const b2PolygonShape* poly2, const b2Transform& xf2) { - int32 count1 = poly1->m_vertexCount; const b2Vec2* normals1 = poly1->m_normals; int32 count2 = poly2->m_vertexCount; const b2Vec2* vertices2 = poly2->m_vertices; const b2Vec2* normals2 = poly2->m_normals; - b2Assert(0 <= edge1 && edge1 < count1); + b2Assert(0 <= edge1 && edge1 < poly1->m_vertexCount); // Get the normal of the reference edge in poly2's frame. - b2Vec2 normal1 = b2MulT(xf2.R, b2Mul(xf1.R, normals1[edge1])); + b2Vec2 normal1 = b2MulT(xf2.q, b2Mul(xf1.q, normals1[edge1])); // Find the incident edge on poly2. int32 index = 0; @@ -173,14 +171,16 @@ static void b2FindIncidentEdge(b2ClipVertex c[2], int32 i2 = i1 + 1 < count2 ? i1 + 1 : 0; c[0].v = b2Mul(xf2, vertices2[i1]); - c[0].id.features.referenceEdge = (uint8)edge1; - c[0].id.features.incidentEdge = (uint8)i1; - c[0].id.features.incidentVertex = 0; + c[0].id.cf.indexA = (uint8)edge1; + c[0].id.cf.indexB = (uint8)i1; + c[0].id.cf.typeA = b2ContactFeature::e_face; + c[0].id.cf.typeB = b2ContactFeature::e_vertex; c[1].v = b2Mul(xf2, vertices2[i2]); - c[1].id.features.referenceEdge = (uint8)edge1; - c[1].id.features.incidentEdge = (uint8)i2; - c[1].id.features.incidentVertex = 1; + c[1].id.cf.indexA = (uint8)edge1; + c[1].id.cf.indexB = (uint8)i2; + c[1].id.cf.typeA = b2ContactFeature::e_face; + c[1].id.cf.typeB = b2ContactFeature::e_vertex; } // Find edge normal of max separation on A - return if separating axis is found @@ -242,8 +242,11 @@ void b2CollidePolygons(b2Manifold* manifold, int32 count1 = poly1->m_vertexCount; const b2Vec2* vertices1 = poly1->m_vertices; - b2Vec2 v11 = vertices1[edge1]; - b2Vec2 v12 = edge1 + 1 < count1 ? vertices1[edge1+1] : vertices1[0]; + int32 iv1 = edge1; + int32 iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; + + b2Vec2 v11 = vertices1[iv1]; + b2Vec2 v12 = vertices1[iv2]; b2Vec2 localTangent = v12 - v11; localTangent.Normalize(); @@ -251,7 +254,7 @@ void b2CollidePolygons(b2Manifold* manifold, b2Vec2 localNormal = b2Cross(localTangent, 1.0f); b2Vec2 planePoint = 0.5f * (v11 + v12); - b2Vec2 tangent = b2Mul(xf1.R, localTangent); + b2Vec2 tangent = b2Mul(xf1.q, localTangent); b2Vec2 normal = b2Cross(tangent, 1.0f); v11 = b2Mul(xf1, v11); @@ -270,13 +273,13 @@ void b2CollidePolygons(b2Manifold* manifold, int np; // Clip to box side 1 - np = b2ClipSegmentToLine(clipPoints1, incidentEdge, -tangent, sideOffset1); + np = b2ClipSegmentToLine(clipPoints1, incidentEdge, -tangent, sideOffset1, iv1); if (np < 2) return; // Clip to negative box side 1 - np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2); + np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); if (np < 2) { @@ -297,7 +300,15 @@ void b2CollidePolygons(b2Manifold* manifold, b2ManifoldPoint* cp = manifold->points + pointCount; cp->localPoint = b2MulT(xf2, clipPoints2[i].v); cp->id = clipPoints2[i].id; - cp->id.features.flip = flip; + if (flip) + { + // Swap features + b2ContactFeature cf = cp->id.cf; + cp->id.cf.indexA = cf.indexB; + cp->id.cf.indexB = cf.indexA; + cp->id.cf.typeA = cf.typeB; + cp->id.cf.typeB = cf.typeA; + } ++pointCount; } } diff --git a/src/modules/physics/box2d/Box2D/Collision/b2Collision.cpp b/src/modules/physics/box2d/Box2D/Collision/b2Collision.cpp old mode 100644 new mode 100755 index a86c7c5a8..4b092f0cb --- a/src/modules/physics/box2d/Box2D/Collision/b2Collision.cpp +++ b/src/modules/physics/box2d/Box2D/Collision/b2Collision.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2007-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -49,7 +49,7 @@ void b2WorldManifold::Initialize(const b2Manifold* manifold, case b2Manifold::e_faceA: { - normal = b2Mul(xfA.R, manifold->localNormal); + normal = b2Mul(xfA.q, manifold->localNormal); b2Vec2 planePoint = b2Mul(xfA, manifold->localPoint); for (int32 i = 0; i < manifold->pointCount; ++i) @@ -64,7 +64,7 @@ void b2WorldManifold::Initialize(const b2Manifold* manifold, case b2Manifold::e_faceB: { - normal = b2Mul(xfB.R, manifold->localNormal); + normal = b2Mul(xfB.q, manifold->localNormal); b2Vec2 planePoint = b2Mul(xfB, manifold->localPoint); for (int32 i = 0; i < manifold->pointCount; ++i) @@ -196,7 +196,7 @@ bool b2AABB::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const // Sutherland-Hodgman clipping. int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], - const b2Vec2& normal, float32 offset) + const b2Vec2& normal, float32 offset, int32 vertexIndexA) { // Start with no output points int32 numOut = 0; @@ -215,26 +215,25 @@ int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], // Find intersection point of edge and plane float32 interp = distance0 / (distance0 - distance1); vOut[numOut].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v); - if (distance0 > 0.0f) - { - vOut[numOut].id = vIn[0].id; - } - else - { - vOut[numOut].id = vIn[1].id; - } + + // VertexA is hitting edgeB. + vOut[numOut].id.cf.indexA = vertexIndexA; + vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB; + vOut[numOut].id.cf.typeA = b2ContactFeature::e_vertex; + vOut[numOut].id.cf.typeB = b2ContactFeature::e_face; ++numOut; } return numOut; } -bool b2TestOverlap(const b2Shape* shapeA, const b2Shape* shapeB, - const b2Transform& xfA, const b2Transform& xfB) +bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, + const b2Shape* shapeB, int32 indexB, + const b2Transform& xfA, const b2Transform& xfB) { b2DistanceInput input; - input.proxyA.Set(shapeA); - input.proxyB.Set(shapeB); + input.proxyA.Set(shapeA, indexA); + input.proxyB.Set(shapeB, indexB); input.transformA = xfA; input.transformB = xfB; input.useRadii = true; diff --git a/src/modules/physics/box2d/Box2D/Collision/b2Collision.h b/src/modules/physics/box2d/Box2D/Collision/b2Collision.h old mode 100644 new mode 100755 index baffdbde0..27897f70a --- a/src/modules/physics/box2d/Box2D/Collision/b2Collision.h +++ b/src/modules/physics/box2d/Box2D/Collision/b2Collision.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -28,21 +28,31 @@ class b2Shape; class b2CircleShape; +class b2EdgeShape; class b2PolygonShape; const uint8 b2_nullFeature = UCHAR_MAX; +/// The features that intersect to form the contact point +/// This must be 4 bytes or less. +struct b2ContactFeature +{ + enum Type + { + e_vertex = 0, + e_face = 1 + }; + + uint8 indexA; ///< Feature index on shapeA + uint8 indexB; ///< Feature index on shapeB + uint8 typeA; ///< The feature type on shapeA + uint8 typeB; ///< The feature type on shapeB +}; + /// Contact ids to facilitate warm starting. union b2ContactID { - /// The features that intersect to form the contact point - struct Features - { - uint8 referenceEdge; ///< The edge that defines the outward contact normal. - uint8 incidentEdge; ///< The edge most anti-parallel to the reference edge. - uint8 incidentVertex; ///< The vertex (0 or 1) on the incident edge that was clipped. - uint8 flip; ///< A value of 1 indicates that the reference edge is on shape2. - } features; + b2ContactFeature cf; uint32 key; ///< Used to quickly compare contact ids. }; @@ -107,7 +117,7 @@ struct b2WorldManifold const b2Transform& xfA, float32 radiusA, const b2Transform& xfB, float32 radiusB); - b2Vec2 normal; ///< world vector pointing from A to B + b2Vec2 normal; ///< world vector pointing from A to B b2Vec2 points[b2_maxManifoldPoints]; ///< world contact point (point of intersection) }; @@ -165,6 +175,21 @@ struct b2AABB return 0.5f * (upperBound - lowerBound); } + /// Get the perimeter length + float32 GetPerimeter() const + { + float32 wx = upperBound.x - lowerBound.x; + float32 wy = upperBound.y - lowerBound.y; + return 2.0f * (wx + wy); + } + + /// Combine an AABB into this one. + void Combine(const b2AABB& aabb) + { + lowerBound = b2Min(lowerBound, aabb.lowerBound); + upperBound = b2Max(upperBound, aabb.upperBound); + } + /// Combine two AABBs into this one. void Combine(const b2AABB& aabb1, const b2AABB& aabb2) { @@ -191,26 +216,37 @@ struct b2AABB /// Compute the collision manifold between two circles. void b2CollideCircles(b2Manifold* manifold, - const b2CircleShape* circle1, const b2Transform& xf1, - const b2CircleShape* circle2, const b2Transform& xf2); + const b2CircleShape* circleA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB); /// Compute the collision manifold between a polygon and a circle. void b2CollidePolygonAndCircle(b2Manifold* manifold, - const b2PolygonShape* polygon, const b2Transform& xf1, - const b2CircleShape* circle, const b2Transform& xf2); + const b2PolygonShape* polygonA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB); /// Compute the collision manifold between two polygons. void b2CollidePolygons(b2Manifold* manifold, - const b2PolygonShape* polygon1, const b2Transform& xf1, - const b2PolygonShape* polygon2, const b2Transform& xf2); + const b2PolygonShape* polygonA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB); + +/// Compute the collision manifold between an edge and a circle. +void b2CollideEdgeAndCircle(b2Manifold* manifold, + const b2EdgeShape* polygonA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB); + +/// Compute the collision manifold between an edge and a circle. +void b2CollideEdgeAndPolygon(b2Manifold* manifold, + const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* circleB, const b2Transform& xfB); /// Clipping for contact manifolds. int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], - const b2Vec2& normal, float32 offset); + const b2Vec2& normal, float32 offset, int32 vertexIndexA); /// Determine if two generic shapes overlap. -bool b2TestOverlap(const b2Shape* shapeA, const b2Shape* shapeB, - const b2Transform& xfA, const b2Transform& xfB); +bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, + const b2Shape* shapeB, int32 indexB, + const b2Transform& xfA, const b2Transform& xfB); // ---------------- Inline Functions ------------------------------------------ diff --git a/src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp b/src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp old mode 100644 new mode 100755 index f95c82f21..2bfb7598a --- a/src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp +++ b/src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2007-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -18,12 +18,14 @@ #include #include +#include +#include #include // GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates. int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; -void b2DistanceProxy::Set(const b2Shape* shape) +void b2DistanceProxy::Set(const b2Shape* shape, int32 index) { switch (shape->GetType()) { @@ -45,6 +47,36 @@ void b2DistanceProxy::Set(const b2Shape* shape) } break; + case b2Shape::e_chain: + { + const b2ChainShape* chain = (b2ChainShape*)shape; + b2Assert(0 <= index && index < chain->GetVertexCount()); + + m_buffer[0] = chain->GetVertex(index); + if (index + 1 < chain->GetVertexCount()) + { + m_buffer[1] = chain->GetVertex(index + 1); + } + else + { + m_buffer[1] = chain->GetVertex(0); + } + + m_vertices = m_buffer; + m_count = 2; + m_radius = chain->m_radius; + } + break; + + case b2Shape::e_edge: + { + const b2EdgeShape* edge = (b2EdgeShape*)shape; + m_vertices = &edge->m_vertex1; + m_count = 2; + m_radius = edge->m_radius; + } + break; + default: b2Assert(false); } @@ -500,10 +532,10 @@ void b2Distance(b2DistanceOutput* output, // Compute a tentative new simplex vertex using support points. b2SimplexVertex* vertex = vertices + simplex.m_count; - vertex->indexA = proxyA->GetSupport(b2MulT(transformA.R, -d)); + vertex->indexA = proxyA->GetSupport(b2MulT(transformA.q, -d)); vertex->wA = b2Mul(transformA, proxyA->GetVertex(vertex->indexA)); b2Vec2 wBLocal; - vertex->indexB = proxyB->GetSupport(b2MulT(transformB.R, d)); + vertex->indexB = proxyB->GetSupport(b2MulT(transformB.q, d)); vertex->wB = b2Mul(transformB, proxyB->GetVertex(vertex->indexB)); vertex->w = vertex->wB - vertex->wA; diff --git a/src/modules/physics/box2d/Box2D/Collision/b2Distance.h b/src/modules/physics/box2d/Box2D/Collision/b2Distance.h old mode 100644 new mode 100755 index e56ea0a7b..54ed1e136 --- a/src/modules/physics/box2d/Box2D/Collision/b2Distance.h +++ b/src/modules/physics/box2d/Box2D/Collision/b2Distance.h @@ -1,6 +1,6 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -21,7 +21,6 @@ #define B2_DISTANCE_H #include -#include class b2Shape; @@ -33,7 +32,7 @@ struct b2DistanceProxy /// Initialize the proxy using the given shape. The shape /// must remain in scope while the proxy is in use. - void Set(const b2Shape* shape); + void Set(const b2Shape* shape, int32 index); /// Get the supporting vertex index in the given direction. int32 GetSupport(const b2Vec2& d) const; @@ -47,6 +46,7 @@ struct b2DistanceProxy /// Get a vertex by index. Used by b2Distance. const b2Vec2& GetVertex(int32 index) const; + b2Vec2 m_buffer[2]; const b2Vec2* m_vertices; int32 m_count; float32 m_radius; diff --git a/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.cpp b/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.cpp old mode 100644 new mode 100755 index d8a05ebdf..1a42c3a5f --- a/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.cpp +++ b/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -19,6 +19,8 @@ #include #include #include +using namespace std; + b2DynamicTree::b2DynamicTree() { @@ -26,15 +28,17 @@ b2DynamicTree::b2DynamicTree() m_nodeCapacity = 16; m_nodeCount = 0; - m_nodes = (b2DynamicTreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2DynamicTreeNode)); - memset(m_nodes, 0, m_nodeCapacity * sizeof(b2DynamicTreeNode)); + m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); + memset(m_nodes, 0, m_nodeCapacity * sizeof(b2TreeNode)); // Build a linked list for the free list. for (int32 i = 0; i < m_nodeCapacity - 1; ++i) { m_nodes[i].next = i + 1; + m_nodes[i].height = -1; } m_nodes[m_nodeCapacity-1].next = b2_nullNode; + m_nodes[m_nodeCapacity-1].height = -1; m_freeList = 0; m_path = 0; @@ -57,10 +61,10 @@ int32 b2DynamicTree::AllocateNode() b2Assert(m_nodeCount == m_nodeCapacity); // The free list is empty. Rebuild a bigger pool. - b2DynamicTreeNode* oldNodes = m_nodes; + b2TreeNode* oldNodes = m_nodes; m_nodeCapacity *= 2; - m_nodes = (b2DynamicTreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2DynamicTreeNode)); - memcpy(m_nodes, oldNodes, m_nodeCount * sizeof(b2DynamicTreeNode)); + m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); + memcpy(m_nodes, oldNodes, m_nodeCount * sizeof(b2TreeNode)); b2Free(oldNodes); // Build a linked list for the free list. The parent @@ -68,8 +72,10 @@ int32 b2DynamicTree::AllocateNode() for (int32 i = m_nodeCount; i < m_nodeCapacity - 1; ++i) { m_nodes[i].next = i + 1; + m_nodes[i].height = -1; } m_nodes[m_nodeCapacity-1].next = b2_nullNode; + m_nodes[m_nodeCapacity-1].height = -1; m_freeList = m_nodeCount; } @@ -79,6 +85,8 @@ int32 b2DynamicTree::AllocateNode() m_nodes[nodeId].parent = b2_nullNode; m_nodes[nodeId].child1 = b2_nullNode; m_nodes[nodeId].child2 = b2_nullNode; + m_nodes[nodeId].height = 0; + m_nodes[nodeId].userData = NULL; ++m_nodeCount; return nodeId; } @@ -89,6 +97,7 @@ void b2DynamicTree::FreeNode(int32 nodeId) b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); b2Assert(0 < m_nodeCount); m_nodes[nodeId].next = m_freeList; + m_nodes[nodeId].height = -1; m_freeList = nodeId; --m_nodeCount; } @@ -105,20 +114,10 @@ int32 b2DynamicTree::CreateProxy(const b2AABB& aabb, void* userData) m_nodes[proxyId].aabb.lowerBound = aabb.lowerBound - r; m_nodes[proxyId].aabb.upperBound = aabb.upperBound + r; m_nodes[proxyId].userData = userData; + m_nodes[proxyId].height = 0; InsertLeaf(proxyId); - // Rebalance if necessary. - int32 iterationCount = m_nodeCount >> 4; - int32 tryCount = 0; - int32 height = ComputeHeight(); - while (height > 64 && tryCount < 10) - { - Rebalance(iterationCount); - height = ComputeHeight(); - ++tryCount; - } - return proxyId; } @@ -188,79 +187,133 @@ void b2DynamicTree::InsertLeaf(int32 leaf) return; } - // Find the best sibling for this node. - b2Vec2 center = m_nodes[leaf].aabb.GetCenter(); - int32 sibling = m_root; - if (m_nodes[sibling].IsLeaf() == false) + // Find the best sibling for this node + b2AABB leafAABB = m_nodes[leaf].aabb; + int32 index = m_root; + while (m_nodes[index].IsLeaf() == false) { - do + int32 child1 = m_nodes[index].child1; + int32 child2 = m_nodes[index].child2; + + float32 area = m_nodes[index].aabb.GetPerimeter(); + + b2AABB combinedAABB; + combinedAABB.Combine(m_nodes[index].aabb, leafAABB); + float32 combinedArea = combinedAABB.GetPerimeter(); + + // Cost of creating a new parent for this node and the new leaf + float32 cost = 2.0f * combinedArea; + + // Minimum cost of pushing the leaf further down the tree + float32 inheritanceCost = 2.0f * (combinedArea - area); + + // Cost of descending into child1 + float32 cost1; + if (m_nodes[child1].IsLeaf()) { - int32 child1 = m_nodes[sibling].child1; - int32 child2 = m_nodes[sibling].child2; - - b2Vec2 delta1 = b2Abs(m_nodes[child1].aabb.GetCenter() - center); - b2Vec2 delta2 = b2Abs(m_nodes[child2].aabb.GetCenter() - center); - - float32 norm1 = delta1.x + delta1.y; - float32 norm2 = delta2.x + delta2.y; - - if (norm1 < norm2) - { - sibling = child1; - } - else - { - sibling = child2; - } - - } - while(m_nodes[sibling].IsLeaf() == false); - } - - // Create a parent for the siblings. - int32 node1 = m_nodes[sibling].parent; - int32 node2 = AllocateNode(); - m_nodes[node2].parent = node1; - m_nodes[node2].userData = NULL; - m_nodes[node2].aabb.Combine(m_nodes[leaf].aabb, m_nodes[sibling].aabb); - - if (node1 != b2_nullNode) - { - if (m_nodes[m_nodes[sibling].parent].child1 == sibling) - { - m_nodes[node1].child1 = node2; + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child1].aabb); + cost1 = aabb.GetPerimeter() + inheritanceCost; } else { - m_nodes[node1].child2 = node2; + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child1].aabb); + float32 oldArea = m_nodes[child1].aabb.GetPerimeter(); + float32 newArea = aabb.GetPerimeter(); + cost1 = (newArea - oldArea) + inheritanceCost; } - m_nodes[node2].child1 = sibling; - m_nodes[node2].child2 = leaf; - m_nodes[sibling].parent = node2; - m_nodes[leaf].parent = node2; - - do + // Cost of descending into child2 + float32 cost2; + if (m_nodes[child2].IsLeaf()) { - if (m_nodes[node1].aabb.Contains(m_nodes[node2].aabb)) - { - break; - } - - m_nodes[node1].aabb.Combine(m_nodes[m_nodes[node1].child1].aabb, m_nodes[m_nodes[node1].child2].aabb); - node2 = node1; - node1 = m_nodes[node1].parent; + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child2].aabb); + cost2 = aabb.GetPerimeter() + inheritanceCost; } - while(node1 != b2_nullNode); + else + { + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child2].aabb); + float32 oldArea = m_nodes[child2].aabb.GetPerimeter(); + float32 newArea = aabb.GetPerimeter(); + cost2 = newArea - oldArea + inheritanceCost; + } + + // Descend according to the minimum cost. + if (cost < cost1 && cost < cost2) + { + break; + } + + // Descend + if (cost1 < cost2) + { + index = child1; + } + else + { + index = child2; + } + } + + int32 sibling = index; + + // Create a new parent. + int32 oldParent = m_nodes[sibling].parent; + int32 newParent = AllocateNode(); + m_nodes[newParent].parent = oldParent; + m_nodes[newParent].userData = NULL; + m_nodes[newParent].aabb.Combine(leafAABB, m_nodes[sibling].aabb); + m_nodes[newParent].height = m_nodes[sibling].height + 1; + + if (oldParent != b2_nullNode) + { + // The sibling was not the root. + if (m_nodes[oldParent].child1 == sibling) + { + m_nodes[oldParent].child1 = newParent; + } + else + { + m_nodes[oldParent].child2 = newParent; + } + + m_nodes[newParent].child1 = sibling; + m_nodes[newParent].child2 = leaf; + m_nodes[sibling].parent = newParent; + m_nodes[leaf].parent = newParent; } else { - m_nodes[node2].child1 = sibling; - m_nodes[node2].child2 = leaf; - m_nodes[sibling].parent = node2; - m_nodes[leaf].parent = node2; - m_root = node2; + // The sibling was the root. + m_nodes[newParent].child1 = sibling; + m_nodes[newParent].child2 = leaf; + m_nodes[sibling].parent = newParent; + m_nodes[leaf].parent = newParent; + m_root = newParent; } + + // Walk back up the tree fixing heights and AABBs + index = m_nodes[leaf].parent; + while (index != b2_nullNode) + { + index = Balance(index); + + int32 child1 = m_nodes[index].child1; + int32 child2 = m_nodes[index].child2; + + b2Assert(child1 != b2_nullNode); + b2Assert(child2 != b2_nullNode); + + m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); + m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); + + index = m_nodes[index].parent; + } + + //Validate(); } void b2DynamicTree::RemoveLeaf(int32 leaf) @@ -271,89 +324,250 @@ void b2DynamicTree::RemoveLeaf(int32 leaf) return; } - int32 node2 = m_nodes[leaf].parent; - int32 node1 = m_nodes[node2].parent; + int32 parent = m_nodes[leaf].parent; + int32 grandParent = m_nodes[parent].parent; int32 sibling; - if (m_nodes[node2].child1 == leaf) + if (m_nodes[parent].child1 == leaf) { - sibling = m_nodes[node2].child2; + sibling = m_nodes[parent].child2; } else { - sibling = m_nodes[node2].child1; + sibling = m_nodes[parent].child1; } - if (node1 != b2_nullNode) + if (grandParent != b2_nullNode) { - // Destroy node2 and connect node1 to sibling. - if (m_nodes[node1].child1 == node2) + // Destroy parent and connect sibling to grandParent. + if (m_nodes[grandParent].child1 == parent) { - m_nodes[node1].child1 = sibling; + m_nodes[grandParent].child1 = sibling; } else { - m_nodes[node1].child2 = sibling; + m_nodes[grandParent].child2 = sibling; } - m_nodes[sibling].parent = node1; - FreeNode(node2); + m_nodes[sibling].parent = grandParent; + FreeNode(parent); // Adjust ancestor bounds. - while (node1 != b2_nullNode) + int32 index = grandParent; + while (index != b2_nullNode) { - b2AABB oldAABB = m_nodes[node1].aabb; - m_nodes[node1].aabb.Combine(m_nodes[m_nodes[node1].child1].aabb, m_nodes[m_nodes[node1].child2].aabb); + index = Balance(index); - if (oldAABB.Contains(m_nodes[node1].aabb)) - { - break; - } + int32 child1 = m_nodes[index].child1; + int32 child2 = m_nodes[index].child2; - node1 = m_nodes[node1].parent; + m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); + m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); + + index = m_nodes[index].parent; } } else { m_root = sibling; m_nodes[sibling].parent = b2_nullNode; - FreeNode(node2); + FreeNode(parent); } + + //Validate(); } -void b2DynamicTree::Rebalance(int32 iterations) +// Perform a left or right rotation if node A is imbalanced. +// Returns the new root index. +int32 b2DynamicTree::Balance(int32 iA) +{ + b2Assert(iA != b2_nullNode); + + b2TreeNode* A = m_nodes + iA; + if (A->IsLeaf() || A->height < 2) + { + return iA; + } + + int32 iB = A->child1; + int32 iC = A->child2; + b2Assert(0 <= iB && iB < m_nodeCapacity); + b2Assert(0 <= iC && iC < m_nodeCapacity); + + b2TreeNode* B = m_nodes + iB; + b2TreeNode* C = m_nodes + iC; + + int32 balance = C->height - B->height; + + // Rotate C up + if (balance > 1) + { + int32 iF = C->child1; + int32 iG = C->child2; + b2TreeNode* F = m_nodes + iF; + b2TreeNode* G = m_nodes + iG; + b2Assert(0 <= iF && iF < m_nodeCapacity); + b2Assert(0 <= iG && iG < m_nodeCapacity); + + // Swap A and C + C->child1 = iA; + C->parent = A->parent; + A->parent = iC; + + // A's old parent should point to C + if (C->parent != b2_nullNode) + { + if (m_nodes[C->parent].child1 == iA) + { + m_nodes[C->parent].child1 = iC; + } + else + { + b2Assert(m_nodes[C->parent].child2 == iA); + m_nodes[C->parent].child2 = iC; + } + } + else + { + m_root = iC; + } + + // Rotate + if (F->height > G->height) + { + C->child2 = iF; + A->child2 = iG; + G->parent = iA; + A->aabb.Combine(B->aabb, G->aabb); + C->aabb.Combine(A->aabb, F->aabb); + + A->height = 1 + b2Max(B->height, G->height); + C->height = 1 + b2Max(A->height, F->height); + } + else + { + C->child2 = iG; + A->child2 = iF; + F->parent = iA; + A->aabb.Combine(B->aabb, F->aabb); + C->aabb.Combine(A->aabb, G->aabb); + + A->height = 1 + b2Max(B->height, F->height); + C->height = 1 + b2Max(A->height, G->height); + } + + return iC; + } + + // Rotate B up + if (balance < -1) + { + int32 iD = B->child1; + int32 iE = B->child2; + b2TreeNode* D = m_nodes + iD; + b2TreeNode* E = m_nodes + iE; + b2Assert(0 <= iD && iD < m_nodeCapacity); + b2Assert(0 <= iE && iE < m_nodeCapacity); + + // Swap A and B + B->child1 = iA; + B->parent = A->parent; + A->parent = iB; + + // A's old parent should point to B + if (B->parent != b2_nullNode) + { + if (m_nodes[B->parent].child1 == iA) + { + m_nodes[B->parent].child1 = iB; + } + else + { + b2Assert(m_nodes[B->parent].child2 == iA); + m_nodes[B->parent].child2 = iB; + } + } + else + { + m_root = iB; + } + + // Rotate + if (D->height > E->height) + { + B->child2 = iD; + A->child1 = iE; + E->parent = iA; + A->aabb.Combine(C->aabb, E->aabb); + B->aabb.Combine(A->aabb, D->aabb); + + A->height = 1 + b2Max(C->height, E->height); + B->height = 1 + b2Max(A->height, D->height); + } + else + { + B->child2 = iE; + A->child1 = iD; + D->parent = iA; + A->aabb.Combine(C->aabb, D->aabb); + B->aabb.Combine(A->aabb, E->aabb); + + A->height = 1 + b2Max(C->height, D->height); + B->height = 1 + b2Max(A->height, E->height); + } + + return iB; + } + + return iA; +} + +int32 b2DynamicTree::GetHeight() const { if (m_root == b2_nullNode) { - return; + return 0; } - for (int32 i = 0; i < iterations; ++i) + return m_nodes[m_root].height; +} + +// +float32 b2DynamicTree::GetAreaRatio() const +{ + if (m_root == b2_nullNode) { - int32 node = m_root; - - uint32 bit = 0; - while (m_nodes[node].IsLeaf() == false) - { - int32* children = &m_nodes[node].child1; - node = children[(m_path >> bit) & 1]; - bit = (bit + 1) & (8* sizeof(uint32) - 1); - } - ++m_path; - - RemoveLeaf(node); - InsertLeaf(node); + return 0.0f; } + + const b2TreeNode* root = m_nodes + m_root; + float32 rootArea = root->aabb.GetPerimeter(); + + float32 totalArea = 0.0f; + for (int32 i = 0; i < m_nodeCapacity; ++i) + { + const b2TreeNode* node = m_nodes + i; + if (node->height < 0) + { + // Free node in pool + continue; + } + + totalArea += node->aabb.GetPerimeter(); + } + + return totalArea / rootArea; } // Compute the height of a sub-tree. int32 b2DynamicTree::ComputeHeight(int32 nodeId) const { - if (nodeId == b2_nullNode) + b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); + b2TreeNode* node = m_nodes + nodeId; + + if (node->IsLeaf()) { return 0; } - b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); - b2DynamicTreeNode* node = m_nodes + nodeId; int32 height1 = ComputeHeight(node->child1); int32 height2 = ComputeHeight(node->child2); return 1 + b2Max(height1, height2); @@ -361,5 +575,197 @@ int32 b2DynamicTree::ComputeHeight(int32 nodeId) const int32 b2DynamicTree::ComputeHeight() const { - return ComputeHeight(m_root); + int32 height = ComputeHeight(m_root); + return height; +} + +void b2DynamicTree::ValidateStructure(int32 index) const +{ + if (index == b2_nullNode) + { + return; + } + + if (index == m_root) + { + b2Assert(m_nodes[index].parent == b2_nullNode); + } + + const b2TreeNode* node = m_nodes + index; + + int32 child1 = node->child1; + int32 child2 = node->child2; + + if (node->IsLeaf()) + { + b2Assert(child1 == b2_nullNode); + b2Assert(child2 == b2_nullNode); + b2Assert(node->height == 0); + return; + } + + b2Assert(0 <= child1 && child1 < m_nodeCapacity); + b2Assert(0 <= child2 && child2 < m_nodeCapacity); + + b2Assert(m_nodes[child1].parent == index); + b2Assert(m_nodes[child2].parent == index); + + ValidateStructure(child1); + ValidateStructure(child2); +} + +void b2DynamicTree::ValidateMetrics(int32 index) const +{ + if (index == b2_nullNode) + { + return; + } + + const b2TreeNode* node = m_nodes + index; + + int32 child1 = node->child1; + int32 child2 = node->child2; + + if (node->IsLeaf()) + { + b2Assert(child1 == b2_nullNode); + b2Assert(child2 == b2_nullNode); + b2Assert(node->height == 0); + return; + } + + b2Assert(0 <= child1 && child1 < m_nodeCapacity); + b2Assert(0 <= child2 && child2 < m_nodeCapacity); + + int32 height1 = m_nodes[child1].height; + int32 height2 = m_nodes[child2].height; + int32 height; + height = 1 + b2Max(height1, height2); + b2Assert(node->height == height); + + b2AABB aabb; + aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); + + b2Assert(aabb.lowerBound == node->aabb.lowerBound); + b2Assert(aabb.upperBound == node->aabb.upperBound); + + ValidateMetrics(child1); + ValidateMetrics(child2); +} + +void b2DynamicTree::Validate() const +{ + ValidateStructure(m_root); + ValidateMetrics(m_root); + + int32 freeCount = 0; + int32 freeIndex = m_freeList; + while (freeIndex != b2_nullNode) + { + b2Assert(0 <= freeIndex && freeIndex < m_nodeCapacity); + freeIndex = m_nodes[freeIndex].next; + ++freeCount; + } + + b2Assert(GetHeight() == ComputeHeight()); + + b2Assert(m_nodeCount + freeCount == m_nodeCapacity); +} + +int32 b2DynamicTree::GetMaxBalance() const +{ + int32 maxBalance = 0; + for (int32 i = 0; i < m_nodeCapacity; ++i) + { + const b2TreeNode* node = m_nodes + i; + if (node->height <= 1) + { + continue; + } + + b2Assert(node->IsLeaf() == false); + + int32 child1 = node->child1; + int32 child2 = node->child2; + int32 balance = b2Abs(m_nodes[child2].height - m_nodes[child1].height); + maxBalance = b2Max(maxBalance, balance); + } + + return maxBalance; +} + +void b2DynamicTree::RebuildBottomUp() +{ + int32* nodes = (int32*)b2Alloc(m_nodeCount * sizeof(int32)); + int32 count = 0; + + // Build array of leaves. Free the rest. + for (int32 i = 0; i < m_nodeCapacity; ++i) + { + if (m_nodes[i].height < 0) + { + // free node in pool + continue; + } + + if (m_nodes[i].IsLeaf()) + { + m_nodes[i].parent = b2_nullNode; + nodes[count] = i; + ++count; + } + else + { + FreeNode(i); + } + } + + while (count > 1) + { + float32 minCost = b2_maxFloat; + int32 iMin = -1, jMin = -1; + for (int32 i = 0; i < count; ++i) + { + b2AABB aabbi = m_nodes[nodes[i]].aabb; + + for (int32 j = i + 1; j < count; ++j) + { + b2AABB aabbj = m_nodes[nodes[j]].aabb; + b2AABB b; + b.Combine(aabbi, aabbj); + float32 cost = b.GetPerimeter(); + if (cost < minCost) + { + iMin = i; + jMin = j; + minCost = cost; + } + } + } + + int32 index1 = nodes[iMin]; + int32 index2 = nodes[jMin]; + b2TreeNode* child1 = m_nodes + index1; + b2TreeNode* child2 = m_nodes + index2; + + int32 parentIndex = AllocateNode(); + b2TreeNode* parent = m_nodes + parentIndex; + parent->child1 = index1; + parent->child2 = index2; + parent->height = 1 + b2Max(child1->height, child2->height); + parent->aabb.Combine(child1->aabb, child2->aabb); + parent->parent = b2_nullNode; + + child1->parent = parentIndex; + child2->parent = parentIndex; + + nodes[jMin] = nodes[count-1]; + nodes[iMin] = parentIndex; + --count; + } + + m_root = nodes[0]; + b2Free(nodes); + + Validate(); } diff --git a/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.h b/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.h old mode 100644 new mode 100755 index b67686b5c..a9bfbf379 --- a/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.h +++ b/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -20,23 +20,21 @@ #define B2_DYNAMIC_TREE_H #include - -/// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. +#include #define b2_nullNode (-1) /// A node in the dynamic tree. The client does not interact with this directly. -struct b2DynamicTreeNode +struct b2TreeNode { bool IsLeaf() const { return child1 == b2_nullNode; } - /// This is the fattened AABB. + /// Enlarged AABB b2AABB aabb; - //int32 userData; void* userData; union @@ -47,8 +45,12 @@ struct b2DynamicTreeNode int32 child1; int32 child2; + + // leaf = 0, free node = -1 + int32 height; }; +/// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. /// A dynamic tree arranges data in a binary tree to accelerate /// queries such as volume queries and ray casts. Leafs are proxies /// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor @@ -59,7 +61,6 @@ struct b2DynamicTreeNode class b2DynamicTree { public: - /// Constructing the tree initializes the node pool. b2DynamicTree(); @@ -78,9 +79,6 @@ public: /// @return true if the proxy was re-inserted. bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement); - /// Perform some iterations to re-balance the tree. - void Rebalance(int32 iterations); - /// Get proxy user data. /// @return the proxy user data or 0 if the id is invalid. void* GetUserData(int32 proxyId) const; @@ -88,9 +86,6 @@ public: /// Get the fat AABB for a proxy. const b2AABB& GetFatAABB(int32 proxyId) const; - /// Compute the height of the tree. - int32 ComputeHeight() const; - /// Query an AABB for overlapping proxies. The callback class /// is called for each proxy that overlaps the supplied AABB. template @@ -106,6 +101,23 @@ public: template void RayCast(T* callback, const b2RayCastInput& input) const; + /// Validate this tree. For testing. + void Validate() const; + + /// Compute the height of the binary tree in O(N) time. Should not be + /// called often. + int32 GetHeight() const; + + /// Get the maximum balance of an node in the tree. The balance is the difference + /// in height of the two children of a node. + int32 GetMaxBalance() const; + + /// Get the ratio of the sum of the node areas to the root area. + float32 GetAreaRatio() const; + + /// Build an optimal tree. Very expensive. For testing. + void RebuildBottomUp(); + private: int32 AllocateNode(); @@ -114,17 +126,23 @@ private: void InsertLeaf(int32 node); void RemoveLeaf(int32 node); + int32 Balance(int32 index); + + int32 ComputeHeight() const; int32 ComputeHeight(int32 nodeId) const; + void ValidateStructure(int32 index) const; + void ValidateMetrics(int32 index) const; + int32 m_root; - b2DynamicTreeNode* m_nodes; + b2TreeNode* m_nodes; int32 m_nodeCount; int32 m_nodeCapacity; int32 m_freeList; - /// This is used incrementally traverse the tree for re-balancing. + /// This is used to incrementally traverse the tree for re-balancing. uint32 m_path; int32 m_insertionCount; @@ -145,21 +163,18 @@ inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const template inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const { - const int32 k_stackSize = 128; - int32 stack[k_stackSize]; + b2GrowableStack stack; + stack.Push(m_root); - int32 count = 0; - stack[count++] = m_root; - - while (count > 0) + while (stack.GetCount() > 0) { - int32 nodeId = stack[--count]; + int32 nodeId = stack.Pop(); if (nodeId == b2_nullNode) { continue; } - const b2DynamicTreeNode* node = m_nodes + nodeId; + const b2TreeNode* node = m_nodes + nodeId; if (b2TestOverlap(node->aabb, aabb)) { @@ -173,15 +188,8 @@ inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const } else { - if (count < k_stackSize) - { - stack[count++] = node->child1; - } - - if (count < k_stackSize) - { - stack[count++] = node->child2; - } + stack.Push(node->child1); + stack.Push(node->child2); } } } @@ -213,21 +221,18 @@ inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) con segmentAABB.upperBound = b2Max(p1, t); } - const int32 k_stackSize = 128; - int32 stack[k_stackSize]; + b2GrowableStack stack; + stack.Push(m_root); - int32 count = 0; - stack[count++] = m_root; - - while (count > 0) + while (stack.GetCount() > 0) { - int32 nodeId = stack[--count]; + int32 nodeId = stack.Pop(); if (nodeId == b2_nullNode) { continue; } - const b2DynamicTreeNode* node = m_nodes + nodeId; + const b2TreeNode* node = m_nodes + nodeId; if (b2TestOverlap(node->aabb, segmentAABB) == false) { @@ -270,15 +275,8 @@ inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) con } else { - if (count < k_stackSize) - { - stack[count++] = node->child1; - } - - if (count < k_stackSize) - { - stack[count++] = node->child2; - } + stack.Push(node->child1); + stack.Push(node->child2); } } } diff --git a/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.cpp b/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.cpp old mode 100644 new mode 100755 index b1f2f4e5a..5c33e828c --- a/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.cpp +++ b/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2007-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -23,12 +23,11 @@ #include #include +using namespace std; int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; int32 b2_toiRootIters, b2_toiMaxRootIters; -int32 b2_toiMaxOptIters; - struct b2SeparationFunction { enum Type @@ -42,7 +41,8 @@ struct b2SeparationFunction float32 Initialize(const b2SimplexCache* cache, const b2DistanceProxy* proxyA, const b2Sweep& sweepA, - const b2DistanceProxy* proxyB, const b2Sweep& sweepB) + const b2DistanceProxy* proxyB, const b2Sweep& sweepB, + float32 t1) { m_proxyA = proxyA; m_proxyB = proxyB; @@ -53,8 +53,8 @@ struct b2SeparationFunction m_sweepB = sweepB; b2Transform xfA, xfB; - m_sweepA.GetTransform(&xfA, 0.0f); - m_sweepB.GetTransform(&xfB, 0.0f); + m_sweepA.GetTransform(&xfA, t1); + m_sweepB.GetTransform(&xfB, t1); if (count == 1) { @@ -76,7 +76,7 @@ struct b2SeparationFunction m_axis = b2Cross(localPointB2 - localPointB1, 1.0f); m_axis.Normalize(); - b2Vec2 normal = b2Mul(xfB.R, m_axis); + b2Vec2 normal = b2Mul(xfB.q, m_axis); m_localPoint = 0.5f * (localPointB1 + localPointB2); b2Vec2 pointB = b2Mul(xfB, m_localPoint); @@ -101,7 +101,7 @@ struct b2SeparationFunction m_axis = b2Cross(localPointA2 - localPointA1, 1.0f); m_axis.Normalize(); - b2Vec2 normal = b2Mul(xfA.R, m_axis); + b2Vec2 normal = b2Mul(xfA.q, m_axis); m_localPoint = 0.5f * (localPointA1 + localPointA2); b2Vec2 pointA = b2Mul(xfA, m_localPoint); @@ -129,8 +129,8 @@ struct b2SeparationFunction { case e_points: { - b2Vec2 axisA = b2MulT(xfA.R, m_axis); - b2Vec2 axisB = b2MulT(xfB.R, -m_axis); + b2Vec2 axisA = b2MulT(xfA.q, m_axis); + b2Vec2 axisB = b2MulT(xfB.q, -m_axis); *indexA = m_proxyA->GetSupport(axisA); *indexB = m_proxyB->GetSupport(axisB); @@ -147,10 +147,10 @@ struct b2SeparationFunction case e_faceA: { - b2Vec2 normal = b2Mul(xfA.R, m_axis); + b2Vec2 normal = b2Mul(xfA.q, m_axis); b2Vec2 pointA = b2Mul(xfA, m_localPoint); - b2Vec2 axisB = b2MulT(xfB.R, -normal); + b2Vec2 axisB = b2MulT(xfB.q, -normal); *indexA = -1; *indexB = m_proxyB->GetSupport(axisB); @@ -164,10 +164,10 @@ struct b2SeparationFunction case e_faceB: { - b2Vec2 normal = b2Mul(xfB.R, m_axis); + b2Vec2 normal = b2Mul(xfB.q, m_axis); b2Vec2 pointB = b2Mul(xfB, m_localPoint); - b2Vec2 axisA = b2MulT(xfA.R, -normal); + b2Vec2 axisA = b2MulT(xfA.q, -normal); *indexB = -1; *indexA = m_proxyA->GetSupport(axisA); @@ -197,8 +197,8 @@ struct b2SeparationFunction { case e_points: { - b2Vec2 axisA = b2MulT(xfA.R, m_axis); - b2Vec2 axisB = b2MulT(xfB.R, -m_axis); + b2Vec2 axisA = b2MulT(xfA.q, m_axis); + b2Vec2 axisB = b2MulT(xfB.q, -m_axis); b2Vec2 localPointA = m_proxyA->GetVertex(indexA); b2Vec2 localPointB = m_proxyB->GetVertex(indexB); @@ -212,10 +212,10 @@ struct b2SeparationFunction case e_faceA: { - b2Vec2 normal = b2Mul(xfA.R, m_axis); + b2Vec2 normal = b2Mul(xfA.q, m_axis); b2Vec2 pointA = b2Mul(xfA, m_localPoint); - b2Vec2 axisB = b2MulT(xfB.R, -normal); + b2Vec2 axisB = b2MulT(xfB.q, -normal); b2Vec2 localPointB = m_proxyB->GetVertex(indexB); b2Vec2 pointB = b2Mul(xfB, localPointB); @@ -226,10 +226,10 @@ struct b2SeparationFunction case e_faceB: { - b2Vec2 normal = b2Mul(xfB.R, m_axis); + b2Vec2 normal = b2Mul(xfB.q, m_axis); b2Vec2 pointB = b2Mul(xfB, m_localPoint); - b2Vec2 axisA = b2MulT(xfA.R, -normal); + b2Vec2 axisA = b2MulT(xfA.q, -normal); b2Vec2 localPointA = m_proxyA->GetVertex(indexA); b2Vec2 pointA = b2Mul(xfA, localPointA); @@ -325,7 +325,7 @@ void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input) // Initialize the separating axis. b2SeparationFunction fcn; - fcn.Initialize(&cache, proxyA, sweepA, proxyB, sweepB); + fcn.Initialize(&cache, proxyA, sweepA, proxyB, sweepB, t1); #if 0 // Dump the curve seen by the root finder { diff --git a/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.h b/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.h old mode 100644 new mode 100755 index b59fb831c..179a1700e --- a/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.h +++ b/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -21,7 +21,6 @@ #include #include -#include /// Input parameters for b2TimeOfImpact struct b2TOIInput diff --git a/src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.cpp b/src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.cpp old mode 100644 new mode 100755 index ba06f0494..f5060daa2 --- a/src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.cpp +++ b/src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -21,6 +21,7 @@ #include #include #include +using namespace std; int32 b2BlockAllocator::s_blockSizes[b2_blockSizes] = { @@ -100,7 +101,12 @@ void* b2BlockAllocator::Allocate(int32 size) if (size == 0) return NULL; - b2Assert(0 < size && size <= b2_maxBlockSize); + b2Assert(0 < size); + + if (size > b2_maxBlockSize) + { + return b2Alloc(size); + } int32 index = s_blockSizeLookup[size]; b2Assert(0 <= index && index < b2_blockSizes); @@ -155,7 +161,13 @@ void b2BlockAllocator::Free(void* p, int32 size) return; } - b2Assert(0 < size && size <= b2_maxBlockSize); + b2Assert(0 < size); + + if (size > b2_maxBlockSize) + { + b2Free(p); + return; + } int32 index = s_blockSizeLookup[size]; b2Assert(0 <= index && index < b2_blockSizes); diff --git a/src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.h b/src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.h old mode 100644 new mode 100755 index 93eb2e311..8ba29a5e9 --- a/src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.h +++ b/src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -21,7 +21,7 @@ #include -const int32 b2_chunkSize = 4096; +const int32 b2_chunkSize = 16 * 1024; const int32 b2_maxBlockSize = 640; const int32 b2_blockSizes = 14; const int32 b2_chunkArrayIncrement = 128; @@ -29,16 +29,19 @@ const int32 b2_chunkArrayIncrement = 128; struct b2Block; struct b2Chunk; -// This is a small object allocator used for allocating small -// objects that persist for more than one time step. -// See: http://www.codeproject.com/useritems/Small_Block_Allocator.asp +/// This is a small object allocator used for allocating small +/// objects that persist for more than one time step. +/// See: http://www.codeproject.com/useritems/Small_Block_Allocator.asp class b2BlockAllocator { public: b2BlockAllocator(); ~b2BlockAllocator(); + /// Allocate memory. This will use b2Alloc if the size is larger than b2_maxBlockSize. void* Allocate(int32 size); + + /// Free memory. This will use b2Free if the size is larger than b2_maxBlockSize. void Free(void* p, int32 size); void Clear(); diff --git a/src/modules/physics/box2d/Box2D/Common/b2Draw.cpp b/src/modules/physics/box2d/Box2D/Common/b2Draw.cpp new file mode 100755 index 000000000..327b58079 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Common/b2Draw.cpp @@ -0,0 +1,44 @@ +/* +* Copyright (c) 2011 Erin Catto http://box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +b2Draw::b2Draw() +{ + m_drawFlags = 0; +} + +void b2Draw::SetFlags(uint32 flags) +{ + m_drawFlags = flags; +} + +uint32 b2Draw::GetFlags() const +{ + return m_drawFlags; +} + +void b2Draw::AppendFlags(uint32 flags) +{ + m_drawFlags |= flags; +} + +void b2Draw::ClearFlags(uint32 flags) +{ + m_drawFlags &= ~flags; +} diff --git a/src/modules/physics/box2d/Box2D/Common/b2Draw.h b/src/modules/physics/box2d/Box2D/Common/b2Draw.h new file mode 100755 index 000000000..de62dd611 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Common/b2Draw.h @@ -0,0 +1,81 @@ +/* +* Copyright (c) 2011 Erin Catto http://box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +/// Color for debug drawing. Each value has the range [0,1]. +struct b2Color +{ + b2Color() {} + b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {} + void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi; } + float32 r, g, b; +}; + +/// Implement and register this class with a b2World to provide debug drawing of physics +/// entities in your game. +class b2Draw +{ +public: + b2Draw(); + + virtual ~b2Draw() {} + + enum + { + e_shapeBit = 0x0001, ///< draw shapes + e_jointBit = 0x0002, ///< draw joint connections + e_aabbBit = 0x0004, ///< draw axis aligned bounding boxes + e_pairBit = 0x0008, ///< draw broad-phase pairs + e_centerOfMassBit = 0x0010 ///< draw center of mass frame + }; + + /// Set the drawing flags. + void SetFlags(uint32 flags); + + /// Get the drawing flags. + uint32 GetFlags() const; + + /// Append flags to the current flags. + void AppendFlags(uint32 flags); + + /// Clear flags from the current flags. + void ClearFlags(uint32 flags); + + /// Draw a closed polygon provided in CCW order. + virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; + + /// Draw a solid closed polygon provided in CCW order. + virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; + + /// Draw a circle. + virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) = 0; + + /// Draw a solid circle. + virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) = 0; + + /// Draw a line segment. + virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0; + + /// Draw a transform. Choose your own length scale. + /// @param xf a transform. + virtual void DrawTransform(const b2Transform& xf) = 0; + +protected: + uint32 m_drawFlags; +}; diff --git a/src/modules/physics/box2d/Box2D/Common/b2GrowableStack.h b/src/modules/physics/box2d/Box2D/Common/b2GrowableStack.h new file mode 100755 index 000000000..d2e07120f --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Common/b2GrowableStack.h @@ -0,0 +1,85 @@ +/* +* Copyright (c) 2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_GROWABLE_STACK_H +#define B2_GROWABLE_STACK_H +#include +#include + +/// This is a growable LIFO stack with an initial capacity of N. +/// If the stack size exceeds the initial capacity, the heap is used +/// to increase the size of the stack. +template +class b2GrowableStack +{ +public: + b2GrowableStack() + { + m_stack = m_array; + m_count = 0; + m_capacity = N; + } + + ~b2GrowableStack() + { + if (m_stack != m_array) + { + b2Free(m_stack); + m_stack = NULL; + } + } + + void Push(const T& element) + { + if (m_count == m_capacity) + { + T* old = m_stack; + m_capacity *= 2; + m_stack = (T*)b2Alloc(m_capacity * sizeof(T)); + std::memcpy(m_stack, old, m_count * sizeof(T)); + if (old != m_array) + { + b2Free(old); + } + } + + m_stack[m_count] = element; + ++m_count; + } + + T Pop() + { + b2Assert(m_count > 0); + --m_count; + return m_stack[m_count]; + } + + int32 GetCount() + { + return m_count; + } + +private: + T* m_stack; + T m_array[N]; + int32 m_count; + int32 m_capacity; +}; + + +#endif diff --git a/src/modules/physics/box2d/Box2D/Common/b2Math.cpp b/src/modules/physics/box2d/Box2D/Common/b2Math.cpp old mode 100644 new mode 100755 index f15a43bd5..b06111dc4 --- a/src/modules/physics/box2d/Box2D/Common/b2Math.cpp +++ b/src/modules/physics/box2d/Box2D/Common/b2Math.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2007-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -19,22 +19,20 @@ #include const b2Vec2 b2Vec2_zero(0.0f, 0.0f); -const b2Mat22 b2Mat22_identity(1.0f, 0.0f, 0.0f, 1.0f); -const b2Transform b2Transform_identity(b2Vec2_zero, b2Mat22_identity); /// Solve A * x = b, where b is a column vector. This is more efficient /// than computing the inverse in one-shot cases. b2Vec3 b2Mat33::Solve33(const b2Vec3& b) const { - float32 det = b2Dot(col1, b2Cross(col2, col3)); + float32 det = b2Dot(ex, b2Cross(ey, ez)); if (det != 0.0f) { det = 1.0f / det; } b2Vec3 x; - x.x = det * b2Dot(b, b2Cross(col2, col3)); - x.y = det * b2Dot(col1, b2Cross(b, col3)); - x.z = det * b2Dot(col1, b2Cross(col2, b)); + x.x = det * b2Dot(b, b2Cross(ey, ez)); + x.y = det * b2Dot(ex, b2Cross(b, ez)); + x.z = det * b2Dot(ex, b2Cross(ey, b)); return x; } @@ -42,7 +40,7 @@ b2Vec3 b2Mat33::Solve33(const b2Vec3& b) const /// than computing the inverse in one-shot cases. b2Vec2 b2Mat33::Solve22(const b2Vec2& b) const { - float32 a11 = col1.x, a12 = col2.x, a21 = col1.y, a22 = col2.y; + float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; float32 det = a11 * a22 - a12 * a21; if (det != 0.0f) { diff --git a/src/modules/physics/box2d/Box2D/Common/b2Math.h b/src/modules/physics/box2d/Box2D/Common/b2Math.h old mode 100644 new mode 100755 index c29f59430..fdcd939de --- a/src/modules/physics/box2d/Box2D/Common/b2Math.h +++ b/src/modules/physics/box2d/Box2D/Common/b2Math.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -57,13 +57,8 @@ inline float32 b2InvSqrt(float32 x) return x; } -#define b2Sqrt(x) sqrtf(x) -#define b2Atan2(y, x) atan2f(y, x) - -inline float32 b2Abs(float32 a) -{ - return a > 0.0f ? a : -a; -} +#define b2Sqrt(x) std::sqrt(x) +#define b2Atan2(y, x) std::atan2(y, x) /// A 2D column vector. struct b2Vec2 @@ -147,6 +142,12 @@ struct b2Vec2 return b2IsValid(x) && b2IsValid(y); } + /// Get the skew vector such that dot(skew_vec, other) == cross(vec, other) + b2Vec2 Skew() const + { + return b2Vec2(-y, x); + } + float32 x, y; }; @@ -198,75 +199,49 @@ struct b2Mat22 /// Construct this matrix using columns. b2Mat22(const b2Vec2& c1, const b2Vec2& c2) { - col1 = c1; - col2 = c2; + ex = c1; + ey = c2; } /// Construct this matrix using scalars. b2Mat22(float32 a11, float32 a12, float32 a21, float32 a22) { - col1.x = a11; col1.y = a21; - col2.x = a12; col2.y = a22; - } - - /// Construct this matrix using an angle. This matrix becomes - /// an orthonormal rotation matrix. - explicit b2Mat22(float32 angle) - { - // TODO_ERIN compute sin+cos together. - float32 c = cosf(angle), s = sinf(angle); - col1.x = c; col2.x = -s; - col1.y = s; col2.y = c; + ex.x = a11; ex.y = a21; + ey.x = a12; ey.y = a22; } /// Initialize this matrix using columns. void Set(const b2Vec2& c1, const b2Vec2& c2) { - col1 = c1; - col2 = c2; - } - - /// Initialize this matrix using an angle. This matrix becomes - /// an orthonormal rotation matrix. - void Set(float32 angle) - { - float32 c = cosf(angle), s = sinf(angle); - col1.x = c; col2.x = -s; - col1.y = s; col2.y = c; + ex = c1; + ey = c2; } /// Set this to the identity matrix. void SetIdentity() { - col1.x = 1.0f; col2.x = 0.0f; - col1.y = 0.0f; col2.y = 1.0f; + ex.x = 1.0f; ey.x = 0.0f; + ex.y = 0.0f; ey.y = 1.0f; } /// Set this matrix to all zeros. void SetZero() { - col1.x = 0.0f; col2.x = 0.0f; - col1.y = 0.0f; col2.y = 0.0f; - } - - /// Extract the angle from this matrix (assumed to be - /// a rotation matrix). - float32 GetAngle() const - { - return b2Atan2(col1.y, col1.x); + ex.x = 0.0f; ey.x = 0.0f; + ex.y = 0.0f; ey.y = 0.0f; } b2Mat22 GetInverse() const { - float32 a = col1.x, b = col2.x, c = col1.y, d = col2.y; + float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; b2Mat22 B; float32 det = a * d - b * c; if (det != 0.0f) { det = 1.0f / det; } - B.col1.x = det * d; B.col2.x = -det * b; - B.col1.y = -det * c; B.col2.y = det * a; + B.ex.x = det * d; B.ey.x = -det * b; + B.ex.y = -det * c; B.ey.y = det * a; return B; } @@ -274,7 +249,7 @@ struct b2Mat22 /// than computing the inverse in one-shot cases. b2Vec2 Solve(const b2Vec2& b) const { - float32 a11 = col1.x, a12 = col2.x, a21 = col1.y, a22 = col2.y; + float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; float32 det = a11 * a22 - a12 * a21; if (det != 0.0f) { @@ -286,7 +261,7 @@ struct b2Mat22 return x; } - b2Vec2 col1, col2; + b2Vec2 ex, ey; }; /// A 3-by-3 matrix. Stored in column-major order. @@ -298,17 +273,17 @@ struct b2Mat33 /// Construct this matrix using columns. b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3) { - col1 = c1; - col2 = c2; - col3 = c3; + ex = c1; + ey = c2; + ez = c3; } /// Set this matrix to all zeros. void SetZero() { - col1.SetZero(); - col2.SetZero(); - col3.SetZero(); + ex.SetZero(); + ey.SetZero(); + ez.SetZero(); } /// Solve A * x = b, where b is a column vector. This is more efficient @@ -320,41 +295,85 @@ struct b2Mat33 /// 2-by-2 matrix equation. b2Vec2 Solve22(const b2Vec2& b) const; - b2Vec3 col1, col2, col3; + b2Vec3 ex, ey, ez; +}; + +/// Rotation +struct b2Rot +{ + b2Rot() {} + + /// Initialize from an angle in radians + explicit b2Rot(float32 angle) + { + /// TODO_ERIN optimize + s = sinf(angle); + c = cosf(angle); + } + + /// Set using an angle in radians. + void Set(float32 angle) + { + /// TODO_ERIN optimize + s = sinf(angle); + c = cosf(angle); + } + + /// Set to the identity rotation + void SetIdentity() + { + s = 0.0f; + c = 1.0f; + } + + /// Get the angle in radians + float32 GetAngle() const + { + return b2Atan2(s, c); + } + + /// Get the x-axis + b2Vec2 GetXAxis() const + { + return b2Vec2(c, s); + } + + /// Get the u-axis + b2Vec2 GetYAxis() const + { + return b2Vec2(-s, c); + } + + /// Sine and cosine + float32 s, c; }; /// A transform contains translation and rotation. It is used to represent /// the position and orientation of rigid frames. struct b2Transform { - /// The default constructor does nothing (for performance). + /// The default constructor does nothing. b2Transform() {} - /// Initialize using a position vector and a rotation matrix. - b2Transform(const b2Vec2& position, const b2Mat22& R) : position(position), R(R) {} + /// Initialize using a position vector and a rotation. + b2Transform(const b2Vec2& position, const b2Rot& rotation) : p(position), q(rotation) {} /// Set this to the identity transform. void SetIdentity() { - position.SetZero(); - R.SetIdentity(); + p.SetZero(); + q.SetIdentity(); } /// Set this based on the position and angle. - void Set(const b2Vec2& p, float32 angle) + void Set(const b2Vec2& position, float32 angle) { - position = p; - R.Set(angle); + p = position; + q.Set(angle); } - /// Calculate the angle that the rotation matrix represents. - float32 GetAngle() const - { - return b2Atan2(R.col1.y, R.col1.x); - } - - b2Vec2 position; - b2Mat22 R; + b2Vec2 p; + b2Rot q; }; /// This describes the motion of a body/shape for TOI computation. @@ -364,12 +383,12 @@ struct b2Transform struct b2Sweep { /// Get the interpolated transform at a specific time. - /// @param alpha is a factor in [0,1], where 0 indicates t0. - void GetTransform(b2Transform* xf, float32 alpha) const; + /// @param beta is a factor in [0,1], where 0 indicates alpha0. + void GetTransform(b2Transform* xfb, float32 beta) const; /// Advance the sweep forward, yielding a new initial state. - /// @param t the new initial time. - void Advance(float32 t); + /// @param alpha the new initial time. + void Advance(float32 alpha); /// Normalize the angles. void Normalize(); @@ -377,12 +396,14 @@ struct b2Sweep b2Vec2 localCenter; ///< local center of mass position b2Vec2 c0, c; ///< center world positions float32 a0, a; ///< world angles + + /// Fraction of the current time step in the range [0,1] + /// c0 and a0 are the positions at alpha0. + float32 alpha0; }; - +/// Useful constant extern const b2Vec2 b2Vec2_zero; -extern const b2Mat22 b2Mat22_identity; -extern const b2Transform b2Transform_identity; /// Perform the dot product on two vectors. inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b) @@ -414,14 +435,14 @@ inline b2Vec2 b2Cross(float32 s, const b2Vec2& a) /// then this transforms the vector from one frame to another. inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v) { - return b2Vec2(A.col1.x * v.x + A.col2.x * v.y, A.col1.y * v.x + A.col2.y * v.y); + return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); } /// Multiply a matrix transpose times a vector. If a rotation matrix is provided, /// then this transforms the vector from one frame to another (inverse transform). inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v) { - return b2Vec2(b2Dot(v, A.col1), b2Dot(v, A.col2)); + return b2Vec2(b2Dot(v, A.ex), b2Dot(v, A.ey)); } /// Add two vectors component-wise. @@ -489,40 +510,109 @@ inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b) inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B) { - return b2Mat22(A.col1 + B.col1, A.col2 + B.col2); + return b2Mat22(A.ex + B.ex, A.ey + B.ey); } // A * B inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B) { - return b2Mat22(b2Mul(A, B.col1), b2Mul(A, B.col2)); + return b2Mat22(b2Mul(A, B.ex), b2Mul(A, B.ey)); } // A^T * B inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B) { - b2Vec2 c1(b2Dot(A.col1, B.col1), b2Dot(A.col2, B.col1)); - b2Vec2 c2(b2Dot(A.col1, B.col2), b2Dot(A.col2, B.col2)); + b2Vec2 c1(b2Dot(A.ex, B.ex), b2Dot(A.ey, B.ex)); + b2Vec2 c2(b2Dot(A.ex, B.ey), b2Dot(A.ey, B.ey)); return b2Mat22(c1, c2); } /// Multiply a matrix times a vector. inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v) { - return v.x * A.col1 + v.y * A.col2 + v.z * A.col3; + return v.x * A.ex + v.y * A.ey + v.z * A.ez; +} + +/// Multiply two rotations: q * r +inline b2Rot b2Mul(const b2Rot& q, const b2Rot& r) +{ + // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] + // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] + // s = qs * rc + qc * rs + // c = qc * rc - qs * rs + b2Rot qr; + qr.s = q.s * r.c + q.c * r.s; + qr.c = q.c * r.c - q.s * r.s; + return qr; +} + +/// Transpose multiply two rotations: qT * r +inline b2Rot b2MulT(const b2Rot& q, const b2Rot& r) +{ + // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] + // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] + // s = qc * rs - qs * rc + // c = qc * rc + qs * rs + b2Rot qr; + qr.s = q.c * r.s - q.s * r.c; + qr.c = q.c * r.c + q.s * r.s; + return qr; +} + +/// Rotate a vector +inline b2Vec2 b2Mul(const b2Rot& q, const b2Vec2& v) +{ + return b2Vec2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y); +} + +/// Inverse rotate a vector +inline b2Vec2 b2MulT(const b2Rot& q, const b2Vec2& v) +{ + return b2Vec2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y); } inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v) { - float32 x = T.position.x + T.R.col1.x * v.x + T.R.col2.x * v.y; - float32 y = T.position.y + T.R.col1.y * v.x + T.R.col2.y * v.y; + float32 x = (T.q.c * v.x - T.q.s * v.y) + T.p.x; + float32 y = (T.q.s * v.x + T.q.c * v.y) + T.p.y; return b2Vec2(x, y); } inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v) { - return b2MulT(T.R, v - T.position); + float32 px = v.x - T.p.x; + float32 py = v.y - T.p.y; + float32 x = (T.q.c * px + T.q.s * py); + float32 y = (-T.q.s * px + T.q.c * py); + + return b2Vec2(x, y); +} + +// v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p +// = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p +inline b2Transform b2Mul(const b2Transform& A, const b2Transform& B) +{ + b2Transform C; + C.q = b2Mul(A.q, B.q); + C.p = b2Mul(A.q, B.p) + A.p; + return C; +} + +// v2 = A.q' * (B.q * v1 + B.p - A.p) +// = A.q' * B.q * v1 + A.q' * (B.p - A.p) +inline b2Transform b2MulT(const b2Transform& A, const b2Transform& B) +{ + b2Transform C; + C.q = b2MulT(A.q, B.q); + C.p = b2MulT(A.q, B.p - A.p); + return C; +} + +template +inline T b2Abs(T a) +{ + return a > T(0) ? a : -a; } inline b2Vec2 b2Abs(const b2Vec2& a) @@ -532,7 +622,7 @@ inline b2Vec2 b2Abs(const b2Vec2& a) inline b2Mat22 b2Abs(const b2Mat22& A) { - return b2Mat22(b2Abs(A.col1), b2Abs(A.col2)); + return b2Mat22(b2Abs(A.ex), b2Abs(A.ey)); } template @@ -596,20 +686,23 @@ inline bool b2IsPowerOfTwo(uint32 x) return result; } -inline void b2Sweep::GetTransform(b2Transform* xf, float32 alpha) const +inline void b2Sweep::GetTransform(b2Transform* xf, float32 beta) const { - xf->position = (1.0f - alpha) * c0 + alpha * c; - float32 angle = (1.0f - alpha) * a0 + alpha * a; - xf->R.Set(angle); + xf->p = (1.0f - beta) * c0 + beta * c; + float32 angle = (1.0f - beta) * a0 + beta * a; + xf->q.Set(angle); // Shift to origin - xf->position -= b2Mul(xf->R, localCenter); + xf->p -= b2Mul(xf->q, localCenter); } -inline void b2Sweep::Advance(float32 t) +inline void b2Sweep::Advance(float32 alpha) { - c0 = (1.0f - t) * c0 + t * c; - a0 = (1.0f - t) * a0 + t * a; + b2Assert(alpha0 < 1.0f); + float32 beta = (alpha - alpha0) / (1.0f - alpha0); + c0 = (1.0f - beta) * c0 + beta * c; + a0 = (1.0f - beta) * a0 + beta * a; + alpha0 = alpha; } /// Normalize an angle in radians to be between -pi and pi diff --git a/src/modules/physics/box2d/Box2D/Common/b2Settings.cpp b/src/modules/physics/box2d/Box2D/Common/b2Settings.cpp old mode 100644 new mode 100755 index da308149f..97f5283f4 --- a/src/modules/physics/box2d/Box2D/Common/b2Settings.cpp +++ b/src/modules/physics/box2d/Box2D/Common/b2Settings.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -19,7 +19,7 @@ #include #include -b2Version b2_version = {2, 1, 2}; +b2Version b2_version = {2, 2, 0}; // Memory allocators. Modify these to use your own allocator. void* b2Alloc(int32 size) diff --git a/src/modules/physics/box2d/Box2D/Common/b2Settings.h b/src/modules/physics/box2d/Box2D/Common/b2Settings.h old mode 100644 new mode 100755 index 1aa8c2661..eabc526d0 --- a/src/modules/physics/box2d/Box2D/Common/b2Settings.h +++ b/src/modules/physics/box2d/Box2D/Common/b2Settings.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -32,6 +32,7 @@ typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned int uint32; typedef float float32; +typedef double float64; #define b2_maxFloat FLT_MAX #define b2_epsilon FLT_EPSILON @@ -43,10 +44,12 @@ typedef float float32; // Collision -/// The maximum number of contact points between two convex shapes. +/// The maximum number of contact points between two convex shapes. Do +/// not change this value. #define b2_maxManifoldPoints 2 -/// The maximum number of vertices on a convex polygon. +/// The maximum number of vertices on a convex polygon. You cannot increase +/// this too much because b2BlockAllocator has a maximum object size. #define b2_maxPolygonVertices 8 /// This is used to fatten AABBs in the dynamic tree. This allows proxies @@ -72,6 +75,9 @@ typedef float float32; /// Making it larger may create artifacts for vertex collision. #define b2_polygonRadius (2.0f * b2_linearSlop) +/// Maximum number of sub-steps per contact in continuous physics simulation. +#define b2_maxSubSteps 8 + // Dynamics @@ -103,7 +109,9 @@ typedef float float32; /// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so /// that overlap is removed in one time step. However using values close to 1 often lead /// to overshoot. -#define b2_contactBaumgarte 0.2f +#define b2_baumgarte 0.2f +#define b2_toiBaugarte 0.75f + // Sleep @@ -136,16 +144,4 @@ struct b2Version /// Current version. extern b2Version b2_version; -/// Friction mixing law. Feel free to customize this. -inline float32 b2MixFriction(float32 friction1, float32 friction2) -{ - return sqrtf(friction1 * friction2); -} - -/// Restitution mixing law. Feel free to customize this. -inline float32 b2MixRestitution(float32 restitution1, float32 restitution2) -{ - return restitution1 > restitution2 ? restitution1 : restitution2; -} - #endif diff --git a/src/modules/physics/box2d/Box2D/Common/b2StackAllocator.cpp b/src/modules/physics/box2d/Box2D/Common/b2StackAllocator.cpp old mode 100644 new mode 100755 index cb2c42e01..4a862835b --- a/src/modules/physics/box2d/Box2D/Common/b2StackAllocator.cpp +++ b/src/modules/physics/box2d/Box2D/Common/b2StackAllocator.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages diff --git a/src/modules/physics/box2d/Box2D/Common/b2StackAllocator.h b/src/modules/physics/box2d/Box2D/Common/b2StackAllocator.h old mode 100644 new mode 100755 index 315cc02ff..796c51dfd --- a/src/modules/physics/box2d/Box2D/Common/b2StackAllocator.h +++ b/src/modules/physics/box2d/Box2D/Common/b2StackAllocator.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages diff --git a/src/modules/physics/box2d/Box2D/Common/b2Timer.cpp b/src/modules/physics/box2d/Box2D/Common/b2Timer.cpp new file mode 100755 index 000000000..b1863c296 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Common/b2Timer.cpp @@ -0,0 +1,100 @@ +/* +* Copyright (c) 2011 Erin Catto http://box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +#if defined(WIN32) + +float64 b2Timer::s_invFrequency = 0.0f; + +#include + +b2Timer::b2Timer() +{ + LARGE_INTEGER largeInteger; + + if (s_invFrequency == 0.0f) + { + QueryPerformanceFrequency(&largeInteger); + s_invFrequency = float64(largeInteger.QuadPart); + if (s_invFrequency > 0.0f) + { + s_invFrequency = 1000.0f / s_invFrequency; + } + } + + QueryPerformanceCounter(&largeInteger); + m_start = float64(largeInteger.QuadPart); +} + +void b2Timer::Reset() +{ + LARGE_INTEGER largeInteger; + QueryPerformanceCounter(&largeInteger); + m_start = float64(largeInteger.QuadPart); +} + +float32 b2Timer::GetMilliseconds() const +{ + LARGE_INTEGER largeInteger; + QueryPerformanceCounter(&largeInteger); + float64 count = float64(largeInteger.QuadPart); + float32 ms = float32(s_invFrequency * (count - m_start)); + return ms; +} + +#elif defined(__linux__) || defined (__APPLE__) + +#include + +b2Timer::b2Timer() +{ + Reset(); +} + +void b2Timer::Reset() +{ + timeval t; + gettimeofday(&t, 0); + m_start_sec = t.tv_sec; + m_start_msec = t.tv_usec * 0.001f; +} + +float32 b2Timer::GetMilliseconds() const +{ + timeval t; + gettimeofday(&t, 0); + return (t.tv_sec - m_start_sec) * 1000 + t.tv_usec * 0.001f - m_start_msec; +} + +#else + +b2Timer::b2Timer() +{ +} + +void b2Timer::Reset() +{ +} + +float32 b2Timer::GetMilliseconds() const +{ + return 0.0f; +} + +#endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.h b/src/modules/physics/box2d/Box2D/Common/b2Timer.h old mode 100644 new mode 100755 similarity index 54% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.h rename to src/modules/physics/box2d/Box2D/Common/b2Timer.h index c092e2a81..678f6ffe4 --- a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.h +++ b/src/modules/physics/box2d/Box2D/Common/b2Timer.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2010 Erin Catto http://www.gphysics.com +* Copyright (c) 2011 Erin Catto http://box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -16,36 +16,30 @@ * 3. This notice may not be removed or altered from any source distribution. */ -#ifndef B2_TOI_SOLVER_H -#define B2_TOI_SOLVER_H +#include -#include - -class b2Contact; -class b2Body; -struct b2TOIConstraint; -class b2StackAllocator; - -/// This is a pure position solver for a single movable body in contact with -/// multiple non-moving bodies. -class b2TOISolver +/// Timer for profiling. This has platform specific code and may +/// not work on every platform. +class b2Timer { public: - b2TOISolver(b2StackAllocator* allocator); - ~b2TOISolver(); - void Initialize(b2Contact** contacts, int32 contactCount, b2Body* toiBody); - void Clear(); + /// Constructor + b2Timer(); - // Perform one solver iteration. Returns true if converged. - bool Solve(float32 baumgarte); + /// Reset the timer. + void Reset(); + + /// Get the time since construction or the last reset. + float32 GetMilliseconds() const; private: - b2TOIConstraint* m_constraints; - int32 m_count; - b2Body* m_toiBody; - b2StackAllocator* m_allocator; -}; - +#if defined(WIN32) + float64 m_start; + static float64 s_invFrequency; +#elif defined(__linux__) || defined (__APPLE__) + unsigned long m_start_sec; + unsigned long m_start_msec; #endif +}; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp new file mode 100755 index 000000000..3886dfd70 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2ChainAndCircleContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2ChainAndCircleContact)); + return new (mem) b2ChainAndCircleContact(fixtureA, indexA, fixtureB, indexB); +} + +void b2ChainAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2ChainAndCircleContact*)contact)->~b2ChainAndCircleContact(); + allocator->Free(contact, sizeof(b2ChainAndCircleContact)); +} + +b2ChainAndCircleContact::b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB) +: b2Contact(fixtureA, indexA, fixtureB, indexB) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); +} + +void b2ChainAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); + b2EdgeShape edge; + chain->GetChildEdge(&edge, m_indexA); + b2CollideEdgeAndCircle( manifold, &edge, xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h new file mode 100755 index 000000000..2dad0b64f --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CHAIN_AND_CIRCLE_CONTACT_H +#define B2_CHAIN_AND_CIRCLE_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2ChainAndCircleContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); + ~b2ChainAndCircleContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp new file mode 100755 index 000000000..02bcaaf6a --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2ChainAndPolygonContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2ChainAndPolygonContact)); + return new (mem) b2ChainAndPolygonContact(fixtureA, indexA, fixtureB, indexB); +} + +void b2ChainAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2ChainAndPolygonContact*)contact)->~b2ChainAndPolygonContact(); + allocator->Free(contact, sizeof(b2ChainAndPolygonContact)); +} + +b2ChainAndPolygonContact::b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB) +: b2Contact(fixtureA, indexA, fixtureB, indexB) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); + b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); +} + +void b2ChainAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); + b2EdgeShape edge; + chain->GetChildEdge(&edge, m_indexA); + b2CollideEdgeAndPolygon( manifold, &edge, xfA, + (b2PolygonShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h new file mode 100755 index 000000000..8f30ee867 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CHAIN_AND_POLYGON_CONTACT_H +#define B2_CHAIN_AND_POLYGON_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2ChainAndPolygonContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); + ~b2ChainAndPolygonContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.cpp old mode 100644 new mode 100755 index 6df009125..584ef2f1f --- a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -24,8 +24,9 @@ #include #include +using namespace std; -b2Contact* b2CircleContact::Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator) +b2Contact* b2CircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) { void* mem = allocator->Allocate(sizeof(b2CircleContact)); return new (mem) b2CircleContact(fixtureA, fixtureB); @@ -38,7 +39,7 @@ void b2CircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) } b2CircleContact::b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) - : b2Contact(fixtureA, fixtureB) + : b2Contact(fixtureA, 0, fixtureB, 0) { b2Assert(m_fixtureA->GetType() == b2Shape::e_circle); b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.h old mode 100644 new mode 100755 index afc277aa0..aac1f0bd6 --- a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -26,7 +26,8 @@ class b2BlockAllocator; class b2CircleContact : public b2Contact { public: - static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator); + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp old mode 100644 new mode 100755 index e7ad1ca5b..557af7f08 --- a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -20,6 +20,10 @@ #include #include #include +#include +#include +#include +#include #include #include @@ -38,13 +42,17 @@ void b2Contact::InitializeRegisters() AddType(b2CircleContact::Create, b2CircleContact::Destroy, b2Shape::e_circle, b2Shape::e_circle); AddType(b2PolygonAndCircleContact::Create, b2PolygonAndCircleContact::Destroy, b2Shape::e_polygon, b2Shape::e_circle); AddType(b2PolygonContact::Create, b2PolygonContact::Destroy, b2Shape::e_polygon, b2Shape::e_polygon); + AddType(b2EdgeAndCircleContact::Create, b2EdgeAndCircleContact::Destroy, b2Shape::e_edge, b2Shape::e_circle); + AddType(b2EdgeAndPolygonContact::Create, b2EdgeAndPolygonContact::Destroy, b2Shape::e_edge, b2Shape::e_polygon); + AddType(b2ChainAndCircleContact::Create, b2ChainAndCircleContact::Destroy, b2Shape::e_chain, b2Shape::e_circle); + AddType(b2ChainAndPolygonContact::Create, b2ChainAndPolygonContact::Destroy, b2Shape::e_chain, b2Shape::e_polygon); } void b2Contact::AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destoryFcn, b2Shape::Type type1, b2Shape::Type type2) { - b2Assert(b2Shape::e_unknown < type1 && type1 < b2Shape::e_typeCount); - b2Assert(b2Shape::e_unknown < type2 && type2 < b2Shape::e_typeCount); + b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); + b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); s_registers[type1][type2].createFcn = createFcn; s_registers[type1][type2].destroyFcn = destoryFcn; @@ -58,7 +66,7 @@ void b2Contact::AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* dest } } -b2Contact* b2Contact::Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator) +b2Contact* b2Contact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) { if (s_initialized == false) { @@ -69,19 +77,19 @@ b2Contact* b2Contact::Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAl b2Shape::Type type1 = fixtureA->GetType(); b2Shape::Type type2 = fixtureB->GetType(); - b2Assert(b2Shape::e_unknown < type1 && type1 < b2Shape::e_typeCount); - b2Assert(b2Shape::e_unknown < type2 && type2 < b2Shape::e_typeCount); + b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); + b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); b2ContactCreateFcn* createFcn = s_registers[type1][type2].createFcn; if (createFcn) { if (s_registers[type1][type2].primary) { - return createFcn(fixtureA, fixtureB, allocator); + return createFcn(fixtureA, indexA, fixtureB, indexB, allocator); } else { - return createFcn(fixtureB, fixtureA, allocator); + return createFcn(fixtureB, indexB, fixtureA, indexA, allocator); } } else @@ -103,20 +111,23 @@ void b2Contact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) b2Shape::Type typeA = contact->GetFixtureA()->GetType(); b2Shape::Type typeB = contact->GetFixtureB()->GetType(); - b2Assert(b2Shape::e_unknown < typeA && typeB < b2Shape::e_typeCount); - b2Assert(b2Shape::e_unknown < typeA && typeB < b2Shape::e_typeCount); + b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); + b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); b2ContactDestroyFcn* destroyFcn = s_registers[typeA][typeB].destroyFcn; destroyFcn(contact, allocator); } -b2Contact::b2Contact(b2Fixture* fA, b2Fixture* fB) +b2Contact::b2Contact(b2Fixture* fA, int32 indexA, b2Fixture* fB, int32 indexB) { m_flags = e_enabledFlag; m_fixtureA = fA; m_fixtureB = fB; + m_indexA = indexA; + m_indexB = indexB; + m_manifold.pointCount = 0; m_prev = NULL; @@ -133,6 +144,9 @@ b2Contact::b2Contact(b2Fixture* fA, b2Fixture* fB) m_nodeB.other = NULL; m_toiCount = 0; + + m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); + m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); } // Update the contact manifold and touching status. @@ -161,7 +175,7 @@ void b2Contact::Update(b2ContactListener* listener) { const b2Shape* shapeA = m_fixtureA->GetShape(); const b2Shape* shapeB = m_fixtureB->GetShape(); - touching = b2TestOverlap(shapeA, shapeB, xfA, xfB); + touching = b2TestOverlap(shapeA, m_indexA, shapeB, m_indexB, xfA, xfB); // Sensors don't generate manifolds. m_manifold.pointCount = 0; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.h old mode 100644 new mode 100755 index a6add3dc4..7b5a6ab88 --- a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -22,7 +22,6 @@ #include #include #include -#include #include class b2Body; @@ -33,7 +32,23 @@ class b2BlockAllocator; class b2StackAllocator; class b2ContactListener; -typedef b2Contact* b2ContactCreateFcn(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator); +/// Friction mixing law. The idea is to allow either fixture to drive the restitution to zero. +/// For example, anything slides on ice. +inline float32 b2MixFriction(float32 friction1, float32 friction2) +{ + return std::sqrt(friction1 * friction2); +} + +/// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. +/// For example, a superball bounces on anything. +inline float32 b2MixRestitution(float32 restitution1, float32 restitution2) +{ + return restitution1 > restitution2 ? restitution1 : restitution2; +} + +typedef b2Contact* b2ContactCreateFcn( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, + b2BlockAllocator* allocator); typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator); struct b2ContactRegister @@ -86,14 +101,40 @@ public: b2Contact* GetNext(); const b2Contact* GetNext() const; - /// Get the first fixture in this contact. + /// Get fixture A in this contact. b2Fixture* GetFixtureA(); const b2Fixture* GetFixtureA() const; - /// Get the second fixture in this contact. + /// Get the child primitive index for fixture A. + int32 GetChildIndexA() const; + + /// Get fixture B in this contact. b2Fixture* GetFixtureB(); const b2Fixture* GetFixtureB() const; + /// Get the child primitive index for fixture B. + int32 GetChildIndexB() const; + + /// Override the default friction mixture. You can call this in b2ContactListener::PreSolve. + /// This value persists until set or reset. + void SetFriction(float32 friction); + + /// Get the friction. + float32 GetFriction() const; + + /// Reset the friction mixture to the default value. + void ResetFriction(); + + /// Override the default restitution mixture. You can call this in b2ContactListener::PreSolve. + /// The value persists until you set or reset. + void SetRestitution(float32 restitution); + + /// Get the restitution. + float32 GetRestitution() const; + + /// Reset the restitution to the default value. + void ResetRestitution(); + /// Evaluate this contact with your own manifold and transforms. virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) = 0; @@ -122,6 +163,8 @@ protected: // This bullet contact had a TOI event e_bulletHitFlag = 0x0010, + // This contact has a valid TOI in m_toi + e_toiFlag = 0x0020 }; /// Flag this contact for filtering. Filtering will occur the next time step. @@ -130,12 +173,12 @@ protected: static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn, b2Shape::Type typeA, b2Shape::Type typeB); static void InitializeRegisters(); - static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator); + static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::Type typeB, b2BlockAllocator* allocator); static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); b2Contact() : m_fixtureA(NULL), m_fixtureB(NULL) {} - b2Contact(b2Fixture* fixtureA, b2Fixture* fixtureB); + b2Contact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); virtual ~b2Contact() {} void Update(b2ContactListener* listener); @@ -156,10 +199,16 @@ protected: b2Fixture* m_fixtureA; b2Fixture* m_fixtureB; + int32 m_indexA; + int32 m_indexB; + b2Manifold m_manifold; int32 m_toiCount; -// float32 m_toi; + float32 m_toi; + + float32 m_friction; + float32 m_restitution; }; inline b2Manifold* b2Contact::GetManifold() @@ -229,14 +278,54 @@ inline b2Fixture* b2Contact::GetFixtureB() return m_fixtureB; } +inline int32 b2Contact::GetChildIndexA() const +{ + return m_indexA; +} + inline const b2Fixture* b2Contact::GetFixtureB() const { return m_fixtureB; } +inline int32 b2Contact::GetChildIndexB() const +{ + return m_indexB; +} + inline void b2Contact::FlagForFiltering() { m_flags |= e_filterFlag; } +inline void b2Contact::SetFriction(float32 friction) +{ + m_friction = friction; +} + +inline float32 b2Contact::GetFriction() const +{ + return m_friction; +} + +inline void b2Contact::ResetFriction() +{ + m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); +} + +inline void b2Contact::SetRestitution(float32 restitution) +{ + m_restitution = restitution; +} + +inline float32 b2Contact::GetRestitution() const +{ + return m_restitution; +} + +inline void b2Contact::ResetRestitution() +{ + m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); +} + #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.cpp old mode 100644 new mode 100755 index f65fb60ee..c990d7fb8 --- a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -17,6 +17,7 @@ */ #include + #include #include #include @@ -25,17 +26,36 @@ #define B2_DEBUG_SOLVER 0 -b2ContactSolver::b2ContactSolver(b2Contact** contacts, int32 contactCount, - b2StackAllocator* allocator, float32 impulseRatio) +struct b2ContactPositionConstraint { - m_allocator = allocator; + b2Vec2 localPoints[b2_maxManifoldPoints]; + b2Vec2 localNormal; + b2Vec2 localPoint; + int32 indexA; + int32 indexB; + float32 invMassA, invMassB; + b2Vec2 localCenterA, localCenterB; + float32 invIA, invIB; + b2Manifold::Type type; + float32 radiusA, radiusB; + int32 pointCount; +}; - m_constraintCount = contactCount; - m_constraints = (b2ContactConstraint*)m_allocator->Allocate(m_constraintCount * sizeof(b2ContactConstraint)); +b2ContactSolver::b2ContactSolver(b2ContactSolverDef* def) +{ + m_step = def->step; + m_allocator = def->allocator; + m_count = def->count; + m_positionConstraints = (b2ContactPositionConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactPositionConstraint)); + m_velocityConstraints = (b2ContactVelocityConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactVelocityConstraint)); + m_positions = def->positions; + m_velocities = def->velocities; + m_contacts = def->contacts; - for (int32 i = 0; i < m_constraintCount; ++i) + // Initialize position independent portions of the constraints. + for (int32 i = 0; i < m_count; ++i) { - b2Contact* contact = contacts[i]; + b2Contact* contact = m_contacts[i]; b2Fixture* fixtureA = contact->m_fixtureA; b2Fixture* fixtureB = contact->m_fixtureB; @@ -47,222 +67,302 @@ b2ContactSolver::b2ContactSolver(b2Contact** contacts, int32 contactCount, b2Body* bodyB = fixtureB->GetBody(); b2Manifold* manifold = contact->GetManifold(); - float32 friction = b2MixFriction(fixtureA->GetFriction(), fixtureB->GetFriction()); - float32 restitution = b2MixRestitution(fixtureA->GetRestitution(), fixtureB->GetRestitution()); + int32 pointCount = manifold->pointCount; + b2Assert(pointCount > 0); - b2Vec2 vA = bodyA->m_linearVelocity; - b2Vec2 vB = bodyB->m_linearVelocity; - float32 wA = bodyA->m_angularVelocity; - float32 wB = bodyB->m_angularVelocity; + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + vc->friction = contact->m_friction; + vc->restitution = contact->m_restitution; + vc->indexA = bodyA->m_islandIndex; + vc->indexB = bodyB->m_islandIndex; + vc->invMassA = bodyA->m_invMass; + vc->invMassB = bodyB->m_invMass; + vc->invIA = bodyA->m_invI; + vc->invIB = bodyB->m_invI; + vc->contactIndex = i; + vc->pointCount = pointCount; + vc->K.SetZero(); + vc->normalMass.SetZero(); - b2Assert(manifold->pointCount > 0); + b2ContactPositionConstraint* pc = m_positionConstraints + i; + pc->indexA = bodyA->m_islandIndex; + pc->indexB = bodyB->m_islandIndex; + pc->invMassA = bodyA->m_invMass; + pc->invMassB = bodyB->m_invMass; + pc->localCenterA = bodyA->m_sweep.localCenter; + pc->localCenterB = bodyB->m_sweep.localCenter; + pc->invIA = bodyA->m_invI; + pc->invIB = bodyB->m_invI; + pc->localNormal = manifold->localNormal; + pc->localPoint = manifold->localPoint; + pc->pointCount = pointCount; + pc->radiusA = radiusA; + pc->radiusB = radiusB; + pc->type = manifold->type; - b2WorldManifold worldManifold; - worldManifold.Initialize(manifold, bodyA->m_xf, radiusA, bodyB->m_xf, radiusB); - - b2ContactConstraint* cc = m_constraints + i; - cc->bodyA = bodyA; - cc->bodyB = bodyB; - cc->manifold = manifold; - cc->normal = worldManifold.normal; - cc->pointCount = manifold->pointCount; - cc->friction = friction; - - cc->localNormal = manifold->localNormal; - cc->localPoint = manifold->localPoint; - cc->radius = radiusA + radiusB; - cc->type = manifold->type; - - for (int32 j = 0; j < cc->pointCount; ++j) + for (int32 j = 0; j < pointCount; ++j) { b2ManifoldPoint* cp = manifold->points + j; - b2ContactConstraintPoint* ccp = cc->points + j; - - ccp->normalImpulse = impulseRatio * cp->normalImpulse; - ccp->tangentImpulse = impulseRatio * cp->tangentImpulse; - - ccp->localPoint = cp->localPoint; - - ccp->rA = worldManifold.points[j] - bodyA->m_sweep.c; - ccp->rB = worldManifold.points[j] - bodyB->m_sweep.c; - - float32 rnA = b2Cross(ccp->rA, cc->normal); - float32 rnB = b2Cross(ccp->rB, cc->normal); - rnA *= rnA; - rnB *= rnB; - - float32 kNormal = bodyA->m_invMass + bodyB->m_invMass + bodyA->m_invI * rnA + bodyB->m_invI * rnB; - - b2Assert(kNormal > b2_epsilon); - ccp->normalMass = 1.0f / kNormal; - - b2Vec2 tangent = b2Cross(cc->normal, 1.0f); - - float32 rtA = b2Cross(ccp->rA, tangent); - float32 rtB = b2Cross(ccp->rB, tangent); - rtA *= rtA; - rtB *= rtB; - - float32 kTangent = bodyA->m_invMass + bodyB->m_invMass + bodyA->m_invI * rtA + bodyB->m_invI * rtB; - - b2Assert(kTangent > b2_epsilon); - ccp->tangentMass = 1.0f / kTangent; - - // Setup a velocity bias for restitution. - ccp->velocityBias = 0.0f; - float32 vRel = b2Dot(cc->normal, vB + b2Cross(wB, ccp->rB) - vA - b2Cross(wA, ccp->rA)); - if (vRel < -b2_velocityThreshold) + b2VelocityConstraintPoint* vcp = vc->points + j; + + if (m_step.warmStarting) { - ccp->velocityBias = -restitution * vRel; - } - } - - // If we have two points, then prepare the block solver. - if (cc->pointCount == 2) - { - b2ContactConstraintPoint* ccp1 = cc->points + 0; - b2ContactConstraintPoint* ccp2 = cc->points + 1; - - float32 invMassA = bodyA->m_invMass; - float32 invIA = bodyA->m_invI; - float32 invMassB = bodyB->m_invMass; - float32 invIB = bodyB->m_invI; - - float32 rn1A = b2Cross(ccp1->rA, cc->normal); - float32 rn1B = b2Cross(ccp1->rB, cc->normal); - float32 rn2A = b2Cross(ccp2->rA, cc->normal); - float32 rn2B = b2Cross(ccp2->rB, cc->normal); - - float32 k11 = invMassA + invMassB + invIA * rn1A * rn1A + invIB * rn1B * rn1B; - float32 k22 = invMassA + invMassB + invIA * rn2A * rn2A + invIB * rn2B * rn2B; - float32 k12 = invMassA + invMassB + invIA * rn1A * rn2A + invIB * rn1B * rn2B; - - // Ensure a reasonable condition number. - const float32 k_maxConditionNumber = 100.0f; - if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) - { - // K is safe to invert. - cc->K.col1.Set(k11, k12); - cc->K.col2.Set(k12, k22); - cc->normalMass = cc->K.GetInverse(); + vcp->normalImpulse = m_step.dtRatio * cp->normalImpulse; + vcp->tangentImpulse = m_step.dtRatio * cp->tangentImpulse; } else { - // The constraints are redundant, just use one. - // TODO_ERIN use deepest? - cc->pointCount = 1; + vcp->normalImpulse = 0.0f; + vcp->tangentImpulse = 0.0f; } + + vcp->rA.SetZero(); + vcp->rB.SetZero(); + vcp->normalMass = 0.0f; + vcp->tangentMass = 0.0f; + vcp->velocityBias = 0.0f; + + pc->localPoints[j] = cp->localPoint; } } } b2ContactSolver::~b2ContactSolver() { - m_allocator->Free(m_constraints); + m_allocator->Free(m_velocityConstraints); + m_allocator->Free(m_positionConstraints); +} + +// Initialize position dependent portions of the velocity constraints. +void b2ContactSolver::InitializeVelocityConstraints() +{ + for (int32 i = 0; i < m_count; ++i) + { + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + b2ContactPositionConstraint* pc = m_positionConstraints + i; + + float32 radiusA = pc->radiusA; + float32 radiusB = pc->radiusB; + b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); + + int32 indexA = vc->indexA; + int32 indexB = vc->indexB; + + float32 mA = vc->invMassA; + float32 mB = vc->invMassB; + float32 iA = vc->invIA; + float32 iB = vc->invIB; + b2Vec2 localCenterA = pc->localCenterA; + b2Vec2 localCenterB = pc->localCenterB; + + b2Vec2 cA = m_positions[indexA].c; + float32 aA = m_positions[indexA].a; + b2Vec2 vA = m_velocities[indexA].v; + float32 wA = m_velocities[indexA].w; + + b2Vec2 cB = m_positions[indexB].c; + float32 aB = m_positions[indexB].a; + b2Vec2 vB = m_velocities[indexB].v; + float32 wB = m_velocities[indexB].w; + + b2Assert(manifold->pointCount > 0); + + b2Transform xfA, xfB; + xfA.q.Set(aA); + xfB.q.Set(aB); + xfA.p = cA - b2Mul(xfA.q, localCenterA); + xfB.p = cB - b2Mul(xfB.q, localCenterB); + + b2WorldManifold worldManifold; + worldManifold.Initialize(manifold, xfA, radiusA, xfB, radiusB); + + vc->normal = worldManifold.normal; + + int32 pointCount = vc->pointCount; + for (int32 j = 0; j < pointCount; ++j) + { + b2VelocityConstraintPoint* vcp = vc->points + j; + + vcp->rA = worldManifold.points[j] - cA; + vcp->rB = worldManifold.points[j] - cB; + + float32 rnA = b2Cross(vcp->rA, vc->normal); + float32 rnB = b2Cross(vcp->rB, vc->normal); + + float32 kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; + + vcp->normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; + + b2Vec2 tangent = b2Cross(vc->normal, 1.0f); + + float32 rtA = b2Cross(vcp->rA, tangent); + float32 rtB = b2Cross(vcp->rB, tangent); + + float32 kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; + + vcp->tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; + + // Setup a velocity bias for restitution. + vcp->velocityBias = 0.0f; + float32 vRel = b2Dot(vc->normal, vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA)); + if (vRel < -b2_velocityThreshold) + { + vcp->velocityBias = -vc->restitution * vRel; + } + } + + // If we have two points, then prepare the block solver. + if (vc->pointCount == 2) + { + b2VelocityConstraintPoint* vcp1 = vc->points + 0; + b2VelocityConstraintPoint* vcp2 = vc->points + 1; + + float32 rn1A = b2Cross(vcp1->rA, vc->normal); + float32 rn1B = b2Cross(vcp1->rB, vc->normal); + float32 rn2A = b2Cross(vcp2->rA, vc->normal); + float32 rn2B = b2Cross(vcp2->rB, vc->normal); + + float32 k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; + float32 k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; + float32 k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; + + // Ensure a reasonable condition number. + const float32 k_maxConditionNumber = 1000.0f; + if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) + { + // K is safe to invert. + vc->K.ex.Set(k11, k12); + vc->K.ey.Set(k12, k22); + vc->normalMass = vc->K.GetInverse(); + } + else + { + // The constraints are redundant, just use one. + // TODO_ERIN use deepest? + vc->pointCount = 1; + } + } + } } void b2ContactSolver::WarmStart() { // Warm start. - for (int32 i = 0; i < m_constraintCount; ++i) + for (int32 i = 0; i < m_count; ++i) { - b2ContactConstraint* c = m_constraints + i; + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - b2Body* bodyA = c->bodyA; - b2Body* bodyB = c->bodyB; - float32 invMassA = bodyA->m_invMass; - float32 invIA = bodyA->m_invI; - float32 invMassB = bodyB->m_invMass; - float32 invIB = bodyB->m_invI; - b2Vec2 normal = c->normal; + int32 indexA = vc->indexA; + int32 indexB = vc->indexB; + float32 mA = vc->invMassA; + float32 iA = vc->invIA; + float32 mB = vc->invMassB; + float32 iB = vc->invIB; + int32 pointCount = vc->pointCount; + + b2Vec2 vA = m_velocities[indexA].v; + float32 wA = m_velocities[indexA].w; + b2Vec2 vB = m_velocities[indexB].v; + float32 wB = m_velocities[indexB].w; + + b2Vec2 normal = vc->normal; b2Vec2 tangent = b2Cross(normal, 1.0f); - for (int32 j = 0; j < c->pointCount; ++j) + for (int32 j = 0; j < pointCount; ++j) { - b2ContactConstraintPoint* ccp = c->points + j; - b2Vec2 P = ccp->normalImpulse * normal + ccp->tangentImpulse * tangent; - bodyA->m_angularVelocity -= invIA * b2Cross(ccp->rA, P); - bodyA->m_linearVelocity -= invMassA * P; - bodyB->m_angularVelocity += invIB * b2Cross(ccp->rB, P); - bodyB->m_linearVelocity += invMassB * P; + b2VelocityConstraintPoint* vcp = vc->points + j; + b2Vec2 P = vcp->normalImpulse * normal + vcp->tangentImpulse * tangent; + wA -= iA * b2Cross(vcp->rA, P); + vA -= mA * P; + wB += iB * b2Cross(vcp->rB, P); + vB += mB * P; } + + m_velocities[indexA].v = vA; + m_velocities[indexA].w = wA; + m_velocities[indexB].v = vB; + m_velocities[indexB].w = wB; } } void b2ContactSolver::SolveVelocityConstraints() { - for (int32 i = 0; i < m_constraintCount; ++i) + for (int32 i = 0; i < m_count; ++i) { - b2ContactConstraint* c = m_constraints + i; - b2Body* bodyA = c->bodyA; - b2Body* bodyB = c->bodyB; - float32 wA = bodyA->m_angularVelocity; - float32 wB = bodyB->m_angularVelocity; - b2Vec2 vA = bodyA->m_linearVelocity; - b2Vec2 vB = bodyB->m_linearVelocity; - float32 invMassA = bodyA->m_invMass; - float32 invIA = bodyA->m_invI; - float32 invMassB = bodyB->m_invMass; - float32 invIB = bodyB->m_invI; - b2Vec2 normal = c->normal; + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + + int32 indexA = vc->indexA; + int32 indexB = vc->indexB; + float32 mA = vc->invMassA; + float32 iA = vc->invIA; + float32 mB = vc->invMassB; + float32 iB = vc->invIB; + int32 pointCount = vc->pointCount; + + b2Vec2 vA = m_velocities[indexA].v; + float32 wA = m_velocities[indexA].w; + b2Vec2 vB = m_velocities[indexB].v; + float32 wB = m_velocities[indexB].w; + + b2Vec2 normal = vc->normal; b2Vec2 tangent = b2Cross(normal, 1.0f); - float32 friction = c->friction; + float32 friction = vc->friction; - b2Assert(c->pointCount == 1 || c->pointCount == 2); + b2Assert(pointCount == 1 || pointCount == 2); - // Solve tangent constraints - for (int32 j = 0; j < c->pointCount; ++j) + // Solve tangent constraints first because non-penetration is more important + // than friction. + for (int32 j = 0; j < pointCount; ++j) { - b2ContactConstraintPoint* ccp = c->points + j; + b2VelocityConstraintPoint* vcp = vc->points + j; // Relative velocity at contact - b2Vec2 dv = vB + b2Cross(wB, ccp->rB) - vA - b2Cross(wA, ccp->rA); + b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); // Compute tangent force float32 vt = b2Dot(dv, tangent); - float32 lambda = ccp->tangentMass * (-vt); + float32 lambda = vcp->tangentMass * (-vt); // b2Clamp the accumulated force - float32 maxFriction = friction * ccp->normalImpulse; - float32 newImpulse = b2Clamp(ccp->tangentImpulse + lambda, -maxFriction, maxFriction); - lambda = newImpulse - ccp->tangentImpulse; + float32 maxFriction = friction * vcp->normalImpulse; + float32 newImpulse = b2Clamp(vcp->tangentImpulse + lambda, -maxFriction, maxFriction); + lambda = newImpulse - vcp->tangentImpulse; + vcp->tangentImpulse = newImpulse; // Apply contact impulse b2Vec2 P = lambda * tangent; - vA -= invMassA * P; - wA -= invIA * b2Cross(ccp->rA, P); + vA -= mA * P; + wA -= iA * b2Cross(vcp->rA, P); - vB += invMassB * P; - wB += invIB * b2Cross(ccp->rB, P); - - ccp->tangentImpulse = newImpulse; + vB += mB * P; + wB += iB * b2Cross(vcp->rB, P); } // Solve normal constraints - if (c->pointCount == 1) + if (vc->pointCount == 1) { - b2ContactConstraintPoint* ccp = c->points + 0; + b2VelocityConstraintPoint* vcp = vc->points + 0; // Relative velocity at contact - b2Vec2 dv = vB + b2Cross(wB, ccp->rB) - vA - b2Cross(wA, ccp->rA); + b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); // Compute normal impulse float32 vn = b2Dot(dv, normal); - float32 lambda = -ccp->normalMass * (vn - ccp->velocityBias); + float32 lambda = -vcp->normalMass * (vn - vcp->velocityBias); // b2Clamp the accumulated impulse - float32 newImpulse = b2Max(ccp->normalImpulse + lambda, 0.0f); - lambda = newImpulse - ccp->normalImpulse; + float32 newImpulse = b2Max(vcp->normalImpulse + lambda, 0.0f); + lambda = newImpulse - vcp->normalImpulse; + vcp->normalImpulse = newImpulse; // Apply contact impulse b2Vec2 P = lambda * normal; - vA -= invMassA * P; - wA -= invIA * b2Cross(ccp->rA, P); + vA -= mA * P; + wA -= iA * b2Cross(vcp->rA, P); - vB += invMassB * P; - wB += invIB * b2Cross(ccp->rB, P); - ccp->normalImpulse = newImpulse; + vB += mB * P; + wB += iB * b2Cross(vcp->rB, P); } else { @@ -272,7 +372,7 @@ void b2ContactSolver::SolveVelocityConstraints() // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2 // // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) - // b = vn_0 - velocityBias + // b = vn0 - velocityBias // // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases @@ -284,18 +384,23 @@ void b2ContactSolver::SolveVelocityConstraints() // // Substitute: // - // x = x' - a + // x = a + d // - // Plug into above equation: + // a := old total impulse + // x := new total impulse + // d := incremental impulse // - // vn = A * x + b - // = A * (x' - a) + b - // = A * x' + b - A * a - // = A * x' + b' + // For the current iteration we extend the formula for the incremental impulse + // to compute the new total impulse: + // + // vn = A * d + b + // = A * (x - a) + b + // = A * x + b - A * a + // = A * x + b' // b' = b - A * a; - b2ContactConstraintPoint* cp1 = c->points + 0; - b2ContactConstraintPoint* cp2 = c->points + 1; + b2VelocityConstraintPoint* cp1 = vc->points + 0; + b2VelocityConstraintPoint* cp2 = vc->points + 1; b2Vec2 a(cp1->normalImpulse, cp2->normalImpulse); b2Assert(a.x >= 0.0f && a.y >= 0.0f); @@ -311,7 +416,9 @@ void b2ContactSolver::SolveVelocityConstraints() b2Vec2 b; b.x = vn1 - cp1->velocityBias; b.y = vn2 - cp2->velocityBias; - b -= b2Mul(c->K, a); + + // Compute b' + b -= b2Mul(vc->K, a); const float32 k_errorTol = 1e-3f; B2_NOT_USED(k_errorTol); @@ -321,27 +428,27 @@ void b2ContactSolver::SolveVelocityConstraints() // // Case 1: vn = 0 // - // 0 = A * x' + b' + // 0 = A * x + b' // - // Solve for x': + // Solve for x: // - // x' = - inv(A) * b' + // x = - inv(A) * b' // - b2Vec2 x = - b2Mul(c->normalMass, b); + b2Vec2 x = - b2Mul(vc->normalMass, b); if (x.x >= 0.0f && x.y >= 0.0f) { - // Resubstitute for the incremental impulse + // Get the incremental impulse b2Vec2 d = x - a; // Apply incremental impulse b2Vec2 P1 = d.x * normal; b2Vec2 P2 = d.y * normal; - vA -= invMassA * (P1 + P2); - wA -= invIA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - vB += invMassB * (P1 + P2); - wB += invIB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); // Accumulate cp1->normalImpulse = x.x; @@ -365,27 +472,27 @@ void b2ContactSolver::SolveVelocityConstraints() // // Case 2: vn1 = 0 and x2 = 0 // - // 0 = a11 * x1' + a12 * 0 + b1' - // vn2 = a21 * x1' + a22 * 0 + b2' + // 0 = a11 * x1 + a12 * 0 + b1' + // vn2 = a21 * x1 + a22 * 0 + b2' // x.x = - cp1->normalMass * b.x; x.y = 0.0f; vn1 = 0.0f; - vn2 = c->K.col1.y * x.x + b.y; + vn2 = vc->K.ex.y * x.x + b.y; if (x.x >= 0.0f && vn2 >= 0.0f) { - // Resubstitute for the incremental impulse + // Get the incremental impulse b2Vec2 d = x - a; // Apply incremental impulse b2Vec2 P1 = d.x * normal; b2Vec2 P2 = d.y * normal; - vA -= invMassA * (P1 + P2); - wA -= invIA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - vB += invMassB * (P1 + P2); - wB += invIB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); // Accumulate cp1->normalImpulse = x.x; @@ -407,12 +514,12 @@ void b2ContactSolver::SolveVelocityConstraints() // // Case 3: vn2 = 0 and x1 = 0 // - // vn1 = a11 * 0 + a12 * x2' + b1' - // 0 = a21 * 0 + a22 * x2' + b2' + // vn1 = a11 * 0 + a12 * x2 + b1' + // 0 = a21 * 0 + a22 * x2 + b2' // x.x = 0.0f; x.y = - cp2->normalMass * b.y; - vn1 = c->K.col2.x * x.y + b.x; + vn1 = vc->K.ey.x * x.y + b.x; vn2 = 0.0f; if (x.y >= 0.0f && vn1 >= 0.0f) @@ -423,11 +530,11 @@ void b2ContactSolver::SolveVelocityConstraints() // Apply incremental impulse b2Vec2 P1 = d.x * normal; b2Vec2 P2 = d.y * normal; - vA -= invMassA * (P1 + P2); - wA -= invIA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - vB += invMassB * (P1 + P2); - wB += invIB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); // Accumulate cp1->normalImpulse = x.x; @@ -463,11 +570,11 @@ void b2ContactSolver::SolveVelocityConstraints() // Apply incremental impulse b2Vec2 P1 = d.x * normal; b2Vec2 P2 = d.y * normal; - vA -= invMassA * (P1 + P2); - wA -= invIA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - vB += invMassB * (P1 + P2); - wB += invIB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); // Accumulate cp1->normalImpulse = x.x; @@ -481,73 +588,65 @@ void b2ContactSolver::SolveVelocityConstraints() } } - bodyA->m_linearVelocity = vA; - bodyA->m_angularVelocity = wA; - bodyB->m_linearVelocity = vB; - bodyB->m_angularVelocity = wB; + m_velocities[indexA].v = vA; + m_velocities[indexA].w = wA; + m_velocities[indexB].v = vB; + m_velocities[indexB].w = wB; } } void b2ContactSolver::StoreImpulses() { - for (int32 i = 0; i < m_constraintCount; ++i) + for (int32 i = 0; i < m_count; ++i) { - b2ContactConstraint* c = m_constraints + i; - b2Manifold* m = c->manifold; + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); - for (int32 j = 0; j < c->pointCount; ++j) + for (int32 j = 0; j < vc->pointCount; ++j) { - m->points[j].normalImpulse = c->points[j].normalImpulse; - m->points[j].tangentImpulse = c->points[j].tangentImpulse; + manifold->points[j].normalImpulse = vc->points[j].normalImpulse; + manifold->points[j].tangentImpulse = vc->points[j].tangentImpulse; } } } struct b2PositionSolverManifold { - void Initialize(b2ContactConstraint* cc, int32 index) + void Initialize(b2ContactPositionConstraint* pc, const b2Transform& xfA, const b2Transform& xfB, int32 index) { - b2Assert(cc->pointCount > 0); + b2Assert(pc->pointCount > 0); - switch (cc->type) + switch (pc->type) { case b2Manifold::e_circles: { - b2Vec2 pointA = cc->bodyA->GetWorldPoint(cc->localPoint); - b2Vec2 pointB = cc->bodyB->GetWorldPoint(cc->points[0].localPoint); - if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon) - { - normal = pointB - pointA; - normal.Normalize(); - } - else - { - normal.Set(1.0f, 0.0f); - } - + b2Vec2 pointA = b2Mul(xfA, pc->localPoint); + b2Vec2 pointB = b2Mul(xfB, pc->localPoints[0]); + normal = pointB - pointA; + normal.Normalize(); point = 0.5f * (pointA + pointB); - separation = b2Dot(pointB - pointA, normal) - cc->radius; + separation = b2Dot(pointB - pointA, normal) - pc->radiusA - pc->radiusB; } break; case b2Manifold::e_faceA: { - normal = cc->bodyA->GetWorldVector(cc->localNormal); - b2Vec2 planePoint = cc->bodyA->GetWorldPoint(cc->localPoint); + normal = b2Mul(xfA.q, pc->localNormal); + b2Vec2 planePoint = b2Mul(xfA, pc->localPoint); - b2Vec2 clipPoint = cc->bodyB->GetWorldPoint(cc->points[index].localPoint); - separation = b2Dot(clipPoint - planePoint, normal) - cc->radius; + b2Vec2 clipPoint = b2Mul(xfB, pc->localPoints[index]); + separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; point = clipPoint; } break; case b2Manifold::e_faceB: { - normal = cc->bodyB->GetWorldVector(cc->localNormal); - b2Vec2 planePoint = cc->bodyB->GetWorldPoint(cc->localPoint); + normal = b2Mul(xfB.q, pc->localNormal); + b2Vec2 planePoint = b2Mul(xfB, pc->localPoint); - b2Vec2 clipPoint = cc->bodyA->GetWorldPoint(cc->points[index].localPoint); - separation = b2Dot(clipPoint - planePoint, normal) - cc->radius; + b2Vec2 clipPoint = b2Mul(xfA, pc->localPoints[index]); + separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; point = clipPoint; // Ensure normal points from A to B @@ -563,58 +662,168 @@ struct b2PositionSolverManifold }; // Sequential solver. -bool b2ContactSolver::SolvePositionConstraints(float32 baumgarte) +bool b2ContactSolver::SolvePositionConstraints() { float32 minSeparation = 0.0f; - for (int32 i = 0; i < m_constraintCount; ++i) + for (int32 i = 0; i < m_count; ++i) { - b2ContactConstraint* c = m_constraints + i; - b2Body* bodyA = c->bodyA; - b2Body* bodyB = c->bodyB; + b2ContactPositionConstraint* pc = m_positionConstraints + i; - float32 invMassA = bodyA->m_mass * bodyA->m_invMass; - float32 invIA = bodyA->m_mass * bodyA->m_invI; - float32 invMassB = bodyB->m_mass * bodyB->m_invMass; - float32 invIB = bodyB->m_mass * bodyB->m_invI; + int32 indexA = pc->indexA; + int32 indexB = pc->indexB; + b2Vec2 localCenterA = pc->localCenterA; + float32 mA = pc->invMassA; + float32 iA = pc->invIA; + b2Vec2 localCenterB = pc->localCenterB; + float32 mB = pc->invMassB; + float32 iB = pc->invIB; + int32 pointCount = pc->pointCount; + + b2Vec2 cA = m_positions[indexA].c; + float32 aA = m_positions[indexA].a; + + b2Vec2 cB = m_positions[indexB].c; + float32 aB = m_positions[indexB].a; // Solve normal constraints - for (int32 j = 0; j < c->pointCount; ++j) + for (int32 j = 0; j < pointCount; ++j) { + b2Transform xfA, xfB; + xfA.q.Set(aA); + xfB.q.Set(aB); + xfA.p = cA - b2Mul(xfA.q, localCenterA); + xfB.p = cB - b2Mul(xfB.q, localCenterB); + b2PositionSolverManifold psm; - psm.Initialize(c, j); + psm.Initialize(pc, xfA, xfB, j); b2Vec2 normal = psm.normal; b2Vec2 point = psm.point; float32 separation = psm.separation; - b2Vec2 rA = point - bodyA->m_sweep.c; - b2Vec2 rB = point - bodyB->m_sweep.c; + b2Vec2 rA = point - cA; + b2Vec2 rB = point - cB; // Track max constraint error. minSeparation = b2Min(minSeparation, separation); // Prevent large corrections and allow slop. - float32 C = b2Clamp(baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); + float32 C = b2Clamp(b2_baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); // Compute the effective mass. float32 rnA = b2Cross(rA, normal); float32 rnB = b2Cross(rB, normal); - float32 K = invMassA + invMassB + invIA * rnA * rnA + invIB * rnB * rnB; + float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; // Compute normal impulse float32 impulse = K > 0.0f ? - C / K : 0.0f; b2Vec2 P = impulse * normal; - bodyA->m_sweep.c -= invMassA * P; - bodyA->m_sweep.a -= invIA * b2Cross(rA, P); - bodyA->SynchronizeTransform(); + cA -= mA * P; + aA -= iA * b2Cross(rA, P); - bodyB->m_sweep.c += invMassB * P; - bodyB->m_sweep.a += invIB * b2Cross(rB, P); - bodyB->SynchronizeTransform(); + cB += mB * P; + aB += iB * b2Cross(rB, P); } + + m_positions[indexA].c = cA; + m_positions[indexA].a = aA; + + m_positions[indexB].c = cB; + m_positions[indexB].a = aB; + } + + // We can't expect minSpeparation >= -b2_linearSlop because we don't + // push the separation above -b2_linearSlop. + return minSeparation >= -3.0f * b2_linearSlop; +} + +// Sequential position solver for position constraints. +bool b2ContactSolver::SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB) +{ + float32 minSeparation = 0.0f; + + for (int32 i = 0; i < m_count; ++i) + { + b2ContactPositionConstraint* pc = m_positionConstraints + i; + + int32 indexA = pc->indexA; + int32 indexB = pc->indexB; + b2Vec2 localCenterA = pc->localCenterA; + b2Vec2 localCenterB = pc->localCenterB; + int32 pointCount = pc->pointCount; + + float32 mA = 0.0f; + float32 iA = 0.0f; + if (indexA == toiIndexA || indexA == toiIndexB) + { + mA = pc->invMassA; + iA = pc->invIA; + } + + float32 mB = pc->invMassB; + float32 iB = pc->invIB; + if (indexB == toiIndexA || indexB == toiIndexB) + { + mB = pc->invMassB; + iB = pc->invIB; + } + + b2Vec2 cA = m_positions[indexA].c; + float32 aA = m_positions[indexA].a; + + b2Vec2 cB = m_positions[indexB].c; + float32 aB = m_positions[indexB].a; + + // Solve normal constraints + for (int32 j = 0; j < pointCount; ++j) + { + b2Transform xfA, xfB; + xfA.q.Set(aA); + xfB.q.Set(aB); + xfA.p = cA - b2Mul(xfA.q, localCenterA); + xfB.p = cB - b2Mul(xfB.q, localCenterB); + + b2PositionSolverManifold psm; + psm.Initialize(pc, xfA, xfB, j); + b2Vec2 normal = psm.normal; + + b2Vec2 point = psm.point; + float32 separation = psm.separation; + + b2Vec2 rA = point - cA; + b2Vec2 rB = point - cB; + + // Track max constraint error. + minSeparation = b2Min(minSeparation, separation); + + // Prevent large corrections and allow slop. + float32 C = b2Clamp(b2_toiBaugarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); + + // Compute the effective mass. + float32 rnA = b2Cross(rA, normal); + float32 rnB = b2Cross(rB, normal); + float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; + + // Compute normal impulse + float32 impulse = K > 0.0f ? - C / K : 0.0f; + + b2Vec2 P = impulse * normal; + + cA -= mA * P; + aA -= iA * b2Cross(rA, P); + + cB += mB * P; + aB += iB * b2Cross(rB, P); + } + + m_positions[indexA].c = cA; + m_positions[indexA].a = aA; + + m_positions[indexB].c = cB; + m_positions[indexB].a = aB; } // We can't expect minSpeparation >= -b2_linearSlop because we don't diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.h old mode 100644 new mode 100755 index b8555bbb4..ca9de04db --- a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -21,15 +21,15 @@ #include #include -#include +#include class b2Contact; class b2Body; class b2StackAllocator; +struct b2ContactPositionConstraint; -struct b2ContactConstraintPoint +struct b2VelocityConstraintPoint { - b2Vec2 localPoint; b2Vec2 rA; b2Vec2 rB; float32 normalImpulse; @@ -39,40 +39,56 @@ struct b2ContactConstraintPoint float32 velocityBias; }; -struct b2ContactConstraint +struct b2ContactVelocityConstraint { - b2ContactConstraintPoint points[b2_maxManifoldPoints]; - b2Vec2 localNormal; - b2Vec2 localPoint; + b2VelocityConstraintPoint points[b2_maxManifoldPoints]; b2Vec2 normal; b2Mat22 normalMass; b2Mat22 K; - b2Body* bodyA; - b2Body* bodyB; - b2Manifold::Type type; - float32 radius; + int32 indexA; + int32 indexB; + float32 invMassA, invMassB; + float32 invIA, invIB; float32 friction; + float32 restitution; int32 pointCount; - b2Manifold* manifold; + int32 contactIndex; +}; + +struct b2ContactSolverDef +{ + b2TimeStep step; + b2Contact** contacts; + int32 count; + b2Position* positions; + b2Velocity* velocities; + b2StackAllocator* allocator; }; class b2ContactSolver { public: - b2ContactSolver(b2Contact** contacts, int32 contactCount, - b2StackAllocator* allocator, float32 impulseRatio); - + b2ContactSolver(b2ContactSolverDef* def); ~b2ContactSolver(); + void InitializeVelocityConstraints(); + void WarmStart(); void SolveVelocityConstraints(); void StoreImpulses(); - bool SolvePositionConstraints(float32 baumgarte); + bool SolvePositionConstraints(); + bool SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB); + b2TimeStep m_step; + b2Position* m_positions; + b2Velocity* m_velocities; b2StackAllocator* m_allocator; - b2ContactConstraint* m_constraints; - int m_constraintCount; + b2ContactPositionConstraint* m_positionConstraints; + b2ContactVelocityConstraint* m_velocityConstraints; + b2Contact** m_contacts; + int m_count; }; #endif + diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp new file mode 100755 index 000000000..043365070 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2EdgeAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2EdgeAndCircleContact)); + return new (mem) b2EdgeAndCircleContact(fixtureA, fixtureB); +} + +void b2EdgeAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2EdgeAndCircleContact*)contact)->~b2EdgeAndCircleContact(); + allocator->Free(contact, sizeof(b2EdgeAndCircleContact)); +} + +b2EdgeAndCircleContact::b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) +: b2Contact(fixtureA, 0, fixtureB, 0) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); +} + +void b2EdgeAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollideEdgeAndCircle( manifold, + (b2EdgeShape*)m_fixtureA->GetShape(), xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h new file mode 100755 index 000000000..11b61b880 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_EDGE_AND_CIRCLE_CONTACT_H +#define B2_EDGE_AND_CIRCLE_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2EdgeAndCircleContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2EdgeAndCircleContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp new file mode 100755 index 000000000..8bac536a0 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2EdgeAndPolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2EdgeAndPolygonContact)); + return new (mem) b2EdgeAndPolygonContact(fixtureA, fixtureB); +} + +void b2EdgeAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2EdgeAndPolygonContact*)contact)->~b2EdgeAndPolygonContact(); + allocator->Free(contact, sizeof(b2EdgeAndPolygonContact)); +} + +b2EdgeAndPolygonContact::b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) +: b2Contact(fixtureA, 0, fixtureB, 0) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); + b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); +} + +void b2EdgeAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollideEdgeAndPolygon( manifold, + (b2EdgeShape*)m_fixtureA->GetShape(), xfA, + (b2PolygonShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h new file mode 100755 index 000000000..74b27ee01 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_EDGE_AND_POLYGON_CONTACT_H +#define B2_EDGE_AND_POLYGON_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2EdgeAndPolygonContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2EdgeAndPolygonContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp old mode 100644 new mode 100755 index 837722d92..880f83e22 --- a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -18,14 +18,12 @@ #include #include -#include -#include #include -#include #include +using namespace std; -b2Contact* b2PolygonAndCircleContact::Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator) +b2Contact* b2PolygonAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) { void* mem = allocator->Allocate(sizeof(b2PolygonAndCircleContact)); return new (mem) b2PolygonAndCircleContact(fixtureA, fixtureB); @@ -38,7 +36,7 @@ void b2PolygonAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* al } b2PolygonAndCircleContact::b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) -: b2Contact(fixtureA, fixtureB) +: b2Contact(fixtureA, 0, fixtureB, 0) { b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h old mode 100644 new mode 100755 index 684b2ae04..6beca16a2 --- a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -26,7 +26,7 @@ class b2BlockAllocator; class b2PolygonAndCircleContact : public b2Contact { public: - static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator); + static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.cpp old mode 100644 new mode 100755 index eab2af579..52e1be874 --- a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -24,8 +24,9 @@ #include #include +using namespace std; -b2Contact* b2PolygonContact::Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator) +b2Contact* b2PolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) { void* mem = allocator->Allocate(sizeof(b2PolygonContact)); return new (mem) b2PolygonContact(fixtureA, fixtureB); @@ -38,7 +39,7 @@ void b2PolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) } b2PolygonContact::b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) - : b2Contact(fixtureA, fixtureB) + : b2Contact(fixtureA, 0, fixtureB, 0) { b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.h b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.h old mode 100644 new mode 100755 index af544c2e7..45932148c --- a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -26,7 +26,8 @@ class b2BlockAllocator; class b2PolygonContact : public b2Contact { public: - static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator); + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.cpp deleted file mode 100644 index 567cd7125..000000000 --- a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2TOISolver.cpp +++ /dev/null @@ -1,231 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -struct b2TOIConstraint -{ - b2Vec2 localPoints[b2_maxManifoldPoints]; - b2Vec2 localNormal; - b2Vec2 localPoint; - b2Manifold::Type type; - float32 radius; - int32 pointCount; - b2Body* bodyA; - b2Body* bodyB; -}; - -b2TOISolver::b2TOISolver(b2StackAllocator* allocator) -{ - m_allocator = allocator; - m_constraints = NULL; - m_count = NULL; - m_toiBody = NULL; -} - -b2TOISolver::~b2TOISolver() -{ - Clear(); -} - -void b2TOISolver::Clear() -{ - if (m_allocator && m_constraints) - { - m_allocator->Free(m_constraints); - m_constraints = NULL; - } -} - -void b2TOISolver::Initialize(b2Contact** contacts, int32 count, b2Body* toiBody) -{ - Clear(); - - m_count = count; - m_toiBody = toiBody; - - m_constraints = (b2TOIConstraint*) m_allocator->Allocate(m_count * sizeof(b2TOIConstraint)); - - for (int32 i = 0; i < m_count; ++i) - { - b2Contact* contact = contacts[i]; - - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); - b2Shape* shapeA = fixtureA->GetShape(); - b2Shape* shapeB = fixtureB->GetShape(); - float32 radiusA = shapeA->m_radius; - float32 radiusB = shapeB->m_radius; - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - b2Manifold* manifold = contact->GetManifold(); - - b2Assert(manifold->pointCount > 0); - - b2TOIConstraint* constraint = m_constraints + i; - constraint->bodyA = bodyA; - constraint->bodyB = bodyB; - constraint->localNormal = manifold->localNormal; - constraint->localPoint = manifold->localPoint; - constraint->type = manifold->type; - constraint->pointCount = manifold->pointCount; - constraint->radius = radiusA + radiusB; - - for (int32 j = 0; j < constraint->pointCount; ++j) - { - b2ManifoldPoint* cp = manifold->points + j; - constraint->localPoints[j] = cp->localPoint; - } - } -} - -struct b2TOISolverManifold -{ - void Initialize(b2TOIConstraint* cc, int32 index) - { - b2Assert(cc->pointCount > 0); - - switch (cc->type) - { - case b2Manifold::e_circles: - { - b2Vec2 pointA = cc->bodyA->GetWorldPoint(cc->localPoint); - b2Vec2 pointB = cc->bodyB->GetWorldPoint(cc->localPoints[0]); - if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon) - { - normal = pointB - pointA; - normal.Normalize(); - } - else - { - normal.Set(1.0f, 0.0f); - } - - point = 0.5f * (pointA + pointB); - separation = b2Dot(pointB - pointA, normal) - cc->radius; - } - break; - - case b2Manifold::e_faceA: - { - normal = cc->bodyA->GetWorldVector(cc->localNormal); - b2Vec2 planePoint = cc->bodyA->GetWorldPoint(cc->localPoint); - - b2Vec2 clipPoint = cc->bodyB->GetWorldPoint(cc->localPoints[index]); - separation = b2Dot(clipPoint - planePoint, normal) - cc->radius; - point = clipPoint; - } - break; - - case b2Manifold::e_faceB: - { - normal = cc->bodyB->GetWorldVector(cc->localNormal); - b2Vec2 planePoint = cc->bodyB->GetWorldPoint(cc->localPoint); - - b2Vec2 clipPoint = cc->bodyA->GetWorldPoint(cc->localPoints[index]); - separation = b2Dot(clipPoint - planePoint, normal) - cc->radius; - point = clipPoint; - - // Ensure normal points from A to B - normal = -normal; - } - break; - } - } - - b2Vec2 normal; - b2Vec2 point; - float32 separation; -}; - -// Push out the toi body to provide clearance for further simulation. -bool b2TOISolver::Solve(float32 baumgarte) -{ - float32 minSeparation = 0.0f; - - for (int32 i = 0; i < m_count; ++i) - { - b2TOIConstraint* c = m_constraints + i; - b2Body* bodyA = c->bodyA; - b2Body* bodyB = c->bodyB; - - float32 massA = bodyA->m_mass; - float32 massB = bodyB->m_mass; - - // Only the TOI body should move. - if (bodyA == m_toiBody) - { - massB = 0.0f; - } - else - { - massA = 0.0f; - } - - float32 invMassA = massA * bodyA->m_invMass; - float32 invIA = massA * bodyA->m_invI; - float32 invMassB = massB * bodyB->m_invMass; - float32 invIB = massB * bodyB->m_invI; - - // Solve normal constraints - for (int32 j = 0; j < c->pointCount; ++j) - { - b2TOISolverManifold psm; - psm.Initialize(c, j); - b2Vec2 normal = psm.normal; - - b2Vec2 point = psm.point; - float32 separation = psm.separation; - - b2Vec2 rA = point - bodyA->m_sweep.c; - b2Vec2 rB = point - bodyB->m_sweep.c; - - // Track max constraint error. - minSeparation = b2Min(minSeparation, separation); - - // Prevent large corrections and allow slop. - float32 C = b2Clamp(baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); - - // Compute the effective mass. - float32 rnA = b2Cross(rA, normal); - float32 rnB = b2Cross(rB, normal); - float32 K = invMassA + invMassB + invIA * rnA * rnA + invIB * rnB * rnB; - - // Compute normal impulse - float32 impulse = K > 0.0f ? - C / K : 0.0f; - - b2Vec2 P = impulse * normal; - - bodyA->m_sweep.c -= invMassA * P; - bodyA->m_sweep.a -= invIA * b2Cross(rA, P); - bodyA->SynchronizeTransform(); - - bodyB->m_sweep.c += invMassB * P; - bodyB->m_sweep.a += invIB * b2Cross(rB, P); - bodyB->SynchronizeTransform(); - } - } - - // We can't expect minSpeparation >= -b2_linearSlop because we don't - // push the separation above -b2_linearSlop. - return minSeparation >= -1.5f * b2_linearSlop; -} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp old mode 100644 new mode 100755 index 3469bd9e1..7b0e2a507 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -46,12 +46,11 @@ void b2DistanceJointDef::Initialize(b2Body* b1, b2Body* b2, length = d.Length(); } - b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def) : b2Joint(def) { - m_localAnchor1 = def->localAnchorA; - m_localAnchor2 = def->localAnchorB; + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; m_length = def->length; m_frequencyHz = def->frequencyHz; m_dampingRatio = def->dampingRatio; @@ -60,15 +59,32 @@ b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def) m_bias = 0.0f; } -void b2DistanceJoint::InitVelocityConstraints(const b2TimeStep& step) +void b2DistanceJoint::InitVelocityConstraints(const b2SolverData& data) { - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; - // Compute the effective mass matrix. - b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); - m_u = b2->m_sweep.c + r2 - b1->m_sweep.c - r1; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + m_u = cB + m_rB - cA - m_rA; // Handle singularity. float32 length = m_u.Length(); @@ -81,10 +97,11 @@ void b2DistanceJoint::InitVelocityConstraints(const b2TimeStep& step) m_u.Set(0.0f, 0.0f); } - float32 cr1u = b2Cross(r1, m_u); - float32 cr2u = b2Cross(r2, m_u); - float32 invMass = b1->m_invMass + b1->m_invI * cr1u * cr1u + b2->m_invMass + b2->m_invI * cr2u * cr2u; + float32 crAu = b2Cross(m_rA, m_u); + float32 crBu = b2Cross(m_rB, m_u); + float32 invMass = m_invMassA + m_invIA * crAu * crAu + m_invMassB + m_invIB * crBu * crBu; + // Compute the effective mass matrix. m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; if (m_frequencyHz > 0.0f) @@ -101,101 +118,111 @@ void b2DistanceJoint::InitVelocityConstraints(const b2TimeStep& step) float32 k = m_mass * omega * omega; // magic formulas - m_gamma = step.dt * (d + step.dt * k); + float32 h = data.step.dt; + m_gamma = h * (d + h * k); m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; - m_bias = C * step.dt * k * m_gamma; + m_bias = C * h * k * m_gamma; m_mass = invMass + m_gamma; m_mass = m_mass != 0.0f ? 1.0f / m_mass : 0.0f; } - if (step.warmStarting) + if (data.step.warmStarting) { // Scale the impulse to support a variable time step. - m_impulse *= step.dtRatio; + m_impulse *= data.step.dtRatio; b2Vec2 P = m_impulse * m_u; - b1->m_linearVelocity -= b1->m_invMass * P; - b1->m_angularVelocity -= b1->m_invI * b2Cross(r1, P); - b2->m_linearVelocity += b2->m_invMass * P; - b2->m_angularVelocity += b2->m_invI * b2Cross(r2, P); + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); } else { m_impulse = 0.0f; } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } -void b2DistanceJoint::SolveVelocityConstraints(const b2TimeStep& step) +void b2DistanceJoint::SolveVelocityConstraints(const b2SolverData& data) { - B2_NOT_USED(step); - - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; - - b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; // Cdot = dot(u, v + cross(w, r)) - b2Vec2 v1 = b1->m_linearVelocity + b2Cross(b1->m_angularVelocity, r1); - b2Vec2 v2 = b2->m_linearVelocity + b2Cross(b2->m_angularVelocity, r2); - float32 Cdot = b2Dot(m_u, v2 - v1); + b2Vec2 vpA = vA + b2Cross(wA, m_rA); + b2Vec2 vpB = vB + b2Cross(wB, m_rB); + float32 Cdot = b2Dot(m_u, vpB - vpA); float32 impulse = -m_mass * (Cdot + m_bias + m_gamma * m_impulse); m_impulse += impulse; b2Vec2 P = impulse * m_u; - b1->m_linearVelocity -= b1->m_invMass * P; - b1->m_angularVelocity -= b1->m_invI * b2Cross(r1, P); - b2->m_linearVelocity += b2->m_invMass * P; - b2->m_angularVelocity += b2->m_invI * b2Cross(r2, P); + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } -bool b2DistanceJoint::SolvePositionConstraints(float32 baumgarte) +bool b2DistanceJoint::SolvePositionConstraints(const b2SolverData& data) { - B2_NOT_USED(baumgarte); - if (m_frequencyHz > 0.0f) { // There is no position correction for soft distance constraints. return true; } - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; - b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); + b2Rot qA(aA), qB(aB); - b2Vec2 d = b2->m_sweep.c + r2 - b1->m_sweep.c - r1; + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 u = cB + rB - cA - rA; - float32 length = d.Normalize(); + float32 length = u.Normalize(); float32 C = length - m_length; C = b2Clamp(C, -b2_maxLinearCorrection, b2_maxLinearCorrection); float32 impulse = -m_mass * C; - m_u = d; - b2Vec2 P = impulse * m_u; + b2Vec2 P = impulse * u; - b1->m_sweep.c -= b1->m_invMass * P; - b1->m_sweep.a -= b1->m_invI * b2Cross(r1, P); - b2->m_sweep.c += b2->m_invMass * P; - b2->m_sweep.a += b2->m_invI * b2Cross(r2, P); + cA -= m_invMassA * P; + aA -= m_invIA * b2Cross(rA, P); + cB += m_invMassB * P; + aB += m_invIB * b2Cross(rB, P); - b1->SynchronizeTransform(); - b2->SynchronizeTransform(); + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; return b2Abs(C) < b2_linearSlop; } b2Vec2 b2DistanceJoint::GetAnchorA() const { - return m_bodyA->GetWorldPoint(m_localAnchor1); + return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2DistanceJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchor2); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2DistanceJoint::GetReactionForce(float32 inv_dt) const diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h old mode 100644 new mode 100755 index 448faa668..a8d35a5e6 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -70,7 +70,12 @@ public: b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorB() const; + /// Get the reaction force given the inverse time step. + /// Unit is N. b2Vec2 GetReactionForce(float32 inv_dt) const; + + /// Get the reaction torque given the inverse time step. + /// Unit is N*m. This is always zero for a distance joint. float32 GetReactionTorque(float32 inv_dt) const; /// Set/get the natural length. @@ -91,20 +96,34 @@ protected: friend class b2Joint; b2DistanceJoint(const b2DistanceJointDef* data); - void InitVelocityConstraints(const b2TimeStep& step); - void SolveVelocityConstraints(const b2TimeStep& step); - bool SolvePositionConstraints(float32 baumgarte); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - b2Vec2 m_localAnchor1; - b2Vec2 m_localAnchor2; - b2Vec2 m_u; float32 m_frequencyHz; float32 m_dampingRatio; - float32 m_gamma; float32 m_bias; + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_gamma; float32 m_impulse; - float32 m_mass; float32 m_length; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_u; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + float32 m_mass; }; inline void b2DistanceJoint::SetLength(float32 length) diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp old mode 100644 new mode 100755 index 9097deec3..8c363e6a1 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -53,14 +53,30 @@ b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def) m_maxTorque = def->maxTorque; } -void b2FrictionJoint::InitVelocityConstraints(const b2TimeStep& step) +void b2FrictionJoint::InitVelocityConstraints(const b2SolverData& data) { - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); // Compute the effective mass matrix. - b2Vec2 rA = b2Mul(bA->GetTransform().R, m_localAnchorA - bA->GetLocalCenter()); - b2Vec2 rB = b2Mul(bB->GetTransform().R, m_localAnchorB - bB->GetLocalCenter()); + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] @@ -71,22 +87,15 @@ void b2FrictionJoint::InitVelocityConstraints(const b2TimeStep& step) // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - float32 mA = bA->m_invMass, mB = bB->m_invMass; - float32 iA = bA->m_invI, iB = bB->m_invI; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - b2Mat22 K1; - K1.col1.x = mA + mB; K1.col2.x = 0.0f; - K1.col1.y = 0.0f; K1.col2.y = mA + mB; + b2Mat22 K; + K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y; + K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y; + K.ey.x = K.ex.y; + K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x; - b2Mat22 K2; - K2.col1.x = iA * rA.y * rA.y; K2.col2.x = -iA * rA.x * rA.y; - K2.col1.y = -iA * rA.x * rA.y; K2.col2.y = iA * rA.x * rA.x; - - b2Mat22 K3; - K3.col1.x = iB * rB.y * rB.y; K3.col2.x = -iB * rB.x * rB.y; - K3.col1.y = -iB * rB.x * rB.y; K3.col2.y = iB * rB.x * rB.x; - - b2Mat22 K = K1 + K2 + K3; m_linearMass = K.GetInverse(); m_angularMass = iA + iB; @@ -95,44 +104,41 @@ void b2FrictionJoint::InitVelocityConstraints(const b2TimeStep& step) m_angularMass = 1.0f / m_angularMass; } - if (step.warmStarting) + if (data.step.warmStarting) { // Scale impulses to support a variable time step. - m_linearImpulse *= step.dtRatio; - m_angularImpulse *= step.dtRatio; + m_linearImpulse *= data.step.dtRatio; + m_angularImpulse *= data.step.dtRatio; b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y); - - bA->m_linearVelocity -= mA * P; - bA->m_angularVelocity -= iA * (b2Cross(rA, P) + m_angularImpulse); - - bB->m_linearVelocity += mB * P; - bB->m_angularVelocity += iB * (b2Cross(rB, P) + m_angularImpulse); + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse); + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + m_angularImpulse); } else { m_linearImpulse.SetZero(); m_angularImpulse = 0.0f; } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } -void b2FrictionJoint::SolveVelocityConstraints(const b2TimeStep& step) +void b2FrictionJoint::SolveVelocityConstraints(const b2SolverData& data) { - B2_NOT_USED(step); + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - b2Vec2 vA = bA->m_linearVelocity; - float32 wA = bA->m_angularVelocity; - b2Vec2 vB = bB->m_linearVelocity; - float32 wB = bB->m_angularVelocity; - - float32 mA = bA->m_invMass, mB = bB->m_invMass; - float32 iA = bA->m_invI, iB = bB->m_invI; - - b2Vec2 rA = b2Mul(bA->GetTransform().R, m_localAnchorA - bA->GetLocalCenter()); - b2Vec2 rB = b2Mul(bB->GetTransform().R, m_localAnchorB - bB->GetLocalCenter()); + float32 h = data.step.dt; // Solve angular friction { @@ -140,7 +146,7 @@ void b2FrictionJoint::SolveVelocityConstraints(const b2TimeStep& step) float32 impulse = -m_angularMass * Cdot; float32 oldImpulse = m_angularImpulse; - float32 maxImpulse = step.dt * m_maxTorque; + float32 maxImpulse = h * m_maxTorque; m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = m_angularImpulse - oldImpulse; @@ -150,13 +156,13 @@ void b2FrictionJoint::SolveVelocityConstraints(const b2TimeStep& step) // Solve linear friction { - b2Vec2 Cdot = vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA); + b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); b2Vec2 impulse = -b2Mul(m_linearMass, Cdot); b2Vec2 oldImpulse = m_linearImpulse; m_linearImpulse += impulse; - float32 maxImpulse = step.dt * m_maxForce; + float32 maxImpulse = h * m_maxForce; if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) { @@ -167,21 +173,21 @@ void b2FrictionJoint::SolveVelocityConstraints(const b2TimeStep& step) impulse = m_linearImpulse - oldImpulse; vA -= mA * impulse; - wA -= iA * b2Cross(rA, impulse); + wA -= iA * b2Cross(m_rA, impulse); vB += mB * impulse; - wB += iB * b2Cross(rB, impulse); + wB += iB * b2Cross(m_rB, impulse); } - bA->m_linearVelocity = vA; - bA->m_angularVelocity = wA; - bB->m_linearVelocity = vB; - bB->m_angularVelocity = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } -bool b2FrictionJoint::SolvePositionConstraints(float32 baumgarte) +bool b2FrictionJoint::SolvePositionConstraints(const b2SolverData& data) { - B2_NOT_USED(baumgarte); + B2_NOT_USED(data); return true; } diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h old mode 100644 new mode 100755 index b4c4af261..3e72be2fe --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -79,21 +79,32 @@ protected: b2FrictionJoint(const b2FrictionJointDef* def); - void InitVelocityConstraints(const b2TimeStep& step); - void SolveVelocityConstraints(const b2TimeStep& step); - bool SolvePositionConstraints(float32 baumgarte); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); b2Vec2 m_localAnchorA; b2Vec2 m_localAnchorB; - b2Mat22 m_linearMass; - float32 m_angularMass; - + // Solver shared b2Vec2 m_linearImpulse; float32 m_angularImpulse; - float32 m_maxForce; float32 m_maxTorque; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Mat22 m_linearMass; + float32 m_angularMass; }; #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp old mode 100644 new mode 100755 index 89b17ee2c..cff95f2bc --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -24,9 +24,8 @@ // Gear Joint: // C0 = (coordinate1 + ratio * coordinate2)_initial -// C = C0 - (cordinate1 + ratio * coordinate2) = 0 -// Cdot = -(Cdot1 + ratio * Cdot2) -// J = -[J1 ratio * J2] +// C = (coordinate1 + ratio * coordinate2) - C0 = 0 +// J = [J1 ratio * J2] // K = J * invM * JT // = J1 * invM1 * J1T + ratio * ratio * J2 * invM2 * J2T // @@ -45,177 +44,323 @@ b2GearJoint::b2GearJoint(const b2GearJointDef* def) : b2Joint(def) { - b2JointType type1 = def->joint1->GetType(); - b2JointType type2 = def->joint2->GetType(); + m_typeA = def->joint1->GetType(); + m_typeB = def->joint2->GetType(); - b2Assert(type1 == e_revoluteJoint || type1 == e_prismaticJoint); - b2Assert(type2 == e_revoluteJoint || type2 == e_prismaticJoint); - b2Assert(def->joint1->GetBodyA()->GetType() == b2_staticBody); - b2Assert(def->joint2->GetBodyA()->GetType() == b2_staticBody); + b2Assert(m_typeA == e_revoluteJoint || m_typeA == e_prismaticJoint); + b2Assert(m_typeB == e_revoluteJoint || m_typeB == e_prismaticJoint); - m_revolute1 = NULL; - m_prismatic1 = NULL; - m_revolute2 = NULL; - m_prismatic2 = NULL; + float32 coordinateA, coordinateB; - float32 coordinate1, coordinate2; - - m_ground1 = def->joint1->GetBodyA(); + m_bodyC = def->joint1->GetBodyA(); m_bodyA = def->joint1->GetBodyB(); - if (type1 == e_revoluteJoint) + + // Get geometry of joint1 + b2Transform xfA = m_bodyA->m_xf; + float32 aA = m_bodyA->m_sweep.a; + b2Transform xfC = m_bodyC->m_xf; + float32 aC = m_bodyC->m_sweep.a; + + if (m_typeA == e_revoluteJoint) { - m_revolute1 = (b2RevoluteJoint*)def->joint1; - m_groundAnchor1 = m_revolute1->m_localAnchor1; - m_localAnchor1 = m_revolute1->m_localAnchor2; - coordinate1 = m_revolute1->GetJointAngle(); + b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint1; + m_localAnchorC = revolute->m_localAnchorA; + m_localAnchorA = revolute->m_localAnchorB; + m_referenceAngleA = revolute->m_referenceAngle; + m_localAxisC.SetZero(); + + coordinateA = aA - aC - m_referenceAngleA; } else { - m_prismatic1 = (b2PrismaticJoint*)def->joint1; - m_groundAnchor1 = m_prismatic1->m_localAnchor1; - m_localAnchor1 = m_prismatic1->m_localAnchor2; - coordinate1 = m_prismatic1->GetJointTranslation(); + b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint1; + m_localAnchorC = prismatic->m_localAnchorA; + m_localAnchorA = prismatic->m_localAnchorB; + m_referenceAngleA = prismatic->m_refAngle; + m_localAxisC = prismatic->m_localXAxisA; + + b2Vec2 pC = m_localAnchorC; + b2Vec2 pA = b2MulT(xfC.q, b2Mul(xfA.q, m_localAnchorA) + (xfA.p - xfC.p)); + coordinateA = b2Dot(pA - pC, m_localAxisC); } - m_ground2 = def->joint2->GetBodyA(); + m_bodyD = def->joint2->GetBodyA(); m_bodyB = def->joint2->GetBodyB(); - if (type2 == e_revoluteJoint) + + // Get geometry of joint2 + b2Transform xfB = m_bodyB->m_xf; + float32 aB = m_bodyB->m_sweep.a; + b2Transform xfD = m_bodyD->m_xf; + float32 aD = m_bodyD->m_sweep.a; + + if (m_typeB == e_revoluteJoint) { - m_revolute2 = (b2RevoluteJoint*)def->joint2; - m_groundAnchor2 = m_revolute2->m_localAnchor1; - m_localAnchor2 = m_revolute2->m_localAnchor2; - coordinate2 = m_revolute2->GetJointAngle(); + b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint2; + m_localAnchorD = revolute->m_localAnchorA; + m_localAnchorB = revolute->m_localAnchorB; + m_referenceAngleB = revolute->m_referenceAngle; + m_localAxisD.SetZero(); + + coordinateB = aB - aD - m_referenceAngleB; } else { - m_prismatic2 = (b2PrismaticJoint*)def->joint2; - m_groundAnchor2 = m_prismatic2->m_localAnchor1; - m_localAnchor2 = m_prismatic2->m_localAnchor2; - coordinate2 = m_prismatic2->GetJointTranslation(); + b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint2; + m_localAnchorD = prismatic->m_localAnchorA; + m_localAnchorB = prismatic->m_localAnchorB; + m_referenceAngleB = prismatic->m_refAngle; + m_localAxisD = prismatic->m_localXAxisA; + + b2Vec2 pD = m_localAnchorD; + b2Vec2 pB = b2MulT(xfD.q, b2Mul(xfB.q, m_localAnchorB) + (xfB.p - xfD.p)); + coordinateB = b2Dot(pB - pD, m_localAxisD); } m_ratio = def->ratio; - m_constant = coordinate1 + m_ratio * coordinate2; + m_constant = coordinateA + m_ratio * coordinateB; m_impulse = 0.0f; } -void b2GearJoint::InitVelocityConstraints(const b2TimeStep& step) +void b2GearJoint::InitVelocityConstraints(const b2SolverData& data) { - b2Body* g1 = m_ground1; - b2Body* g2 = m_ground2; - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_indexC = m_bodyC->m_islandIndex; + m_indexD = m_bodyD->m_islandIndex; + m_lcA = m_bodyA->m_sweep.localCenter; + m_lcB = m_bodyB->m_sweep.localCenter; + m_lcC = m_bodyC->m_sweep.localCenter; + m_lcD = m_bodyD->m_sweep.localCenter; + m_mA = m_bodyA->m_invMass; + m_mB = m_bodyB->m_invMass; + m_mC = m_bodyC->m_invMass; + m_mD = m_bodyD->m_invMass; + m_iA = m_bodyA->m_invI; + m_iB = m_bodyB->m_invI; + m_iC = m_bodyC->m_invI; + m_iD = m_bodyD->m_invI; - float32 K = 0.0f; - m_J.SetZero(); + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; - if (m_revolute1) + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Vec2 cC = data.positions[m_indexC].c; + float32 aC = data.positions[m_indexC].a; + b2Vec2 vC = data.velocities[m_indexC].v; + float32 wC = data.velocities[m_indexC].w; + + b2Vec2 cD = data.positions[m_indexD].c; + float32 aD = data.positions[m_indexD].a; + b2Vec2 vD = data.velocities[m_indexD].v; + float32 wD = data.velocities[m_indexD].w; + + b2Rot qA(aA), qB(aB), qC(aC), qD(aD); + + m_mass = 0.0f; + + if (m_typeA == e_revoluteJoint) { - m_J.angularA = -1.0f; - K += b1->m_invI; + m_JvAC.SetZero(); + m_JwA = 1.0f; + m_JwC = 1.0f; + m_mass += m_iA + m_iC; } else { - b2Vec2 ug = b2Mul(g1->GetTransform().R, m_prismatic1->m_localXAxis1); - b2Vec2 r = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); - float32 crug = b2Cross(r, ug); - m_J.linearA = -ug; - m_J.angularA = -crug; - K += b1->m_invMass + b1->m_invI * crug * crug; + b2Vec2 u = b2Mul(qC, m_localAxisC); + b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); + m_JvAC = u; + m_JwC = b2Cross(rC, u); + m_JwA = b2Cross(rA, u); + m_mass += m_mC + m_mA + m_iC * m_JwC * m_JwC + m_iA * m_JwA * m_JwA; } - if (m_revolute2) + if (m_typeB == e_revoluteJoint) { - m_J.angularB = -m_ratio; - K += m_ratio * m_ratio * b2->m_invI; + m_JvBD.SetZero(); + m_JwB = m_ratio; + m_JwD = m_ratio; + m_mass += m_ratio * m_ratio * (m_iB + m_iD); } else { - b2Vec2 ug = b2Mul(g2->GetTransform().R, m_prismatic2->m_localXAxis1); - b2Vec2 r = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); - float32 crug = b2Cross(r, ug); - m_J.linearB = -m_ratio * ug; - m_J.angularB = -m_ratio * crug; - K += m_ratio * m_ratio * (b2->m_invMass + b2->m_invI * crug * crug); + b2Vec2 u = b2Mul(qD, m_localAxisD); + b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); + m_JvBD = m_ratio * u; + m_JwD = m_ratio * b2Cross(rD, u); + m_JwB = m_ratio * b2Cross(rB, u); + m_mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * m_JwD * m_JwD + m_iB * m_JwB * m_JwB; } // Compute effective mass. - m_mass = K > 0.0f ? 1.0f / K : 0.0f; + m_mass = m_mass > 0.0f ? 1.0f / m_mass : 0.0f; - if (step.warmStarting) + if (data.step.warmStarting) { - // Warm starting. - b1->m_linearVelocity += b1->m_invMass * m_impulse * m_J.linearA; - b1->m_angularVelocity += b1->m_invI * m_impulse * m_J.angularA; - b2->m_linearVelocity += b2->m_invMass * m_impulse * m_J.linearB; - b2->m_angularVelocity += b2->m_invI * m_impulse * m_J.angularB; + vA += (m_mA * m_impulse) * m_JvAC; + wA += m_iA * m_impulse * m_JwA; + vB += (m_mB * m_impulse) * m_JvBD; + wB += m_iB * m_impulse * m_JwB; + vC -= (m_mC * m_impulse) * m_JvAC; + wC -= m_iC * m_impulse * m_JwC; + vD -= (m_mD * m_impulse) * m_JvBD; + wD -= m_iD * m_impulse * m_JwD; } else { m_impulse = 0.0f; } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; + data.velocities[m_indexC].v = vC; + data.velocities[m_indexC].w = wC; + data.velocities[m_indexD].v = vD; + data.velocities[m_indexD].w = wD; } -void b2GearJoint::SolveVelocityConstraints(const b2TimeStep& step) +void b2GearJoint::SolveVelocityConstraints(const b2SolverData& data) { - B2_NOT_USED(step); + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + b2Vec2 vC = data.velocities[m_indexC].v; + float32 wC = data.velocities[m_indexC].w; + b2Vec2 vD = data.velocities[m_indexD].v; + float32 wD = data.velocities[m_indexD].w; - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + float32 Cdot = b2Dot(m_JvAC, vA - vC) + b2Dot(m_JvBD, vB - vD); + Cdot += (m_JwA * wA - m_JwC * wC) + (m_JwB * wB - m_JwD * wD); - float32 Cdot = m_J.Compute( b1->m_linearVelocity, b1->m_angularVelocity, - b2->m_linearVelocity, b2->m_angularVelocity); - - float32 impulse = m_mass * (-Cdot); + float32 impulse = -m_mass * Cdot; m_impulse += impulse; - b1->m_linearVelocity += b1->m_invMass * impulse * m_J.linearA; - b1->m_angularVelocity += b1->m_invI * impulse * m_J.angularA; - b2->m_linearVelocity += b2->m_invMass * impulse * m_J.linearB; - b2->m_angularVelocity += b2->m_invI * impulse * m_J.angularB; + vA += (m_mA * impulse) * m_JvAC; + wA += m_iA * impulse * m_JwA; + vB += (m_mB * impulse) * m_JvBD; + wB += m_iB * impulse * m_JwB; + vC -= (m_mC * impulse) * m_JvAC; + wC -= m_iC * impulse * m_JwC; + vD -= (m_mD * impulse) * m_JvBD; + wD -= m_iD * impulse * m_JwD; + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; + data.velocities[m_indexC].v = vC; + data.velocities[m_indexC].w = wC; + data.velocities[m_indexD].v = vD; + data.velocities[m_indexD].w = wD; } -bool b2GearJoint::SolvePositionConstraints(float32 baumgarte) +bool b2GearJoint::SolvePositionConstraints(const b2SolverData& data) { - B2_NOT_USED(baumgarte); - + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 cC = data.positions[m_indexC].c; + float32 aC = data.positions[m_indexC].a; + b2Vec2 cD = data.positions[m_indexD].c; + float32 aD = data.positions[m_indexD].a; + + b2Rot qA(aA), qB(aB), qC(aC), qD(aD); + float32 linearError = 0.0f; - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + float32 coordinateA, coordinateB; - float32 coordinate1, coordinate2; - if (m_revolute1) + b2Vec2 JvAC, JvBD; + float32 JwA, JwB, JwC, JwD; + float32 mass = 0.0f; + + if (m_typeA == e_revoluteJoint) { - coordinate1 = m_revolute1->GetJointAngle(); + JvAC.SetZero(); + JwA = 1.0f; + JwC = 1.0f; + mass += m_iA + m_iC; + + coordinateA = aA - aC - m_referenceAngleA; } else { - coordinate1 = m_prismatic1->GetJointTranslation(); + b2Vec2 u = b2Mul(qC, m_localAxisC); + b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); + JvAC = u; + JwC = b2Cross(rC, u); + JwA = b2Cross(rA, u); + mass += m_mC + m_mA + m_iC * JwC * JwC + m_iA * JwA * JwA; + + b2Vec2 pC = m_localAnchorC - m_lcC; + b2Vec2 pA = b2MulT(qC, rA + (cA - cC)); + coordinateA = b2Dot(pA - pC, m_localAxisC); } - if (m_revolute2) + if (m_typeB == e_revoluteJoint) { - coordinate2 = m_revolute2->GetJointAngle(); + JvBD.SetZero(); + JwB = 1.0f; + JwD = 1.0f; + mass += m_iB + m_iD; + + coordinateB = aB - aD - m_referenceAngleB; } else { - coordinate2 = m_prismatic2->GetJointTranslation(); + b2Vec2 u = b2Mul(qD, m_localAxisD); + b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); + JvBD = m_ratio * u; + JwD = m_ratio * b2Cross(rD, u); + JwB = m_ratio * b2Cross(rB, u); + mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * JwD * JwD + m_iB * JwB * JwB; + + b2Vec2 pD = m_localAnchorD - m_lcD; + b2Vec2 pB = b2MulT(qD, rB + (cB - cD)); + coordinateB = b2Dot(pB - pD, m_localAxisD); } - float32 C = m_constant - (coordinate1 + m_ratio * coordinate2); + float32 C = (coordinateA + m_ratio * coordinateB) - m_constant; - float32 impulse = m_mass * (-C); + float32 impulse = 0.0f; + if (mass > 0.0f) + { + impulse = -C / mass; + } - b1->m_sweep.c += b1->m_invMass * impulse * m_J.linearA; - b1->m_sweep.a += b1->m_invI * impulse * m_J.angularA; - b2->m_sweep.c += b2->m_invMass * impulse * m_J.linearB; - b2->m_sweep.a += b2->m_invI * impulse * m_J.angularB; + cA += m_mA * impulse * JvAC; + aA += m_iA * impulse * JwA; + cB += m_mB * impulse * JvBD; + aB += m_iB * impulse * JwB; + cC -= m_mC * impulse * JvAC; + aC -= m_iC * impulse * JwC; + cD -= m_mD * impulse * JvBD; + aD -= m_iD * impulse * JwD; - b1->SynchronizeTransform(); - b2->SynchronizeTransform(); + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + data.positions[m_indexC].c = cC; + data.positions[m_indexC].a = aC; + data.positions[m_indexD].c = cD; + data.positions[m_indexD].a = aD; // TODO_ERIN not implemented return linearError < b2_linearSlop; @@ -223,27 +368,23 @@ bool b2GearJoint::SolvePositionConstraints(float32 baumgarte) b2Vec2 b2GearJoint::GetAnchorA() const { - return m_bodyA->GetWorldPoint(m_localAnchor1); + return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2GearJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchor2); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2GearJoint::GetReactionForce(float32 inv_dt) const { - // TODO_ERIN not tested - b2Vec2 P = m_impulse * m_J.linearB; + b2Vec2 P = m_impulse * m_JvAC; return inv_dt * P; } float32 b2GearJoint::GetReactionTorque(float32 inv_dt) const { - // TODO_ERIN not tested - b2Vec2 r = b2Mul(m_bodyB->GetTransform().R, m_localAnchor2 - m_bodyB->GetLocalCenter()); - b2Vec2 P = m_impulse * m_J.linearB; - float32 L = m_impulse * m_J.angularB - b2Cross(r, P); + float32 L = m_impulse * m_JwA; return inv_dt * L; } diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.h old mode 100644 new mode 100755 index eccca0da0..5651d5418 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -21,12 +21,8 @@ #include -class b2RevoluteJoint; -class b2PrismaticJoint; - /// Gear joint definition. This definition requires two existing /// revolute or prismatic joints (any combination will work). -/// The provided joints must attach a dynamic body to a static body. struct b2GearJointDef : public b2JointDef { b2GearJointDef() @@ -55,8 +51,8 @@ struct b2GearJointDef : public b2JointDef /// The ratio can be negative or positive. If one joint is a revolute joint /// and the other joint is a prismatic joint, then the ratio will have units /// of length or units of 1/length. -/// @warning The revolute and prismatic joints must be attached to -/// fixed bodies (which must be body1 on those joints). +/// @warning You have to manually destroy the gear joint if joint1 or joint2 +/// is destroyed. class b2GearJoint : public b2Joint { public: @@ -75,37 +71,43 @@ protected: friend class b2Joint; b2GearJoint(const b2GearJointDef* data); - void InitVelocityConstraints(const b2TimeStep& step); - void SolveVelocityConstraints(const b2TimeStep& step); - bool SolvePositionConstraints(float32 baumgarte); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - b2Body* m_ground1; - b2Body* m_ground2; + b2JointType m_typeA; + b2JointType m_typeB; - // One of these is NULL. - b2RevoluteJoint* m_revolute1; - b2PrismaticJoint* m_prismatic1; + // Body A is connected to body C + // Body B is connected to body D + b2Body* m_bodyC; + b2Body* m_bodyD; - // One of these is NULL. - b2RevoluteJoint* m_revolute2; - b2PrismaticJoint* m_prismatic2; + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec2 m_localAnchorC; + b2Vec2 m_localAnchorD; - b2Vec2 m_groundAnchor1; - b2Vec2 m_groundAnchor2; + b2Vec2 m_localAxisC; + b2Vec2 m_localAxisD; - b2Vec2 m_localAnchor1; - b2Vec2 m_localAnchor2; - - b2Jacobian m_J; + float32 m_referenceAngleA; + float32 m_referenceAngleB; float32 m_constant; float32 m_ratio; - // Effective mass - float32 m_mass; - - // Impulse for accumulation/warm starting. float32 m_impulse; + + // Solver temp + int32 m_indexA, m_indexB, m_indexC, m_indexD; + b2Vec2 m_lcA, m_lcB, m_lcC, m_lcD; + float32 m_mA, m_mB, m_mC, m_mD; + float32 m_iA, m_iB, m_iC, m_iD; + b2Vec2 m_JvAC, m_JvBD; + float32 m_JwA, m_JwB, m_JwC, m_JwD; + float32 m_mass; }; #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.cpp old mode 100644 new mode 100755 index a7e19d34d..eee195a9d --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -18,7 +18,7 @@ #include #include -#include +#include #include #include #include @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -80,10 +81,10 @@ b2Joint* b2Joint::Create(const b2JointDef* def, b2BlockAllocator* allocator) } break; - case e_lineJoint: + case e_wheelJoint: { - void* mem = allocator->Allocate(sizeof(b2LineJoint)); - joint = new (mem) b2LineJoint((b2LineJointDef*)def); + void* mem = allocator->Allocate(sizeof(b2WheelJoint)); + joint = new (mem) b2WheelJoint((b2WheelJointDef*)def); } break; @@ -101,6 +102,13 @@ b2Joint* b2Joint::Create(const b2JointDef* def, b2BlockAllocator* allocator) } break; + case e_ropeJoint: + { + void* mem = allocator->Allocate(sizeof(b2RopeJoint)); + joint = new (mem) b2RopeJoint((b2RopeJointDef*)def); + } + break; + default: b2Assert(false); break; @@ -138,8 +146,8 @@ void b2Joint::Destroy(b2Joint* joint, b2BlockAllocator* allocator) allocator->Free(joint, sizeof(b2GearJoint)); break; - case e_lineJoint: - allocator->Free(joint, sizeof(b2LineJoint)); + case e_wheelJoint: + allocator->Free(joint, sizeof(b2WheelJoint)); break; case e_weldJoint: @@ -150,6 +158,10 @@ void b2Joint::Destroy(b2Joint* joint, b2BlockAllocator* allocator) allocator->Free(joint, sizeof(b2FrictionJoint)); break; + case e_ropeJoint: + allocator->Free(joint, sizeof(b2RopeJoint)); + break; + default: b2Assert(false); break; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.h old mode 100644 new mode 100755 index 213ad7d1d..ed6ad4103 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -23,7 +23,7 @@ class b2Body; class b2Joint; -struct b2TimeStep; +struct b2SolverData; class b2BlockAllocator; enum b2JointType @@ -35,9 +35,10 @@ enum b2JointType e_pulleyJoint, e_mouseJoint, e_gearJoint, - e_lineJoint, + e_wheelJoint, e_weldJoint, e_frictionJoint, + e_ropeJoint }; enum b2LimitState @@ -50,14 +51,9 @@ enum b2LimitState struct b2Jacobian { - b2Vec2 linearA; + b2Vec2 linear; float32 angularA; - b2Vec2 linearB; float32 angularB; - - void SetZero(); - void Set(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2); - float32 Compute(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2); }; /// A joint edge is used to connect bodies and joints together @@ -130,6 +126,7 @@ public: /// Get the next joint the world joint list. b2Joint* GetNext(); + const b2Joint* GetNext() const; /// Get the user data pointer. void* GetUserData() const; @@ -140,6 +137,11 @@ public: /// Short-cut function to determine if either body is inactive. bool IsActive() const; + /// Get collide connected. + /// Note: modifying the collide connect flag won't work correctly because + /// the flag is only checked when fixture AABBs begin to overlap. + bool GetCollideConnected() const; + protected: friend class b2World; friend class b2Body; @@ -151,11 +153,11 @@ protected: b2Joint(const b2JointDef* def); virtual ~b2Joint() {} - virtual void InitVelocityConstraints(const b2TimeStep& step) = 0; - virtual void SolveVelocityConstraints(const b2TimeStep& step) = 0; + virtual void InitVelocityConstraints(const b2SolverData& data) = 0; + virtual void SolveVelocityConstraints(const b2SolverData& data) = 0; // This returns true if the position errors are within tolerance. - virtual bool SolvePositionConstraints(float32 baumgarte) = 0; + virtual bool SolvePositionConstraints(const b2SolverData& data) = 0; b2JointType m_type; b2Joint* m_prev; @@ -169,30 +171,8 @@ protected: bool m_collideConnected; void* m_userData; - - // Cache here per time step to reduce cache misses. - b2Vec2 m_localCenterA, m_localCenterB; - float32 m_invMassA, m_invIA; - float32 m_invMassB, m_invIB; }; -inline void b2Jacobian::SetZero() -{ - linearA.SetZero(); angularA = 0.0f; - linearB.SetZero(); angularB = 0.0f; -} - -inline void b2Jacobian::Set(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2) -{ - linearA = x1; angularA = a1; - linearB = x2; angularB = a2; -} - -inline float32 b2Jacobian::Compute(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2) -{ - return b2Dot(linearA, x1) + angularA * a1 + b2Dot(linearB, x2) + angularB * a2; -} - inline b2JointType b2Joint::GetType() const { return m_type; @@ -213,6 +193,11 @@ inline b2Joint* b2Joint::GetNext() return m_next; } +inline const b2Joint* b2Joint::GetNext() const +{ + return m_next; +} + inline void* b2Joint::GetUserData() const { return m_userData; @@ -223,4 +208,9 @@ inline void b2Joint::SetUserData(void* data) m_userData = data; } +inline bool b2Joint::GetCollideConnected() const +{ + return m_collideConnected; +} + #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.cpp deleted file mode 100644 index b6b0a1cb2..000000000 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.cpp +++ /dev/null @@ -1,591 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// Linear constraint (point-to-line) -// d = p2 - p1 = x2 + r2 - x1 - r1 -// C = dot(perp, d) -// Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1)) -// = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2) -// J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)] -// -// K = J * invM * JT -// -// J = [-a -s1 a s2] -// a = perp -// s1 = cross(d + r1, a) = cross(p2 - x1, a) -// s2 = cross(r2, a) = cross(p2 - x2, a) - - -// Motor/Limit linear constraint -// C = dot(ax1, d) -// Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2) -// J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)] - -// Block Solver -// We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even -// when the mass has poor distribution (leading to large torques about the joint anchor points). -// -// The Jacobian has 3 rows: -// J = [-uT -s1 uT s2] // linear -// [-vT -a1 vT a2] // limit -// -// u = perp -// v = axis -// s1 = cross(d + r1, u), s2 = cross(r2, u) -// a1 = cross(d + r1, v), a2 = cross(r2, v) - -// M * (v2 - v1) = JT * df -// J * v2 = bias -// -// v2 = v1 + invM * JT * df -// J * (v1 + invM * JT * df) = bias -// K * df = bias - J * v1 = -Cdot -// K = J * invM * JT -// Cdot = J * v1 - bias -// -// Now solve for f2. -// df = f2 - f1 -// K * (f2 - f1) = -Cdot -// f2 = invK * (-Cdot) + f1 -// -// Clamp accumulated limit impulse. -// lower: f2(2) = max(f2(2), 0) -// upper: f2(2) = min(f2(2), 0) -// -// Solve for correct f2(1) -// K(1,1) * f2(1) = -Cdot(1) - K(1,2) * f2(2) + K(1,1:2) * f1 -// = -Cdot(1) - K(1,2) * f2(2) + K(1,1) * f1(1) + K(1,2) * f1(2) -// K(1,1) * f2(1) = -Cdot(1) - K(1,2) * (f2(2) - f1(2)) + K(1,1) * f1(1) -// f2(1) = invK(1,1) * (-Cdot(1) - K(1,2) * (f2(2) - f1(2))) + f1(1) -// -// Now compute impulse to be applied: -// df = f2 - f1 - -void b2LineJointDef::Initialize(b2Body* b1, b2Body* b2, const b2Vec2& anchor, const b2Vec2& axis) -{ - bodyA = b1; - bodyB = b2; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - localAxisA = bodyA->GetLocalVector(axis); -} - -b2LineJoint::b2LineJoint(const b2LineJointDef* def) -: b2Joint(def) -{ - m_localAnchor1 = def->localAnchorA; - m_localAnchor2 = def->localAnchorB; - m_localXAxis1 = def->localAxisA; - m_localYAxis1 = b2Cross(1.0f, m_localXAxis1); - - m_impulse.SetZero(); - m_motorMass = 0.0; - m_motorImpulse = 0.0f; - - m_lowerTranslation = def->lowerTranslation; - m_upperTranslation = def->upperTranslation; - m_maxMotorForce = def->maxMotorForce; - m_motorSpeed = def->motorSpeed; - m_enableLimit = def->enableLimit; - m_enableMotor = def->enableMotor; - m_limitState = e_inactiveLimit; - - m_axis.SetZero(); - m_perp.SetZero(); -} - -void b2LineJoint::InitVelocityConstraints(const b2TimeStep& step) -{ - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; - - m_localCenterA = b1->GetLocalCenter(); - m_localCenterB = b2->GetLocalCenter(); - - b2Transform xf1 = b1->GetTransform(); - b2Transform xf2 = b2->GetTransform(); - - // Compute the effective masses. - b2Vec2 r1 = b2Mul(xf1.R, m_localAnchor1 - m_localCenterA); - b2Vec2 r2 = b2Mul(xf2.R, m_localAnchor2 - m_localCenterB); - b2Vec2 d = b2->m_sweep.c + r2 - b1->m_sweep.c - r1; - - m_invMassA = b1->m_invMass; - m_invIA = b1->m_invI; - m_invMassB = b2->m_invMass; - m_invIB = b2->m_invI; - - // Compute motor Jacobian and effective mass. - { - m_axis = b2Mul(xf1.R, m_localXAxis1); - m_a1 = b2Cross(d + r1, m_axis); - m_a2 = b2Cross(r2, m_axis); - - m_motorMass = m_invMassA + m_invMassB + m_invIA * m_a1 * m_a1 + m_invIB * m_a2 * m_a2; - if (m_motorMass > b2_epsilon) - { - m_motorMass = 1.0f / m_motorMass; - } - else - { - m_motorMass = 0.0f; - } - } - - // Prismatic constraint. - { - m_perp = b2Mul(xf1.R, m_localYAxis1); - - m_s1 = b2Cross(d + r1, m_perp); - m_s2 = b2Cross(r2, m_perp); - - float32 m1 = m_invMassA, m2 = m_invMassB; - float32 i1 = m_invIA, i2 = m_invIB; - - float32 k11 = m1 + m2 + i1 * m_s1 * m_s1 + i2 * m_s2 * m_s2; - float32 k12 = i1 * m_s1 * m_a1 + i2 * m_s2 * m_a2; - float32 k22 = m1 + m2 + i1 * m_a1 * m_a1 + i2 * m_a2 * m_a2; - - m_K.col1.Set(k11, k12); - m_K.col2.Set(k12, k22); - } - - // Compute motor and limit terms. - if (m_enableLimit) - { - float32 jointTranslation = b2Dot(m_axis, d); - if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) - { - m_limitState = e_equalLimits; - } - else if (jointTranslation <= m_lowerTranslation) - { - if (m_limitState != e_atLowerLimit) - { - m_limitState = e_atLowerLimit; - m_impulse.y = 0.0f; - } - } - else if (jointTranslation >= m_upperTranslation) - { - if (m_limitState != e_atUpperLimit) - { - m_limitState = e_atUpperLimit; - m_impulse.y = 0.0f; - } - } - else - { - m_limitState = e_inactiveLimit; - m_impulse.y = 0.0f; - } - } - else - { - m_limitState = e_inactiveLimit; - } - - if (m_enableMotor == false) - { - m_motorImpulse = 0.0f; - } - - if (step.warmStarting) - { - // Account for variable time step. - m_impulse *= step.dtRatio; - m_motorImpulse *= step.dtRatio; - - b2Vec2 P = m_impulse.x * m_perp + (m_motorImpulse + m_impulse.y) * m_axis; - float32 L1 = m_impulse.x * m_s1 + (m_motorImpulse + m_impulse.y) * m_a1; - float32 L2 = m_impulse.x * m_s2 + (m_motorImpulse + m_impulse.y) * m_a2; - - b1->m_linearVelocity -= m_invMassA * P; - b1->m_angularVelocity -= m_invIA * L1; - - b2->m_linearVelocity += m_invMassB * P; - b2->m_angularVelocity += m_invIB * L2; - } - else - { - m_impulse.SetZero(); - m_motorImpulse = 0.0f; - } -} - -void b2LineJoint::SolveVelocityConstraints(const b2TimeStep& step) -{ - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; - - b2Vec2 v1 = b1->m_linearVelocity; - float32 w1 = b1->m_angularVelocity; - b2Vec2 v2 = b2->m_linearVelocity; - float32 w2 = b2->m_angularVelocity; - - // Solve linear motor constraint. - if (m_enableMotor && m_limitState != e_equalLimits) - { - float32 Cdot = b2Dot(m_axis, v2 - v1) + m_a2 * w2 - m_a1 * w1; - float32 impulse = m_motorMass * (m_motorSpeed - Cdot); - float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = step.dt * m_maxMotorForce; - m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_motorImpulse - oldImpulse; - - b2Vec2 P = impulse * m_axis; - float32 L1 = impulse * m_a1; - float32 L2 = impulse * m_a2; - - v1 -= m_invMassA * P; - w1 -= m_invIA * L1; - - v2 += m_invMassB * P; - w2 += m_invIB * L2; - } - - float32 Cdot1 = b2Dot(m_perp, v2 - v1) + m_s2 * w2 - m_s1 * w1; - - if (m_enableLimit && m_limitState != e_inactiveLimit) - { - // Solve prismatic and limit constraint in block form. - float32 Cdot2 = b2Dot(m_axis, v2 - v1) + m_a2 * w2 - m_a1 * w1; - b2Vec2 Cdot(Cdot1, Cdot2); - - b2Vec2 f1 = m_impulse; - b2Vec2 df = m_K.Solve(-Cdot); - m_impulse += df; - - if (m_limitState == e_atLowerLimit) - { - m_impulse.y = b2Max(m_impulse.y, 0.0f); - } - else if (m_limitState == e_atUpperLimit) - { - m_impulse.y = b2Min(m_impulse.y, 0.0f); - } - - // f2(1) = invK(1,1) * (-Cdot(1) - K(1,2) * (f2(2) - f1(2))) + f1(1) - float32 b = -Cdot1 - (m_impulse.y - f1.y) * m_K.col2.x; - float32 f2r; - if (m_K.col1.x != 0.0f) - { - f2r = b / m_K.col1.x + f1.x; - } - else - { - f2r = f1.x; - } - - m_impulse.x = f2r; - - df = m_impulse - f1; - - b2Vec2 P = df.x * m_perp + df.y * m_axis; - float32 L1 = df.x * m_s1 + df.y * m_a1; - float32 L2 = df.x * m_s2 + df.y * m_a2; - - v1 -= m_invMassA * P; - w1 -= m_invIA * L1; - - v2 += m_invMassB * P; - w2 += m_invIB * L2; - } - else - { - // Limit is inactive, just solve the prismatic constraint in block form. - float32 df; - if (m_K.col1.x != 0.0f) - { - df = - Cdot1 / m_K.col1.x; - } - else - { - df = 0.0f; - } - m_impulse.x += df; - - b2Vec2 P = df * m_perp; - float32 L1 = df * m_s1; - float32 L2 = df * m_s2; - - v1 -= m_invMassA * P; - w1 -= m_invIA * L1; - - v2 += m_invMassB * P; - w2 += m_invIB * L2; - } - - b1->m_linearVelocity = v1; - b1->m_angularVelocity = w1; - b2->m_linearVelocity = v2; - b2->m_angularVelocity = w2; -} - -bool b2LineJoint::SolvePositionConstraints(float32 baumgarte) -{ - B2_NOT_USED(baumgarte); - - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; - - b2Vec2 c1 = b1->m_sweep.c; - float32 a1 = b1->m_sweep.a; - - b2Vec2 c2 = b2->m_sweep.c; - float32 a2 = b2->m_sweep.a; - - // Solve linear limit constraint. - float32 linearError = 0.0f, angularError = 0.0f; - bool active = false; - float32 C2 = 0.0f; - - b2Mat22 R1(a1), R2(a2); - - b2Vec2 r1 = b2Mul(R1, m_localAnchor1 - m_localCenterA); - b2Vec2 r2 = b2Mul(R2, m_localAnchor2 - m_localCenterB); - b2Vec2 d = c2 + r2 - c1 - r1; - - if (m_enableLimit) - { - m_axis = b2Mul(R1, m_localXAxis1); - - m_a1 = b2Cross(d + r1, m_axis); - m_a2 = b2Cross(r2, m_axis); - - float32 translation = b2Dot(m_axis, d); - if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) - { - // Prevent large angular corrections - C2 = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection); - linearError = b2Abs(translation); - active = true; - } - else if (translation <= m_lowerTranslation) - { - // Prevent large linear corrections and allow some slop. - C2 = b2Clamp(translation - m_lowerTranslation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); - linearError = m_lowerTranslation - translation; - active = true; - } - else if (translation >= m_upperTranslation) - { - // Prevent large linear corrections and allow some slop. - C2 = b2Clamp(translation - m_upperTranslation - b2_linearSlop, 0.0f, b2_maxLinearCorrection); - linearError = translation - m_upperTranslation; - active = true; - } - } - - m_perp = b2Mul(R1, m_localYAxis1); - - m_s1 = b2Cross(d + r1, m_perp); - m_s2 = b2Cross(r2, m_perp); - - b2Vec2 impulse; - float32 C1; - C1 = b2Dot(m_perp, d); - - linearError = b2Max(linearError, b2Abs(C1)); - angularError = 0.0f; - - if (active) - { - float32 m1 = m_invMassA, m2 = m_invMassB; - float32 i1 = m_invIA, i2 = m_invIB; - - float32 k11 = m1 + m2 + i1 * m_s1 * m_s1 + i2 * m_s2 * m_s2; - float32 k12 = i1 * m_s1 * m_a1 + i2 * m_s2 * m_a2; - float32 k22 = m1 + m2 + i1 * m_a1 * m_a1 + i2 * m_a2 * m_a2; - - m_K.col1.Set(k11, k12); - m_K.col2.Set(k12, k22); - - b2Vec2 C; - C.x = C1; - C.y = C2; - - impulse = m_K.Solve(-C); - } - else - { - float32 m1 = m_invMassA, m2 = m_invMassB; - float32 i1 = m_invIA, i2 = m_invIB; - - float32 k11 = m1 + m2 + i1 * m_s1 * m_s1 + i2 * m_s2 * m_s2; - - float32 impulse1; - if (k11 != 0.0f) - { - impulse1 = - C1 / k11; - } - else - { - impulse1 = 0.0f; - } - - impulse.x = impulse1; - impulse.y = 0.0f; - } - - b2Vec2 P = impulse.x * m_perp + impulse.y * m_axis; - float32 L1 = impulse.x * m_s1 + impulse.y * m_a1; - float32 L2 = impulse.x * m_s2 + impulse.y * m_a2; - - c1 -= m_invMassA * P; - a1 -= m_invIA * L1; - c2 += m_invMassB * P; - a2 += m_invIB * L2; - - // TODO_ERIN remove need for this. - b1->m_sweep.c = c1; - b1->m_sweep.a = a1; - b2->m_sweep.c = c2; - b2->m_sweep.a = a2; - b1->SynchronizeTransform(); - b2->SynchronizeTransform(); - - return linearError <= b2_linearSlop && angularError <= b2_angularSlop; -} - -b2Vec2 b2LineJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchor1); -} - -b2Vec2 b2LineJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchor2); -} - -b2Vec2 b2LineJoint::GetReactionForce(float32 inv_dt) const -{ - return inv_dt * (m_impulse.x * m_perp + (m_motorImpulse + m_impulse.y) * m_axis); -} - -float32 b2LineJoint::GetReactionTorque(float32 inv_dt) const -{ - B2_NOT_USED(inv_dt); - return 0.0f; -} - -float32 b2LineJoint::GetJointTranslation() const -{ - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; - - b2Vec2 p1 = b1->GetWorldPoint(m_localAnchor1); - b2Vec2 p2 = b2->GetWorldPoint(m_localAnchor2); - b2Vec2 d = p2 - p1; - b2Vec2 axis = b1->GetWorldVector(m_localXAxis1); - - float32 translation = b2Dot(d, axis); - return translation; -} - -float32 b2LineJoint::GetJointSpeed() const -{ - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; - - b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); - b2Vec2 p1 = b1->m_sweep.c + r1; - b2Vec2 p2 = b2->m_sweep.c + r2; - b2Vec2 d = p2 - p1; - b2Vec2 axis = b1->GetWorldVector(m_localXAxis1); - - b2Vec2 v1 = b1->m_linearVelocity; - b2Vec2 v2 = b2->m_linearVelocity; - float32 w1 = b1->m_angularVelocity; - float32 w2 = b2->m_angularVelocity; - - float32 speed = b2Dot(d, b2Cross(w1, axis)) + b2Dot(axis, v2 + b2Cross(w2, r2) - v1 - b2Cross(w1, r1)); - return speed; -} - -bool b2LineJoint::IsLimitEnabled() const -{ - return m_enableLimit; -} - -void b2LineJoint::EnableLimit(bool flag) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableLimit = flag; -} - -float32 b2LineJoint::GetLowerLimit() const -{ - return m_lowerTranslation; -} - -float32 b2LineJoint::GetUpperLimit() const -{ - return m_upperTranslation; -} - -void b2LineJoint::SetLimits(float32 lower, float32 upper) -{ - b2Assert(lower <= upper); - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_lowerTranslation = lower; - m_upperTranslation = upper; -} - -bool b2LineJoint::IsMotorEnabled() const -{ - return m_enableMotor; -} - -void b2LineJoint::EnableMotor(bool flag) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableMotor = flag; -} - -void b2LineJoint::SetMotorSpeed(float32 speed) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_motorSpeed = speed; -} - -void b2LineJoint::SetMaxMotorForce(float32 force) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_maxMotorForce = force; -} - -float32 b2LineJoint::GetMotorForce() const -{ - return m_motorImpulse; -} - - - - - diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.h deleted file mode 100644 index 803e4c12d..000000000 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2LineJoint.h +++ /dev/null @@ -1,170 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_LINE_JOINT_H -#define B2_LINE_JOINT_H - -#include - -/// Line joint definition. This requires defining a line of -/// motion using an axis and an anchor point. The definition uses local -/// anchor points and a local axis so that the initial configuration -/// can violate the constraint slightly. The joint translation is zero -/// when the local anchor points coincide in world space. Using local -/// anchors and a local axis helps when saving and loading a game. -struct b2LineJointDef : public b2JointDef -{ - b2LineJointDef() - { - type = e_lineJoint; - localAnchorA.SetZero(); - localAnchorB.SetZero(); - localAxisA.Set(1.0f, 0.0f); - enableLimit = false; - lowerTranslation = 0.0f; - upperTranslation = 0.0f; - enableMotor = false; - maxMotorForce = 0.0f; - motorSpeed = 0.0f; - } - - /// Initialize the bodies, anchors, axis, and reference angle using the world - /// anchor and world axis. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); - - /// The local anchor point relative to body1's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to body2's origin. - b2Vec2 localAnchorB; - - /// The local translation axis in body1. - b2Vec2 localAxisA; - - /// Enable/disable the joint limit. - bool enableLimit; - - /// The lower translation limit, usually in meters. - float32 lowerTranslation; - - /// The upper translation limit, usually in meters. - float32 upperTranslation; - - /// Enable/disable the joint motor. - bool enableMotor; - - /// The maximum motor torque, usually in N-m. - float32 maxMotorForce; - - /// The desired motor speed in radians per second. - float32 motorSpeed; -}; - -/// A line joint. This joint provides two degrees of freedom: translation -/// along an axis fixed in body1 and rotation in the plane. You can use a -/// joint limit to restrict the range of motion and a joint motor to drive -/// the motion or to model joint friction. -class b2LineJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// Get the current joint translation, usually in meters. - float32 GetJointTranslation() const; - - /// Get the current joint translation speed, usually in meters per second. - float32 GetJointSpeed() const; - - /// Is the joint limit enabled? - bool IsLimitEnabled() const; - - /// Enable/disable the joint limit. - void EnableLimit(bool flag); - - /// Get the lower joint limit, usually in meters. - float32 GetLowerLimit() const; - - /// Get the upper joint limit, usually in meters. - float32 GetUpperLimit() const; - - /// Set the joint limits, usually in meters. - void SetLimits(float32 lower, float32 upper); - - /// Is the joint motor enabled? - bool IsMotorEnabled() const; - - /// Enable/disable the joint motor. - void EnableMotor(bool flag); - - /// Set the motor speed, usually in meters per second. - void SetMotorSpeed(float32 speed); - - /// Get the motor speed, usually in meters per second. - float32 GetMotorSpeed() const; - - /// Set/Get the maximum motor force, usually in N. - void SetMaxMotorForce(float32 force); - float32 GetMaxMotorForce() const; - - /// Get the current motor force, usually in N. - float32 GetMotorForce() const; - -protected: - - friend class b2Joint; - b2LineJoint(const b2LineJointDef* def); - - void InitVelocityConstraints(const b2TimeStep& step); - void SolveVelocityConstraints(const b2TimeStep& step); - bool SolvePositionConstraints(float32 baumgarte); - - b2Vec2 m_localAnchor1; - b2Vec2 m_localAnchor2; - b2Vec2 m_localXAxis1; - b2Vec2 m_localYAxis1; - - b2Vec2 m_axis, m_perp; - float32 m_s1, m_s2; - float32 m_a1, m_a2; - - b2Mat22 m_K; - b2Vec2 m_impulse; - - float32 m_motorMass; // effective mass for motor/limit translational constraint. - float32 m_motorImpulse; - - float32 m_lowerTranslation; - float32 m_upperTranslation; - float32 m_maxMotorForce; - float32 m_motorSpeed; - - bool m_enableLimit; - bool m_enableMotor; - b2LimitState m_limitState; -}; - -inline float32 b2LineJoint::GetMotorSpeed() const -{ - return m_motorSpeed; -} - -#endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.cpp old mode 100644 new mode 100755 index b72ac5f30..be7c38348 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -36,8 +36,8 @@ b2MouseJoint::b2MouseJoint(const b2MouseJointDef* def) b2Assert(b2IsValid(def->frequencyHz) && def->frequencyHz >= 0.0f); b2Assert(b2IsValid(def->dampingRatio) && def->dampingRatio >= 0.0f); - m_target = def->target; - m_localAnchor = b2MulT(m_bodyB->GetTransform(), m_target); + m_targetA = def->target; + m_localAnchorB = b2MulT(m_bodyB->GetTransform(), m_targetA); m_maxForce = def->maxForce; m_impulse.SetZero(); @@ -55,12 +55,12 @@ void b2MouseJoint::SetTarget(const b2Vec2& target) { m_bodyB->SetAwake(true); } - m_target = target; + m_targetA = target; } const b2Vec2& b2MouseJoint::GetTarget() const { - return m_target; + return m_targetA; } void b2MouseJoint::SetMaxForce(float32 force) @@ -93,11 +93,21 @@ float32 b2MouseJoint::GetDampingRatio() const return m_dampingRatio; } -void b2MouseJoint::InitVelocityConstraints(const b2TimeStep& step) +void b2MouseJoint::InitVelocityConstraints(const b2SolverData& data) { - b2Body* b = m_bodyB; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassB = m_bodyB->m_invMass; + m_invIB = m_bodyB->m_invI; - float32 mass = b->GetMass(); + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qB(aB); + + float32 mass = m_bodyB->GetMass(); // Frequency float32 omega = 2.0f * b2_pi * m_frequencyHz; @@ -111,79 +121,89 @@ void b2MouseJoint::InitVelocityConstraints(const b2TimeStep& step) // magic formulas // gamma has units of inverse mass. // beta has units of inverse time. - b2Assert(d + step.dt * k > b2_epsilon); - m_gamma = step.dt * (d + step.dt * k); + float32 h = data.step.dt; + b2Assert(d + h * k > b2_epsilon); + m_gamma = h * (d + h * k); if (m_gamma != 0.0f) { m_gamma = 1.0f / m_gamma; } - m_beta = step.dt * k * m_gamma; + m_beta = h * k * m_gamma; // Compute the effective mass matrix. - b2Vec2 r = b2Mul(b->GetTransform().R, m_localAnchor - b->GetLocalCenter()); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] - float32 invMass = b->m_invMass; - float32 invI = b->m_invI; - - b2Mat22 K1; - K1.col1.x = invMass; K1.col2.x = 0.0f; - K1.col1.y = 0.0f; K1.col2.y = invMass; - - b2Mat22 K2; - K2.col1.x = invI * r.y * r.y; K2.col2.x = -invI * r.x * r.y; - K2.col1.y = -invI * r.x * r.y; K2.col2.y = invI * r.x * r.x; - - b2Mat22 K = K1 + K2; - K.col1.x += m_gamma; - K.col2.y += m_gamma; + b2Mat22 K; + K.ex.x = m_invMassB + m_invIB * m_rB.y * m_rB.y + m_gamma; + K.ex.y = -m_invIB * m_rB.x * m_rB.y; + K.ey.x = K.ex.y; + K.ey.y = m_invMassB + m_invIB * m_rB.x * m_rB.x + m_gamma; m_mass = K.GetInverse(); - m_C = b->m_sweep.c + r - m_target; + m_C = cB + m_rB - m_targetA; + m_C *= m_beta; // Cheat with some damping - b->m_angularVelocity *= 0.98f; + wB *= 0.98f; - // Warm starting. - m_impulse *= step.dtRatio; - b->m_linearVelocity += invMass * m_impulse; - b->m_angularVelocity += invI * b2Cross(r, m_impulse); + if (data.step.warmStarting) + { + m_impulse *= data.step.dtRatio; + vB += m_invMassB * m_impulse; + wB += m_invIB * b2Cross(m_rB, m_impulse); + } + else + { + m_impulse.SetZero(); + } + + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } -void b2MouseJoint::SolveVelocityConstraints(const b2TimeStep& step) +void b2MouseJoint::SolveVelocityConstraints(const b2SolverData& data) { - b2Body* b = m_bodyB; - - b2Vec2 r = b2Mul(b->GetTransform().R, m_localAnchor - b->GetLocalCenter()); + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; // Cdot = v + cross(w, r) - b2Vec2 Cdot = b->m_linearVelocity + b2Cross(b->m_angularVelocity, r); - b2Vec2 impulse = b2Mul(m_mass, -(Cdot + m_beta * m_C + m_gamma * m_impulse)); + b2Vec2 Cdot = vB + b2Cross(wB, m_rB); + b2Vec2 impulse = b2Mul(m_mass, -(Cdot + m_C + m_gamma * m_impulse)); b2Vec2 oldImpulse = m_impulse; m_impulse += impulse; - float32 maxImpulse = step.dt * m_maxForce; + float32 maxImpulse = data.step.dt * m_maxForce; if (m_impulse.LengthSquared() > maxImpulse * maxImpulse) { m_impulse *= maxImpulse / m_impulse.Length(); } impulse = m_impulse - oldImpulse; - b->m_linearVelocity += b->m_invMass * impulse; - b->m_angularVelocity += b->m_invI * b2Cross(r, impulse); + vB += m_invMassB * impulse; + wB += m_invIB * b2Cross(m_rB, impulse); + + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2MouseJoint::SolvePositionConstraints(const b2SolverData& data) +{ + B2_NOT_USED(data); + return true; } b2Vec2 b2MouseJoint::GetAnchorA() const { - return m_target; + return m_targetA; } b2Vec2 b2MouseJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchor); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2MouseJoint::GetReactionForce(float32 inv_dt) const diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.h old mode 100644 new mode 100755 index cd1959a42..3c90d0161 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -94,21 +94,30 @@ protected: b2MouseJoint(const b2MouseJointDef* def); - void InitVelocityConstraints(const b2TimeStep& step); - void SolveVelocityConstraints(const b2TimeStep& step); - bool SolvePositionConstraints(float32 baumgarte) { B2_NOT_USED(baumgarte); return true; } + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - b2Vec2 m_localAnchor; - b2Vec2 m_target; - b2Vec2 m_impulse; - - b2Mat22 m_mass; // effective mass for point-to-point constraint. - b2Vec2 m_C; // position error - float32 m_maxForce; + b2Vec2 m_localAnchorB; + b2Vec2 m_targetA; float32 m_frequencyHz; float32 m_dampingRatio; float32 m_beta; + + // Solver shared + b2Vec2 m_impulse; + float32 m_maxForce; float32 m_gamma; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rB; + b2Vec2 m_localCenterB; + float32 m_invMassB; + float32 m_invIB; + b2Mat22 m_mass; + b2Vec2 m_C; }; #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp old mode 100644 new mode 100755 index a019888a4..99f0c7d6f --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -87,23 +87,23 @@ // Now compute impulse to be applied: // df = f2 - f1 -void b2PrismaticJointDef::Initialize(b2Body* b1, b2Body* b2, const b2Vec2& anchor, const b2Vec2& axis) +void b2PrismaticJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) { - bodyA = b1; - bodyB = b2; + bodyA = bA; + bodyB = bB; localAnchorA = bodyA->GetLocalPoint(anchor); localAnchorB = bodyB->GetLocalPoint(anchor); - localAxis1 = bodyA->GetLocalVector(axis); + localAxisA = bodyA->GetLocalVector(axis); referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); } b2PrismaticJoint::b2PrismaticJoint(const b2PrismaticJointDef* def) : b2Joint(def) { - m_localAnchor1 = def->localAnchorA; - m_localAnchor2 = def->localAnchorB; - m_localXAxis1 = def->localAxis1; - m_localYAxis1 = b2Cross(1.0f, m_localXAxis1); + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_localXAxisA = def->localAxisA; + m_localYAxisA = b2Cross(1.0f, m_localXAxisA); m_refAngle = def->referenceAngle; m_impulse.SetZero(); @@ -122,35 +122,45 @@ b2PrismaticJoint::b2PrismaticJoint(const b2PrismaticJointDef* def) m_perp.SetZero(); } -void b2PrismaticJoint::InitVelocityConstraints(const b2TimeStep& step) +void b2PrismaticJoint::InitVelocityConstraints(const b2SolverData& data) { - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; - m_localCenterA = b1->GetLocalCenter(); - m_localCenterB = b2->GetLocalCenter(); + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; - b2Transform xf1 = b1->GetTransform(); - b2Transform xf2 = b2->GetTransform(); + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); // Compute the effective masses. - b2Vec2 r1 = b2Mul(xf1.R, m_localAnchor1 - m_localCenterA); - b2Vec2 r2 = b2Mul(xf2.R, m_localAnchor2 - m_localCenterB); - b2Vec2 d = b2->m_sweep.c + r2 - b1->m_sweep.c - r1; + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = (cB - cA) + rB - rA; - m_invMassA = b1->m_invMass; - m_invIA = b1->m_invI; - m_invMassB = b2->m_invMass; - m_invIB = b2->m_invI; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; // Compute motor Jacobian and effective mass. { - m_axis = b2Mul(xf1.R, m_localXAxis1); - m_a1 = b2Cross(d + r1, m_axis); - m_a2 = b2Cross(r2, m_axis); + m_axis = b2Mul(qA, m_localXAxisA); + m_a1 = b2Cross(d + rA, m_axis); + m_a2 = b2Cross(rB, m_axis); - m_motorMass = m_invMassA + m_invMassB + m_invIA * m_a1 * m_a1 + m_invIB * m_a2 * m_a2; - if (m_motorMass > b2_epsilon) + m_motorMass = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; + if (m_motorMass > 0.0f) { m_motorMass = 1.0f / m_motorMass; } @@ -158,24 +168,26 @@ void b2PrismaticJoint::InitVelocityConstraints(const b2TimeStep& step) // Prismatic constraint. { - m_perp = b2Mul(xf1.R, m_localYAxis1); + m_perp = b2Mul(qA, m_localYAxisA); - m_s1 = b2Cross(d + r1, m_perp); - m_s2 = b2Cross(r2, m_perp); + m_s1 = b2Cross(d + rA, m_perp); + m_s2 = b2Cross(rB, m_perp); - float32 m1 = m_invMassA, m2 = m_invMassB; - float32 i1 = m_invIA, i2 = m_invIB; + float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2; + float32 k12 = iA * m_s1 + iB * m_s2; + float32 k13 = iA * m_s1 * m_a1 + iB * m_s2 * m_a2; + float32 k22 = iA + iB; + if (k22 == 0.0f) + { + // For bodies with fixed rotation. + k22 = 1.0f; + } + float32 k23 = iA * m_a1 + iB * m_a2; + float32 k33 = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; - float32 k11 = m1 + m2 + i1 * m_s1 * m_s1 + i2 * m_s2 * m_s2; - float32 k12 = i1 * m_s1 + i2 * m_s2; - float32 k13 = i1 * m_s1 * m_a1 + i2 * m_s2 * m_a2; - float32 k22 = i1 + i2; - float32 k23 = i1 * m_a1 + i2 * m_a2; - float32 k33 = m1 + m2 + i1 * m_a1 * m_a1 + i2 * m_a2 * m_a2; - - m_K.col1.Set(k11, k12, k13); - m_K.col2.Set(k12, k22, k23); - m_K.col3.Set(k13, k23, k33); + m_K.ex.Set(k11, k12, k13); + m_K.ey.Set(k12, k22, k23); + m_K.ez.Set(k13, k23, k33); } // Compute motor and limit terms. @@ -219,69 +231,74 @@ void b2PrismaticJoint::InitVelocityConstraints(const b2TimeStep& step) m_motorImpulse = 0.0f; } - if (step.warmStarting) + if (data.step.warmStarting) { // Account for variable time step. - m_impulse *= step.dtRatio; - m_motorImpulse *= step.dtRatio; + m_impulse *= data.step.dtRatio; + m_motorImpulse *= data.step.dtRatio; b2Vec2 P = m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis; - float32 L1 = m_impulse.x * m_s1 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a1; - float32 L2 = m_impulse.x * m_s2 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a2; + float32 LA = m_impulse.x * m_s1 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a1; + float32 LB = m_impulse.x * m_s2 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a2; - b1->m_linearVelocity -= m_invMassA * P; - b1->m_angularVelocity -= m_invIA * L1; + vA -= mA * P; + wA -= iA * LA; - b2->m_linearVelocity += m_invMassB * P; - b2->m_angularVelocity += m_invIB * L2; + vB += mB * P; + wB += iB * LB; } else { m_impulse.SetZero(); m_motorImpulse = 0.0f; } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } -void b2PrismaticJoint::SolveVelocityConstraints(const b2TimeStep& step) +void b2PrismaticJoint::SolveVelocityConstraints(const b2SolverData& data) { - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Vec2 v1 = b1->m_linearVelocity; - float32 w1 = b1->m_angularVelocity; - b2Vec2 v2 = b2->m_linearVelocity; - float32 w2 = b2->m_angularVelocity; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; // Solve linear motor constraint. if (m_enableMotor && m_limitState != e_equalLimits) { - float32 Cdot = b2Dot(m_axis, v2 - v1) + m_a2 * w2 - m_a1 * w1; + float32 Cdot = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; float32 impulse = m_motorMass * (m_motorSpeed - Cdot); float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = step.dt * m_maxMotorForce; + float32 maxImpulse = data.step.dt * m_maxMotorForce; m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = m_motorImpulse - oldImpulse; b2Vec2 P = impulse * m_axis; - float32 L1 = impulse * m_a1; - float32 L2 = impulse * m_a2; + float32 LA = impulse * m_a1; + float32 LB = impulse * m_a2; - v1 -= m_invMassA * P; - w1 -= m_invIA * L1; + vA -= mA * P; + wA -= iA * LA; - v2 += m_invMassB * P; - w2 += m_invIB * L2; + vB += mB * P; + wB += iB * LB; } b2Vec2 Cdot1; - Cdot1.x = b2Dot(m_perp, v2 - v1) + m_s2 * w2 - m_s1 * w1; - Cdot1.y = w2 - w1; + Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; + Cdot1.y = wB - wA; if (m_enableLimit && m_limitState != e_inactiveLimit) { // Solve prismatic and limit constraint in block form. float32 Cdot2; - Cdot2 = b2Dot(m_axis, v2 - v1) + m_a2 * w2 - m_a1 * w1; + Cdot2 = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); b2Vec3 f1 = m_impulse; @@ -298,7 +315,7 @@ void b2PrismaticJoint::SolveVelocityConstraints(const b2TimeStep& step) } // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) - b2Vec2 b = -Cdot1 - (m_impulse.z - f1.z) * b2Vec2(m_K.col3.x, m_K.col3.y); + b2Vec2 b = -Cdot1 - (m_impulse.z - f1.z) * b2Vec2(m_K.ez.x, m_K.ez.y); b2Vec2 f2r = m_K.Solve22(b) + b2Vec2(f1.x, f1.y); m_impulse.x = f2r.x; m_impulse.y = f2r.y; @@ -306,14 +323,14 @@ void b2PrismaticJoint::SolveVelocityConstraints(const b2TimeStep& step) df = m_impulse - f1; b2Vec2 P = df.x * m_perp + df.z * m_axis; - float32 L1 = df.x * m_s1 + df.y + df.z * m_a1; - float32 L2 = df.x * m_s2 + df.y + df.z * m_a2; + float32 LA = df.x * m_s1 + df.y + df.z * m_a1; + float32 LB = df.x * m_s2 + df.y + df.z * m_a2; - v1 -= m_invMassA * P; - w1 -= m_invIA * L1; + vA -= mA * P; + wA -= iA * LA; - v2 += m_invMassB * P; - w2 += m_invIB * L2; + vB += mB * P; + wB += iB * LB; } else { @@ -323,105 +340,100 @@ void b2PrismaticJoint::SolveVelocityConstraints(const b2TimeStep& step) m_impulse.y += df.y; b2Vec2 P = df.x * m_perp; - float32 L1 = df.x * m_s1 + df.y; - float32 L2 = df.x * m_s2 + df.y; + float32 LA = df.x * m_s1 + df.y; + float32 LB = df.x * m_s2 + df.y; - v1 -= m_invMassA * P; - w1 -= m_invIA * L1; + vA -= mA * P; + wA -= iA * LA; - v2 += m_invMassB * P; - w2 += m_invIB * L2; + vB += mB * P; + wB += iB * LB; } - b1->m_linearVelocity = v1; - b1->m_angularVelocity = w1; - b2->m_linearVelocity = v2; - b2->m_angularVelocity = w2; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } -bool b2PrismaticJoint::SolvePositionConstraints(float32 baumgarte) +bool b2PrismaticJoint::SolvePositionConstraints(const b2SolverData& data) { - B2_NOT_USED(baumgarte); + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + b2Rot qA(aA), qB(aB); - b2Vec2 c1 = b1->m_sweep.c; - float32 a1 = b1->m_sweep.a; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - b2Vec2 c2 = b2->m_sweep.c; - float32 a2 = b2->m_sweep.a; + // Compute fresh Jacobians + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = cB + rB - cA - rA; + + b2Vec2 axis = b2Mul(qA, m_localXAxisA); + float32 a1 = b2Cross(d + rA, axis); + float32 a2 = b2Cross(rB, axis); + b2Vec2 perp = b2Mul(qA, m_localYAxisA); + + float32 s1 = b2Cross(d + rA, perp); + float32 s2 = b2Cross(rB, perp); + + b2Vec3 impulse; + b2Vec2 C1; + C1.x = b2Dot(perp, d); + C1.y = aB - aA - m_refAngle; + + float32 linearError = b2Abs(C1.x); + float32 angularError = b2Abs(C1.y); - // Solve linear limit constraint. - float32 linearError = 0.0f, angularError = 0.0f; bool active = false; float32 C2 = 0.0f; - - b2Mat22 R1(a1), R2(a2); - - b2Vec2 r1 = b2Mul(R1, m_localAnchor1 - m_localCenterA); - b2Vec2 r2 = b2Mul(R2, m_localAnchor2 - m_localCenterB); - b2Vec2 d = c2 + r2 - c1 - r1; - if (m_enableLimit) { - m_axis = b2Mul(R1, m_localXAxis1); - - m_a1 = b2Cross(d + r1, m_axis); - m_a2 = b2Cross(r2, m_axis); - - float32 translation = b2Dot(m_axis, d); + float32 translation = b2Dot(axis, d); if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) { // Prevent large angular corrections C2 = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection); - linearError = b2Abs(translation); + linearError = b2Max(linearError, b2Abs(translation)); active = true; } else if (translation <= m_lowerTranslation) { // Prevent large linear corrections and allow some slop. C2 = b2Clamp(translation - m_lowerTranslation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); - linearError = m_lowerTranslation - translation; + linearError = b2Max(linearError, m_lowerTranslation - translation); active = true; } else if (translation >= m_upperTranslation) { // Prevent large linear corrections and allow some slop. C2 = b2Clamp(translation - m_upperTranslation - b2_linearSlop, 0.0f, b2_maxLinearCorrection); - linearError = translation - m_upperTranslation; + linearError = b2Max(linearError, translation - m_upperTranslation); active = true; } } - m_perp = b2Mul(R1, m_localYAxis1); - - m_s1 = b2Cross(d + r1, m_perp); - m_s2 = b2Cross(r2, m_perp); - - b2Vec3 impulse; - b2Vec2 C1; - C1.x = b2Dot(m_perp, d); - C1.y = a2 - a1 - m_refAngle; - - linearError = b2Max(linearError, b2Abs(C1.x)); - angularError = b2Abs(C1.y); - if (active) { - float32 m1 = m_invMassA, m2 = m_invMassB; - float32 i1 = m_invIA, i2 = m_invIB; + float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2; + float32 k12 = iA * m_s1 + iB * m_s2; + float32 k13 = iA * m_s1 * m_a1 + iB * m_s2 * m_a2; + float32 k22 = iA + iB; + if (k22 == 0.0f) + { + // For fixed rotation + k22 = 1.0f; + } + float32 k23 = iA * m_a1 + iB * m_a2; + float32 k33 = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; - float32 k11 = m1 + m2 + i1 * m_s1 * m_s1 + i2 * m_s2 * m_s2; - float32 k12 = i1 * m_s1 + i2 * m_s2; - float32 k13 = i1 * m_s1 * m_a1 + i2 * m_s2 * m_a2; - float32 k22 = i1 + i2; - float32 k23 = i1 * m_a1 + i2 * m_a2; - float32 k33 = m1 + m2 + i1 * m_a1 * m_a1 + i2 * m_a2 * m_a2; - - m_K.col1.Set(k11, k12, k13); - m_K.col2.Set(k12, k22, k23); - m_K.col3.Set(k13, k23, k33); + m_K.ex.Set(k11, k12, k13); + m_K.ey.Set(k12, k22, k23); + m_K.ez.Set(k13, k23, k33); b2Vec3 C; C.x = C1.x; @@ -432,15 +444,16 @@ bool b2PrismaticJoint::SolvePositionConstraints(float32 baumgarte) } else { - float32 m1 = m_invMassA, m2 = m_invMassB; - float32 i1 = m_invIA, i2 = m_invIB; + float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2; + float32 k12 = iA * m_s1 + iB * m_s2; + float32 k22 = iA + iB; + if (k22 == 0.0f) + { + k22 = 1.0f; + } - float32 k11 = m1 + m2 + i1 * m_s1 * m_s1 + i2 * m_s2 * m_s2; - float32 k12 = i1 * m_s1 + i2 * m_s2; - float32 k22 = i1 + i2; - - m_K.col1.Set(k11, k12, 0.0f); - m_K.col2.Set(k12, k22, 0.0f); + m_K.ex.Set(k11, k12, 0.0f); + m_K.ey.Set(k12, k22, 0.0f); b2Vec2 impulse1 = m_K.Solve22(-C1); impulse.x = impulse1.x; @@ -448,34 +461,31 @@ bool b2PrismaticJoint::SolvePositionConstraints(float32 baumgarte) impulse.z = 0.0f; } - b2Vec2 P = impulse.x * m_perp + impulse.z * m_axis; - float32 L1 = impulse.x * m_s1 + impulse.y + impulse.z * m_a1; - float32 L2 = impulse.x * m_s2 + impulse.y + impulse.z * m_a2; + b2Vec2 P = impulse.x * perp + impulse.z * axis; + float32 LA = impulse.x * s1 + impulse.y + impulse.z * a1; + float32 LB = impulse.x * s2 + impulse.y + impulse.z * a2; - c1 -= m_invMassA * P; - a1 -= m_invIA * L1; - c2 += m_invMassB * P; - a2 += m_invIB * L2; + cA -= mA * P; + aA -= iA * LA; + cB += mB * P; + aB += iB * LB; + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; - // TODO_ERIN remove need for this. - b1->m_sweep.c = c1; - b1->m_sweep.a = a1; - b2->m_sweep.c = c2; - b2->m_sweep.a = a2; - b1->SynchronizeTransform(); - b2->SynchronizeTransform(); - return linearError <= b2_linearSlop && angularError <= b2_angularSlop; } b2Vec2 b2PrismaticJoint::GetAnchorA() const { - return m_bodyA->GetWorldPoint(m_localAnchor1); + return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2PrismaticJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchor2); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2PrismaticJoint::GetReactionForce(float32 inv_dt) const @@ -490,13 +500,10 @@ float32 b2PrismaticJoint::GetReactionTorque(float32 inv_dt) const float32 b2PrismaticJoint::GetJointTranslation() const { - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; - - b2Vec2 p1 = b1->GetWorldPoint(m_localAnchor1); - b2Vec2 p2 = b2->GetWorldPoint(m_localAnchor2); - b2Vec2 d = p2 - p1; - b2Vec2 axis = b1->GetWorldVector(m_localXAxis1); + b2Vec2 pA = m_bodyA->GetWorldPoint(m_localAnchorA); + b2Vec2 pB = m_bodyB->GetWorldPoint(m_localAnchorB); + b2Vec2 d = pB - pA; + b2Vec2 axis = m_bodyA->GetWorldVector(m_localXAxisA); float32 translation = b2Dot(d, axis); return translation; @@ -504,22 +511,22 @@ float32 b2PrismaticJoint::GetJointTranslation() const float32 b2PrismaticJoint::GetJointSpeed() const { - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; - b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); - b2Vec2 p1 = b1->m_sweep.c + r1; - b2Vec2 p2 = b2->m_sweep.c + r2; + b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter); + b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter); + b2Vec2 p1 = bA->m_sweep.c + rA; + b2Vec2 p2 = bB->m_sweep.c + rB; b2Vec2 d = p2 - p1; - b2Vec2 axis = b1->GetWorldVector(m_localXAxis1); + b2Vec2 axis = b2Mul(bA->m_xf.q, m_localXAxisA); - b2Vec2 v1 = b1->m_linearVelocity; - b2Vec2 v2 = b2->m_linearVelocity; - float32 w1 = b1->m_angularVelocity; - float32 w2 = b2->m_angularVelocity; + b2Vec2 vA = bA->m_linearVelocity; + b2Vec2 vB = bB->m_linearVelocity; + float32 wA = bA->m_angularVelocity; + float32 wB = bB->m_angularVelocity; - float32 speed = b2Dot(d, b2Cross(w1, axis)) + b2Dot(axis, v2 + b2Cross(w2, r2) - v1 - b2Cross(w1, r1)); + float32 speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA)); return speed; } @@ -530,9 +537,13 @@ bool b2PrismaticJoint::IsLimitEnabled() const void b2PrismaticJoint::EnableLimit(bool flag) { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableLimit = flag; + if (flag != m_enableLimit) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableLimit = flag; + m_impulse.z = 0.0f; + } } float32 b2PrismaticJoint::GetLowerLimit() const @@ -548,10 +559,14 @@ float32 b2PrismaticJoint::GetUpperLimit() const void b2PrismaticJoint::SetLimits(float32 lower, float32 upper) { b2Assert(lower <= upper); - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_lowerTranslation = lower; - m_upperTranslation = upper; + if (lower != m_lowerTranslation || upper != m_upperTranslation) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_lowerTranslation = lower; + m_upperTranslation = upper; + m_impulse.z = 0.0f; + } } bool b2PrismaticJoint::IsMotorEnabled() const @@ -580,7 +595,7 @@ void b2PrismaticJoint::SetMaxMotorForce(float32 force) m_maxMotorForce = force; } -float32 b2PrismaticJoint::GetMotorForce() const +float32 b2PrismaticJoint::GetMotorForce(float32 inv_dt) const { - return m_motorImpulse; + return inv_dt * m_motorImpulse; } diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h old mode 100644 new mode 100755 index 7a12c5df8..f271e7579 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -27,7 +27,6 @@ /// can violate the constraint slightly. The joint translation is zero /// when the local anchor points coincide in world space. Using local /// anchors and a local axis helps when saving and loading a game. -/// @warning at least one body should by dynamic with a non-fixed rotation. struct b2PrismaticJointDef : public b2JointDef { b2PrismaticJointDef() @@ -35,7 +34,7 @@ struct b2PrismaticJointDef : public b2JointDef type = e_prismaticJoint; localAnchorA.SetZero(); localAnchorB.SetZero(); - localAxis1.Set(1.0f, 0.0f); + localAxisA.Set(1.0f, 0.0f); referenceAngle = 0.0f; enableLimit = false; lowerTranslation = 0.0f; @@ -56,9 +55,9 @@ struct b2PrismaticJointDef : public b2JointDef b2Vec2 localAnchorB; /// The local translation axis in body1. - b2Vec2 localAxis1; + b2Vec2 localAxisA; - /// The constrained angle between the bodies: body2_angle - body1_angle. + /// The constrained angle between the bodies: bodyB_angle - bodyA_angle. float32 referenceAngle; /// Enable/disable the joint limit. @@ -81,7 +80,7 @@ struct b2PrismaticJointDef : public b2JointDef }; /// A prismatic joint. This joint provides one degree of freedom: translation -/// along an axis fixed in body1. Relative rotation is prevented. You can +/// along an axis fixed in bodyA. Relative rotation is prevented. You can /// use a joint limit to restrict the range of motion and a joint motor to /// drive the motion or to model joint friction. class b2PrismaticJoint : public b2Joint @@ -129,42 +128,48 @@ public: /// Set the maximum motor force, usually in N. void SetMaxMotorForce(float32 force); - /// Get the current motor force, usually in N. - float32 GetMotorForce() const; + /// Get the current motor force given the inverse time step, usually in N. + float32 GetMotorForce(float32 inv_dt) const; protected: friend class b2Joint; friend class b2GearJoint; b2PrismaticJoint(const b2PrismaticJointDef* def); - void InitVelocityConstraints(const b2TimeStep& step); - void SolveVelocityConstraints(const b2TimeStep& step); - bool SolvePositionConstraints(float32 baumgarte); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - b2Vec2 m_localAnchor1; - b2Vec2 m_localAnchor2; - b2Vec2 m_localXAxis1; - b2Vec2 m_localYAxis1; + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec2 m_localXAxisA; + b2Vec2 m_localYAxisA; float32 m_refAngle; - - b2Vec2 m_axis, m_perp; - float32 m_s1, m_s2; - float32 m_a1, m_a2; - - b2Mat33 m_K; b2Vec3 m_impulse; - - float32 m_motorMass; // effective mass for motor/limit translational constraint. float32 m_motorImpulse; - float32 m_lowerTranslation; float32 m_upperTranslation; float32 m_maxMotorForce; float32 m_motorSpeed; - bool m_enableLimit; bool m_enableMotor; b2LimitState m_limitState; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Vec2 m_axis, m_perp; + float32 m_s1, m_s2; + float32 m_a1, m_a2; + b2Mat33 m_K; + float32 m_motorMass; }; inline float32 b2PrismaticJoint::GetMotorSpeed() const diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp old mode 100644 new mode 100755 index beb7db8fb..1a09d907e --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2007 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -24,368 +24,251 @@ // length1 = norm(p1 - s1) // length2 = norm(p2 - s2) // C0 = (length1 + ratio * length2)_initial -// C = C0 - (length1 + ratio * length2) >= 0 +// C = C0 - (length1 + ratio * length2) // u1 = (p1 - s1) / norm(p1 - s1) // u2 = (p2 - s2) / norm(p2 - s2) // Cdot = -dot(u1, v1 + cross(w1, r1)) - ratio * dot(u2, v2 + cross(w2, r2)) // J = -[u1 cross(r1, u1) ratio * u2 ratio * cross(r2, u2)] // K = J * invM * JT // = invMass1 + invI1 * cross(r1, u1)^2 + ratio^2 * (invMass2 + invI2 * cross(r2, u2)^2) -// -// Limit: -// C = maxLength - length -// u = (p - s) / norm(p - s) -// Cdot = -dot(u, v + cross(w, r)) -// K = invMass + invI * cross(r, u)^2 -// 0 <= impulse -void b2PulleyJointDef::Initialize(b2Body* b1, b2Body* b2, - const b2Vec2& ga1, const b2Vec2& ga2, - const b2Vec2& anchor1, const b2Vec2& anchor2, +void b2PulleyJointDef::Initialize(b2Body* bA, b2Body* bB, + const b2Vec2& groundA, const b2Vec2& groundB, + const b2Vec2& anchorA, const b2Vec2& anchorB, float32 r) { - bodyA = b1; - bodyB = b2; - groundAnchorA = ga1; - groundAnchorB = ga2; - localAnchorA = bodyA->GetLocalPoint(anchor1); - localAnchorB = bodyB->GetLocalPoint(anchor2); - b2Vec2 d1 = anchor1 - ga1; - lengthA = d1.Length(); - b2Vec2 d2 = anchor2 - ga2; - lengthB = d2.Length(); + bodyA = bA; + bodyB = bB; + groundAnchorA = groundA; + groundAnchorB = groundB; + localAnchorA = bodyA->GetLocalPoint(anchorA); + localAnchorB = bodyB->GetLocalPoint(anchorB); + b2Vec2 dA = anchorA - groundA; + lengthA = dA.Length(); + b2Vec2 dB = anchorB - groundB; + lengthB = dB.Length(); ratio = r; b2Assert(ratio > b2_epsilon); - float32 C = lengthA + ratio * lengthB; - maxLengthA = C - ratio * b2_minPulleyLength; - maxLengthB = (C - b2_minPulleyLength) / ratio; } b2PulleyJoint::b2PulleyJoint(const b2PulleyJointDef* def) : b2Joint(def) { - m_groundAnchor1 = def->groundAnchorA; - m_groundAnchor2 = def->groundAnchorB; - m_localAnchor1 = def->localAnchorA; - m_localAnchor2 = def->localAnchorB; + m_groundAnchorA = def->groundAnchorA; + m_groundAnchorB = def->groundAnchorB; + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; b2Assert(def->ratio != 0.0f); m_ratio = def->ratio; m_constant = def->lengthA + m_ratio * def->lengthB; - m_maxLength1 = b2Min(def->maxLengthA, m_constant - m_ratio * b2_minPulleyLength); - m_maxLength2 = b2Min(def->maxLengthB, (m_constant - b2_minPulleyLength) / m_ratio); - m_impulse = 0.0f; - m_limitImpulse1 = 0.0f; - m_limitImpulse2 = 0.0f; } -void b2PulleyJoint::InitVelocityConstraints(const b2TimeStep& step) +void b2PulleyJoint::InitVelocityConstraints(const b2SolverData& data) { - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; - b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; - b2Vec2 p1 = b1->m_sweep.c + r1; - b2Vec2 p2 = b2->m_sweep.c + r2; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Vec2 s1 = m_groundAnchor1; - b2Vec2 s2 = m_groundAnchor2; + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); // Get the pulley axes. - m_u1 = p1 - s1; - m_u2 = p2 - s2; + m_uA = cA + m_rA - m_groundAnchorA; + m_uB = cB + m_rB - m_groundAnchorB; - float32 length1 = m_u1.Length(); - float32 length2 = m_u2.Length(); + float32 lengthA = m_uA.Length(); + float32 lengthB = m_uB.Length(); - if (length1 > b2_linearSlop) + if (lengthA > 10.0f * b2_linearSlop) { - m_u1 *= 1.0f / length1; + m_uA *= 1.0f / lengthA; } else { - m_u1.SetZero(); + m_uA.SetZero(); } - if (length2 > b2_linearSlop) + if (lengthB > 10.0f * b2_linearSlop) { - m_u2 *= 1.0f / length2; + m_uB *= 1.0f / lengthB; } else { - m_u2.SetZero(); - } - - float32 C = m_constant - length1 - m_ratio * length2; - if (C > 0.0f) - { - m_state = e_inactiveLimit; - m_impulse = 0.0f; - } - else - { - m_state = e_atUpperLimit; - } - - if (length1 < m_maxLength1) - { - m_limitState1 = e_inactiveLimit; - m_limitImpulse1 = 0.0f; - } - else - { - m_limitState1 = e_atUpperLimit; - } - - if (length2 < m_maxLength2) - { - m_limitState2 = e_inactiveLimit; - m_limitImpulse2 = 0.0f; - } - else - { - m_limitState2 = e_atUpperLimit; + m_uB.SetZero(); } // Compute effective mass. - float32 cr1u1 = b2Cross(r1, m_u1); - float32 cr2u2 = b2Cross(r2, m_u2); + float32 ruA = b2Cross(m_rA, m_uA); + float32 ruB = b2Cross(m_rB, m_uB); - m_limitMass1 = b1->m_invMass + b1->m_invI * cr1u1 * cr1u1; - m_limitMass2 = b2->m_invMass + b2->m_invI * cr2u2 * cr2u2; - m_pulleyMass = m_limitMass1 + m_ratio * m_ratio * m_limitMass2; - b2Assert(m_limitMass1 > b2_epsilon); - b2Assert(m_limitMass2 > b2_epsilon); - b2Assert(m_pulleyMass > b2_epsilon); - m_limitMass1 = 1.0f / m_limitMass1; - m_limitMass2 = 1.0f / m_limitMass2; - m_pulleyMass = 1.0f / m_pulleyMass; + float32 mA = m_invMassA + m_invIA * ruA * ruA; + float32 mB = m_invMassB + m_invIB * ruB * ruB; - if (step.warmStarting) + m_mass = mA + m_ratio * m_ratio * mB; + + if (m_mass > 0.0f) + { + m_mass = 1.0f / m_mass; + } + + if (data.step.warmStarting) { // Scale impulses to support variable time steps. - m_impulse *= step.dtRatio; - m_limitImpulse1 *= step.dtRatio; - m_limitImpulse2 *= step.dtRatio; + m_impulse *= data.step.dtRatio; // Warm starting. - b2Vec2 P1 = -(m_impulse + m_limitImpulse1) * m_u1; - b2Vec2 P2 = (-m_ratio * m_impulse - m_limitImpulse2) * m_u2; - b1->m_linearVelocity += b1->m_invMass * P1; - b1->m_angularVelocity += b1->m_invI * b2Cross(r1, P1); - b2->m_linearVelocity += b2->m_invMass * P2; - b2->m_angularVelocity += b2->m_invI * b2Cross(r2, P2); + b2Vec2 PA = -(m_impulse) * m_uA; + b2Vec2 PB = (-m_ratio * m_impulse) * m_uB; + + vA += m_invMassA * PA; + wA += m_invIA * b2Cross(m_rA, PA); + vB += m_invMassB * PB; + wB += m_invIB * b2Cross(m_rB, PB); } else { m_impulse = 0.0f; - m_limitImpulse1 = 0.0f; - m_limitImpulse2 = 0.0f; } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } -void b2PulleyJoint::SolveVelocityConstraints(const b2TimeStep& step) +void b2PulleyJoint::SolveVelocityConstraints(const b2SolverData& data) { - B2_NOT_USED(step); + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + b2Vec2 vpA = vA + b2Cross(wA, m_rA); + b2Vec2 vpB = vB + b2Cross(wB, m_rB); - b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); + float32 Cdot = -b2Dot(m_uA, vpA) - m_ratio * b2Dot(m_uB, vpB); + float32 impulse = -m_mass * Cdot; + m_impulse += impulse; - if (m_state == e_atUpperLimit) - { - b2Vec2 v1 = b1->m_linearVelocity + b2Cross(b1->m_angularVelocity, r1); - b2Vec2 v2 = b2->m_linearVelocity + b2Cross(b2->m_angularVelocity, r2); + b2Vec2 PA = -impulse * m_uA; + b2Vec2 PB = -m_ratio * impulse * m_uB; + vA += m_invMassA * PA; + wA += m_invIA * b2Cross(m_rA, PA); + vB += m_invMassB * PB; + wB += m_invIB * b2Cross(m_rB, PB); - float32 Cdot = -b2Dot(m_u1, v1) - m_ratio * b2Dot(m_u2, v2); - float32 impulse = m_pulleyMass * (-Cdot); - float32 oldImpulse = m_impulse; - m_impulse = b2Max(0.0f, m_impulse + impulse); - impulse = m_impulse - oldImpulse; - - b2Vec2 P1 = -impulse * m_u1; - b2Vec2 P2 = -m_ratio * impulse * m_u2; - b1->m_linearVelocity += b1->m_invMass * P1; - b1->m_angularVelocity += b1->m_invI * b2Cross(r1, P1); - b2->m_linearVelocity += b2->m_invMass * P2; - b2->m_angularVelocity += b2->m_invI * b2Cross(r2, P2); - } - - if (m_limitState1 == e_atUpperLimit) - { - b2Vec2 v1 = b1->m_linearVelocity + b2Cross(b1->m_angularVelocity, r1); - - float32 Cdot = -b2Dot(m_u1, v1); - float32 impulse = -m_limitMass1 * Cdot; - float32 oldImpulse = m_limitImpulse1; - m_limitImpulse1 = b2Max(0.0f, m_limitImpulse1 + impulse); - impulse = m_limitImpulse1 - oldImpulse; - - b2Vec2 P1 = -impulse * m_u1; - b1->m_linearVelocity += b1->m_invMass * P1; - b1->m_angularVelocity += b1->m_invI * b2Cross(r1, P1); - } - - if (m_limitState2 == e_atUpperLimit) - { - b2Vec2 v2 = b2->m_linearVelocity + b2Cross(b2->m_angularVelocity, r2); - - float32 Cdot = -b2Dot(m_u2, v2); - float32 impulse = -m_limitMass2 * Cdot; - float32 oldImpulse = m_limitImpulse2; - m_limitImpulse2 = b2Max(0.0f, m_limitImpulse2 + impulse); - impulse = m_limitImpulse2 - oldImpulse; - - b2Vec2 P2 = -impulse * m_u2; - b2->m_linearVelocity += b2->m_invMass * P2; - b2->m_angularVelocity += b2->m_invI * b2Cross(r2, P2); - } + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } -bool b2PulleyJoint::SolvePositionConstraints(float32 baumgarte) +bool b2PulleyJoint::SolvePositionConstraints(const b2SolverData& data) { - B2_NOT_USED(baumgarte); + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + b2Rot qA(aA), qB(aB); - b2Vec2 s1 = m_groundAnchor1; - b2Vec2 s2 = m_groundAnchor2; + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - float32 linearError = 0.0f; + // Get the pulley axes. + b2Vec2 uA = cA + rA - m_groundAnchorA; + b2Vec2 uB = cB + rB - m_groundAnchorB; - if (m_state == e_atUpperLimit) + float32 lengthA = uA.Length(); + float32 lengthB = uB.Length(); + + if (lengthA > 10.0f * b2_linearSlop) { - b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); - - b2Vec2 p1 = b1->m_sweep.c + r1; - b2Vec2 p2 = b2->m_sweep.c + r2; - - // Get the pulley axes. - m_u1 = p1 - s1; - m_u2 = p2 - s2; - - float32 length1 = m_u1.Length(); - float32 length2 = m_u2.Length(); - - if (length1 > b2_linearSlop) - { - m_u1 *= 1.0f / length1; - } - else - { - m_u1.SetZero(); - } - - if (length2 > b2_linearSlop) - { - m_u2 *= 1.0f / length2; - } - else - { - m_u2.SetZero(); - } - - float32 C = m_constant - length1 - m_ratio * length2; - linearError = b2Max(linearError, -C); - - C = b2Clamp(C + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); - float32 impulse = -m_pulleyMass * C; - - b2Vec2 P1 = -impulse * m_u1; - b2Vec2 P2 = -m_ratio * impulse * m_u2; - - b1->m_sweep.c += b1->m_invMass * P1; - b1->m_sweep.a += b1->m_invI * b2Cross(r1, P1); - b2->m_sweep.c += b2->m_invMass * P2; - b2->m_sweep.a += b2->m_invI * b2Cross(r2, P2); - - b1->SynchronizeTransform(); - b2->SynchronizeTransform(); + uA *= 1.0f / lengthA; + } + else + { + uA.SetZero(); } - if (m_limitState1 == e_atUpperLimit) + if (lengthB > 10.0f * b2_linearSlop) { - b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 p1 = b1->m_sweep.c + r1; - - m_u1 = p1 - s1; - float32 length1 = m_u1.Length(); - - if (length1 > b2_linearSlop) - { - m_u1 *= 1.0f / length1; - } - else - { - m_u1.SetZero(); - } - - float32 C = m_maxLength1 - length1; - linearError = b2Max(linearError, -C); - C = b2Clamp(C + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); - float32 impulse = -m_limitMass1 * C; - - b2Vec2 P1 = -impulse * m_u1; - b1->m_sweep.c += b1->m_invMass * P1; - b1->m_sweep.a += b1->m_invI * b2Cross(r1, P1); - - b1->SynchronizeTransform(); + uB *= 1.0f / lengthB; + } + else + { + uB.SetZero(); } - if (m_limitState2 == e_atUpperLimit) + // Compute effective mass. + float32 ruA = b2Cross(rA, uA); + float32 ruB = b2Cross(rB, uB); + + float32 mA = m_invMassA + m_invIA * ruA * ruA; + float32 mB = m_invMassB + m_invIB * ruB * ruB; + + float32 mass = mA + m_ratio * m_ratio * mB; + + if (mass > 0.0f) { - b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); - b2Vec2 p2 = b2->m_sweep.c + r2; - - m_u2 = p2 - s2; - float32 length2 = m_u2.Length(); - - if (length2 > b2_linearSlop) - { - m_u2 *= 1.0f / length2; - } - else - { - m_u2.SetZero(); - } - - float32 C = m_maxLength2 - length2; - linearError = b2Max(linearError, -C); - C = b2Clamp(C + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); - float32 impulse = -m_limitMass2 * C; - - b2Vec2 P2 = -impulse * m_u2; - b2->m_sweep.c += b2->m_invMass * P2; - b2->m_sweep.a += b2->m_invI * b2Cross(r2, P2); - - b2->SynchronizeTransform(); + mass = 1.0f / mass; } + float32 C = m_constant - lengthA - m_ratio * lengthB; + float32 linearError = b2Abs(C); + + float32 impulse = -mass * C; + + b2Vec2 PA = -impulse * uA; + b2Vec2 PB = -m_ratio * impulse * uB; + + cA += m_invMassA * PA; + aA += m_invIA * b2Cross(rA, PA); + cB += m_invMassB * PB; + aB += m_invIB * b2Cross(rB, PB); + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + return linearError < b2_linearSlop; } b2Vec2 b2PulleyJoint::GetAnchorA() const { - return m_bodyA->GetWorldPoint(m_localAnchor1); + return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2PulleyJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchor2); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2PulleyJoint::GetReactionForce(float32 inv_dt) const { - b2Vec2 P = m_impulse * m_u2; + b2Vec2 P = m_impulse * m_uB; return inv_dt * P; } @@ -397,26 +280,26 @@ float32 b2PulleyJoint::GetReactionTorque(float32 inv_dt) const b2Vec2 b2PulleyJoint::GetGroundAnchorA() const { - return m_groundAnchor1; + return m_groundAnchorA; } b2Vec2 b2PulleyJoint::GetGroundAnchorB() const { - return m_groundAnchor2; + return m_groundAnchorB; } -float32 b2PulleyJoint::GetLength1() const +float32 b2PulleyJoint::GetLengthA() const { - b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchor1); - b2Vec2 s = m_groundAnchor1; + b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchorA); + b2Vec2 s = m_groundAnchorA; b2Vec2 d = p - s; return d.Length(); } -float32 b2PulleyJoint::GetLength2() const +float32 b2PulleyJoint::GetLengthB() const { - b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchor2); - b2Vec2 s = m_groundAnchor2; + b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchorB); + b2Vec2 s = m_groundAnchorB; b2Vec2 d = p - s; return d.Length(); } diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.h old mode 100644 new mode 100755 index 189decb31..a5269c618 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -24,8 +24,7 @@ const float32 b2_minPulleyLength = 2.0f; /// Pulley joint definition. This requires two ground anchors, -/// two dynamic body anchor points, max lengths for each side, -/// and a pulley ratio. +/// two dynamic body anchor points, and a pulley ratio. struct b2PulleyJointDef : public b2JointDef { b2PulleyJointDef() @@ -36,9 +35,7 @@ struct b2PulleyJointDef : public b2JointDef localAnchorA.Set(-1.0f, 0.0f); localAnchorB.Set(1.0f, 0.0f); lengthA = 0.0f; - maxLengthA = 0.0f; lengthB = 0.0f; - maxLengthB = 0.0f; ratio = 1.0f; collideConnected = true; } @@ -64,15 +61,9 @@ struct b2PulleyJointDef : public b2JointDef /// The a reference length for the segment attached to bodyA. float32 lengthA; - /// The maximum length of the segment attached to bodyA. - float32 maxLengthA; - /// The a reference length for the segment attached to bodyB. float32 lengthB; - /// The maximum length of the segment attached to bodyB. - float32 maxLengthB; - /// The pulley ratio, used to simulate a block-and-tackle. float32 ratio; }; @@ -81,8 +72,10 @@ struct b2PulleyJointDef : public b2JointDef /// The pulley supports a ratio such that: /// length1 + ratio * length2 <= constant /// Yes, the force transmitted is scaled by the ratio. -/// The pulley also enforces a maximum length limit on both sides. This is -/// useful to prevent one side of the pulley hitting the top. +/// Warning: the pulley joint can get a bit squirrelly by itself. They often +/// work better when combined with prismatic joints. You should also cover the +/// the anchor points with static shapes to prevent one side from going to +/// zero length. class b2PulleyJoint : public b2Joint { public: @@ -98,11 +91,11 @@ public: /// Get the second ground anchor. b2Vec2 GetGroundAnchorB() const; - /// Get the current length of the segment attached to body1. - float32 GetLength1() const; + /// Get the current length of the segment attached to bodyA. + float32 GetLengthA() const; - /// Get the current length of the segment attached to body2. - float32 GetLength2() const; + /// Get the current length of the segment attached to bodyB. + float32 GetLengthB() const; /// Get the pulley ratio. float32 GetRatio() const; @@ -112,37 +105,34 @@ protected: friend class b2Joint; b2PulleyJoint(const b2PulleyJointDef* data); - void InitVelocityConstraints(const b2TimeStep& step); - void SolveVelocityConstraints(const b2TimeStep& step); - bool SolvePositionConstraints(float32 baumgarte); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - b2Vec2 m_groundAnchor1; - b2Vec2 m_groundAnchor2; - b2Vec2 m_localAnchor1; - b2Vec2 m_localAnchor2; - - b2Vec2 m_u1; - b2Vec2 m_u2; + b2Vec2 m_groundAnchorA; + b2Vec2 m_groundAnchorB; + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; float32 m_constant; float32 m_ratio; - - float32 m_maxLength1; - float32 m_maxLength2; - - // Effective masses - float32 m_pulleyMass; - float32 m_limitMass1; - float32 m_limitMass2; - - // Impulses for accumulation/warm starting. float32 m_impulse; - float32 m_limitImpulse1; - float32 m_limitImpulse2; - b2LimitState m_state; - b2LimitState m_limitState1; - b2LimitState m_limitState2; + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_uA; + b2Vec2 m_uB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + float32 m_mass; }; #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp old mode 100644 new mode 100755 index f9845265a..7718f03fc --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -33,10 +33,10 @@ // J = [0 0 -1 0 0 1] // K = invI1 + invI2 -void b2RevoluteJointDef::Initialize(b2Body* b1, b2Body* b2, const b2Vec2& anchor) +void b2RevoluteJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) { - bodyA = b1; - bodyB = b2; + bodyA = bA; + bodyB = bB; localAnchorA = bodyA->GetLocalPoint(anchor); localAnchorB = bodyB->GetLocalPoint(anchor); referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); @@ -45,8 +45,8 @@ void b2RevoluteJointDef::Initialize(b2Body* b1, b2Body* b2, const b2Vec2& anchor b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def) : b2Joint(def) { - m_localAnchor1 = def->localAnchorA; - m_localAnchor2 = def->localAnchorB; + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; m_referenceAngle = def->referenceAngle; m_impulse.SetZero(); @@ -61,58 +61,70 @@ b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def) m_limitState = e_inactiveLimit; } -void b2RevoluteJoint::InitVelocityConstraints(const b2TimeStep& step) +void b2RevoluteJoint::InitVelocityConstraints(const b2SolverData& data) { - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; - if (m_enableMotor || m_enableLimit) - { - // You cannot create a rotation limit between bodies that - // both have fixed rotation. - b2Assert(b1->m_invI > 0.0f || b2->m_invI > 0.0f); - } + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; - // Compute the effective mass matrix. - b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab - // K = [ m1+r1y^2*i1+m2+r2y^2*i2, -r1y*i1*r1x-r2y*i2*r2x, -r1y*i1-r2y*i2] - // [ -r1y*i1*r1x-r2y*i2*r2x, m1+r1x^2*i1+m2+r2x^2*i2, r1x*i1+r2x*i2] - // [ -r1y*i1-r2y*i2, r1x*i1+r2x*i2, i1+i2] + // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] + // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] + // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - float32 m1 = b1->m_invMass, m2 = b2->m_invMass; - float32 i1 = b1->m_invI, i2 = b2->m_invI; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - m_mass.col1.x = m1 + m2 + r1.y * r1.y * i1 + r2.y * r2.y * i2; - m_mass.col2.x = -r1.y * r1.x * i1 - r2.y * r2.x * i2; - m_mass.col3.x = -r1.y * i1 - r2.y * i2; - m_mass.col1.y = m_mass.col2.x; - m_mass.col2.y = m1 + m2 + r1.x * r1.x * i1 + r2.x * r2.x * i2; - m_mass.col3.y = r1.x * i1 + r2.x * i2; - m_mass.col1.z = m_mass.col3.x; - m_mass.col2.z = m_mass.col3.y; - m_mass.col3.z = i1 + i2; + bool fixedRotation = (iA + iB == 0.0f); - m_motorMass = i1 + i2; + m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; + m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; + m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB; + m_mass.ex.y = m_mass.ey.x; + m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; + m_mass.ez.y = m_rA.x * iA + m_rB.x * iB; + m_mass.ex.z = m_mass.ez.x; + m_mass.ey.z = m_mass.ez.y; + m_mass.ez.z = iA + iB; + + m_motorMass = iA + iB; if (m_motorMass > 0.0f) { m_motorMass = 1.0f / m_motorMass; } - if (m_enableMotor == false) + if (m_enableMotor == false || fixedRotation) { m_motorImpulse = 0.0f; } - if (m_enableLimit) + if (m_enableLimit && fixedRotation == false) { - float32 jointAngle = b2->m_sweep.a - b1->m_sweep.a - m_referenceAngle; + float32 jointAngle = aB - aA - m_referenceAngle; if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop) { m_limitState = e_equalLimits; @@ -144,66 +156,66 @@ void b2RevoluteJoint::InitVelocityConstraints(const b2TimeStep& step) m_limitState = e_inactiveLimit; } - if (step.warmStarting) + if (data.step.warmStarting) { // Scale impulses to support a variable time step. - m_impulse *= step.dtRatio; - m_motorImpulse *= step.dtRatio; + m_impulse *= data.step.dtRatio; + m_motorImpulse *= data.step.dtRatio; b2Vec2 P(m_impulse.x, m_impulse.y); - b1->m_linearVelocity -= m1 * P; - b1->m_angularVelocity -= i1 * (b2Cross(r1, P) + m_motorImpulse + m_impulse.z); + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + m_motorImpulse + m_impulse.z); - b2->m_linearVelocity += m2 * P; - b2->m_angularVelocity += i2 * (b2Cross(r2, P) + m_motorImpulse + m_impulse.z); + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + m_motorImpulse + m_impulse.z); } else { m_impulse.SetZero(); m_motorImpulse = 0.0f; } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } -void b2RevoluteJoint::SolveVelocityConstraints(const b2TimeStep& step) +void b2RevoluteJoint::SolveVelocityConstraints(const b2SolverData& data) { - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Vec2 v1 = b1->m_linearVelocity; - float32 w1 = b1->m_angularVelocity; - b2Vec2 v2 = b2->m_linearVelocity; - float32 w2 = b2->m_angularVelocity; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - float32 m1 = b1->m_invMass, m2 = b2->m_invMass; - float32 i1 = b1->m_invI, i2 = b2->m_invI; + bool fixedRotation = (iA + iB == 0.0f); // Solve motor constraint. - if (m_enableMotor && m_limitState != e_equalLimits) + if (m_enableMotor && m_limitState != e_equalLimits && fixedRotation == false) { - float32 Cdot = w2 - w1 - m_motorSpeed; - float32 impulse = m_motorMass * (-Cdot); + float32 Cdot = wB - wA - m_motorSpeed; + float32 impulse = -m_motorMass * Cdot; float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = step.dt * m_maxMotorTorque; + float32 maxImpulse = data.step.dt * m_maxMotorTorque; m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = m_motorImpulse - oldImpulse; - w1 -= i1 * impulse; - w2 += i2 * impulse; + wA -= iA * impulse; + wB += iB * impulse; } // Solve limit constraint. - if (m_enableLimit && m_limitState != e_inactiveLimit) + if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) { - b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); - - // Solve point-to-point constraint - b2Vec2 Cdot1 = v2 + b2Cross(w2, r2) - v1 - b2Cross(w1, r1); - float32 Cdot2 = w2 - w1; + b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + float32 Cdot2 = wB - wA; b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); - b2Vec3 impulse = m_mass.Solve33(-Cdot); + b2Vec3 impulse = -m_mass.Solve33(Cdot); if (m_limitState == e_equalLimits) { @@ -214,7 +226,8 @@ void b2RevoluteJoint::SolveVelocityConstraints(const b2TimeStep& step) float32 newImpulse = m_impulse.z + impulse.z; if (newImpulse < 0.0f) { - b2Vec2 reduced = m_mass.Solve22(-Cdot1); + b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); + b2Vec2 reduced = m_mass.Solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -m_impulse.z; @@ -222,13 +235,18 @@ void b2RevoluteJoint::SolveVelocityConstraints(const b2TimeStep& step) m_impulse.y += reduced.y; m_impulse.z = 0.0f; } + else + { + m_impulse += impulse; + } } else if (m_limitState == e_atUpperLimit) { float32 newImpulse = m_impulse.z + impulse.z; if (newImpulse > 0.0f) { - b2Vec2 reduced = m_mass.Solve22(-Cdot1); + b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); + b2Vec2 reduced = m_mass.Solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -m_impulse.z; @@ -236,57 +254,60 @@ void b2RevoluteJoint::SolveVelocityConstraints(const b2TimeStep& step) m_impulse.y += reduced.y; m_impulse.z = 0.0f; } + else + { + m_impulse += impulse; + } } b2Vec2 P(impulse.x, impulse.y); - v1 -= m1 * P; - w1 -= i1 * (b2Cross(r1, P) + impulse.z); + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + impulse.z); - v2 += m2 * P; - w2 += i2 * (b2Cross(r2, P) + impulse.z); + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + impulse.z); } else { - b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); - // Solve point-to-point constraint - b2Vec2 Cdot = v2 + b2Cross(w2, r2) - v1 - b2Cross(w1, r1); + b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); b2Vec2 impulse = m_mass.Solve22(-Cdot); m_impulse.x += impulse.x; m_impulse.y += impulse.y; - v1 -= m1 * impulse; - w1 -= i1 * b2Cross(r1, impulse); + vA -= mA * impulse; + wA -= iA * b2Cross(m_rA, impulse); - v2 += m2 * impulse; - w2 += i2 * b2Cross(r2, impulse); + vB += mB * impulse; + wB += iB * b2Cross(m_rB, impulse); } - b1->m_linearVelocity = v1; - b1->m_angularVelocity = w1; - b2->m_linearVelocity = v2; - b2->m_angularVelocity = w2; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } -bool b2RevoluteJoint::SolvePositionConstraints(float32 baumgarte) +bool b2RevoluteJoint::SolvePositionConstraints(const b2SolverData& data) { - // TODO_ERIN block solve with limit. + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; - B2_NOT_USED(baumgarte); - - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; + b2Rot qA(aA), qB(aB); float32 angularError = 0.0f; float32 positionError = 0.0f; + bool fixedRotation = (m_invIA + m_invIB == 0.0f); + // Solve angular limit constraint. - if (m_enableLimit && m_limitState != e_inactiveLimit) + if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) { - float32 angle = b2->m_sweep.a - b1->m_sweep.a - m_referenceAngle; + float32 angle = aB - aA - m_referenceAngle; float32 limitImpulse = 0.0f; if (m_limitState == e_equalLimits) @@ -315,79 +336,54 @@ bool b2RevoluteJoint::SolvePositionConstraints(float32 baumgarte) limitImpulse = -m_motorMass * C; } - b1->m_sweep.a -= b1->m_invI * limitImpulse; - b2->m_sweep.a += b2->m_invI * limitImpulse; - - b1->SynchronizeTransform(); - b2->SynchronizeTransform(); + aA -= m_invIA * limitImpulse; + aB += m_invIB * limitImpulse; } // Solve point-to-point constraint. { - b2Vec2 r1 = b2Mul(b1->GetTransform().R, m_localAnchor1 - b1->GetLocalCenter()); - b2Vec2 r2 = b2Mul(b2->GetTransform().R, m_localAnchor2 - b2->GetLocalCenter()); + qA.Set(aA); + qB.Set(aB); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 C = b2->m_sweep.c + r2 - b1->m_sweep.c - r1; + b2Vec2 C = cB + rB - cA - rA; positionError = C.Length(); - float32 invMass1 = b1->m_invMass, invMass2 = b2->m_invMass; - float32 invI1 = b1->m_invI, invI2 = b2->m_invI; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - // Handle large detachment. - const float32 k_allowedStretch = 10.0f * b2_linearSlop; - if (C.LengthSquared() > k_allowedStretch * k_allowedStretch) - { - // Use a particle solution (no rotation). - b2Vec2 u = C; u.Normalize(); - float32 m = invMass1 + invMass2; - if (m > 0.0f) - { - m = 1.0f / m; - } - b2Vec2 impulse = m * (-C); - const float32 k_beta = 0.5f; - b1->m_sweep.c -= k_beta * invMass1 * impulse; - b2->m_sweep.c += k_beta * invMass2 * impulse; + b2Mat22 K; + K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; + K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; + K.ey.x = K.ex.y; + K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; - C = b2->m_sweep.c + r2 - b1->m_sweep.c - r1; - } + b2Vec2 impulse = -K.Solve(C); - b2Mat22 K1; - K1.col1.x = invMass1 + invMass2; K1.col2.x = 0.0f; - K1.col1.y = 0.0f; K1.col2.y = invMass1 + invMass2; + cA -= mA * impulse; + aA -= iA * b2Cross(rA, impulse); - b2Mat22 K2; - K2.col1.x = invI1 * r1.y * r1.y; K2.col2.x = -invI1 * r1.x * r1.y; - K2.col1.y = -invI1 * r1.x * r1.y; K2.col2.y = invI1 * r1.x * r1.x; - - b2Mat22 K3; - K3.col1.x = invI2 * r2.y * r2.y; K3.col2.x = -invI2 * r2.x * r2.y; - K3.col1.y = -invI2 * r2.x * r2.y; K3.col2.y = invI2 * r2.x * r2.x; - - b2Mat22 K = K1 + K2 + K3; - b2Vec2 impulse = K.Solve(-C); - - b1->m_sweep.c -= b1->m_invMass * impulse; - b1->m_sweep.a -= b1->m_invI * b2Cross(r1, impulse); - - b2->m_sweep.c += b2->m_invMass * impulse; - b2->m_sweep.a += b2->m_invI * b2Cross(r2, impulse); - - b1->SynchronizeTransform(); - b2->SynchronizeTransform(); + cB += mB * impulse; + aB += iB * b2Cross(rB, impulse); } + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; return positionError <= b2_linearSlop && angularError <= b2_angularSlop; } b2Vec2 b2RevoluteJoint::GetAnchorA() const { - return m_bodyA->GetWorldPoint(m_localAnchor1); + return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2RevoluteJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchor2); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2RevoluteJoint::GetReactionForce(float32 inv_dt) const @@ -403,16 +399,16 @@ float32 b2RevoluteJoint::GetReactionTorque(float32 inv_dt) const float32 b2RevoluteJoint::GetJointAngle() const { - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; - return b2->m_sweep.a - b1->m_sweep.a - m_referenceAngle; + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle; } float32 b2RevoluteJoint::GetJointSpeed() const { - b2Body* b1 = m_bodyA; - b2Body* b2 = m_bodyB; - return b2->m_angularVelocity - b1->m_angularVelocity; + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + return bB->m_angularVelocity - bA->m_angularVelocity; } bool b2RevoluteJoint::IsMotorEnabled() const @@ -427,9 +423,9 @@ void b2RevoluteJoint::EnableMotor(bool flag) m_enableMotor = flag; } -float32 b2RevoluteJoint::GetMotorTorque() const +float32 b2RevoluteJoint::GetMotorTorque(float32 inv_dt) const { - return m_motorImpulse; + return inv_dt * m_motorImpulse; } void b2RevoluteJoint::SetMotorSpeed(float32 speed) @@ -453,9 +449,13 @@ bool b2RevoluteJoint::IsLimitEnabled() const void b2RevoluteJoint::EnableLimit(bool flag) { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableLimit = flag; + if (flag != m_enableLimit) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableLimit = flag; + m_impulse.z = 0.0f; + } } float32 b2RevoluteJoint::GetLowerLimit() const @@ -471,8 +471,13 @@ float32 b2RevoluteJoint::GetUpperLimit() const void b2RevoluteJoint::SetLimits(float32 lower, float32 upper) { b2Assert(lower <= upper); - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_lowerAngle = lower; - m_upperAngle = upper; + + if (lower != m_lowerAngle || upper != m_upperAngle) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_impulse.z = 0.0f; + m_lowerAngle = lower; + m_upperAngle = upper; + } } diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h old mode 100644 new mode 100755 index c0180beba..03eae0b3a --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -93,9 +93,6 @@ public: b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorB() const; - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - /// Get the current joint angle in radians. float32 GetJointAngle() const; @@ -132,8 +129,17 @@ public: /// Set the maximum motor torque, usually in N-m. void SetMaxMotorTorque(float32 torque); - /// Get the current motor torque, usually in N-m. - float32 GetMotorTorque() const; + /// Get the reaction force given the inverse time step. + /// Unit is N. + b2Vec2 GetReactionForce(float32 inv_dt) const; + + /// Get the reaction torque due to the joint limit given the inverse time step. + /// Unit is N*m. + float32 GetReactionTorque(float32 inv_dt) const; + + /// Get the current motor torque given the inverse time step. + /// Unit is N*m. + float32 GetMotorTorque(float32 inv_dt) const; protected: @@ -142,19 +148,16 @@ protected: b2RevoluteJoint(const b2RevoluteJointDef* def); - void InitVelocityConstraints(const b2TimeStep& step); - void SolveVelocityConstraints(const b2TimeStep& step); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - bool SolvePositionConstraints(float32 baumgarte); - - b2Vec2 m_localAnchor1; // relative - b2Vec2 m_localAnchor2; + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; b2Vec3 m_impulse; float32 m_motorImpulse; - b2Mat33 m_mass; // effective mass for point-to-point constraint. - float32 m_motorMass; // effective mass for motor/limit angular constraint. - bool m_enableMotor; float32 m_maxMotorTorque; float32 m_motorSpeed; @@ -163,6 +166,20 @@ protected: float32 m_referenceAngle; float32 m_lowerAngle; float32 m_upperAngle; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Mat33 m_mass; // effective mass for point-to-point constraint. + float32 m_motorMass; // effective mass for motor/limit angular constraint. b2LimitState m_limitState; }; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.cpp new file mode 100755 index 000000000..4b1e666c1 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.cpp @@ -0,0 +1,226 @@ +/* +* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + + +// Limit: +// C = norm(pB - pA) - L +// u = (pB - pA) / norm(pB - pA) +// Cdot = dot(u, vB + cross(wB, rB) - vA - cross(wA, rA)) +// J = [-u -cross(rA, u) u cross(rB, u)] +// K = J * invM * JT +// = invMassA + invIA * cross(rA, u)^2 + invMassB + invIB * cross(rB, u)^2 + +b2RopeJoint::b2RopeJoint(const b2RopeJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + + m_maxLength = def->maxLength; + + m_mass = 0.0f; + m_impulse = 0.0f; + m_state = e_inactiveLimit; + m_length = 0.0f; +} + +void b2RopeJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + m_u = cB + m_rB - cA - m_rA; + + m_length = m_u.Length(); + + float32 C = m_length - m_maxLength; + if (C > 0.0f) + { + m_state = e_atUpperLimit; + } + else + { + m_state = e_inactiveLimit; + } + + if (m_length > b2_linearSlop) + { + m_u *= 1.0f / m_length; + } + else + { + m_u.SetZero(); + m_mass = 0.0f; + m_impulse = 0.0f; + return; + } + + // Compute effective mass. + float32 crA = b2Cross(m_rA, m_u); + float32 crB = b2Cross(m_rB, m_u); + float32 invMass = m_invMassA + m_invIA * crA * crA + m_invMassB + m_invIB * crB * crB; + + m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; + + if (data.step.warmStarting) + { + // Scale the impulse to support a variable time step. + m_impulse *= data.step.dtRatio; + + b2Vec2 P = m_impulse * m_u; + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); + } + else + { + m_impulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2RopeJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + // Cdot = dot(u, v + cross(w, r)) + b2Vec2 vpA = vA + b2Cross(wA, m_rA); + b2Vec2 vpB = vB + b2Cross(wB, m_rB); + float32 C = m_length - m_maxLength; + float32 Cdot = b2Dot(m_u, vpB - vpA); + + // Predictive constraint. + if (C < 0.0f) + { + Cdot += data.step.inv_dt * C; + } + + float32 impulse = -m_mass * Cdot; + float32 oldImpulse = m_impulse; + m_impulse = b2Min(0.0f, m_impulse + impulse); + impulse = m_impulse - oldImpulse; + + b2Vec2 P = impulse * m_u; + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2RopeJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 u = cB + rB - cA - rA; + + float32 length = u.Normalize(); + float32 C = length - m_maxLength; + + C = b2Clamp(C, 0.0f, b2_maxLinearCorrection); + + float32 impulse = -m_mass * C; + b2Vec2 P = impulse * u; + + cA -= m_invMassA * P; + aA -= m_invIA * b2Cross(rA, P); + cB += m_invMassB * P; + aB += m_invIB * b2Cross(rB, P); + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return length - m_maxLength < b2_linearSlop; +} + +b2Vec2 b2RopeJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2RopeJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2RopeJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 F = (inv_dt * m_impulse) * m_u; + return F; +} + +float32 b2RopeJoint::GetReactionTorque(float32 inv_dt) const +{ + B2_NOT_USED(inv_dt); + return 0.0f; +} + +float32 b2RopeJoint::GetMaxLength() const +{ + return m_maxLength; +} + +b2LimitState b2RopeJoint::GetLimitState() const +{ + return m_state; +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.h new file mode 100755 index 000000000..660b4ed50 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.h @@ -0,0 +1,104 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_ROPE_JOINT_H +#define B2_ROPE_JOINT_H + +#include + +/// Rope joint definition. This requires two body anchor points and +/// a maximum lengths. +/// Note: by default the connected objects will not collide. +/// see collideConnected in b2JointDef. +struct b2RopeJointDef : public b2JointDef +{ + b2RopeJointDef() + { + type = e_ropeJoint; + localAnchorA.Set(-1.0f, 0.0f); + localAnchorB.Set(1.0f, 0.0f); + maxLength = 0.0f; + } + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The maximum length of the rope. + /// Warning: this must be larger than b2_linearSlop or + /// the joint will have no effect. + float32 maxLength; +}; + +/// A rope joint enforces a maximum distance between two points +/// on two bodies. It has no other effect. +/// Warning: if you attempt to change the maximum length during +/// the simulation you will get some non-physical behavior. +/// A model that would allow you to dynamically modify the length +/// would have some sponginess, so I chose not to implement it +/// that way. See b2DistanceJoint if you want to dynamically +/// control length. +class b2RopeJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// Get the maximum length of the rope. + float32 GetMaxLength() const; + + b2LimitState GetLimitState() const; + +protected: + + friend class b2Joint; + b2RopeJoint(const b2RopeJointDef* data); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_maxLength; + float32 m_length; + float32 m_impulse; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_u; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + float32 m_mass; + b2LimitState m_state; +}; + +#endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp old mode 100644 new mode 100755 index 49b5513ba..11eb5ec65 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -53,14 +53,31 @@ b2WeldJoint::b2WeldJoint(const b2WeldJointDef* def) m_impulse.SetZero(); } -void b2WeldJoint::InitVelocityConstraints(const b2TimeStep& step) +void b2WeldJoint::InitVelocityConstraints(const b2SolverData& data) { - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; - // Compute the effective mass matrix. - b2Vec2 rA = b2Mul(bA->GetTransform().R, m_localAnchorA - bA->GetLocalCenter()); - b2Vec2 rB = b2Mul(bB->GetTransform().R, m_localAnchorB - bB->GetLocalCenter()); + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] @@ -71,128 +88,121 @@ void b2WeldJoint::InitVelocityConstraints(const b2TimeStep& step) // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - float32 mA = bA->m_invMass, mB = bB->m_invMass; - float32 iA = bA->m_invI, iB = bB->m_invI; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - m_mass.col1.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; - m_mass.col2.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; - m_mass.col3.x = -rA.y * iA - rB.y * iB; - m_mass.col1.y = m_mass.col2.x; - m_mass.col2.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; - m_mass.col3.y = rA.x * iA + rB.x * iB; - m_mass.col1.z = m_mass.col3.x; - m_mass.col2.z = m_mass.col3.y; - m_mass.col3.z = iA + iB; + m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; + m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; + m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB; + m_mass.ex.y = m_mass.ey.x; + m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; + m_mass.ez.y = m_rA.x * iA + m_rB.x * iB; + m_mass.ex.z = m_mass.ez.x; + m_mass.ey.z = m_mass.ez.y; + m_mass.ez.z = iA + iB; - if (step.warmStarting) + if (data.step.warmStarting) { // Scale impulses to support a variable time step. - m_impulse *= step.dtRatio; + m_impulse *= data.step.dtRatio; b2Vec2 P(m_impulse.x, m_impulse.y); - bA->m_linearVelocity -= mA * P; - bA->m_angularVelocity -= iA * (b2Cross(rA, P) + m_impulse.z); + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + m_impulse.z); - bB->m_linearVelocity += mB * P; - bB->m_angularVelocity += iB * (b2Cross(rB, P) + m_impulse.z); + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + m_impulse.z); } else { m_impulse.SetZero(); } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } -void b2WeldJoint::SolveVelocityConstraints(const b2TimeStep& step) +void b2WeldJoint::SolveVelocityConstraints(const b2SolverData& data) { - B2_NOT_USED(step); + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - b2Vec2 vA = bA->m_linearVelocity; - float32 wA = bA->m_angularVelocity; - b2Vec2 vB = bB->m_linearVelocity; - float32 wB = bB->m_angularVelocity; - - float32 mA = bA->m_invMass, mB = bB->m_invMass; - float32 iA = bA->m_invI, iB = bB->m_invI; - - b2Vec2 rA = b2Mul(bA->GetTransform().R, m_localAnchorA - bA->GetLocalCenter()); - b2Vec2 rB = b2Mul(bB->GetTransform().R, m_localAnchorB - bB->GetLocalCenter()); - - // Solve point-to-point constraint - b2Vec2 Cdot1 = vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA); + b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); float32 Cdot2 = wB - wA; b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); - b2Vec3 impulse = m_mass.Solve33(-Cdot); + b2Vec3 impulse = -m_mass.Solve33(Cdot); m_impulse += impulse; b2Vec2 P(impulse.x, impulse.y); vA -= mA * P; - wA -= iA * (b2Cross(rA, P) + impulse.z); + wA -= iA * (b2Cross(m_rA, P) + impulse.z); vB += mB * P; - wB += iB * (b2Cross(rB, P) + impulse.z); + wB += iB * (b2Cross(m_rB, P) + impulse.z); - bA->m_linearVelocity = vA; - bA->m_angularVelocity = wA; - bB->m_linearVelocity = vB; - bB->m_angularVelocity = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } -bool b2WeldJoint::SolvePositionConstraints(float32 baumgarte) +bool b2WeldJoint::SolvePositionConstraints(const b2SolverData& data) { - B2_NOT_USED(baumgarte); + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; + b2Rot qA(aA), qB(aB); - float32 mA = bA->m_invMass, mB = bB->m_invMass; - float32 iA = bA->m_invI, iB = bB->m_invI; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - b2Vec2 rA = b2Mul(bA->GetTransform().R, m_localAnchorA - bA->GetLocalCenter()); - b2Vec2 rB = b2Mul(bB->GetTransform().R, m_localAnchorB - bB->GetLocalCenter()); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 C1 = bB->m_sweep.c + rB - bA->m_sweep.c - rA; - float32 C2 = bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle; + b2Vec2 C1 = cB + rB - cA - rA; + float32 C2 = aB - aA - m_referenceAngle; - // Handle large detachment. - const float32 k_allowedStretch = 10.0f * b2_linearSlop; float32 positionError = C1.Length(); float32 angularError = b2Abs(C2); - if (positionError > k_allowedStretch) - { - iA *= 1.0f; - iB *= 1.0f; - } - m_mass.col1.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; - m_mass.col2.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; - m_mass.col3.x = -rA.y * iA - rB.y * iB; - m_mass.col1.y = m_mass.col2.x; - m_mass.col2.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; - m_mass.col3.y = rA.x * iA + rB.x * iB; - m_mass.col1.z = m_mass.col3.x; - m_mass.col2.z = m_mass.col3.y; - m_mass.col3.z = iA + iB; + m_mass.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; + m_mass.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; + m_mass.ez.x = -rA.y * iA - rB.y * iB; + m_mass.ex.y = m_mass.ey.x; + m_mass.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; + m_mass.ez.y = rA.x * iA + rB.x * iB; + m_mass.ex.z = m_mass.ez.x; + m_mass.ey.z = m_mass.ez.y; + m_mass.ez.z = iA + iB; b2Vec3 C(C1.x, C1.y, C2); - b2Vec3 impulse = m_mass.Solve33(-C); + b2Vec3 impulse = -m_mass.Solve33(C); b2Vec2 P(impulse.x, impulse.y); - bA->m_sweep.c -= mA * P; - bA->m_sweep.a -= iA * (b2Cross(rA, P) + impulse.z); + cA -= mA * P; + aA -= iA * (b2Cross(rA, P) + impulse.z); - bB->m_sweep.c += mB * P; - bB->m_sweep.a += iB * (b2Cross(rB, P) + impulse.z); + cB += mB * P; + aB += iB * (b2Cross(rB, P) + impulse.z); - bA->SynchronizeTransform(); - bB->SynchronizeTransform(); + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; return positionError <= b2_linearSlop && angularError <= b2_angularSlop; } diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h old mode 100644 new mode 100755 index 4e63b6aa6..51c4b402b --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -65,17 +65,27 @@ protected: b2WeldJoint(const b2WeldJointDef* def); - void InitVelocityConstraints(const b2TimeStep& step); - void SolveVelocityConstraints(const b2TimeStep& step); - - bool SolvePositionConstraints(float32 baumgarte); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + // Solver shared b2Vec2 m_localAnchorA; b2Vec2 m_localAnchorB; float32 m_referenceAngle; - b2Vec3 m_impulse; + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; b2Mat33 m_mass; }; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.cpp new file mode 100755 index 000000000..826192347 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.cpp @@ -0,0 +1,404 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Linear constraint (point-to-line) +// d = pB - pA = xB + rB - xA - rA +// C = dot(ay, d) +// Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA)) +// = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB) +// J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)] + +// Spring linear constraint +// C = dot(ax, d) +// Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB) +// J = [-ax -cross(d+rA, ax) ax cross(rB, ax)] + +// Motor rotational constraint +// Cdot = wB - wA +// J = [0 0 -1 0 0 1] + +void b2WheelJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) +{ + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + localAxisA = bodyA->GetLocalVector(axis); +} + +b2WheelJoint::b2WheelJoint(const b2WheelJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_localXAxisA = def->localAxisA; + m_localYAxisA = b2Cross(1.0f, m_localXAxisA); + + m_mass = 0.0f; + m_impulse = 0.0f; + m_motorMass = 0.0; + m_motorImpulse = 0.0f; + m_springMass = 0.0f; + m_springImpulse = 0.0f; + + m_maxMotorTorque = def->maxMotorTorque; + m_motorSpeed = def->motorSpeed; + m_enableMotor = def->enableMotor; + + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; + + m_bias = 0.0f; + m_gamma = 0.0f; + + m_ax.SetZero(); + m_ay.SetZero(); +} + +void b2WheelJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + // Compute the effective masses. + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = cB + rB - cA - rA; + + // Point to line constraint + { + m_ay = b2Mul(qA, m_localYAxisA); + m_sAy = b2Cross(d + rA, m_ay); + m_sBy = b2Cross(rB, m_ay); + + m_mass = mA + mB + iA * m_sAy * m_sAy + iB * m_sBy * m_sBy; + + if (m_mass > 0.0f) + { + m_mass = 1.0f / m_mass; + } + } + + // Spring constraint + m_springMass = 0.0f; + m_bias = 0.0f; + m_gamma = 0.0f; + if (m_frequencyHz > 0.0f) + { + m_ax = b2Mul(qA, m_localXAxisA); + m_sAx = b2Cross(d + rA, m_ax); + m_sBx = b2Cross(rB, m_ax); + + float32 invMass = mA + mB + iA * m_sAx * m_sAx + iB * m_sBx * m_sBx; + + if (invMass > 0.0f) + { + m_springMass = 1.0f / invMass; + + float32 C = b2Dot(d, m_ax); + + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; + + // Damping coefficient + float32 d = 2.0f * m_springMass * m_dampingRatio * omega; + + // Spring stiffness + float32 k = m_springMass * omega * omega; + + // magic formulas + float32 h = data.step.dt; + m_gamma = h * (d + h * k); + if (m_gamma > 0.0f) + { + m_gamma = 1.0f / m_gamma; + } + + m_bias = C * h * k * m_gamma; + + m_springMass = invMass + m_gamma; + if (m_springMass > 0.0f) + { + m_springMass = 1.0f / m_springMass; + } + } + } + else + { + m_springImpulse = 0.0f; + } + + // Rotational motor + if (m_enableMotor) + { + m_motorMass = iA + iB; + if (m_motorMass > 0.0f) + { + m_motorMass = 1.0f / m_motorMass; + } + } + else + { + m_motorMass = 0.0f; + m_motorImpulse = 0.0f; + } + + if (data.step.warmStarting) + { + // Account for variable time step. + m_impulse *= data.step.dtRatio; + m_springImpulse *= data.step.dtRatio; + m_motorImpulse *= data.step.dtRatio; + + b2Vec2 P = m_impulse * m_ay + m_springImpulse * m_ax; + float32 LA = m_impulse * m_sAy + m_springImpulse * m_sAx + m_motorImpulse; + float32 LB = m_impulse * m_sBy + m_springImpulse * m_sBx + m_motorImpulse; + + vA -= m_invMassA * P; + wA -= m_invIA * LA; + + vB += m_invMassB * P; + wB += m_invIB * LB; + } + else + { + m_impulse = 0.0f; + m_springImpulse = 0.0f; + m_motorImpulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2WheelJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + // Solve spring constraint + { + float32 Cdot = b2Dot(m_ax, vB - vA) + m_sBx * wB - m_sAx * wA; + float32 impulse = -m_springMass * (Cdot + m_bias + m_gamma * m_springImpulse); + m_springImpulse += impulse; + + b2Vec2 P = impulse * m_ax; + float32 LA = impulse * m_sAx; + float32 LB = impulse * m_sBx; + + vA -= mA * P; + wA -= iA * LA; + + vB += mB * P; + wB += iB * LB; + } + + // Solve rotational motor constraint + { + float32 Cdot = wB - wA - m_motorSpeed; + float32 impulse = -m_motorMass * Cdot; + + float32 oldImpulse = m_motorImpulse; + float32 maxImpulse = data.step.dt * m_maxMotorTorque; + m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_motorImpulse - oldImpulse; + + wA -= iA * impulse; + wB += iB * impulse; + } + + // Solve point to line constraint + { + float32 Cdot = b2Dot(m_ay, vB - vA) + m_sBy * wB - m_sAy * wA; + float32 impulse = -m_mass * Cdot; + m_impulse += impulse; + + b2Vec2 P = impulse * m_ay; + float32 LA = impulse * m_sAy; + float32 LB = impulse * m_sBy; + + vA -= mA * P; + wA -= iA * LA; + + vB += mB * P; + wB += iB * LB; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2WheelJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = (cB - cA) + rB - rA; + + b2Vec2 ay = b2Mul(qA, m_localYAxisA); + + float32 sAy = b2Cross(d + rA, ay); + float32 sBy = b2Cross(rB, ay); + + float32 C = b2Dot(d, ay); + + float32 k = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy; + + float32 impulse; + if (k != 0.0f) + { + impulse = - C / k; + } + else + { + impulse = 0.0f; + } + + b2Vec2 P = impulse * ay; + float32 LA = impulse * sAy; + float32 LB = impulse * sBy; + + cA -= m_invMassA * P; + aA -= m_invIA * LA; + cB += m_invMassB * P; + aB += m_invIB * LB; + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return b2Abs(C) <= b2_linearSlop; +} + +b2Vec2 b2WheelJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2WheelJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2WheelJoint::GetReactionForce(float32 inv_dt) const +{ + return inv_dt * (m_impulse * m_ay + m_springImpulse * m_ax); +} + +float32 b2WheelJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_motorImpulse; +} + +float32 b2WheelJoint::GetJointTranslation() const +{ + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + + b2Vec2 pA = bA->GetWorldPoint(m_localAnchorA); + b2Vec2 pB = bB->GetWorldPoint(m_localAnchorB); + b2Vec2 d = pB - pA; + b2Vec2 axis = bA->GetWorldVector(m_localXAxisA); + + float32 translation = b2Dot(d, axis); + return translation; +} + +float32 b2WheelJoint::GetJointSpeed() const +{ + float32 wA = m_bodyA->m_angularVelocity; + float32 wB = m_bodyB->m_angularVelocity; + return wB - wA; +} + +bool b2WheelJoint::IsMotorEnabled() const +{ + return m_enableMotor; +} + +void b2WheelJoint::EnableMotor(bool flag) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableMotor = flag; +} + +void b2WheelJoint::SetMotorSpeed(float32 speed) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_motorSpeed = speed; +} + +void b2WheelJoint::SetMaxMotorTorque(float32 torque) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_maxMotorTorque = torque; +} + +float32 b2WheelJoint::GetMotorTorque(float32 inv_dt) const +{ + return inv_dt * m_motorImpulse; +} + + + + + diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.h new file mode 100755 index 000000000..7398d218c --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.h @@ -0,0 +1,199 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_WHEEL_JOINT_H +#define B2_WHEEL_JOINT_H + +#include + +/// Wheel joint definition. This requires defining a line of +/// motion using an axis and an anchor point. The definition uses local +/// anchor points and a local axis so that the initial configuration +/// can violate the constraint slightly. The joint translation is zero +/// when the local anchor points coincide in world space. Using local +/// anchors and a local axis helps when saving and loading a game. +struct b2WheelJointDef : public b2JointDef +{ + b2WheelJointDef() + { + type = e_wheelJoint; + localAnchorA.SetZero(); + localAnchorB.SetZero(); + localAxisA.Set(1.0f, 0.0f); + enableMotor = false; + maxMotorTorque = 0.0f; + motorSpeed = 0.0f; + frequencyHz = 2.0f; + dampingRatio = 0.7f; + } + + /// Initialize the bodies, anchors, axis, and reference angle using the world + /// anchor and world axis. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); + + /// The local anchor point relative to body1's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to body2's origin. + b2Vec2 localAnchorB; + + /// The local translation axis in body1. + b2Vec2 localAxisA; + + /// Enable/disable the joint motor. + bool enableMotor; + + /// The maximum motor torque, usually in N-m. + float32 maxMotorTorque; + + /// The desired motor speed in radians per second. + float32 motorSpeed; + + /// Suspension frequency, zero indicates no suspension + float32 frequencyHz; + + /// Suspension damping ratio, one indicates critical damping + float32 dampingRatio; +}; + +/// A wheel joint. This joint provides two degrees of freedom: translation +/// along an axis fixed in body1 and rotation in the plane. You can use a +/// joint limit to restrict the range of motion and a joint motor to drive +/// the rotation or to model rotational friction. +/// This joint is designed for vehicle suspensions. +class b2WheelJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// Get the current joint translation, usually in meters. + float32 GetJointTranslation() const; + + /// Get the current joint translation speed, usually in meters per second. + float32 GetJointSpeed() const; + + /// Is the joint motor enabled? + bool IsMotorEnabled() const; + + /// Enable/disable the joint motor. + void EnableMotor(bool flag); + + /// Set the motor speed, usually in radians per second. + void SetMotorSpeed(float32 speed); + + /// Get the motor speed, usually in radians per second. + float32 GetMotorSpeed() const; + + /// Set/Get the maximum motor force, usually in N-m. + void SetMaxMotorTorque(float32 torque); + float32 GetMaxMotorTorque() const; + + /// Get the current motor torque given the inverse time step, usually in N-m. + float32 GetMotorTorque(float32 inv_dt) const; + + /// Set/Get the spring frequency in hertz. Setting the frequency to zero disables the spring. + void SetSpringFrequencyHz(float32 hz); + float32 GetSpringFrequencyHz() const; + + /// Set/Get the spring damping ratio + void SetSpringDampingRatio(float32 ratio); + float32 GetSpringDampingRatio() const; + +protected: + + friend class b2Joint; + b2WheelJoint(const b2WheelJointDef* def); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + float32 m_frequencyHz; + float32 m_dampingRatio; + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec2 m_localXAxisA; + b2Vec2 m_localYAxisA; + + float32 m_impulse; + float32 m_motorImpulse; + float32 m_springImpulse; + + float32 m_maxMotorTorque; + float32 m_motorSpeed; + bool m_enableMotor; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + + b2Vec2 m_ax, m_ay; + float32 m_sAx, m_sBx; + float32 m_sAy, m_sBy; + + float32 m_mass; + float32 m_motorMass; + float32 m_springMass; + + float32 m_bias; + float32 m_gamma; +}; + +inline float32 b2WheelJoint::GetMotorSpeed() const +{ + return m_motorSpeed; +} + +inline float32 b2WheelJoint::GetMaxMotorTorque() const +{ + return m_maxMotorTorque; +} + +inline void b2WheelJoint::SetSpringFrequencyHz(float32 hz) +{ + m_frequencyHz = hz; +} + +inline float32 b2WheelJoint::GetSpringFrequencyHz() const +{ + return m_frequencyHz; +} + +inline void b2WheelJoint::SetSpringDampingRatio(float32 ratio) +{ + m_dampingRatio = ratio; +} + +inline float32 b2WheelJoint::GetSpringDampingRatio() const +{ + return m_dampingRatio; +} + +#endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp old mode 100644 new mode 100755 index 4b8865148..858977c81 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -28,7 +28,6 @@ b2Body::b2Body(const b2BodyDef* bd, b2World* world) b2Assert(bd->linearVelocity.IsValid()); b2Assert(b2IsValid(bd->angle)); b2Assert(b2IsValid(bd->angularVelocity)); - b2Assert(b2IsValid(bd->inertiaScale) && bd->inertiaScale >= 0.0f); b2Assert(b2IsValid(bd->angularDamping) && bd->angularDamping >= 0.0f); b2Assert(b2IsValid(bd->linearDamping) && bd->linearDamping >= 0.0f); @@ -57,12 +56,15 @@ b2Body::b2Body(const b2BodyDef* bd, b2World* world) m_world = world; - m_xf.position = bd->position; - m_xf.R.Set(bd->angle); + m_xf.p = bd->position; + m_xf.q.Set(bd->angle); m_sweep.localCenter.SetZero(); - m_sweep.a0 = m_sweep.a = bd->angle; - m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + m_sweep.c0 = m_xf.p; + m_sweep.c = m_xf.p; + m_sweep.a0 = bd->angle; + m_sweep.a = bd->angle; + m_sweep.alpha0 = 0.0f; m_jointList = NULL; m_contactList = NULL; @@ -74,6 +76,7 @@ b2Body::b2Body(const b2BodyDef* bd, b2World* world) m_linearDamping = bd->linearDamping; m_angularDamping = bd->angularDamping; + m_gravityScale = bd->gravityScale; m_force.SetZero(); m_torque = 0.0f; @@ -109,6 +112,12 @@ b2Body::~b2Body() void b2Body::SetType(b2BodyType type) { + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } + if (m_type == type) { return; @@ -122,6 +131,9 @@ void b2Body::SetType(b2BodyType type) { m_linearVelocity.SetZero(); m_angularVelocity = 0.0f; + m_sweep.a0 = m_sweep.a; + m_sweep.c0 = m_sweep.c; + SynchronizeFixtures(); } SetAwake(true); @@ -130,9 +142,9 @@ void b2Body::SetType(b2BodyType type) m_torque = 0.0f; // Since the body type changed, we need to flag contacts for filtering. - for (b2ContactEdge* ce = m_contactList; ce; ce = ce->next) + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) { - ce->contact->FlagForFiltering(); + f->Refilter(); } } @@ -153,7 +165,7 @@ b2Fixture* b2Body::CreateFixture(const b2FixtureDef* def) if (m_flags & e_activeFlag) { b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - fixture->CreateProxy(broadPhase, m_xf); + fixture->CreateProxies(broadPhase, m_xf); } fixture->m_next = m_fixtureList; @@ -235,13 +247,8 @@ void b2Body::DestroyFixture(b2Fixture* fixture) if (m_flags & e_activeFlag) { - b2Assert(fixture->m_proxyId != b2BroadPhase::e_nullProxy); b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - fixture->DestroyProxy(broadPhase); - } - else - { - b2Assert(fixture->m_proxyId == b2BroadPhase::e_nullProxy); + fixture->DestroyProxies(broadPhase); } fixture->Destroy(allocator); @@ -268,14 +275,16 @@ void b2Body::ResetMassData() // Static and kinematic bodies have zero mass. if (m_type == b2_staticBody || m_type == b2_kinematicBody) { - m_sweep.c0 = m_sweep.c = m_xf.position; + m_sweep.c0 = m_xf.p; + m_sweep.c = m_xf.p; + m_sweep.a0 = m_sweep.a; return; } b2Assert(m_type == b2_dynamicBody); // Accumulate mass over all fixtures. - b2Vec2 center = b2Vec2_zero; + b2Vec2 localCenter = b2Vec2_zero; for (b2Fixture* f = m_fixtureList; f; f = f->m_next) { if (f->m_density == 0.0f) @@ -286,7 +295,7 @@ void b2Body::ResetMassData() b2MassData massData; f->GetMassData(&massData); m_mass += massData.mass; - center += massData.mass * massData.center; + localCenter += massData.mass * massData.center; m_I += massData.I; } @@ -294,7 +303,7 @@ void b2Body::ResetMassData() if (m_mass > 0.0f) { m_invMass = 1.0f / m_mass; - center *= m_invMass; + localCenter *= m_invMass; } else { @@ -306,7 +315,7 @@ void b2Body::ResetMassData() if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) { // Center the inertia about the center of mass. - m_I -= m_mass * b2Dot(center, center); + m_I -= m_mass * b2Dot(localCenter, localCenter); b2Assert(m_I > 0.0f); m_invI = 1.0f / m_I; @@ -319,7 +328,7 @@ void b2Body::ResetMassData() // Move center of mass. b2Vec2 oldCenter = m_sweep.c; - m_sweep.localCenter = center; + m_sweep.localCenter = localCenter; m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); // Update center of mass velocity. @@ -360,7 +369,7 @@ void b2Body::SetMassData(const b2MassData* massData) // Move center of mass. b2Vec2 oldCenter = m_sweep.c; - m_sweep.localCenter = massData->center; + m_sweep.localCenter = massData->center; m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); // Update center of mass velocity. @@ -398,11 +407,14 @@ void b2Body::SetTransform(const b2Vec2& position, float32 angle) return; } - m_xf.R.Set(angle); - m_xf.position = position; + m_xf.q.Set(angle); + m_xf.p = position; - m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - m_sweep.a0 = m_sweep.a = angle; + m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + m_sweep.a = angle; + + m_sweep.c0 = m_sweep.c; + m_sweep.a0 = angle; b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; for (b2Fixture* f = m_fixtureList; f; f = f->m_next) @@ -416,8 +428,8 @@ void b2Body::SetTransform(const b2Vec2& position, float32 angle) void b2Body::SynchronizeFixtures() { b2Transform xf1; - xf1.R.Set(m_sweep.a0); - xf1.position = m_sweep.c0 - b2Mul(xf1.R, m_sweep.localCenter); + xf1.q.Set(m_sweep.a0); + xf1.p = m_sweep.c0 - b2Mul(xf1.q, m_sweep.localCenter); b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; for (b2Fixture* f = m_fixtureList; f; f = f->m_next) @@ -428,6 +440,8 @@ void b2Body::SynchronizeFixtures() void b2Body::SetActive(bool flag) { + b2Assert(m_world->IsLocked() == false); + if (flag == IsActive()) { return; @@ -441,7 +455,7 @@ void b2Body::SetActive(bool flag) b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; for (b2Fixture* f = m_fixtureList; f; f = f->m_next) { - f->CreateProxy(broadPhase, m_xf); + f->CreateProxies(broadPhase, m_xf); } // Contacts are created the next time step. @@ -454,7 +468,7 @@ void b2Body::SetActive(bool flag) b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; for (b2Fixture* f = m_fixtureList; f; f = f->m_next) { - f->DestroyProxy(broadPhase); + f->DestroyProxies(broadPhase); } // Destroy the attached contacts. diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Body.h b/src/modules/physics/box2d/Box2D/Dynamics/b2Body.h old mode 100644 new mode 100755 index f2f915faa..5ebc5ddd1 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2Body.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Body.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -40,7 +40,10 @@ enum b2BodyType { b2_staticBody = 0, b2_kinematicBody, - b2_dynamicBody, + b2_dynamicBody + + // TODO_ERIN + //b2_bulletBody, }; /// A body definition holds all the data needed to construct a rigid body. @@ -63,7 +66,7 @@ struct b2BodyDef bullet = false; type = b2_staticBody; active = true; - inertiaScale = 1.0f; + gravityScale = 1.0f; } /// The body type: static, kinematic, or dynamic. @@ -115,8 +118,8 @@ struct b2BodyDef /// Use this to store application specific body data. void* userData; - /// Experimental: scales the inertia tensor. - float32 inertiaScale; + /// Scale the gravity applied to this body. + float32 gravityScale; }; /// A rigid body. These are created via b2World::CreateBody. @@ -198,6 +201,10 @@ public: /// @param point the world position of the point of application. void ApplyForce(const b2Vec2& force, const b2Vec2& point); + /// Apply a force to the center of mass. This wakes up the body. + /// @param force the world force vector, usually in Newtons (N). + void ApplyForceToCenter(const b2Vec2& force); + /// Apply a torque. This affects the angular velocity /// without affecting the linear velocity of the center of mass. /// This wakes up the body. @@ -281,6 +288,12 @@ public: /// Set the angular damping of the body. void SetAngularDamping(float32 angularDamping); + /// Get the gravity scale of the body. + float32 GetGravityScale() const; + + /// Set the gravity scale of the body. + void SetGravityScale(float32 scale); + /// Set the type of this body. This may alter the mass and velocity. void SetType(b2BodyType type); @@ -368,17 +381,18 @@ private: friend class b2Island; friend class b2ContactManager; friend class b2ContactSolver; - friend class b2TOISolver; + friend class b2Contact; friend class b2DistanceJoint; friend class b2GearJoint; - friend class b2LineJoint; + friend class b2WheelJoint; friend class b2MouseJoint; friend class b2PrismaticJoint; friend class b2PulleyJoint; friend class b2RevoluteJoint; friend class b2WeldJoint; friend class b2FrictionJoint; + friend class b2RopeJoint; // m_flags enum @@ -389,7 +403,7 @@ private: e_bulletFlag = 0x0008, e_fixedRotationFlag = 0x0010, e_activeFlag = 0x0020, - e_toiFlag = 0x0040, + e_toiFlag = 0x0040 }; b2Body(const b2BodyDef* bd, b2World* world); @@ -436,6 +450,7 @@ private: float32 m_linearDamping; float32 m_angularDamping; + float32 m_gravityScale; float32 m_sleepTime; @@ -454,12 +469,12 @@ inline const b2Transform& b2Body::GetTransform() const inline const b2Vec2& b2Body::GetPosition() const { - return m_xf.position; + return m_xf.p; } inline float32 b2Body::GetAngle() const { - return m_sweep.a; + return m_xf.q.GetAngle(); } inline const b2Vec2& b2Body::GetWorldCenter() const @@ -536,7 +551,7 @@ inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const { - return b2Mul(m_xf.R, localVector); + return b2Mul(m_xf.q, localVector); } inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const @@ -546,7 +561,7 @@ inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const { - return b2MulT(m_xf.R, worldVector); + return b2MulT(m_xf.q, worldVector); } inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const @@ -579,6 +594,16 @@ inline void b2Body::SetAngularDamping(float32 angularDamping) m_angularDamping = angularDamping; } +inline float32 b2Body::GetGravityScale() const +{ + return m_gravityScale; +} + +inline void b2Body::SetGravityScale(float32 scale) +{ + m_gravityScale = scale; +} + inline void b2Body::SetBullet(bool flag) { if (flag) @@ -730,6 +755,21 @@ inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point) m_torque += b2Cross(point - m_sweep.c, force); } +inline void b2Body::ApplyForceToCenter(const b2Vec2& force) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + + m_force += force; +} + inline void b2Body::ApplyTorque(float32 torque) { if (m_type != b2_dynamicBody) @@ -776,17 +816,18 @@ inline void b2Body::ApplyAngularImpulse(float32 impulse) inline void b2Body::SynchronizeTransform() { - m_xf.R.Set(m_sweep.a); - m_xf.position = m_sweep.c - b2Mul(m_xf.R, m_sweep.localCenter); + m_xf.q.Set(m_sweep.a); + m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); } -inline void b2Body::Advance(float32 t) +inline void b2Body::Advance(float32 alpha) { - // Advance to the new safe time. - m_sweep.Advance(t); + // Advance to the new safe time. This doesn't sync the broad-phase. + m_sweep.Advance(alpha); m_sweep.c = m_sweep.c0; m_sweep.a = m_sweep.a0; - SynchronizeTransform(); + m_xf.q.Set(m_sweep.a); + m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); } inline b2World* b2Body::GetWorld() diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp old mode 100644 new mode 100755 index d8d96ddbc..ee12b325e --- a/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -110,10 +110,16 @@ void b2ContactManager::Collide() { b2Fixture* fixtureA = c->GetFixtureA(); b2Fixture* fixtureB = c->GetFixtureB(); + int32 indexA = c->GetChildIndexA(); + int32 indexB = c->GetChildIndexB(); b2Body* bodyA = fixtureA->GetBody(); b2Body* bodyB = fixtureB->GetBody(); + + bool activeA = bodyA->IsAwake() && bodyA->m_type != b2_staticBody; + bool activeB = bodyB->IsAwake() && bodyB->m_type != b2_staticBody; - if (bodyA->IsAwake() == false && bodyB->IsAwake() == false) + // At least one body must be awake and it must be dynamic or kinematic. + if (activeA == false && activeB == false) { c = c->GetNext(); continue; @@ -144,8 +150,8 @@ void b2ContactManager::Collide() c->m_flags &= ~b2Contact::e_filterFlag; } - int32 proxyIdA = fixtureA->m_proxyId; - int32 proxyIdB = fixtureB->m_proxyId; + int32 proxyIdA = fixtureA->m_proxies[indexA].proxyId; + int32 proxyIdB = fixtureB->m_proxies[indexB].proxyId; bool overlap = m_broadPhase.TestOverlap(proxyIdA, proxyIdB); // Here we destroy contacts that cease to overlap in the broad-phase. @@ -170,8 +176,14 @@ void b2ContactManager::FindNewContacts() void b2ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB) { - b2Fixture* fixtureA = (b2Fixture*)proxyUserDataA; - b2Fixture* fixtureB = (b2Fixture*)proxyUserDataB; + b2FixtureProxy* proxyA = (b2FixtureProxy*)proxyUserDataA; + b2FixtureProxy* proxyB = (b2FixtureProxy*)proxyUserDataB; + + b2Fixture* fixtureA = proxyA->fixture; + b2Fixture* fixtureB = proxyB->fixture; + + int32 indexA = proxyA->childIndex; + int32 indexB = proxyB->childIndex; b2Body* bodyA = fixtureA->GetBody(); b2Body* bodyB = fixtureB->GetBody(); @@ -182,6 +194,8 @@ void b2ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB) return; } + // TODO_ERIN use a hash table to remove a potential bottleneck when both + // bodies have a lot of contacts. // Does a contact already exist? b2ContactEdge* edge = bodyB->GetContactList(); while (edge) @@ -190,13 +204,16 @@ void b2ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB) { b2Fixture* fA = edge->contact->GetFixtureA(); b2Fixture* fB = edge->contact->GetFixtureB(); - if (fA == fixtureA && fB == fixtureB) + int32 iA = edge->contact->GetChildIndexA(); + int32 iB = edge->contact->GetChildIndexB(); + + if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB) { // A contact already exists. return; } - if (fA == fixtureB && fB == fixtureA) + if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) { // A contact already exists. return; @@ -219,11 +236,17 @@ void b2ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB) } // Call the factory. - b2Contact* c = b2Contact::Create(fixtureA, fixtureB, m_allocator); + b2Contact* c = b2Contact::Create(fixtureA, indexA, fixtureB, indexB, m_allocator); + if (c == NULL) + { + return; + } // Contact creation may swap fixtures. fixtureA = c->GetFixtureA(); fixtureB = c->GetFixtureB(); + indexA = c->GetChildIndexA(); + indexB = c->GetChildIndexB(); bodyA = fixtureA->GetBody(); bodyB = fixtureB->GetBody(); @@ -262,5 +285,9 @@ void b2ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB) } bodyB->m_contactList = &c->m_nodeB; + // Wake up the bodies + bodyA->SetAwake(true); + bodyB->SetAwake(true); + ++m_contactCount; } diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.h b/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.h old mode 100644 new mode 100755 index fcba54ae7..dc1f77fe5 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp old mode 100644 new mode 100755 index 31355b572..478088a44 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -18,29 +18,26 @@ #include #include +#include #include +#include #include +#include #include #include #include - b2Fixture::b2Fixture() { m_userData = NULL; m_body = NULL; m_next = NULL; - m_proxyId = b2BroadPhase::e_nullProxy; + m_proxies = NULL; + m_proxyCount = 0; m_shape = NULL; m_density = 0.0f; } -b2Fixture::~b2Fixture() -{ - b2Assert(m_shape == NULL); - b2Assert(m_proxyId == b2BroadPhase::e_nullProxy); -} - void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def) { m_userData = def->userData; @@ -56,13 +53,28 @@ void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2Fixtur m_shape = def->shape->Clone(allocator); + // Reserve proxy space + int32 childCount = m_shape->GetChildCount(); + m_proxies = (b2FixtureProxy*)allocator->Allocate(childCount * sizeof(b2FixtureProxy)); + for (int32 i = 0; i < childCount; ++i) + { + m_proxies[i].fixture = NULL; + m_proxies[i].proxyId = b2BroadPhase::e_nullProxy; + } + m_proxyCount = 0; + m_density = def->density; } void b2Fixture::Destroy(b2BlockAllocator* allocator) { - // The proxy must be destroyed before calling this. - b2Assert(m_proxyId == b2BroadPhase::e_nullProxy); + // The proxies must be destroyed before calling this. + b2Assert(m_proxyCount == 0); + + // Free the proxy array. + int32 childCount = m_shape->GetChildCount(); + allocator->Free(m_proxies, childCount * sizeof(b2FixtureProxy)); + m_proxies = NULL; // Free the child shape. switch (m_shape->m_type) @@ -75,6 +87,14 @@ void b2Fixture::Destroy(b2BlockAllocator* allocator) } break; + case b2Shape::e_edge: + { + b2EdgeShape* s = (b2EdgeShape*)m_shape; + s->~b2EdgeShape(); + allocator->Free(s, sizeof(b2EdgeShape)); + } + break; + case b2Shape::e_polygon: { b2PolygonShape* s = (b2PolygonShape*)m_shape; @@ -83,6 +103,14 @@ void b2Fixture::Destroy(b2BlockAllocator* allocator) } break; + case b2Shape::e_chain: + { + b2ChainShape* s = (b2ChainShape*)m_shape; + s->~b2ChainShape(); + allocator->Free(s, sizeof(b2ChainShape)); + } + break; + default: b2Assert(false); break; @@ -91,50 +119,69 @@ void b2Fixture::Destroy(b2BlockAllocator* allocator) m_shape = NULL; } -void b2Fixture::CreateProxy(b2BroadPhase* broadPhase, const b2Transform& xf) +void b2Fixture::CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf) { - b2Assert(m_proxyId == b2BroadPhase::e_nullProxy); + b2Assert(m_proxyCount == 0); - // Create proxy in the broad-phase. - m_shape->ComputeAABB(&m_aabb, xf); - m_proxyId = broadPhase->CreateProxy(m_aabb, this); + // Create proxies in the broad-phase. + m_proxyCount = m_shape->GetChildCount(); + + for (int32 i = 0; i < m_proxyCount; ++i) + { + b2FixtureProxy* proxy = m_proxies + i; + m_shape->ComputeAABB(&proxy->aabb, xf, i); + proxy->proxyId = broadPhase->CreateProxy(proxy->aabb, proxy); + proxy->fixture = this; + proxy->childIndex = i; + } } -void b2Fixture::DestroyProxy(b2BroadPhase* broadPhase) +void b2Fixture::DestroyProxies(b2BroadPhase* broadPhase) { - if (m_proxyId == b2BroadPhase::e_nullProxy) + // Destroy proxies in the broad-phase. + for (int32 i = 0; i < m_proxyCount; ++i) { - return; + b2FixtureProxy* proxy = m_proxies + i; + broadPhase->DestroyProxy(proxy->proxyId); + proxy->proxyId = b2BroadPhase::e_nullProxy; } - // Destroy proxy in the broad-phase. - broadPhase->DestroyProxy(m_proxyId); - m_proxyId = b2BroadPhase::e_nullProxy; + m_proxyCount = 0; } void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2) { - if (m_proxyId == b2BroadPhase::e_nullProxy) + if (m_proxyCount == 0) { return; } - // Compute an AABB that covers the swept shape (may miss some rotation effect). - b2AABB aabb1, aabb2; - m_shape->ComputeAABB(&aabb1, transform1); - m_shape->ComputeAABB(&aabb2, transform2); + for (int32 i = 0; i < m_proxyCount; ++i) + { + b2FixtureProxy* proxy = m_proxies + i; + + // Compute an AABB that covers the swept shape (may miss some rotation effect). + b2AABB aabb1, aabb2; + m_shape->ComputeAABB(&aabb1, transform1, proxy->childIndex); + m_shape->ComputeAABB(&aabb2, transform2, proxy->childIndex); - m_aabb.Combine(aabb1, aabb2); + proxy->aabb.Combine(aabb1, aabb2); - b2Vec2 displacement = transform2.position - transform1.position; + b2Vec2 displacement = transform2.p - transform1.p; - broadPhase->MoveProxy(m_proxyId, m_aabb, displacement); + broadPhase->MoveProxy(proxy->proxyId, proxy->aabb, displacement); + } } void b2Fixture::SetFilterData(const b2Filter& filter) { m_filter = filter; + Refilter(); +} + +void b2Fixture::Refilter() +{ if (m_body == NULL) { return; @@ -154,10 +201,28 @@ void b2Fixture::SetFilterData(const b2Filter& filter) edge = edge->next; } + + b2World* world = m_body->GetWorld(); + + if (world == NULL) + { + return; + } + + // Touch each proxy so that new pairs may be created + b2BroadPhase* broadPhase = &world->m_contactManager.m_broadPhase; + for (int32 i = 0; i < m_proxyCount; ++i) + { + broadPhase->TouchProxy(m_proxies[i].proxyId); + } } void b2Fixture::SetSensor(bool sensor) { - m_isSensor = sensor; + if (sensor != m_isSensor) + { + m_body->SetAwake(true); + m_isSensor = sensor; + } } diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h b/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h old mode 100644 new mode 100755 index d9d325554..a7b5c3428 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -26,6 +26,7 @@ class b2BlockAllocator; class b2Body; class b2BroadPhase; +class b2Fixture; /// This holds contact filtering data. struct b2Filter @@ -61,8 +62,6 @@ struct b2FixtureDef isSensor = false; } - virtual ~b2FixtureDef() {} - /// The shape, this must be set. The shape will be cloned, so you /// can create the shape on the stack. const b2Shape* shape; @@ -87,6 +86,14 @@ struct b2FixtureDef b2Filter filter; }; +/// This proxy is used internally to connect fixtures to the broad-phase. +struct b2FixtureProxy +{ + b2AABB aabb; + b2Fixture* fixture; + int32 childIndex; + int32 proxyId; +}; /// A fixture is used to attach a shape to a body for collision detection. A fixture /// inherits its transform from its parent. Fixtures hold additional non-geometric data @@ -115,11 +122,15 @@ public: /// Set the contact filtering data. This will not update contacts until the next time /// step when either parent body is active and awake. + /// This automatically calls Refilter. void SetFilterData(const b2Filter& filter); /// Get the contact filtering data. const b2Filter& GetFilterData() const; + /// Call this if you want to establish collision that was previously disabled by b2ContactFilter::ShouldCollide. + void Refilter(); + /// Get the parent body of this fixture. This is NULL if the fixture is not attached. /// @return the parent body. b2Body* GetBody(); @@ -138,14 +149,13 @@ public: void SetUserData(void* data); /// Test a point for containment in this fixture. - /// @param xf the shape world transform. /// @param p a point in world coordinates. bool TestPoint(const b2Vec2& p) const; /// Cast a ray against this shape. /// @param output the ray-cast results. /// @param input the ray-cast input parameters. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const; + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const; /// Get the mass data for this fixture. The mass data is based on the density and /// the shape. The rotational inertia is about the shape's origin. This operation @@ -162,19 +172,21 @@ public: /// Get the coefficient of friction. float32 GetFriction() const; - /// Set the coefficient of friction. + /// Set the coefficient of friction. This will _not_ change the friction of + /// existing contacts. void SetFriction(float32 friction); /// Get the coefficient of restitution. float32 GetRestitution() const; - /// Set the coefficient of restitution. + /// Set the coefficient of restitution. This will _not_ change the restitution of + /// existing contacts. void SetRestitution(float32 restitution); /// Get the fixture's AABB. This AABB may be enlarge and/or stale. /// If you need a more accurate AABB, compute it using the shape and /// the body transform. - const b2AABB& GetAABB() const; + const b2AABB& GetAABB(int32 childIndex) const; protected: @@ -184,7 +196,6 @@ protected: friend class b2ContactManager; b2Fixture(); - ~b2Fixture(); // We need separation create/destroy functions from the constructor/destructor because // the destructor cannot access the allocator (no destructor arguments allowed by C++). @@ -192,13 +203,11 @@ protected: void Destroy(b2BlockAllocator* allocator); // These support body activation/deactivation. - void CreateProxy(b2BroadPhase* broadPhase, const b2Transform& xf); - void DestroyProxy(b2BroadPhase* broadPhase); + void CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf); + void DestroyProxies(b2BroadPhase* broadPhase); void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2); - b2AABB m_aabb; - float32 m_density; b2Fixture* m_next; @@ -209,7 +218,9 @@ protected: float32 m_friction; float32 m_restitution; - int32 m_proxyId; + b2FixtureProxy* m_proxies; + int32 m_proxyCount; + b2Filter m_filter; bool m_isSensor; @@ -308,9 +319,9 @@ inline bool b2Fixture::TestPoint(const b2Vec2& p) const return m_shape->TestPoint(m_body->GetTransform(), p); } -inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const +inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const { - return m_shape->RayCast(output, input, m_body->GetTransform()); + return m_shape->RayCast(output, input, m_body->GetTransform(), childIndex); } inline void b2Fixture::GetMassData(b2MassData* massData) const @@ -318,9 +329,10 @@ inline void b2Fixture::GetMassData(b2MassData* massData) const m_shape->ComputeMass(massData, m_density); } -inline const b2AABB& b2Fixture::GetAABB() const +inline const b2AABB& b2Fixture::GetAABB(int32 childIndex) const { - return m_aabb; + b2Assert(0 <= childIndex && childIndex < m_proxyCount); + return m_proxies[childIndex].aabb; } #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Island.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2Island.cpp old mode 100644 new mode 100755 index 009249979..0e2129cf8 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2Island.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Island.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -16,6 +16,7 @@ * 3. This notice may not be removed or altered from any source distribution. */ +#include #include #include #include @@ -24,6 +25,7 @@ #include #include #include +#include /* Position Correction Notes @@ -178,130 +180,166 @@ b2Island::~b2Island() m_allocator->Free(m_bodies); } -void b2Island::Solve(const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep) +void b2Island::Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep) { - // Integrate velocities and apply damping. + b2Timer timer; + + float32 h = step.dt; + + // Integrate velocities and apply damping. Initialize the body state. for (int32 i = 0; i < m_bodyCount; ++i) { b2Body* b = m_bodies[i]; - if (b->GetType() != b2_dynamicBody) - { - continue; - } - - // Integrate velocities. - b->m_linearVelocity += step.dt * (gravity + b->m_invMass * b->m_force); - b->m_angularVelocity += step.dt * b->m_invI * b->m_torque; - - // Apply damping. - // ODE: dv/dt + c * v = 0 - // Solution: v(t) = v0 * exp(-c * t) - // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt) - // v2 = exp(-c * dt) * v1 - // Taylor expansion: - // v2 = (1.0f - c * dt) * v1 - b->m_linearVelocity *= b2Clamp(1.0f - step.dt * b->m_linearDamping, 0.0f, 1.0f); - b->m_angularVelocity *= b2Clamp(1.0f - step.dt * b->m_angularDamping, 0.0f, 1.0f); - } - - // Partition contacts so that contacts with static bodies are solved last. - int32 i1 = -1; - for (int32 i2 = 0; i2 < m_contactCount; ++i2) - { - b2Fixture* fixtureA = m_contacts[i2]->GetFixtureA(); - b2Fixture* fixtureB = m_contacts[i2]->GetFixtureB(); - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - bool nonStatic = bodyA->GetType() != b2_staticBody && bodyB->GetType() != b2_staticBody; - if (nonStatic) - { - ++i1; - b2Swap(m_contacts[i1], m_contacts[i2]); - } - } - - // Initialize velocity constraints. - b2ContactSolver contactSolver(m_contacts, m_contactCount, m_allocator, step.dtRatio); - contactSolver.WarmStart(); - for (int32 i = 0; i < m_jointCount; ++i) - { - m_joints[i]->InitVelocityConstraints(step); - } - - // Solve velocity constraints. - for (int32 i = 0; i < step.velocityIterations; ++i) - { - for (int32 j = 0; j < m_jointCount; ++j) - { - m_joints[j]->SolveVelocityConstraints(step); - } - - contactSolver.SolveVelocityConstraints(); - } - - // Post-solve (store impulses for warm starting). - contactSolver.StoreImpulses(); - - // Integrate positions. - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - - if (b->GetType() == b2_staticBody) - { - continue; - } - - // Check for large velocities. - b2Vec2 translation = step.dt * b->m_linearVelocity; - if (b2Dot(translation, translation) > b2_maxTranslationSquared) - { - float32 ratio = b2_maxTranslation / translation.Length(); - b->m_linearVelocity *= ratio; - } - - float32 rotation = step.dt * b->m_angularVelocity; - if (rotation * rotation > b2_maxRotationSquared) - { - float32 ratio = b2_maxRotation / b2Abs(rotation); - b->m_angularVelocity *= ratio; - } + b2Vec2 c = b->m_sweep.c; + float32 a = b->m_sweep.a; + b2Vec2 v = b->m_linearVelocity; + float32 w = b->m_angularVelocity; // Store positions for continuous collision. b->m_sweep.c0 = b->m_sweep.c; b->m_sweep.a0 = b->m_sweep.a; - // Integrate - b->m_sweep.c += step.dt * b->m_linearVelocity; - b->m_sweep.a += step.dt * b->m_angularVelocity; + if (b->m_type == b2_dynamicBody) + { + // Integrate velocities. + v += h * (b->m_gravityScale * gravity + b->m_invMass * b->m_force); + w += h * b->m_invI * b->m_torque; - // Compute new transform - b->SynchronizeTransform(); + // Apply damping. + // ODE: dv/dt + c * v = 0 + // Solution: v(t) = v0 * exp(-c * t) + // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt) + // v2 = exp(-c * dt) * v1 + // Taylor expansion: + // v2 = (1.0f - c * dt) * v1 + v *= b2Clamp(1.0f - h * b->m_linearDamping, 0.0f, 1.0f); + w *= b2Clamp(1.0f - h * b->m_angularDamping, 0.0f, 1.0f); + } - // Note: shapes are synchronized later. + m_positions[i].c = c; + m_positions[i].a = a; + m_velocities[i].v = v; + m_velocities[i].w = w; } - // Iterate over constraints. + timer.Reset(); + + // Solver data + b2SolverData solverData; + solverData.step = step; + solverData.positions = m_positions; + solverData.velocities = m_velocities; + + // Initialize velocity constraints. + b2ContactSolverDef contactSolverDef; + contactSolverDef.step = step; + contactSolverDef.contacts = m_contacts; + contactSolverDef.count = m_contactCount; + contactSolverDef.positions = m_positions; + contactSolverDef.velocities = m_velocities; + contactSolverDef.allocator = m_allocator; + + b2ContactSolver contactSolver(&contactSolverDef); + contactSolver.InitializeVelocityConstraints(); + + if (step.warmStarting) + { + contactSolver.WarmStart(); + } + + for (int32 i = 0; i < m_jointCount; ++i) + { + m_joints[i]->InitVelocityConstraints(solverData); + } + + profile->solveInit = timer.GetMilliseconds(); + + // Solve velocity constraints + timer.Reset(); + for (int32 i = 0; i < step.velocityIterations; ++i) + { + for (int32 j = 0; j < m_jointCount; ++j) + { + m_joints[j]->SolveVelocityConstraints(solverData); + } + + contactSolver.SolveVelocityConstraints(); + } + + // Store impulses for warm starting + contactSolver.StoreImpulses(); + profile->solveVelocity = timer.GetMilliseconds(); + + // Integrate positions + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Vec2 c = m_positions[i].c; + float32 a = m_positions[i].a; + b2Vec2 v = m_velocities[i].v; + float32 w = m_velocities[i].w; + + // Check for large velocities + b2Vec2 translation = h * v; + if (b2Dot(translation, translation) > b2_maxTranslationSquared) + { + float32 ratio = b2_maxTranslation / translation.Length(); + v *= ratio; + } + + float32 rotation = h * w; + if (rotation * rotation > b2_maxRotationSquared) + { + float32 ratio = b2_maxRotation / b2Abs(rotation); + w *= ratio; + } + + // Integrate + c += h * v; + a += h * w; + + m_positions[i].c = c; + m_positions[i].a = a; + m_velocities[i].v = v; + m_velocities[i].w = w; + } + + // Solve position constraints + timer.Reset(); + bool positionSolved = false; for (int32 i = 0; i < step.positionIterations; ++i) { - bool contactsOkay = contactSolver.SolvePositionConstraints(b2_contactBaumgarte); + bool contactsOkay = contactSolver.SolvePositionConstraints(); bool jointsOkay = true; for (int32 i = 0; i < m_jointCount; ++i) { - bool jointOkay = m_joints[i]->SolvePositionConstraints(b2_contactBaumgarte); + bool jointOkay = m_joints[i]->SolvePositionConstraints(solverData); jointsOkay = jointsOkay && jointOkay; } if (contactsOkay && jointsOkay) { // Exit early if the position errors are small. + positionSolved = true; break; } } - Report(contactSolver.m_constraints); + // Copy state buffers back to the bodies + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* body = m_bodies[i]; + body->m_sweep.c = m_positions[i].c; + body->m_sweep.a = m_positions[i].a; + body->m_linearVelocity = m_velocities[i].v; + body->m_angularVelocity = m_velocities[i].w; + body->SynchronizeTransform(); + } + + profile->solvePosition = timer.GetMilliseconds(); + + Report(contactSolver.m_velocityConstraints); if (allowSleep) { @@ -318,12 +356,6 @@ void b2Island::Solve(const b2TimeStep& step, const b2Vec2& gravity, bool allowSl continue; } - if ((b->m_flags & b2Body::e_autoSleepFlag) == 0) - { - b->m_sleepTime = 0.0f; - minSleepTime = 0.0f; - } - if ((b->m_flags & b2Body::e_autoSleepFlag) == 0 || b->m_angularVelocity * b->m_angularVelocity > angTolSqr || b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr) @@ -333,12 +365,12 @@ void b2Island::Solve(const b2TimeStep& step, const b2Vec2& gravity, bool allowSl } else { - b->m_sleepTime += step.dt; + b->m_sleepTime += h; minSleepTime = b2Min(minSleepTime, b->m_sleepTime); } } - if (minSleepTime >= b2_timeToSleep) + if (minSleepTime >= b2_timeToSleep && positionSolved) { for (int32 i = 0; i < m_bodyCount; ++i) { @@ -349,7 +381,139 @@ void b2Island::Solve(const b2TimeStep& step, const b2Vec2& gravity, bool allowSl } } -void b2Island::Report(const b2ContactConstraint* constraints) +void b2Island::SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB) +{ + b2Assert(toiIndexA < m_bodyCount); + b2Assert(toiIndexB < m_bodyCount); + + // Initialize the body state. + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* b = m_bodies[i]; + m_positions[i].c = b->m_sweep.c; + m_positions[i].a = b->m_sweep.a; + m_velocities[i].v = b->m_linearVelocity; + m_velocities[i].w = b->m_angularVelocity; + } + + b2ContactSolverDef contactSolverDef; + contactSolverDef.contacts = m_contacts; + contactSolverDef.count = m_contactCount; + contactSolverDef.allocator = m_allocator; + contactSolverDef.step = subStep; + contactSolverDef.positions = m_positions; + contactSolverDef.velocities = m_velocities; + b2ContactSolver contactSolver(&contactSolverDef); + + // Solve position constraints. + for (int32 i = 0; i < subStep.positionIterations; ++i) + { + bool contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB); + if (contactsOkay) + { + break; + } + } + +#if 0 + // Is the new position really safe? + for (int32 i = 0; i < m_contactCount; ++i) + { + b2Contact* c = m_contacts[i]; + b2Fixture* fA = c->GetFixtureA(); + b2Fixture* fB = c->GetFixtureB(); + + b2Body* bA = fA->GetBody(); + b2Body* bB = fB->GetBody(); + + int32 indexA = c->GetChildIndexA(); + int32 indexB = c->GetChildIndexB(); + + b2DistanceInput input; + input.proxyA.Set(fA->GetShape(), indexA); + input.proxyB.Set(fB->GetShape(), indexB); + input.transformA = bA->GetTransform(); + input.transformB = bB->GetTransform(); + input.useRadii = false; + + b2DistanceOutput output; + b2SimplexCache cache; + cache.count = 0; + b2Distance(&output, &cache, &input); + + if (output.distance == 0 || cache.count == 3) + { + cache.count += 0; + } + } +#endif + + // Leap of faith to new safe state. + m_bodies[toiIndexA]->m_sweep.c0 = m_positions[toiIndexA].c; + m_bodies[toiIndexA]->m_sweep.a0 = m_positions[toiIndexA].a; + m_bodies[toiIndexB]->m_sweep.c0 = m_positions[toiIndexB].c; + m_bodies[toiIndexB]->m_sweep.a0 = m_positions[toiIndexB].a; + + // No warm starting is needed for TOI events because warm + // starting impulses were applied in the discrete solver. + contactSolver.InitializeVelocityConstraints(); + + // Solve velocity constraints. + for (int32 i = 0; i < subStep.velocityIterations; ++i) + { + contactSolver.SolveVelocityConstraints(); + } + + // Don't store the TOI contact forces for warm starting + // because they can be quite large. + + float32 h = subStep.dt; + + // Integrate positions + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Vec2 c = m_positions[i].c; + float32 a = m_positions[i].a; + b2Vec2 v = m_velocities[i].v; + float32 w = m_velocities[i].w; + + // Check for large velocities + b2Vec2 translation = h * v; + if (b2Dot(translation, translation) > b2_maxTranslationSquared) + { + float32 ratio = b2_maxTranslation / translation.Length(); + v *= ratio; + } + + float32 rotation = h * w; + if (rotation * rotation > b2_maxRotationSquared) + { + float32 ratio = b2_maxRotation / b2Abs(rotation); + w *= ratio; + } + + // Integrate + c += h * v; + a += h * w; + + m_positions[i].c = c; + m_positions[i].a = a; + m_velocities[i].v = v; + m_velocities[i].w = w; + + // Sync bodies + b2Body* body = m_bodies[i]; + body->m_sweep.c = c; + body->m_sweep.a = a; + body->m_linearVelocity = v; + body->m_angularVelocity = w; + body->SynchronizeTransform(); + } + + Report(contactSolver.m_velocityConstraints); +} + +void b2Island::Report(const b2ContactVelocityConstraint* constraints) { if (m_listener == NULL) { @@ -360,13 +524,14 @@ void b2Island::Report(const b2ContactConstraint* constraints) { b2Contact* c = m_contacts[i]; - const b2ContactConstraint* cc = constraints + i; + const b2ContactVelocityConstraint* vc = constraints + i; b2ContactImpulse impulse; - for (int32 j = 0; j < cc->pointCount; ++j) + impulse.count = vc->pointCount; + for (int32 j = 0; j < vc->pointCount; ++j) { - impulse.normalImpulses[j] = cc->points[j].normalImpulse; - impulse.tangentImpulses[j] = cc->points[j].tangentImpulse; + impulse.normalImpulses[j] = vc->points[j].normalImpulse; + impulse.tangentImpulses[j] = vc->points[j].tangentImpulse; } m_listener->PostSolve(c, &impulse); diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Island.h b/src/modules/physics/box2d/Box2D/Dynamics/b2Island.h old mode 100644 new mode 100755 index 3a5fd1131..ef3d9b1df --- a/src/modules/physics/box2d/Box2D/Dynamics/b2Island.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Island.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -27,21 +27,8 @@ class b2Contact; class b2Joint; class b2StackAllocator; class b2ContactListener; -struct b2ContactConstraint; - -/// This is an internal structure. -struct b2Position -{ - b2Vec2 x; - float32 a; -}; - -/// This is an internal structure. -struct b2Velocity -{ - b2Vec2 v; - float32 w; -}; +struct b2ContactVelocityConstraint; +struct b2Profile; /// This is an internal class. class b2Island @@ -58,13 +45,16 @@ public: m_jointCount = 0; } - void Solve(const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep); + void Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep); + + void SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB); void Add(b2Body* body) { b2Assert(m_bodyCount < m_bodyCapacity); body->m_islandIndex = m_bodyCount; - m_bodies[m_bodyCount++] = body; + m_bodies[m_bodyCount] = body; + ++m_bodyCount; } void Add(b2Contact* contact) @@ -79,7 +69,7 @@ public: m_joints[m_jointCount++] = joint; } - void Report(const b2ContactConstraint* constraints); + void Report(const b2ContactVelocityConstraint* constraints); b2StackAllocator* m_allocator; b2ContactListener* m_listener; @@ -98,8 +88,6 @@ public: int32 m_bodyCapacity; int32 m_contactCapacity; int32 m_jointCapacity; - - int32 m_positionIterationCount; }; #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2TimeStep.h b/src/modules/physics/box2d/Box2D/Dynamics/b2TimeStep.h old mode 100644 new mode 100755 index f59245dd6..80916cb65 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2TimeStep.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2TimeStep.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -19,17 +19,52 @@ #ifndef B2_TIME_STEP_H #define B2_TIME_STEP_H -#include +#include -/// This is an internal structure. -struct b2TimeStep +/// Profiling data. Times are in milliseconds. +struct b2Profile { - float32 dt; // time step - float32 inv_dt; // inverse time step (0 if dt == 0). - float32 dtRatio; // dt * inv_dt0 - int32 velocityIterations; - int32 positionIterations; - bool warmStarting; + float32 step; + float32 collide; + float32 solve; + float32 solveInit; + float32 solveVelocity; + float32 solvePosition; + float32 broadphase; + float32 solveTOI; }; +/// This is an internal structure. +struct b2TimeStep +{ + float32 dt; // time step + float32 inv_dt; // inverse time step (0 if dt == 0). + float32 dtRatio; // dt * inv_dt0 + int32 velocityIterations; + int32 positionIterations; + bool warmStarting; +}; + +/// This is an internal structure. +struct b2Position +{ + b2Vec2 c; + float32 a; +}; + +/// This is an internal structure. +struct b2Velocity +{ + b2Vec2 v; + float32 w; +}; + +/// Solver Data +struct b2SolverData +{ + b2TimeStep step; + b2Position* positions; + b2Velocity* velocities; +}; + #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp old mode 100644 new mode 100755 index d3b9e0038..7dcddd03c --- a/src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -23,12 +23,15 @@ #include #include #include -#include #include #include #include +#include +#include #include #include +#include +#include #include b2World::b2World(const b2Vec2& gravity, bool doSleep) @@ -44,6 +47,9 @@ b2World::b2World(const b2Vec2& gravity, bool doSleep) m_warmStarting = true; m_continuousPhysics = true; + m_subStepping = false; + + m_stepComplete = true; m_allowSleep = doSleep; m_gravity = gravity; @@ -53,10 +59,29 @@ b2World::b2World(const b2Vec2& gravity, bool doSleep) m_inv_dt0 = 0.0f; m_contactManager.m_allocator = &m_blockAllocator; + + memset(&m_profile, 0, sizeof(b2Profile)); } b2World::~b2World() { + // Some shapes allocate using b2Alloc. + b2Body* b = m_bodyList; + while (b) + { + b2Body* bNext = b->m_next; + + b2Fixture* f = b->m_fixtureList; + while (f) + { + b2Fixture* fNext = f->m_next; + f->m_proxyCount = 0; + f->Destroy(&m_blockAllocator); + f = fNext; + } + + b = bNext; + } } void b2World::SetDestructionListener(b2DestructionListener* listener) @@ -74,7 +99,7 @@ void b2World::SetContactListener(b2ContactListener* listener) m_contactManager.m_contactListener = listener; } -void b2World::SetDebugDraw(b2DebugDraw* debugDraw) +void b2World::SetDebugDraw(b2Draw* debugDraw) { m_debugDraw = debugDraw; } @@ -125,6 +150,8 @@ void b2World::DestroyBody(b2Body* b) } DestroyJoint(je0->joint); + + b->m_jointList = je; } b->m_jointList = NULL; @@ -150,10 +177,13 @@ void b2World::DestroyBody(b2Body* b) m_destructionListener->SayGoodbye(f0); } - f0->DestroyProxy(&m_contactManager.m_broadPhase); + f0->DestroyProxies(&m_contactManager.m_broadPhase); f0->Destroy(&m_blockAllocator); f0->~b2Fixture(); m_blockAllocator.Free(f0, sizeof(b2Fixture)); + + b->m_fixtureList = f; + b->m_fixtureCount -= 1; } b->m_fixtureList = NULL; b->m_fixtureCount = 0; @@ -337,6 +367,10 @@ void b2World::DestroyJoint(b2Joint* j) // Find islands, integrate and solve constraints, solve position constraints void b2World::Solve(const b2TimeStep& step) { + m_profile.solveInit = 0.0f; + m_profile.solveVelocity = 0.0f; + m_profile.solvePosition = 0.0f; + // Size the island for the worst case. b2Island island(m_bodyCount, m_contactManager.m_contactCount, @@ -475,7 +509,11 @@ void b2World::Solve(const b2TimeStep& step) } } - island.Solve(step, m_gravity, m_allowSleep); + b2Profile profile; + island.Solve(&profile, step, m_gravity, m_allowSleep); + m_profile.solveInit += profile.solveInit; + m_profile.solveVelocity += profile.solveVelocity; + m_profile.solvePosition += profile.solvePosition; // Post solve cleanup. for (int32 i = 0; i < island.m_bodyCount; ++i) @@ -491,292 +529,357 @@ void b2World::Solve(const b2TimeStep& step) m_stackAllocator.Free(stack); - // Synchronize fixtures, check for out of range bodies. - for (b2Body* b = m_bodyList; b; b = b->GetNext()) { - // If a body was not in an island then it did not move. - if ((b->m_flags & b2Body::e_islandFlag) == 0) + b2Timer timer; + // Synchronize fixtures, check for out of range bodies. + for (b2Body* b = m_bodyList; b; b = b->GetNext()) { - continue; - } - - if (b->GetType() == b2_staticBody) - { - continue; - } - - // Update fixtures (for broad-phase). - b->SynchronizeFixtures(); - } - - // Look for new contacts. - m_contactManager.FindNewContacts(); -} - -// Advance a dynamic body to its first time of contact -// and adjust the position to ensure clearance. -void b2World::SolveTOI(b2Body* body) -{ - // Find the minimum contact. - b2Contact* toiContact = NULL; - float32 toi = 1.0f; - b2Body* toiOther = NULL; - bool found; - int32 count; - int32 iter = 0; - - bool bullet = body->IsBullet(); - - // Iterate until all contacts agree on the minimum TOI. We have - // to iterate because the TOI algorithm may skip some intermediate - // collisions when objects rotate through each other. - do - { - count = 0; - found = false; - for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) - { - if (ce->contact == toiContact) + // If a body was not in an island then it did not move. + if ((b->m_flags & b2Body::e_islandFlag) == 0) { continue; } - b2Body* other = ce->other; - b2BodyType type = other->GetType(); - - // Only bullets perform TOI with dynamic bodies. - if (bullet == true) + if (b->GetType() == b2_staticBody) { - // Bullets only perform TOI with bodies that have their TOI resolved. - if ((other->m_flags & b2Body::e_toiFlag) == 0) + continue; + } + + // Update fixtures (for broad-phase). + b->SynchronizeFixtures(); + } + + // Look for new contacts. + m_contactManager.FindNewContacts(); + m_profile.broadphase = timer.GetMilliseconds(); + } +} + +// Find TOI contacts and solve them. +void b2World::SolveTOI(const b2TimeStep& step) +{ + b2Island island(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, &m_stackAllocator, m_contactManager.m_contactListener); + + if (m_stepComplete) + { + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->m_flags &= ~b2Body::e_islandFlag; + b->m_sweep.alpha0 = 0.0f; + } + + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) + { + // Invalidate TOI + c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); + c->m_toiCount = 0; + c->m_toi = 1.0f; + } + } + + // Find TOI events and solve them. + for (;;) + { + // Find the first TOI. + b2Contact* minContact = NULL; + float32 minAlpha = 1.0f; + + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) + { + // Is this contact disabled? + if (c->IsEnabled() == false) + { + continue; + } + + // Prevent excessive sub-stepping. + if (c->m_toiCount > b2_maxSubSteps) + { + continue; + } + + float32 alpha = 1.0f; + if (c->m_flags & b2Contact::e_toiFlag) + { + // This contact has a valid cached TOI. + alpha = c->m_toi; + } + else + { + b2Fixture* fA = c->GetFixtureA(); + b2Fixture* fB = c->GetFixtureB(); + + // Is there a sensor? + if (fA->IsSensor() || fB->IsSensor()) { continue; } - // No repeated hits on non-static bodies - if (type != b2_staticBody && (ce->contact->m_flags & b2Contact::e_bulletHitFlag) != 0) + b2Body* bA = fA->GetBody(); + b2Body* bB = fB->GetBody(); + + b2BodyType typeA = bA->m_type; + b2BodyType typeB = bB->m_type; + b2Assert(typeA == b2_dynamicBody || typeB == b2_dynamicBody); + + bool activeA = bA->IsAwake() && typeA != b2_staticBody; + bool activeB = bB->IsAwake() && typeB != b2_staticBody; + + // Is at least one body active (awake and dynamic or kinematic)? + if (activeA == false && activeB == false) { - continue; + continue; } + + bool collideA = bA->IsBullet() || typeA != b2_dynamicBody; + bool collideB = bB->IsBullet() || typeB != b2_dynamicBody; + + // Are these two non-bullet dynamic bodies? + if (collideA == false && collideB == false) + { + continue; + } + + // Compute the TOI for this contact. + // Put the sweeps onto the same time interval. + float32 alpha0 = bA->m_sweep.alpha0; + + if (bA->m_sweep.alpha0 < bB->m_sweep.alpha0) + { + alpha0 = bB->m_sweep.alpha0; + bA->m_sweep.Advance(alpha0); + } + else if (bB->m_sweep.alpha0 < bA->m_sweep.alpha0) + { + alpha0 = bA->m_sweep.alpha0; + bB->m_sweep.Advance(alpha0); + } + + b2Assert(alpha0 < 1.0f); + + int32 indexA = c->GetChildIndexA(); + int32 indexB = c->GetChildIndexB(); + + // Compute the time of impact in interval [0, minTOI] + b2TOIInput input; + input.proxyA.Set(fA->GetShape(), indexA); + input.proxyB.Set(fB->GetShape(), indexB); + input.sweepA = bA->m_sweep; + input.sweepB = bB->m_sweep; + input.tMax = 1.0f; + + b2TOIOutput output; + b2TimeOfImpact(&output, &input); + + // Beta is the fraction of the remaining portion of the . + float32 beta = output.t; + if (output.state == b2TOIOutput::e_touching) + { + alpha = b2Min(alpha0 + (1.0f - alpha0) * beta, 1.0f); + } + else + { + alpha = 1.0f; + } + + c->m_toi = alpha; + c->m_flags |= b2Contact::e_toiFlag; } - else if (type == b2_dynamicBody) + + if (alpha < minAlpha) { - continue; + // This is the minimum TOI found so far. + minContact = c; + minAlpha = alpha; } - - // Check for a disabled contact. - b2Contact* contact = ce->contact; - if (contact->IsEnabled() == false) - { - continue; - } - - // Prevent infinite looping. - if (contact->m_toiCount > 10) - { - continue; - } - - b2Fixture* fixtureA = contact->m_fixtureA; - b2Fixture* fixtureB = contact->m_fixtureB; - - // Cull sensors. - if (fixtureA->IsSensor() || fixtureB->IsSensor()) - { - continue; - } - - b2Body* bodyA = fixtureA->m_body; - b2Body* bodyB = fixtureB->m_body; - - // Compute the time of impact in interval [0, minTOI] - b2TOIInput input; - input.proxyA.Set(fixtureA->GetShape()); - input.proxyB.Set(fixtureB->GetShape()); - input.sweepA = bodyA->m_sweep; - input.sweepB = bodyB->m_sweep; - input.tMax = toi; - - b2TOIOutput output; - b2TimeOfImpact(&output, &input); - - if (output.state == b2TOIOutput::e_touching && output.t < toi) - { - toiContact = contact; - toi = output.t; - toiOther = other; - found = true; - } - - ++count; } - ++iter; - } while (found && count > 1 && iter < 50); - - if (toiContact == NULL) - { - body->Advance(1.0f); - return; - } - - b2Sweep backup = body->m_sweep; - body->Advance(toi); - toiContact->Update(m_contactManager.m_contactListener); - if (toiContact->IsEnabled() == false) - { - // Contact disabled. Backup and recurse. - body->m_sweep = backup; - SolveTOI(body); - } - - ++toiContact->m_toiCount; - - // Update all the valid contacts on this body and build a contact island. - b2Contact* contacts[b2_maxTOIContacts]; - count = 0; - for (b2ContactEdge* ce = body->m_contactList; ce && count < b2_maxTOIContacts; ce = ce->next) - { - b2Body* other = ce->other; - b2BodyType type = other->GetType(); - - // Only perform correction with static bodies, so the - // body won't get pushed out of the world. - if (type == b2_dynamicBody) + if (minContact == NULL || 1.0f - 10.0f * b2_epsilon < minAlpha) { - continue; - } - - // Check for a disabled contact. - b2Contact* contact = ce->contact; - if (contact->IsEnabled() == false) - { - continue; - } - - b2Fixture* fixtureA = contact->m_fixtureA; - b2Fixture* fixtureB = contact->m_fixtureB; - - // Cull sensors. - if (fixtureA->IsSensor() || fixtureB->IsSensor()) - { - continue; - } - - // The contact likely has some new contact points. The listener - // gives the user a chance to disable the contact. - if (contact != toiContact) - { - contact->Update(m_contactManager.m_contactListener); - } - - // Did the user disable the contact? - if (contact->IsEnabled() == false) - { - // Skip this contact. - continue; - } - - if (contact->IsTouching() == false) - { - continue; - } - - contacts[count] = contact; - ++count; - } - - // Reduce the TOI body's overlap with the contact island. - b2TOISolver solver(&m_stackAllocator); - solver.Initialize(contacts, count, body); - - const float32 k_toiBaumgarte = 0.75f; - bool solved = false; - for (int32 i = 0; i < 20; ++i) - { - bool contactsOkay = solver.Solve(k_toiBaumgarte); - if (contactsOkay) - { - solved = true; + // No more TOI events. Done! + m_stepComplete = true; break; } - } - if (toiOther->GetType() != b2_staticBody) - { - toiContact->m_flags |= b2Contact::e_bulletHitFlag; - } -} + // Advance the bodies to the TOI. + b2Fixture* fA = minContact->GetFixtureA(); + b2Fixture* fB = minContact->GetFixtureB(); + b2Body* bA = fA->GetBody(); + b2Body* bB = fB->GetBody(); -// Sequentially solve TOIs for each body. We bring each -// body to the time of contact and perform some position correction. -// Time is not conserved. -void b2World::SolveTOI() -{ - // Prepare all contacts. - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) - { - // Enable the contact - c->m_flags |= b2Contact::e_enabledFlag; + b2Sweep backup1 = bA->m_sweep; + b2Sweep backup2 = bB->m_sweep; - // Set the number of TOI events for this contact to zero. - c->m_toiCount = 0; - } + bA->Advance(minAlpha); + bB->Advance(minAlpha); - // Initialize the TOI flag. - for (b2Body* body = m_bodyList; body; body = body->m_next) - { - // Kinematic, and static bodies will not be affected by the TOI event. - // If a body was not in an island then it did not move. - if ((body->m_flags & b2Body::e_islandFlag) == 0 || body->GetType() == b2_kinematicBody || body->GetType() == b2_staticBody) - { - body->m_flags |= b2Body::e_toiFlag; - } - else - { - body->m_flags &= ~b2Body::e_toiFlag; - } - } - - // Collide non-bullets. - for (b2Body* body = m_bodyList; body; body = body->m_next) - { - if (body->m_flags & b2Body::e_toiFlag) + // The TOI contact likely has some new contact points. + minContact->Update(m_contactManager.m_contactListener); + minContact->m_flags &= ~b2Contact::e_toiFlag; + ++minContact->m_toiCount; + + // Is the contact solid? + if (minContact->IsEnabled() == false || minContact->IsTouching() == false) { + // Restore the sweeps. + minContact->SetEnabled(false); + bA->m_sweep = backup1; + bB->m_sweep = backup2; + bA->SynchronizeTransform(); + bB->SynchronizeTransform(); continue; } - if (body->IsBullet() == true) + bA->SetAwake(true); + bB->SetAwake(true); + + // Build the island + island.Clear(); + island.Add(bA); + island.Add(bB); + island.Add(minContact); + + bA->m_flags |= b2Body::e_islandFlag; + bB->m_flags |= b2Body::e_islandFlag; + minContact->m_flags |= b2Contact::e_islandFlag; + + // Get contacts on bodyA and bodyB. + b2Body* bodies[2] = {bA, bB}; + for (int32 i = 0; i < 2; ++i) { - continue; + b2Body* body = bodies[i]; + if (body->m_type == b2_dynamicBody) + { + for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) + { + if (island.m_bodyCount == island.m_bodyCapacity) + { + break; + } + + if (island.m_contactCount == island.m_contactCapacity) + { + break; + } + + b2Contact* contact = ce->contact; + + // Has this contact already been added to the island? + if (contact->m_flags & b2Contact::e_islandFlag) + { + continue; + } + + // Only add static, kinematic, or bullet bodies. + b2Body* other = ce->other; + if (other->m_type == b2_dynamicBody && + body->IsBullet() == false && other->IsBullet() == false) + { + continue; + } + + // Skip sensors. + bool sensorA = contact->m_fixtureA->m_isSensor; + bool sensorB = contact->m_fixtureB->m_isSensor; + if (sensorA || sensorB) + { + continue; + } + + // Tentatively advance the body to the TOI. + b2Sweep backup = other->m_sweep; + if ((other->m_flags & b2Body::e_islandFlag) == 0) + { + other->Advance(minAlpha); + } + + // Update the contact points + contact->Update(m_contactManager.m_contactListener); + + // Was the contact disabled by the user? + if (contact->IsEnabled() == false) + { + other->m_sweep = backup; + other->SynchronizeTransform(); + continue; + } + + // Are there contact points? + if (contact->IsTouching() == false) + { + other->m_sweep = backup; + other->SynchronizeTransform(); + continue; + } + + // Add the contact to the island + contact->m_flags |= b2Contact::e_islandFlag; + island.Add(contact); + + // Has the other body already been added to the island? + if (other->m_flags & b2Body::e_islandFlag) + { + continue; + } + + // Add the other body to the island. + other->m_flags |= b2Body::e_islandFlag; + + if (other->m_type != b2_staticBody) + { + other->SetAwake(true); + } + + island.Add(other); + } + } } - SolveTOI(body); + b2TimeStep subStep; + subStep.dt = (1.0f - minAlpha) * step.dt; + subStep.inv_dt = 1.0f / subStep.dt; + subStep.dtRatio = 1.0f; + subStep.positionIterations = 20; + subStep.velocityIterations = step.velocityIterations; + subStep.warmStarting = false; + island.SolveTOI(subStep, bA->m_islandIndex, bB->m_islandIndex); - body->m_flags |= b2Body::e_toiFlag; - } - - // Collide bullets. - for (b2Body* body = m_bodyList; body; body = body->m_next) - { - if (body->m_flags & b2Body::e_toiFlag) + // Reset island flags and synchronize broad-phase proxies. + for (int32 i = 0; i < island.m_bodyCount; ++i) { - continue; + b2Body* body = island.m_bodies[i]; + body->m_flags &= ~b2Body::e_islandFlag; + + if (body->m_type != b2_dynamicBody) + { + continue; + } + + body->SynchronizeFixtures(); + + // Invalidate all contact TOIs on this displaced body. + for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) + { + ce->contact->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); + } } - if (body->IsBullet() == false) + // Commit fixture proxy movements to the broad-phase so that new contacts are created. + // Also, some contacts can be destroyed. + m_contactManager.FindNewContacts(); + + if (m_subStepping) { - continue; + m_stepComplete = false; + break; } - - SolveTOI(body); - - body->m_flags |= b2Body::e_toiFlag; } } void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations) { + b2Timer stepTimer; + // If new fixtures were added, we need to find the new contacts. if (m_flags & e_newFixture) { @@ -802,20 +905,28 @@ void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIteration step.dtRatio = m_inv_dt0 * dt; step.warmStarting = m_warmStarting; - + // Update contacts. This is where some contacts are destroyed. - m_contactManager.Collide(); + { + b2Timer timer; + m_contactManager.Collide(); + m_profile.collide = timer.GetMilliseconds(); + } // Integrate velocities, solve velocity constraints, and integrate positions. - if (step.dt > 0.0f) + if (m_stepComplete && step.dt > 0.0f) { + b2Timer timer; Solve(step); + m_profile.solve = timer.GetMilliseconds(); } // Handle TOI events. if (m_continuousPhysics && step.dt > 0.0f) { - SolveTOI(); + b2Timer timer; + SolveTOI(step); + m_profile.solveTOI = timer.GetMilliseconds(); } if (step.dt > 0.0f) @@ -829,6 +940,8 @@ void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIteration } m_flags &= ~e_locked; + + m_profile.step = stepTimer.GetMilliseconds(); } void b2World::ClearForces() @@ -844,8 +957,8 @@ struct b2WorldQueryWrapper { bool QueryCallback(int32 proxyId) { - b2Fixture* fixture = (b2Fixture*)broadPhase->GetUserData(proxyId); - return callback->ReportFixture(fixture); + b2FixtureProxy* proxy = (b2FixtureProxy*)broadPhase->GetUserData(proxyId); + return callback->ReportFixture(proxy->fixture); } const b2BroadPhase* broadPhase; @@ -865,9 +978,11 @@ struct b2WorldRayCastWrapper float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId) { void* userData = broadPhase->GetUserData(proxyId); - b2Fixture* fixture = (b2Fixture*)userData; + b2FixtureProxy* proxy = (b2FixtureProxy*)userData; + b2Fixture* fixture = proxy->fixture; + int32 index = proxy->childIndex; b2RayCastOutput output; - bool hit = fixture->RayCast(&output, input); + bool hit = fixture->RayCast(&output, input, index); if (hit) { @@ -905,12 +1020,38 @@ void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color b2Vec2 center = b2Mul(xf, circle->m_p); float32 radius = circle->m_radius; - b2Vec2 axis = xf.R.col1; + b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f)); m_debugDraw->DrawSolidCircle(center, radius, axis, color); } break; + case b2Shape::e_edge: + { + b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape(); + b2Vec2 v1 = b2Mul(xf, edge->m_vertex1); + b2Vec2 v2 = b2Mul(xf, edge->m_vertex2); + m_debugDraw->DrawSegment(v1, v2, color); + } + break; + + case b2Shape::e_chain: + { + b2ChainShape* chain = (b2ChainShape*)fixture->GetShape(); + int32 count = chain->GetVertexCount(); + const b2Vec2* vertices = chain->GetVertices(); + + b2Vec2 v1 = b2Mul(xf, vertices[0]); + for (int32 i = 1; i < count; ++i) + { + b2Vec2 v2 = b2Mul(xf, vertices[i]); + m_debugDraw->DrawSegment(v1, v2, color); + m_debugDraw->DrawCircle(v1, 0.05f, color); + v1 = v2; + } + } + break; + case b2Shape::e_polygon: { b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); @@ -926,6 +1067,9 @@ void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color); } break; + + default: + break; } } @@ -935,8 +1079,8 @@ void b2World::DrawJoint(b2Joint* joint) b2Body* bodyB = joint->GetBodyB(); const b2Transform& xf1 = bodyA->GetTransform(); const b2Transform& xf2 = bodyB->GetTransform(); - b2Vec2 x1 = xf1.position; - b2Vec2 x2 = xf2.position; + b2Vec2 x1 = xf1.p; + b2Vec2 x2 = xf2.p; b2Vec2 p1 = joint->GetAnchorA(); b2Vec2 p2 = joint->GetAnchorB(); @@ -979,7 +1123,7 @@ void b2World::DrawDebugData() uint32 flags = m_debugDraw->GetFlags(); - if (flags & b2DebugDraw::e_shapeBit) + if (flags & b2Draw::e_shapeBit) { for (b2Body* b = m_bodyList; b; b = b->GetNext()) { @@ -1010,7 +1154,7 @@ void b2World::DrawDebugData() } } - if (flags & b2DebugDraw::e_jointBit) + if (flags & b2Draw::e_jointBit) { for (b2Joint* j = m_jointList; j; j = j->GetNext()) { @@ -1018,22 +1162,22 @@ void b2World::DrawDebugData() } } - if (flags & b2DebugDraw::e_pairBit) + if (flags & b2Draw::e_pairBit) { b2Color color(0.3f, 0.9f, 0.9f); for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext()) { - b2Fixture* fixtureA = c->GetFixtureA(); - b2Fixture* fixtureB = c->GetFixtureB(); + //b2Fixture* fixtureA = c->GetFixtureA(); + //b2Fixture* fixtureB = c->GetFixtureB(); - b2Vec2 cA = fixtureA->GetAABB().GetCenter(); - b2Vec2 cB = fixtureB->GetAABB().GetCenter(); + //b2Vec2 cA = fixtureA->GetAABB().GetCenter(); + //b2Vec2 cB = fixtureB->GetAABB().GetCenter(); - m_debugDraw->DrawSegment(cA, cB, color); + //m_debugDraw->DrawSegment(cA, cB, color); } } - if (flags & b2DebugDraw::e_aabbBit) + if (flags & b2Draw::e_aabbBit) { b2Color color(0.9f, 0.3f, 0.9f); b2BroadPhase* bp = &m_contactManager.m_broadPhase; @@ -1047,24 +1191,28 @@ void b2World::DrawDebugData() for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) { - b2AABB aabb = bp->GetFatAABB(f->m_proxyId); - b2Vec2 vs[4]; - vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); - vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); - vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); - vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); + for (int32 i = 0; i < f->m_proxyCount; ++i) + { + b2FixtureProxy* proxy = f->m_proxies + i; + b2AABB aabb = bp->GetFatAABB(proxy->proxyId); + b2Vec2 vs[4]; + vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); + vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); + vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); + vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); - m_debugDraw->DrawPolygon(vs, 4, color); + m_debugDraw->DrawPolygon(vs, 4, color); + } } } } - if (flags & b2DebugDraw::e_centerOfMassBit) + if (flags & b2Draw::e_centerOfMassBit) { for (b2Body* b = m_bodyList; b; b = b->GetNext()) { b2Transform xf = b->GetTransform(); - xf.position = b->GetWorldCenter(); + xf.p = b->GetWorldCenter(); m_debugDraw->DrawTransform(xf); } } @@ -1074,3 +1222,18 @@ int32 b2World::GetProxyCount() const { return m_contactManager.m_broadPhase.GetProxyCount(); } + +int32 b2World::GetTreeHeight() const +{ + return m_contactManager.m_broadPhase.GetTreeHeight(); +} + +int32 b2World::GetTreeBalance() const +{ + return m_contactManager.m_broadPhase.GetTreeBalance(); +} + +float32 b2World::GetTreeQuality() const +{ + return m_contactManager.m_broadPhase.GetTreeQuality(); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2World.h b/src/modules/physics/box2d/Box2D/Dynamics/b2World.h old mode 100644 new mode 100755 index bff14272f..381e1f1ac --- a/src/modules/physics/box2d/Box2D/Dynamics/b2World.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2World.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -24,12 +24,14 @@ #include #include #include +#include struct b2AABB; struct b2BodyDef; +struct b2Color; struct b2JointDef; -struct b2TimeStep; class b2Body; +class b2Draw; class b2Fixture; class b2Joint; @@ -63,7 +65,7 @@ public: /// Register a routine for debug drawing. The debug draw functions are called /// inside with b2World::DrawDebugData method. The debug draw object is owned /// by you and must remain in scope. - void SetDebugDraw(b2DebugDraw* debugDraw); + void SetDebugDraw(b2Draw* debugDraw); /// Create a rigid body given a definition. No reference to the definition /// is retained. @@ -94,9 +96,12 @@ public: int32 velocityIterations, int32 positionIterations); - /// Call this after you are done with time steps to clear the forces. You normally - /// call this after each call to Step, unless you are performing sub-steps. By default, - /// forces will be automatically cleared, so you don't need to call this function. + /// Manually clear the force buffer on all bodies. By default, forces are cleared automatically + /// after each call to Step. The default behavior is modified by calling SetAutoClearForces. + /// The purpose of this function is to support sub-stepping. Sub-stepping is often used to maintain + /// a fixed sized time step under a variable frame-rate. + /// When you perform sub-stepping you will disable auto clearing of forces and instead call + /// ClearForces after all sub-steps are complete in one pass of your game loop. /// @see SetAutoClearForces void ClearForces(); @@ -121,17 +126,21 @@ public: /// the next body in the world list. A NULL body indicates the end of the list. /// @return the head of the world body list. b2Body* GetBodyList(); + const b2Body* GetBodyList() const; /// Get the world joint list. With the returned joint, use b2Joint::GetNext to get /// the next joint in the world list. A NULL joint indicates the end of the list. /// @return the head of the world joint list. b2Joint* GetJointList(); + const b2Joint* GetJointList() const; /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get /// the next contact in the world list. A NULL contact indicates the end of the list. /// @return the head of the world contact list. - /// @warning contacts are + /// @warning contacts are created and destroyed in the middle of a time step. + /// Use b2ContactListener to avoid missing contacts. b2Contact* GetContactList(); + const b2Contact* GetContactList() const; /// Enable/disable warm starting. For testing. void SetWarmStarting(bool flag) { m_warmStarting = flag; } @@ -139,6 +148,9 @@ public: /// Enable/disable continuous physics. For testing. void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; } + /// Enable/disable single stepped continuous physics. For testing. + void SetSubStepping(bool flag) { m_subStepping = flag; } + /// Get the number of broad-phase proxies. int32 GetProxyCount() const; @@ -151,6 +163,16 @@ public: /// Get the number of contacts (each may have 0 or more contact points). int32 GetContactCount() const; + /// Get the height of the dynamic tree. + int32 GetTreeHeight() const; + + /// Get the balance of the dynamic tree. + int32 GetTreeBalance() const; + + /// Get the quality metric of the dynamic tree. The smaller the better. + /// The minimum is 1. + float32 GetTreeQuality() const; + /// Change the global gravity vector. void SetGravity(const b2Vec2& gravity); @@ -166,6 +188,12 @@ public: /// Get the flag that controls automatic clearing of forces after each time step. bool GetAutoClearForces() const; + /// Get the contact manager for testing. + const b2ContactManager& GetContactManager() const; + + /// Get the current profile. + const b2Profile& GetProfile() const; + private: // m_flags @@ -173,16 +201,16 @@ private: { e_newFixture = 0x0001, e_locked = 0x0002, - e_clearForces = 0x0004, + e_clearForces = 0x0004 }; friend class b2Body; + friend class b2Fixture; friend class b2ContactManager; friend class b2Controller; void Solve(const b2TimeStep& step); - void SolveTOI(); - void SolveTOI(b2Body* body); + void SolveTOI(const b2TimeStep& step); void DrawJoint(b2Joint* joint); void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color); @@ -203,20 +231,21 @@ private: b2Vec2 m_gravity; bool m_allowSleep; - b2Body* m_groundBody; - b2DestructionListener* m_destructionListener; - b2DebugDraw* m_debugDraw; + b2Draw* m_debugDraw; // This is used to compute the time step ratio to // support a variable time step. float32 m_inv_dt0; - // This is for debugging the solver. + // These are for debugging the solver. bool m_warmStarting; - - // This is for debugging the solver. bool m_continuousPhysics; + bool m_subStepping; + + bool m_stepComplete; + + b2Profile m_profile; }; inline b2Body* b2World::GetBodyList() @@ -224,16 +253,31 @@ inline b2Body* b2World::GetBodyList() return m_bodyList; } +inline const b2Body* b2World::GetBodyList() const +{ + return m_bodyList; +} + inline b2Joint* b2World::GetJointList() { return m_jointList; } +inline const b2Joint* b2World::GetJointList() const +{ + return m_jointList; +} + inline b2Contact* b2World::GetContactList() { return m_contactManager.m_contactList; } +inline const b2Contact* b2World::GetContactList() const +{ + return m_contactManager.m_contactList; +} + inline int32 b2World::GetBodyCount() const { return m_bodyCount; @@ -282,4 +326,14 @@ inline bool b2World::GetAutoClearForces() const return (m_flags & e_clearForces) == e_clearForces; } +inline const b2ContactManager& b2World::GetContactManager() const +{ + return m_contactManager; +} + +inline const b2Profile& b2World::GetProfile() const +{ + return m_profile; +} + #endif diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.cpp old mode 100644 new mode 100755 index bc5fefbdf..82b28cc05 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -34,28 +34,3 @@ bool b2ContactFilter::ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB) bool collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0; return collide; } - -b2DebugDraw::b2DebugDraw() -{ - m_drawFlags = 0; -} - -void b2DebugDraw::SetFlags(uint32 flags) -{ - m_drawFlags = flags; -} - -uint32 b2DebugDraw::GetFlags() const -{ - return m_drawFlags; -} - -void b2DebugDraw::AppendFlags(uint32 flags) -{ - m_drawFlags |= flags; -} - -void b2DebugDraw::ClearFlags(uint32 flags) -{ - m_drawFlags &= ~flags; -} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.h b/src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.h old mode 100644 new mode 100755 index 82ee67ea0..9b937e81f --- a/src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -27,7 +27,6 @@ class b2Fixture; class b2Body; class b2Joint; class b2Contact; -struct b2ContactPoint; struct b2ContactResult; struct b2Manifold; @@ -67,6 +66,7 @@ struct b2ContactImpulse { float32 normalImpulses[b2_maxManifoldPoints]; float32 tangentImpulses[b2_maxManifoldPoints]; + int32 count; }; /// Implement this class to get contact information. You can use these results for @@ -152,66 +152,4 @@ public: const b2Vec2& normal, float32 fraction) = 0; }; -/// Color for debug drawing. Each value has the range [0,1]. -struct b2Color -{ - b2Color() {} - b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {} - void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi; } - float32 r, g, b; -}; - -/// Implement and register this class with a b2World to provide debug drawing of physics -/// entities in your game. -class b2DebugDraw -{ -public: - b2DebugDraw(); - - virtual ~b2DebugDraw() {} - - enum - { - e_shapeBit = 0x0001, ///< draw shapes - e_jointBit = 0x0002, ///< draw joint connections - e_aabbBit = 0x0004, ///< draw axis aligned bounding boxes - e_pairBit = 0x0008, ///< draw broad-phase pairs - e_centerOfMassBit = 0x0010, ///< draw center of mass frame - }; - - /// Set the drawing flags. - void SetFlags(uint32 flags); - - /// Get the drawing flags. - uint32 GetFlags() const; - - /// Append flags to the current flags. - void AppendFlags(uint32 flags); - - /// Clear flags from the current flags. - void ClearFlags(uint32 flags); - - /// Draw a closed polygon provided in CCW order. - virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; - - /// Draw a solid closed polygon provided in CCW order. - virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; - - /// Draw a circle. - virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) = 0; - - /// Draw a solid circle. - virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) = 0; - - /// Draw a line segment. - virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0; - - /// Draw a transform. Choose your own length scale. - /// @param xf a transform. - virtual void DrawTransform(const b2Transform& xf) = 0; - -protected: - uint32 m_drawFlags; -}; - #endif diff --git a/src/modules/physics/box2d/Box2D/Rope/b2Rope.cpp b/src/modules/physics/box2d/Box2D/Rope/b2Rope.cpp new file mode 100755 index 000000000..97578b266 --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Rope/b2Rope.cpp @@ -0,0 +1,259 @@ +/* +* Copyright (c) 2011 Erin Catto http://box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +b2Rope::b2Rope() +{ + m_count = 0; + m_ps = NULL; + m_p0s = NULL; + m_vs = NULL; + m_ims = NULL; + m_Ls = NULL; + m_as = NULL; + m_gravity.SetZero(); + m_k2 = 1.0f; + m_k3 = 0.1f; +} + +b2Rope::~b2Rope() +{ + b2Free(m_ps); + b2Free(m_p0s); + b2Free(m_vs); + b2Free(m_ims); + b2Free(m_Ls); + b2Free(m_as); +} + +void b2Rope::Initialize(const b2RopeDef* def) +{ + b2Assert(def->count >= 3); + m_count = def->count; + m_ps = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + m_p0s = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + m_vs = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + m_ims = (float32*)b2Alloc(m_count * sizeof(float32)); + + for (int32 i = 0; i < m_count; ++i) + { + m_ps[i] = def->vertices[i]; + m_p0s[i] = def->vertices[i]; + m_vs[i].SetZero(); + + float32 m = def->masses[i]; + if (m > 0.0f) + { + m_ims[i] = 1.0f / m; + } + else + { + m_ims[i] = 0.0f; + } + } + + int32 count2 = m_count - 1; + int32 count3 = m_count - 2; + m_Ls = (float32*)b2Alloc(count2 * sizeof(float32)); + m_as = (float32*)b2Alloc(count3 * sizeof(float32)); + + for (int32 i = 0; i < count2; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i+1]; + m_Ls[i] = b2Distance(p1, p2); + } + + for (int32 i = 0; i < count3; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i + 1]; + b2Vec2 p3 = m_ps[i + 2]; + + b2Vec2 d1 = p2 - p1; + b2Vec2 d2 = p3 - p2; + + float32 a = b2Cross(d1, d2); + float32 b = b2Dot(d1, d2); + + m_as[i] = b2Atan2(a, b); + } + + m_gravity = def->gravity; + m_damping = def->damping; + m_k2 = def->k2; + m_k3 = def->k3; +} + +void b2Rope::Step(float32 h, int32 iterations) +{ + if (h == 0.0) + { + return; + } + + float32 d = expf(- h * m_damping); + + for (int32 i = 0; i < m_count; ++i) + { + m_p0s[i] = m_ps[i]; + if (m_ims[i] > 0.0f) + { + m_vs[i] += h * m_gravity; + } + m_vs[i] *= d; + m_ps[i] += h * m_vs[i]; + + } + + for (int32 i = 0; i < iterations; ++i) + { + SolveC2(); + SolveC3(); + SolveC2(); + } + + float32 inv_h = 1.0f / h; + for (int32 i = 0; i < m_count; ++i) + { + m_vs[i] = inv_h * (m_ps[i] - m_p0s[i]); + } +} + +void b2Rope::SolveC2() +{ + int32 count2 = m_count - 1; + + for (int32 i = 0; i < count2; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i + 1]; + + b2Vec2 d = p2 - p1; + float32 L = d.Normalize(); + + float32 im1 = m_ims[i]; + float32 im2 = m_ims[i + 1]; + + if (im1 + im2 == 0.0f) + { + continue; + } + + float32 s1 = im1 / (im1 + im2); + float32 s2 = im2 / (im1 + im2); + + p1 -= m_k2 * s1 * (m_Ls[i] - L) * d; + p2 += m_k2 * s2 * (m_Ls[i] - L) * d; + + m_ps[i] = p1; + m_ps[i + 1] = p2; + } +} + +void b2Rope::SetAngle(float32 angle) +{ + int32 count3 = m_count - 2; + for (int32 i = 0; i < count3; ++i) + { + m_as[i] = angle; + } +} + +void b2Rope::SolveC3() +{ + int32 count3 = m_count - 2; + + for (int32 i = 0; i < count3; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i + 1]; + b2Vec2 p3 = m_ps[i + 2]; + + float32 m1 = m_ims[i]; + float32 m2 = m_ims[i + 1]; + float32 m3 = m_ims[i + 2]; + + b2Vec2 d1 = p2 - p1; + b2Vec2 d2 = p3 - p2; + + float32 L1sqr = d1.LengthSquared(); + float32 L2sqr = d2.LengthSquared(); + + if (L1sqr * L2sqr == 0.0f) + { + continue; + } + + float32 a = b2Cross(d1, d2); + float32 b = b2Dot(d1, d2); + + float32 angle = b2Atan2(a, b); + + b2Vec2 Jd1 = (-1.0f / L1sqr) * d1.Skew(); + b2Vec2 Jd2 = (1.0f / L2sqr) * d2.Skew(); + + b2Vec2 J1 = -Jd1; + b2Vec2 J2 = Jd1 - Jd2; + b2Vec2 J3 = Jd2; + + float32 mass = m1 * b2Dot(J1, J1) + m2 * b2Dot(J2, J2) + m3 * b2Dot(J3, J3); + if (mass == 0.0f) + { + continue; + } + + mass = 1.0f / mass; + + float32 C = angle - m_as[i]; + + while (C > b2_pi) + { + angle -= 2 * b2_pi; + C = angle - m_as[i]; + } + + while (C < -b2_pi) + { + angle += 2.0f * b2_pi; + C = angle - m_as[i]; + } + + float32 impulse = - m_k3 * mass * C; + + p1 += (m1 * impulse) * J1; + p2 += (m2 * impulse) * J2; + p3 += (m3 * impulse) * J3; + + m_ps[i] = p1; + m_ps[i + 1] = p2; + m_ps[i + 2] = p3; + } +} + +void b2Rope::Draw(b2Draw* draw) const +{ + b2Color c(0.4f, 0.5f, 0.7f); + + for (int32 i = 0; i < m_count - 1; ++i) + { + draw->DrawSegment(m_ps[i], m_ps[i+1], c); + } +} diff --git a/src/modules/physics/box2d/Box2D/Rope/b2Rope.h b/src/modules/physics/box2d/Box2D/Rope/b2Rope.h new file mode 100755 index 000000000..bc5375ddb --- /dev/null +++ b/src/modules/physics/box2d/Box2D/Rope/b2Rope.h @@ -0,0 +1,115 @@ +/* +* Copyright (c) 2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_ROPE_H +#define B2_ROPE_H + +#include + +class b2Draw; + +/// +struct b2RopeDef +{ + b2RopeDef() + { + vertices = NULL; + count = 0; + masses = NULL; + gravity.SetZero(); + damping = 0.1f; + k2 = 0.9f; + k3 = 0.1f; + } + + /// + b2Vec2* vertices; + + /// + int32 count; + + /// + float32* masses; + + /// + b2Vec2 gravity; + + /// + float32 damping; + + /// Stretching stiffness + float32 k2; + + /// Bending stiffness. Values above 0.5 can make the simulation blow up. + float32 k3; +}; + +/// +class b2Rope +{ +public: + b2Rope(); + ~b2Rope(); + + /// + void Initialize(const b2RopeDef* def); + + /// + void Step(float32 timeStep, int32 iterations); + + /// + int32 GetVertexCount() const + { + return m_count; + } + + /// + const b2Vec2* GetVertices() const + { + return m_ps; + } + + /// + void Draw(b2Draw* draw) const; + + /// + void SetAngle(float32 angle); + +private: + + void SolveC2(); + void SolveC3(); + + int32 m_count; + b2Vec2* m_ps; + b2Vec2* m_p0s; + b2Vec2* m_vs; + + float32* m_ims; + + float32* m_Ls; + float32* m_as; + + b2Vec2 m_gravity; + float32 m_damping; + + float32 m_k2; + float32 m_k3; +}; + +#endif diff --git a/src/modules/physics/box2d/FrictionJoint.cpp b/src/modules/physics/box2d/FrictionJoint.cpp new file mode 100644 index 000000000..f4d818803 --- /dev/null +++ b/src/modules/physics/box2d/FrictionJoint.cpp @@ -0,0 +1,72 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#include "FrictionJoint.h" + +#include + +// Module +#include "Body.h" +#include "World.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + FrictionJoint::FrictionJoint(Body * body1, Body * body2, float x, float y) + : Joint(body1, body2), joint(NULL) + { + b2FrictionJointDef def; + def.Initialize(body1->body, body2->body, world->scaleDown(b2Vec2(x,y))); + joint = (b2FrictionJoint*)createJoint(&def); + } + + FrictionJoint::~FrictionJoint() + { + destroyJoint(joint); + joint = 0; + } + + void FrictionJoint::setMaxForce(float force) + { + joint->SetMaxForce(force); + } + + float FrictionJoint::getMaxForce() const + { + return joint->GetMaxForce(); + } + + void FrictionJoint::setMaxTorque(float torque) + { + joint->SetMaxTorque(torque); + } + + float FrictionJoint::getMaxTorque() const + { + return joint->GetMaxTorque(); + } + + +} // box2d +} // physics +} // love diff --git a/src/modules/physics/box2d/FrictionJoint.h b/src/modules/physics/box2d/FrictionJoint.h new file mode 100644 index 000000000..ed4599f68 --- /dev/null +++ b/src/modules/physics/box2d/FrictionJoint.h @@ -0,0 +1,78 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BOX2D_FRICTION_JOINT_H +#define LOVE_PHYSICS_BOX2D_FRICTION_JOINT_H + +// Module +#include "Joint.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + /** + * A FrictionJoint applies friction to a body. + **/ + class FrictionJoint : public Joint + { + private: + + // The Box2D friction joint object. + b2FrictionJoint * joint; + + public: + + /** + * Creates a new FrictionJoint connecting body1 and body2. + **/ + FrictionJoint(Body * body1, Body * body2, float x, float y); + + virtual ~FrictionJoint(); + + /** + * Sets the maximum friction force in Newtons. + **/ + void setMaxForce(float force); + + /** + * Gets the maximum friction force in Newtons. + **/ + float getMaxForce() const; + + /** + * Sets the maximum friction torque in Newton-meters. + **/ + void setMaxTorque(float torque); + + /** + * Gets the maximum friction torque in Newton-meters. + **/ + float getMaxTorque() const; + + }; + +} // box2d +} // physics +} // love + +#endif // LOVE_PHYSICS_BOX2D_FRICTION_JOINT_H diff --git a/src/modules/physics/box2d/Joint.cpp b/src/modules/physics/box2d/Joint.cpp index 14f617489..79cf039f0 100644 --- a/src/modules/physics/box2d/Joint.cpp +++ b/src/modules/physics/box2d/Joint.cpp @@ -72,6 +72,14 @@ namespace box2d return JOINT_MOUSE; case e_gearJoint: return JOINT_GEAR; + case e_frictionJoint: + return JOINT_FRICTION; + case e_weldJoint: + return JOINT_WELD; + case e_wheelJoint: + return JOINT_WHEEL; + case e_ropeJoint: + return JOINT_ROPE; default: return JOINT_INVALID; } @@ -116,6 +124,11 @@ namespace box2d { return joint->IsActive(); } + + bool Joint::getCollideConnected() const + { + return joint->GetCollideConnected(); + } } // box2d } // physics diff --git a/src/modules/physics/box2d/Joint.h b/src/modules/physics/box2d/Joint.h index ea6fe9b09..d7e41ba58 100644 --- a/src/modules/physics/box2d/Joint.h +++ b/src/modules/physics/box2d/Joint.h @@ -100,6 +100,8 @@ namespace box2d float getReactionTorque(float dt); bool isActive() const; + + bool getCollideConnected() const; protected: diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index f76d9c9d1..40fd67f12 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -176,6 +176,11 @@ namespace box2d { return new GearJoint(joint1, joint2, ratio); } + + FrictionJoint * Physics::newFrictionJoint(Body * body1, Body * body2, float x, float y) + { + return new FrictionJoint(body1, body2, x, y); + } } // box2d } // physics diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index ed9136e0e..6f631cd97 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -36,6 +36,7 @@ #include "RevoluteJoint.h" #include "PulleyJoint.h" #include "GearJoint.h" +#include "FrictionJoint.h" namespace love { @@ -200,6 +201,13 @@ namespace box2d **/ GearJoint * newGearJoint(Joint * joint1, Joint * joint2, float ratio); + /** + * Creates a new FrictionJoint connecting body1 with body2. + * @param x Anchor along the x-axis. (World coordinates) + * @param y Anchor along the y-axis. (World coordinates) + **/ + FrictionJoint * newFrictionJoint(Body * body1, Body * body2, float x, float y); + }; // Physics diff --git a/src/modules/physics/box2d/PrismaticJoint.cpp b/src/modules/physics/box2d/PrismaticJoint.cpp index f97eba491..4556073a7 100644 --- a/src/modules/physics/box2d/PrismaticJoint.cpp +++ b/src/modules/physics/box2d/PrismaticJoint.cpp @@ -58,7 +58,7 @@ namespace box2d return world->scaleDown(joint->GetJointSpeed()); } - void PrismaticJoint::setMotorEnabled(bool motor) + void PrismaticJoint::enableMotor(bool motor) { return joint->EnableMotor(motor); } @@ -70,30 +70,30 @@ namespace box2d void PrismaticJoint::setMaxMotorForce(float force) { - joint->SetMaxMotorForce(force); + joint->SetMaxMotorForce(world->scaleDown(force)); } void PrismaticJoint::setMotorSpeed(float speed) { - joint->SetMotorSpeed(speed); + joint->SetMotorSpeed(world->scaleDown(speed)); } float PrismaticJoint::getMotorSpeed() const { - return joint->GetMotorSpeed(); + return world->scaleUp(joint->GetMotorSpeed()); } - float PrismaticJoint::getMotorForce() const + float PrismaticJoint::getMotorForce(float inv_dt) const { - return joint->GetMotorForce(); + return world->scaleUp(joint->GetMotorForce(inv_dt)); } - void PrismaticJoint::setLimitsEnabled(bool limit) + void PrismaticJoint::enableLimit(bool limit) { joint->EnableLimit(limit); } - bool PrismaticJoint::isLimitsEnabled() const + bool PrismaticJoint::isLimitEnabled() const { return joint->IsLimitEnabled(); } diff --git a/src/modules/physics/box2d/PrismaticJoint.h b/src/modules/physics/box2d/PrismaticJoint.h index b7f96ed3d..38b7787e9 100644 --- a/src/modules/physics/box2d/PrismaticJoint.h +++ b/src/modules/physics/box2d/PrismaticJoint.h @@ -87,8 +87,9 @@ namespace box2d /** * Get the current motor force, usually in N. + * @param inv_dt The inverse time step. **/ - float getMotorForce() const; + float getMotorForce(float inv_dt) const; /** * Enable/disable the joint limit. diff --git a/src/modules/physics/box2d/WeldJoint.cpp b/src/modules/physics/box2d/WeldJoint.cpp new file mode 100644 index 000000000..05cb7647f --- /dev/null +++ b/src/modules/physics/box2d/WeldJoint.cpp @@ -0,0 +1,51 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#include "WeldJoint.h" + +#include + +// Module +#include "Body.h" +#include "World.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + WeldJoint::WeldJoint(Body * body1, Body * body2, float x, float y) + : Joint(body1, body2), joint(NULL) + { + b2WeldJointDef def; + def.Initialize(body1->body, body2->body, world->scaleDown(b2Vec2(x,y))); + joint = (b2WeldJoint*)createJoint(&def); + } + + WeldJoint::~WeldJoint() + { + destroyJoint(joint); + joint = 0; + } + +} // box2d +} // physics +} // love diff --git a/src/modules/physics/box2d/WeldJoint.h b/src/modules/physics/box2d/WeldJoint.h new file mode 100644 index 000000000..ce38a3759 --- /dev/null +++ b/src/modules/physics/box2d/WeldJoint.h @@ -0,0 +1,58 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BOX2D_WELD_JOINT_H +#define LOVE_PHYSICS_BOX2D_WELD_JOINT_H + +// Module +#include "Joint.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + /** + * A WeldJoint essentially glues two bodies together. + **/ + class WeldJoint : public Joint + { + private: + + // The Box2D weld joint object. + b2WeldJoint * joint; + + public: + + /** + * Creates a new WeldJoint connecting body1 and body2. + **/ + WeldJoint(Body * body1, Body * body2, float x, float y); + + virtual ~WeldJoint(); + + }; + +} // box2d +} // physics +} // love + +#endif // LOVE_PHYSICS_BOX2D_WELD_JOINT_H diff --git a/src/modules/physics/box2d/WheelJoint.cpp b/src/modules/physics/box2d/WheelJoint.cpp new file mode 100644 index 000000000..01f836338 --- /dev/null +++ b/src/modules/physics/box2d/WheelJoint.cpp @@ -0,0 +1,116 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#include "WheelJoint.h" + +// Module +#include "Body.h" +#include "World.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + WheelJoint::WheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay) + : Joint(body1, body2), joint(NULL) + { + b2WheelJointDef def; + + def.Initialize(body1->body, body2->body, world->scaleDown(b2Vec2(x,y)), b2Vec2(ax,ay)); + joint = (b2WheelJoint*)createJoint(&def); + } + + WheelJoint::~WheelJoint() + { + destroyJoint(joint); + joint = 0; + } + + float WheelJoint::getJointTranslation() const + { + return world->scaleDown(joint->GetJointTranslation()); + } + + float WheelJoint::getJointSpeed() const + { + return world->scaleDown(joint->GetJointSpeed()); + } + + void WheelJoint::enableMotor(bool motor) + { + return joint->EnableMotor(motor); + } + + bool WheelJoint::isMotorEnabled() const + { + return joint->IsMotorEnabled(); + } + + void WheelJoint::setMotorSpeed(float speed) + { + joint->SetMotorSpeed(world->scaleDown(speed)); + } + + float WheelJoint::getMotorSpeed() const + { + return world->scaleUp(joint->GetMotorSpeed()); + } + + void WheelJoint::setMaxMotorTorque(float torque) + { + joint->SetMaxMotorTorque(world->scaleDown(torque)); + } + + float WheelJoint::getMaxMotorTorque() const + { + return world->scaleUp(joint->GetMaxMotorTorque()); + } + + float WheelJoint::getMotorTorque(float inv_dt) const + { + return world->scaleUp(joint->getMotorTorque(inv_dt)); + } + + void WheelJoint::setSpringFrequencyHz(float hz) + { + joint->SetSpringFrequencyHz(world->scaleDown(hz)); + } + + float WheelJoint::getSpringFrequencyHz() const + { + return world->scaleUp(joint->GetSpringFrequencyHz()); + } + + void WheelJoint::setSpringDampingRatio(float ratio) + { + joint->SetSpringDampingRatio(world->scaleDown(ratio)); + } + + float WheelJoint::getSpringDampingRatio() const + { + return world->scaleUp(joint->GetSpringDampingRatio()); + } + + +} // box2d +} // physics +} // love diff --git a/src/modules/physics/box2d/WheelJoint.h b/src/modules/physics/box2d/WheelJoint.h new file mode 100644 index 000000000..431ca6fa7 --- /dev/null +++ b/src/modules/physics/box2d/WheelJoint.h @@ -0,0 +1,127 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BOX2D_WHEEL_JOINT_H +#define LOVE_PHYSICS_BOX2D_WHEEL_JOINT_H + +// Module +#include "Joint.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + /** + * WheelJoints provide two degrees of freedom: translation + * along a defined axis and rotation in the plane. Designed + * for vehicle suspensions. + **/ + class WheelJoint : public Joint + { + private: + + // The Box2D wheel joint object. + b2WheelJoint * joint; + + public: + + /** + * Creates a new WheelJoint connecting body1 and body2. + **/ + WheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay); + + virtual ~WheelJoint(); + + /** + * Get the current joint translation, usually in meters. + **/ + float getJointTranslation() const; + + /** + * Get the current joint translation speed, usually in meters per second. + **/ + float getJointSpeed() const; + + /** + * Enable/disable the joint motor. + **/ + void enableMotor(bool motor); + + /** + * Checks whether the motor is enabled. + **/ + bool isMotorEnabled() const; + + /** + * Set the motor speed, usually in meters per second. + **/ + void setMotorSpeed(float speed); + + /** + * Get the motor speed, usually in meters per second. + **/ + float getMotorSpeed() const; + + /** + * Set the maximum motor torque, usually in N. + **/ + void setMaxMotorTorque(float torque); + + /** + * Get the maximum motor torque, usually in N. + **/ + float getMaxMotorTorque() const; + + /** + * Get the current motor torque, usually in N. + * @param inv_dt The inverse time step. + **/ + float getMotorTorque(float inv_dt) const; + + /** + * Set the spring frequency, in hertz. Setting the frequency to 0 + * disables the spring. + **/ + void setSpringFrequencyHz(float hz); + + /** + * Get the spring frequency, in hertz. + **/ + float getSpringFrequencyHz() const; + + /** + * Set the spring damping ratio. + **/ + void setSpringDampingRatio(float ratio); + + /** + * Get the spring damping ratio. + **/ + float getSpringDampingRatio() const; + + }; + +} // box2d +} // physics +} // love + +#endif // LOVE_PHYSICS_BOX2D_WHEEL_JOINT_H diff --git a/src/modules/physics/box2d/wrap_DistanceJoint.cpp b/src/modules/physics/box2d/wrap_DistanceJoint.cpp index 94eeaa28c..65739637c 100644 --- a/src/modules/physics/box2d/wrap_DistanceJoint.cpp +++ b/src/modules/physics/box2d/wrap_DistanceJoint.cpp @@ -88,7 +88,6 @@ namespace box2d { "getAnchors", w_Joint_getAnchors }, { "getReactionForce", w_Joint_getReactionForce }, { "getReactionTorque", w_Joint_getReactionTorque }, - { "setCollideConnected", w_Joint_setCollideConnected }, { "getCollideConnected", w_Joint_getCollideConnected }, { "destroy", w_Joint_destroy }, { 0, 0 } diff --git a/src/modules/physics/box2d/wrap_FrictionJoint.cpp b/src/modules/physics/box2d/wrap_FrictionJoint.cpp new file mode 100644 index 000000000..c57492ed6 --- /dev/null +++ b/src/modules/physics/box2d/wrap_FrictionJoint.cpp @@ -0,0 +1,86 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#include "wrap_FrictionJoint.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + FrictionJoint * luax_checkfrictionjoint(lua_State * L, int idx) + { + return luax_checktype(L, idx, "FrictionJoint", PHYSICS_FRICTION_JOINT_T); + } + + int w_FrictionJoint_setMaxForce(lua_State * L) + { + FrictionJoint * t = luax_checkfrictionjoint(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setMaxForce(arg1); + return 0; + } + + int w_FrictionJoint_getMaxForce(lua_State * L) + { + FrictionJoint * t = luax_checkfrictionjoint(L, 1); + lua_pushnumber(L, t->getMaxForce()); + return 1; + } + + int w_FrictionJoint_setMaxTorque(lua_State * L) + { + FrictionJoint * t = luax_checkfrictionjoint(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setMaxTorque(arg1); + return 0; + } + + int w_FrictionJoint_getMaxTorque(lua_State * L) + { + FrictionJoint * t = luax_checkfrictionjoint(L, 1); + lua_pushnumber(L, t->getMaxTorque()); + return 1; + } + + static const luaL_Reg functions[] = { + { "setMaxForce", w_FrictionJoint_setMaxForce }, + { "getMaxForce", w_FrictionJoint_getMaxForce }, + { "setMaxTorque", w_FrictionJoint_setMaxTorque }, + { "getMaxTorque", w_FrictionJoint_getMaxTorque }, + // From Joint. + { "getType", w_Joint_getType }, + { "getAnchors", w_Joint_getAnchors }, + { "getReactionForce", w_Joint_getReactionForce }, + { "getReactionTorque", w_Joint_getReactionTorque }, + { "getCollideConnected", w_Joint_getCollideConnected }, + { "destroy", w_Joint_destroy }, + { 0, 0 } + }; + + int luaopen_frictionjoint(lua_State * L) + { + return luax_register_type(L, "FrictionJoint", functions); + } + +} // box2d +} // physics +} // love diff --git a/src/modules/physics/box2d/wrap_FrictionJoint.h b/src/modules/physics/box2d/wrap_FrictionJoint.h new file mode 100644 index 000000000..e42ebd1f0 --- /dev/null +++ b/src/modules/physics/box2d/wrap_FrictionJoint.h @@ -0,0 +1,46 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BOX2D_WRAP_FRICTION_JOINT_H +#define LOVE_PHYSICS_BOX2D_WRAP_FRICTION_JOINT_H + +// LOVE +#include +#include "wrap_Joint.h" +#include "FrictionJoint.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + FrictionJoint * luax_checkfrictionjoint(lua_State * L, int idx); + int w_FrictionJoint_setMaxForce(lua_State * L); + int w_FrictionJoint_getMaxForce(lua_State * L); + int w_FrictionJoint_setMaxTorque(lua_State * L); + int w_FrictionJoint_getMaxTorque(lua_State * L); + int luaopen_frictionjoint(lua_State * L); + +} // box2d +} // physics +} // love + +#endif // LOVE_PHYSICS_BOX2D_WRAP_FRICTION_JOINT_H diff --git a/src/modules/physics/box2d/wrap_GearJoint.cpp b/src/modules/physics/box2d/wrap_GearJoint.cpp index 86a212600..125a13776 100644 --- a/src/modules/physics/box2d/wrap_GearJoint.cpp +++ b/src/modules/physics/box2d/wrap_GearJoint.cpp @@ -54,7 +54,6 @@ namespace box2d { "getAnchors", w_Joint_getAnchors }, { "getReactionForce", w_Joint_getReactionForce }, { "getReactionTorque", w_Joint_getReactionTorque }, - { "setCollideConnected", w_Joint_setCollideConnected }, { "getCollideConnected", w_Joint_getCollideConnected }, { "destroy", w_Joint_destroy }, { 0, 0 } diff --git a/src/modules/physics/box2d/wrap_Joint.cpp b/src/modules/physics/box2d/wrap_Joint.cpp index 625660ae4..f71885202 100644 --- a/src/modules/physics/box2d/wrap_Joint.cpp +++ b/src/modules/physics/box2d/wrap_Joint.cpp @@ -63,14 +63,6 @@ namespace box2d return 1; } - int w_Joint_setCollideConnected(lua_State * L) - { - Joint * t = luax_checkjoint(L, 1); - bool arg1 = luax_toboolean(L, 2); - t->setCollideConnected(arg1); - return 0; - } - int w_Joint_getCollideConnected(lua_State * L) { Joint * t = luax_checkjoint(L, 1); @@ -94,7 +86,6 @@ namespace box2d { "getAnchors", w_Joint_getAnchors }, { "getReactionForce", w_Joint_getReactionForce }, { "getReactionTorque", w_Joint_getReactionTorque }, - { "setCollideConnected", w_Joint_setCollideConnected }, { "getCollideConnected", w_Joint_getCollideConnected }, { "destroy", w_Joint_destroy }, { 0, 0 } diff --git a/src/modules/physics/box2d/wrap_Joint.h b/src/modules/physics/box2d/wrap_Joint.h index 0dfdb09d3..0337c58a1 100644 --- a/src/modules/physics/box2d/wrap_Joint.h +++ b/src/modules/physics/box2d/wrap_Joint.h @@ -36,7 +36,6 @@ namespace box2d int w_Joint_getAnchors(lua_State * L); int w_Joint_getReactionForce(lua_State * L); int w_Joint_getReactionTorque(lua_State * L); - int w_Joint_setCollideConnected(lua_State * L); int w_Joint_getCollideConnected(lua_State * L); int w_Joint_destroy(lua_State * L); int luaopen_joint(lua_State * L); diff --git a/src/modules/physics/box2d/wrap_MouseJoint.cpp b/src/modules/physics/box2d/wrap_MouseJoint.cpp index 8739b35f9..e25a74aa8 100644 --- a/src/modules/physics/box2d/wrap_MouseJoint.cpp +++ b/src/modules/physics/box2d/wrap_MouseJoint.cpp @@ -106,7 +106,6 @@ namespace box2d { "getAnchors", w_Joint_getAnchors }, { "getReactionForce", w_Joint_getReactionForce }, { "getReactionTorque", w_Joint_getReactionTorque }, - { "setCollideConnected", w_Joint_setCollideConnected }, { "getCollideConnected", w_Joint_getCollideConnected }, { "destroy", w_Joint_destroy }, { 0, 0 } diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index cd5d79cf8..434b4fa61 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -204,6 +204,17 @@ namespace box2d luax_newtype(L, "GearJoint", PHYSICS_GEAR_JOINT_T, (void*)j); return 1; } + + int w_newFrictionJoint(lua_State * L) + { + Body * body1 = luax_checktype(L, 1, "Body", PHYSICS_BODY_T); + Body * body2 = luax_checktype(L, 2, "Body", PHYSICS_BODY_T); + float x = (float)luaL_checknumber(L, 3); + float y = (float)luaL_checknumber(L, 4); + FrictionJoint * j = instance->newFrictionJoint(body1, body2, x, y); + luax_newtype(L, "FrictionJoint", PHYSICS_FRICTION_JOINT_T, (void*)j); + return 1; + } // List of functions to wrap. static const luaL_Reg functions[] = { @@ -218,6 +229,7 @@ namespace box2d { "newPrismaticJoint", w_newPrismaticJoint }, { "newPulleyJoint", w_newPulleyJoint }, { "newGearJoint", w_newGearJoint }, + { "newFrictionJoint", w_newFrictionJoint }, { 0, 0 }, }; @@ -235,6 +247,7 @@ namespace box2d luaopen_revolutejoint, luaopen_pulleyjoint, luaopen_gearjoint, + luaopen_frictionjoint, 0 }; diff --git a/src/modules/physics/box2d/wrap_Physics.h b/src/modules/physics/box2d/wrap_Physics.h index 5385a6e7b..bdf1bfee3 100644 --- a/src/modules/physics/box2d/wrap_Physics.h +++ b/src/modules/physics/box2d/wrap_Physics.h @@ -37,6 +37,7 @@ #include "wrap_RevoluteJoint.h" #include "wrap_PulleyJoint.h" #include "wrap_GearJoint.h" +#include "wrap_FrictionJoint.h" namespace love { @@ -56,6 +57,7 @@ namespace box2d int w_newPrismaticJoint(lua_State * L); int w_newPulleyJoint(lua_State * L); int w_newGearJoint(lua_State * L); + int w_newFrictionJoint(lua_State * L); extern "C" LOVE_EXPORT int luaopen_love_physics(lua_State * L); } // box2d diff --git a/src/modules/physics/box2d/wrap_PrismaticJoint.cpp b/src/modules/physics/box2d/wrap_PrismaticJoint.cpp index 2981af5f2..bffd37a56 100644 --- a/src/modules/physics/box2d/wrap_PrismaticJoint.cpp +++ b/src/modules/physics/box2d/wrap_PrismaticJoint.cpp @@ -173,7 +173,6 @@ namespace box2d { "getAnchors", w_Joint_getAnchors }, { "getReactionForce", w_Joint_getReactionForce }, { "getReactionTorque", w_Joint_getReactionTorque }, - { "setCollideConnected", w_Joint_setCollideConnected }, { "getCollideConnected", w_Joint_getCollideConnected }, { "destroy", w_Joint_destroy }, { 0, 0 } diff --git a/src/modules/physics/box2d/wrap_PulleyJoint.cpp b/src/modules/physics/box2d/wrap_PulleyJoint.cpp index aa68acda3..d6a4984fb 100644 --- a/src/modules/physics/box2d/wrap_PulleyJoint.cpp +++ b/src/modules/physics/box2d/wrap_PulleyJoint.cpp @@ -69,7 +69,6 @@ namespace box2d { "getAnchors", w_Joint_getAnchors }, { "getReactionForce", w_Joint_getReactionForce }, { "getReactionTorque", w_Joint_getReactionTorque }, - { "setCollideConnected", w_Joint_setCollideConnected }, { "getCollideConnected", w_Joint_getCollideConnected }, { "destroy", w_Joint_destroy }, { 0, 0 } diff --git a/src/modules/physics/box2d/wrap_RevoluteJoint.cpp b/src/modules/physics/box2d/wrap_RevoluteJoint.cpp index 3e87b5b4e..d770e03a4 100644 --- a/src/modules/physics/box2d/wrap_RevoluteJoint.cpp +++ b/src/modules/physics/box2d/wrap_RevoluteJoint.cpp @@ -173,7 +173,6 @@ namespace box2d { "getAnchors", w_Joint_getAnchors }, { "getReactionForce", w_Joint_getReactionForce }, { "getReactionTorque", w_Joint_getReactionTorque }, - { "setCollideConnected", w_Joint_setCollideConnected }, { "getCollideConnected", w_Joint_getCollideConnected }, { "destroy", w_Joint_destroy }, { 0, 0 } diff --git a/src/modules/physics/box2d/wrap_WeldJoint.cpp b/src/modules/physics/box2d/wrap_WeldJoint.cpp new file mode 100644 index 000000000..4d0cbc16a --- /dev/null +++ b/src/modules/physics/box2d/wrap_WeldJoint.cpp @@ -0,0 +1,52 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#include "wrap_WeldJoint.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + WeldJoint * luax_checkweldjoint(lua_State * L, int idx) + { + return luax_checktype(L, idx, "WeldJoint", PHYSICS_WELD_JOINT_T); + } + + static const luaL_Reg functions[] = { + // From Joint. + { "getType", w_Joint_getType }, + { "getAnchors", w_Joint_getAnchors }, + { "getReactionForce", w_Joint_getReactionForce }, + { "getReactionTorque", w_Joint_getReactionTorque }, + { "getCollideConnected", w_Joint_getCollideConnected }, + { "destroy", w_Joint_destroy }, + { 0, 0 } + }; + + int luaopen_weldjoint(lua_State * L) + { + return luax_register_type(L, "WeldJoint", functions); + } + +} // box2d +} // physics +} // love diff --git a/src/modules/physics/box2d/wrap_WeldJoint.h b/src/modules/physics/box2d/wrap_WeldJoint.h new file mode 100644 index 000000000..bf875e85c --- /dev/null +++ b/src/modules/physics/box2d/wrap_WeldJoint.h @@ -0,0 +1,42 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BOX2D_WRAP_WELD_JOINT_H +#define LOVE_PHYSICS_BOX2D_WRAP_WELD_JOINT_H + +// LOVE +#include +#include "wrap_Joint.h" +#include "WeldJoint.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + WeldJoint * luax_checkweldjoint(lua_State * L, int idx); + int luaopen_weldjoint(lua_State * L); + +} // box2d +} // physics +} // love + +#endif // LOVE_PHYSICS_BOX2D_WRAP_WELD_JOINT_H diff --git a/src/modules/physics/box2d/wrap_WheelJoint.cpp b/src/modules/physics/box2d/wrap_WheelJoint.cpp new file mode 100644 index 000000000..bffd37a56 --- /dev/null +++ b/src/modules/physics/box2d/wrap_WheelJoint.cpp @@ -0,0 +1,188 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#include "wrap_PrismaticJoint.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + PrismaticJoint * luax_checkprismaticjoint(lua_State * L, int idx) + { + return luax_checktype(L, idx, "PrismaticJoint", PHYSICS_PRISMATIC_JOINT_T); + } + + int w_PrismaticJoint_getJointTranslation(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + lua_pushnumber(L, t->getJointTranslation()); + return 1; + } + + int w_PrismaticJoint_getJointSpeed(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + lua_pushnumber(L, t->getJointSpeed()); + return 1; + } + + int w_PrismaticJoint_enableMotor(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + bool arg1 = luax_toboolean(L, 2); + t->enableMotor(arg1); + return 0; + } + + int w_PrismaticJoint_isMotorEnabled(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + luax_pushboolean(L, t->isMotorEnabled()); + return 1; + } + + int w_PrismaticJoint_setMaxMotorForce(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setMaxMotorForce(arg1); + return 0; + } + + int w_PrismaticJoint_setMotorSpeed(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setMotorSpeed(arg1); + return 0; + } + + int w_PrismaticJoint_getMotorSpeed(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + lua_pushnumber(L, t->getMotorSpeed()); + return 1; + } + + int w_PrismaticJoint_getMotorForce(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + lua_pushnumber(L, t->getMotorForce()); + return 1; + } + + int w_PrismaticJoint_enableLimit(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + bool arg1 = luax_toboolean(L, 2); + t->enableLimit(arg1); + return 0; + } + + int w_PrismaticJoint_isLimitEnabled(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + luax_pushboolean(L, t->isLimitEnabled()); + return 1; + } + + int w_PrismaticJoint_setUpperLimit(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setUpperLimit(arg1); + return 0; + } + + int w_PrismaticJoint_setLowerLimit(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setLowerLimit(arg1); + return 0; + } + + int w_PrismaticJoint_setLimits(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + float arg2 = (float)luaL_checknumber(L, 3); + t->setLimits(arg1, arg2); + return 0; + } + + int w_PrismaticJoint_getLowerLimit(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + lua_pushnumber(L, t->getLowerLimit()); + return 1; + } + + int w_PrismaticJoint_getUpperLimit(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + lua_pushnumber(L, t->getUpperLimit()); + return 1; + } + + int w_PrismaticJoint_getLimits(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + lua_remove(L, 1); + return t->getLimits(L); + } + + static const luaL_Reg functions[] = { + { "getJointTranslation", w_PrismaticJoint_getJointTranslation }, + { "getJointSpeed", w_PrismaticJoint_getJointSpeed }, + { "enableMotor", w_PrismaticJoint_enableMotor }, + { "isMotorEnabled", w_PrismaticJoint_isMotorEnabled }, + { "setMaxMotorForce", w_PrismaticJoint_setMaxMotorForce }, + { "setMotorSpeed", w_PrismaticJoint_setMotorSpeed }, + { "getMotorSpeed", w_PrismaticJoint_getMotorSpeed }, + { "getMotorForce", w_PrismaticJoint_getMotorForce }, + { "enableLimit", w_PrismaticJoint_enableLimit }, + { "isLimitEnabled", w_PrismaticJoint_isLimitEnabled }, + { "setUpperLimit", w_PrismaticJoint_setUpperLimit }, + { "setLowerLimit", w_PrismaticJoint_setLowerLimit }, + { "setLimits", w_PrismaticJoint_setLimits }, + { "getLowerLimit", w_PrismaticJoint_getLowerLimit }, + { "getUpperLimit", w_PrismaticJoint_getUpperLimit }, + { "getLimits", w_PrismaticJoint_getLimits }, + // From Joint. + { "getType", w_Joint_getType }, + { "getAnchors", w_Joint_getAnchors }, + { "getReactionForce", w_Joint_getReactionForce }, + { "getReactionTorque", w_Joint_getReactionTorque }, + { "getCollideConnected", w_Joint_getCollideConnected }, + { "destroy", w_Joint_destroy }, + { 0, 0 } + }; + + int luaopen_prismaticjoint(lua_State * L) + { + return luax_register_type(L, "PrismaticJoint", functions); + } + +} // box2d +} // physics +} // love diff --git a/src/modules/physics/box2d/wrap_WheelJoint.h b/src/modules/physics/box2d/wrap_WheelJoint.h new file mode 100644 index 000000000..203edaea7 --- /dev/null +++ b/src/modules/physics/box2d/wrap_WheelJoint.h @@ -0,0 +1,58 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BOX2D_WRAP_PRISMATIC_JOINT_H +#define LOVE_PHYSICS_BOX2D_WRAP_PRISMATIC_JOINT_H + +// LOVE +#include +#include "wrap_Joint.h" +#include "PrismaticJoint.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + PrismaticJoint * luax_checkprismaticjoint(lua_State * L, int idx); + int w_PrismaticJoint_getJointTranslation(lua_State * L); + int w_PrismaticJoint_getJointSpeed(lua_State * L); + int w_PrismaticJoint_enableMotor(lua_State * L); + int w_PrismaticJoint_isMotorEnabled(lua_State * L); + int w_PrismaticJoint_setMaxMotorForce(lua_State * L); + int w_PrismaticJoint_setMotorSpeed(lua_State * L); + int w_PrismaticJoint_getMotorSpeed(lua_State * L); + int w_PrismaticJoint_getMotorForce(lua_State * L); + int w_PrismaticJoint_enableLimit(lua_State * L); + int w_PrismaticJoint_isLimitEnabled(lua_State * L); + int w_PrismaticJoint_setUpperLimit(lua_State * L); + int w_PrismaticJoint_setLowerLimit(lua_State * L); + int w_PrismaticJoint_setLimits(lua_State * L); + int w_PrismaticJoint_getLowerLimit(lua_State * L); + int w_PrismaticJoint_getUpperLimit(lua_State * L); + int w_PrismaticJoint_getLimits(lua_State * L); + int luaopen_prismaticjoint(lua_State * L); + +} // box2d +} // physics +} // love + +#endif // LOVE_PHYSICS_BOX2D_WRAP_PRISMATIC_JOINT_H From 551cf591e250672b20dadaacc1c20ea928fbc0a0 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 3 Sep 2011 16:34:36 -0400 Subject: [PATCH 09/78] Add new Shape types to the Shape StringMap --HG-- branch : box2d-update --- src/modules/physics/Shape.cpp | 2 ++ src/modules/physics/Shape.h | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/modules/physics/Shape.cpp b/src/modules/physics/Shape.cpp index cf367e86e..dda9900f1 100644 --- a/src/modules/physics/Shape.cpp +++ b/src/modules/physics/Shape.cpp @@ -42,6 +42,8 @@ namespace physics { {"circle", Shape::SHAPE_CIRCLE}, {"polygon", Shape::SHAPE_POLYGON}, + {"edge", Shape::SHAPE_EDGE}, + {"chain", Shape::SHAPE_CHAIN}, }; StringMap Shape::types(Shape::typeEntries, sizeof(Shape::typeEntries)); diff --git a/src/modules/physics/Shape.h b/src/modules/physics/Shape.h index 84fed6776..e90b8d770 100644 --- a/src/modules/physics/Shape.h +++ b/src/modules/physics/Shape.h @@ -38,6 +38,8 @@ namespace physics SHAPE_INVALID, SHAPE_CIRCLE, SHAPE_POLYGON, + SHAPE_EDGE, + SHAPE_CHAIN, SHAPE_MAX_ENUM }; From 7ec64bf912a41e4b3858f16d894a049d42000717 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 4 Sep 2011 13:21:57 -0400 Subject: [PATCH 10/78] Add basic EdgeShape (todo: all edge-related functionality) and further integrated the new Joints --HG-- branch : box2d-update --- .../macosx/love.xcodeproj/project.pbxproj | 12 ++ src/modules/physics/box2d/CircleShape.cpp | 5 +- src/modules/physics/box2d/EdgeShape.cpp | 44 +++++ src/modules/physics/box2d/EdgeShape.h | 54 ++++++ src/modules/physics/box2d/Physics.cpp | 39 ++-- src/modules/physics/box2d/Physics.h | 43 +++-- src/modules/physics/box2d/Shape.cpp | 4 + src/modules/physics/box2d/wrap_EdgeShape.cpp | 48 +++++ src/modules/physics/box2d/wrap_EdgeShape.h | 42 +++++ src/modules/physics/box2d/wrap_Physics.cpp | 33 +++- src/modules/physics/box2d/wrap_Physics.h | 7 +- src/modules/physics/box2d/wrap_WheelJoint.cpp | 168 ++++++++---------- src/modules/physics/box2d/wrap_WheelJoint.h | 41 ++--- 13 files changed, 384 insertions(+), 156 deletions(-) create mode 100644 src/modules/physics/box2d/EdgeShape.cpp create mode 100644 src/modules/physics/box2d/EdgeShape.h create mode 100644 src/modules/physics/box2d/wrap_EdgeShape.cpp create mode 100644 src/modules/physics/box2d/wrap_EdgeShape.h diff --git a/platform/macosx/love.xcodeproj/project.pbxproj b/platform/macosx/love.xcodeproj/project.pbxproj index 77cba2653..0b351b637 100644 --- a/platform/macosx/love.xcodeproj/project.pbxproj +++ b/platform/macosx/love.xcodeproj/project.pbxproj @@ -163,6 +163,8 @@ A96F41861412AFF80067FE9A /* WeldJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F41841412AFEB0067FE9A /* WeldJoint.cpp */; }; A96F41891412B36D0067FE9A /* wrap_WheelJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F41871412B35B0067FE9A /* wrap_WheelJoint.cpp */; }; A96F418C1412B3AD0067FE9A /* WheelJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F418A1412B3A30067FE9A /* WheelJoint.cpp */; }; + A96F41A41412C91F0067FE9A /* EdgeShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F41A21412C91E0067FE9A /* EdgeShape.cpp */; }; + A96F41A71412C92B0067FE9A /* wrap_EdgeShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F41A51412C92B0067FE9A /* wrap_EdgeShape.cpp */; }; A986DEB5113249A800810279 /* Thread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986DEB1113249A800810279 /* Thread.cpp */; }; A986DEB6113249A800810279 /* wrap_Thread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986DEB3113249A800810279 /* wrap_Thread.cpp */; }; A986EC64132CE6DB00F048C8 /* b2BroadPhase.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBC8132CE6D800F048C8 /* b2BroadPhase.cpp */; }; @@ -571,6 +573,10 @@ A96F41881412B3610067FE9A /* wrap_WheelJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_WheelJoint.h; sourceTree = ""; }; A96F418A1412B3A30067FE9A /* WheelJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WheelJoint.cpp; sourceTree = ""; }; A96F418B1412B3A80067FE9A /* WheelJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WheelJoint.h; sourceTree = ""; }; + A96F41A21412C91E0067FE9A /* EdgeShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = EdgeShape.cpp; sourceTree = ""; }; + A96F41A31412C91E0067FE9A /* EdgeShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EdgeShape.h; sourceTree = ""; }; + A96F41A51412C92B0067FE9A /* wrap_EdgeShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_EdgeShape.cpp; sourceTree = ""; }; + A96F41A61412C92B0067FE9A /* wrap_EdgeShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_EdgeShape.h; sourceTree = ""; }; A97E3842132A9EDE00198A2F /* love-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "love-Info.plist"; sourceTree = ""; }; A986DEB1113249A800810279 /* Thread.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Thread.cpp; sourceTree = ""; }; A986DEB2113249A800810279 /* Thread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Thread.h; sourceTree = ""; }; @@ -1195,6 +1201,8 @@ A93E6AF010420AC7007D418B /* Contact.h */, A93E6AF110420AC7007D418B /* DistanceJoint.cpp */, A93E6AF210420AC7007D418B /* DistanceJoint.h */, + A96F41A21412C91E0067FE9A /* EdgeShape.cpp */, + A96F41A31412C91E0067FE9A /* EdgeShape.h */, A986ECAD132CEB9300F048C8 /* Fixture.cpp */, A986ECAE132CEB9B00F048C8 /* Fixture.h */, A9B6432A13BF833900DC3C7E /* FrictionJoint.cpp */, @@ -1232,6 +1240,8 @@ A93E6B5510420ACA007D418B /* wrap_Contact.h */, A93E6B5610420ACA007D418B /* wrap_DistanceJoint.cpp */, A93E6B5710420ACA007D418B /* wrap_DistanceJoint.h */, + A96F41A51412C92B0067FE9A /* wrap_EdgeShape.cpp */, + A96F41A61412C92B0067FE9A /* wrap_EdgeShape.h */, A9B6432D13BF87E400DC3C7E /* wrap_FrictionJoint.cpp */, A9B6432E13BF87EA00DC3C7E /* wrap_FrictionJoint.h */, A93E6B5810420ACA007D418B /* wrap_GearJoint.cpp */, @@ -1786,6 +1796,8 @@ A96F41861412AFF80067FE9A /* WeldJoint.cpp in Sources */, A96F41891412B36D0067FE9A /* wrap_WheelJoint.cpp in Sources */, A96F418C1412B3AD0067FE9A /* WheelJoint.cpp in Sources */, + A96F41A41412C91F0067FE9A /* EdgeShape.cpp in Sources */, + A96F41A71412C92B0067FE9A /* wrap_EdgeShape.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/src/modules/physics/box2d/CircleShape.cpp b/src/modules/physics/box2d/CircleShape.cpp index 3fa88e1d0..d8b619799 100644 --- a/src/modules/physics/box2d/CircleShape.cpp +++ b/src/modules/physics/box2d/CircleShape.cpp @@ -44,10 +44,7 @@ namespace box2d { return shape->m_radius; } - - /** - * Gets the radius for the circle. - **/ + void CircleShape::setRadius(float r) { shape->m_radius = r; diff --git a/src/modules/physics/box2d/EdgeShape.cpp b/src/modules/physics/box2d/EdgeShape.cpp new file mode 100644 index 000000000..196ea9940 --- /dev/null +++ b/src/modules/physics/box2d/EdgeShape.cpp @@ -0,0 +1,44 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#include "EdgeShape.h" + +// Module +#include "Body.h" +#include "World.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + EdgeShape::EdgeShape(b2EdgeShape * e) + { + shape = e; + } + + EdgeShape::~EdgeShape() + { + } + +} // box2d +} // physics +} // love diff --git a/src/modules/physics/box2d/EdgeShape.h b/src/modules/physics/box2d/EdgeShape.h new file mode 100644 index 000000000..67569b51b --- /dev/null +++ b/src/modules/physics/box2d/EdgeShape.h @@ -0,0 +1,54 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BOX2D_EDGE_SHAPE_H +#define LOVE_PHYSICS_BOX2D_EDGE_SHAPE_H + +// Module +#include "Shape.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + /** + * An Edge is just a line segment. Edges are designed to + * be connected and/or chained together. + **/ + class EdgeShape : public Shape + { + public: + + /** + * Create a new EdgeShape from a Box2D edge shape. + * @param e The edge shape. + **/ + EdgeShape(b2EdgeShape * e); + + virtual ~EdgeShape(); + }; + +} // box2d +} // physics +} // love + +#endif // LOVE_PHYSICS_BOX2D_EDGE_SHAPE_H diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 40fd67f12..20a584021 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -62,30 +62,27 @@ namespace box2d return new Body(world, b2Vec2(0, 0), 1, 1); } - CircleShape * Physics::newCircleShape(Body * body, float radius) + CircleShape * Physics::newCircleShape(float radius) { - return newCircleShape(body, 0, 0, radius); + return newCircleShape(0, 0, radius); } - CircleShape * Physics::newCircleShape(Body * body, float x, float y, float radius) + CircleShape * Physics::newCircleShape(float x, float y, float radius) { - b2CircleDef def; - def.density = 1.0f; - def.localPosition.Set(x, y); - def.friction = 0.5f; - def.restitution = 0.1f; - def.radius = radius; - return new CircleShape(body, &def); + b2CircleShape s; + s.m_p = b2Vec2(x, y); + s.m_radius = radius; + return new CircleShape(&s); } PolygonShape * Physics::newRectangleShape(float w, float h) { - return newRectangleShape(body, 0, 0, w, h, 0); + return newRectangleShape(0, 0, w, h, 0); } PolygonShape * Physics::newRectangleShape(float x, float y, float w, float h) { - return newRectangleShape(body, x, y, w, h, 0); + return newRectangleShape(x, y, w, h, 0); } PolygonShape * Physics::newRectangleShape(float x, float y, float w, float h, float angle) @@ -95,11 +92,11 @@ namespace box2d return new PolygonShape(&s); } - PolygonShape * Physics::newEdgeShape(float x1, float y1, float x2, float y2) + EdgeShape * Physics::newEdgeShape(float x1, float y1, float x2, float y2) { - b2PolygonShape s; - s.SetAsEdge(b2vec2(x1, y1), b2vec2(x2, y2)); - return new PolygonShape(&s); + b2EdgeShape s; + s.Set(b2Vec2(x1, y1), b2Vec2(x2, y2)); + return new EdgeShape(&s); } int Physics::newPolygonShape(lua_State * L) @@ -181,6 +178,16 @@ namespace box2d { return new FrictionJoint(body1, body2, x, y); } + + WeldJoint * Physics::newWeldJoint(Body * body1, Body * body2, float x, float y) + { + return new WeldJoint(body1, body2, x, y); + } + + WheelJoint * Physics::newWheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay) + { + return new WheelJoint(body1, body2, x, y, ax, ay); + } } // box2d } // physics diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index 6f631cd97..9e78e14de 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -29,6 +29,7 @@ #include "Shape.h" #include "CircleShape.h" #include "PolygonShape.h" +#include "EdgeShape.h" #include "Joint.h" #include "MouseJoint.h" #include "DistanceJoint.h" @@ -37,6 +38,8 @@ #include "PulleyJoint.h" #include "GearJoint.h" #include "FrictionJoint.h" +#include "WeldJoint.h" +#include "WheelJoint.h" namespace love { @@ -89,15 +92,13 @@ namespace box2d Body * newBody(World * world); /** - * Creates a new CircleShape at the Body origin. - * @param body The Body to create the Shape on. + * Creates a new CircleShape at (0, 0). * @param radius The radius of the circle. **/ CircleShape * newCircleShape(float radius); /** - * Creates a new CircleShape at (x,y) in local coorinates. - * @param body The Body to create the Shape on. + * Creates a new CircleShape at (x,y) in local coordinates. * @param x The offset along the x-axis. * @param y The offset along the y-axis. * @param radius The radius of the circle. @@ -134,19 +135,17 @@ namespace box2d PolygonShape * newRectangleShape(float x, float y, float w, float h, float angle); /** - * Shorthand for creating edge PolygonShapes. The edge - * will be created at (x,y) in local coordinates. - * @param x The offset along the x-axis. - * @param y The offset along the y-axis. - * @param w The width of the rectangle. - * @param h The height of the rectangle. - * @param angle The angle of the rectangle. (rad) - **/ - PolygonShape * newEdgeShape(float x1, float y1, float x2, float y2); + * Creates a new EdgeShape. The edge will be created from + * (x1,y1) to (x2,y2) in local coordinates. + * @param x1 The x coordinate of the first point. + * @param y1 The y coordinate of the first point. + * @param x2 The x coordinate of the second point. + * @param y2 The y coordinate of the second point. + **/ + EdgeShape * newEdgeShape(float x1, float y1, float x2, float y2); /** * Creates a new PolygonShape. - * @param body The body to create this shape on. * @param ... A variable number of vertices. **/ int newPolygonShape(lua_State * L); @@ -207,6 +206,22 @@ namespace box2d * @param y Anchor along the y-axis. (World coordinates) **/ FrictionJoint * newFrictionJoint(Body * body1, Body * body2, float x, float y); + + /** + * Creates a new WeldJoint connecting body1 with body2. + * @param x Anchor along the x-axis. (World coordinates) + * @param y Anchor along the y-axis. (World coordinates) + **/ + WeldJoint * newWeldJoint(Body * body1, Body * body2, float x, float y); + + /** + * Creates a new WheelJoint connecting body1 with body2. + * @param x Anchor along the x-axis. (World coordinates) + * @param y Anchor along the y-axis. (World coordinates) + * @param ax The x-component of the world-axis. + * @param ay The y-component of the world-axis. + **/ + WheelJoint * newWheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay); }; // Physics diff --git a/src/modules/physics/box2d/Shape.cpp b/src/modules/physics/box2d/Shape.cpp index c3d30854c..e5ab9f7c7 100644 --- a/src/modules/physics/box2d/Shape.cpp +++ b/src/modules/physics/box2d/Shape.cpp @@ -51,6 +51,10 @@ namespace box2d return SHAPE_CIRCLE; case b2Shape::e_polygon: return SHAPE_POLYGON; + case b2Shape::e_edge: + return SHAPE_EDGE; + case b2Shape::e_chain: + return SHAPE_CHAIN; default: return SHAPE_INVALID; } diff --git a/src/modules/physics/box2d/wrap_EdgeShape.cpp b/src/modules/physics/box2d/wrap_EdgeShape.cpp new file mode 100644 index 000000000..be64c4feb --- /dev/null +++ b/src/modules/physics/box2d/wrap_EdgeShape.cpp @@ -0,0 +1,48 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#include "wrap_EdgeShape.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + EdgeShape * luax_checkedgeshape(lua_State * L, int idx) + { + return luax_checktype(L, idx, "EdgeShape", PHYSICS_EDGE_SHAPE_T); + } + + static const luaL_Reg functions[] = { + // From Shape. + { "getType", w_Shape_getType }, + { "destroy", w_Shape_destroy }, + { 0, 0 } + }; + + int luaopen_edgeshape(lua_State * L) + { + return luax_register_type(L, "EdgeShape", functions); + } + +} // box2d +} // physics +} // love diff --git a/src/modules/physics/box2d/wrap_EdgeShape.h b/src/modules/physics/box2d/wrap_EdgeShape.h new file mode 100644 index 000000000..4b9cba3b4 --- /dev/null +++ b/src/modules/physics/box2d/wrap_EdgeShape.h @@ -0,0 +1,42 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BOX2D_WRAP_EDGE_SHAPE_H +#define LOVE_PHYSICS_BOX2D_WRAP_EDGE_SHAPE_H + +// LOVE +#include +#include "wrap_Shape.h" +#include "EdgeShape.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + EdgeShape * luax_checkedgeshape(lua_State * L, int idx); + int luaopen_edgeshape(lua_State * L); + +} // box2d +} // physics +} // love + +#endif // LOVE_PHYSICS_BOX2D_WRAP_EDGE_SHAPE_H diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index 434b4fa61..78508fe3c 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -118,8 +118,8 @@ namespace box2d float y1 = (float)luaL_checknumber(L, 2); float x2 = (float)luaL_checknumber(L, 3); float y2 = (float)luaL_checknumber(L, 4); - PolygonShape * shape = instance->newEdgeShape(x1, y1, x2, y2); - luax_newtype(L, "PolygonShape", PHYSICS_POLYGON_SHAPE_T, (void*)shape); + EdgeShape * shape = instance->newEdgeShape(x1, y1, x2, y2); + luax_newtype(L, "EdgeShape", PHYSICS_EDGE_SHAPE_T, (void*)shape); return 1; } @@ -215,6 +215,30 @@ namespace box2d luax_newtype(L, "FrictionJoint", PHYSICS_FRICTION_JOINT_T, (void*)j); return 1; } + + int w_newWeldJoint(lua_State * L) + { + Body * body1 = luax_checktype(L, 1, "Body", PHYSICS_BODY_T); + Body * body2 = luax_checktype(L, 2, "Body", PHYSICS_BODY_T); + float x = (float)luaL_checknumber(L, 3); + float y = (float)luaL_checknumber(L, 4); + WeldJoint * j = instance->newWeldJoint(body1, body2, x, y); + luax_newtype(L, "WeldJoint", PHYSICS_WELD_JOINT_T, (void*)j); + return 1; + } + + int w_newWheelJoint(lua_State * L) + { + Body * body1 = luax_checktype(L, 1, "Body", PHYSICS_BODY_T); + Body * body2 = luax_checktype(L, 2, "Body", PHYSICS_BODY_T); + float x = (float)luaL_checknumber(L, 3); + float y = (float)luaL_checknumber(L, 4); + float ax = (float)luaL_checknumber(L, 5); + float ay = (float)luaL_checknumber(L, 6); + WheelJoint * j = instance->newWheelJoint(body1, body2, x, y, ax, ay); + luax_newtype(L, "WheelJoint", PHYSICS_WHEEL_JOINT_T, (void*)j); + return 1; + } // List of functions to wrap. static const luaL_Reg functions[] = { @@ -223,6 +247,7 @@ namespace box2d { "newCircleShape", w_newCircleShape }, { "newRectangleShape", w_newRectangleShape }, { "newPolygonShape", w_newPolygonShape }, + { "newEdgeShape", w_newEdgeShape }, { "newDistanceJoint", w_newDistanceJoint }, { "newMouseJoint", w_newMouseJoint }, { "newRevoluteJoint", w_newRevoluteJoint }, @@ -230,6 +255,8 @@ namespace box2d { "newPulleyJoint", w_newPulleyJoint }, { "newGearJoint", w_newGearJoint }, { "newFrictionJoint", w_newFrictionJoint }, + { "newWeldJoint", w_newWeldJoint }, + { "newWheelJoint", w_newWheelJoint }, { 0, 0 }, }; @@ -240,6 +267,7 @@ namespace box2d luaopen_shape, luaopen_circleshape, luaopen_polygonshape, + luaopen_edgeshape, luaopen_joint, luaopen_mousejoint, luaopen_distancejoint, @@ -248,6 +276,7 @@ namespace box2d luaopen_pulleyjoint, luaopen_gearjoint, luaopen_frictionjoint, + luaopen_weldjoint, 0 }; diff --git a/src/modules/physics/box2d/wrap_Physics.h b/src/modules/physics/box2d/wrap_Physics.h index bdf1bfee3..fb715d32b 100644 --- a/src/modules/physics/box2d/wrap_Physics.h +++ b/src/modules/physics/box2d/wrap_Physics.h @@ -30,6 +30,7 @@ #include "wrap_Shape.h" #include "wrap_CircleShape.h" #include "wrap_PolygonShape.h" +#include "wrap_EdgeShape.h" #include "wrap_Joint.h" #include "wrap_MouseJoint.h" #include "wrap_DistanceJoint.h" @@ -38,6 +39,8 @@ #include "wrap_PulleyJoint.h" #include "wrap_GearJoint.h" #include "wrap_FrictionJoint.h" +#include "wrap_WeldJoint.h" +#include "wrap_WheelJoint.h" namespace love { @@ -49,8 +52,8 @@ namespace box2d int w_newBody(lua_State * L); int w_newCircleShape(lua_State * L); int w_newRectangleShape(lua_State * L); - int w_newEdgeShape(lua_State * L); int w_newPolygonShape(lua_State * L); + int w_newEdgeShape(lua_State * L); int w_newDistanceJoint(lua_State * L); int w_newMouseJoint(lua_State * L); int w_newRevoluteJoint(lua_State * L); @@ -58,6 +61,8 @@ namespace box2d int w_newPulleyJoint(lua_State * L); int w_newGearJoint(lua_State * L); int w_newFrictionJoint(lua_State * L); + int w_newWeldJoint(lua_State * L); + int w_newWheelJoint(lua_State * L); extern "C" LOVE_EXPORT int luaopen_love_physics(lua_State * L); } // box2d diff --git a/src/modules/physics/box2d/wrap_WheelJoint.cpp b/src/modules/physics/box2d/wrap_WheelJoint.cpp index bffd37a56..abd4561ba 100644 --- a/src/modules/physics/box2d/wrap_WheelJoint.cpp +++ b/src/modules/physics/box2d/wrap_WheelJoint.cpp @@ -18,7 +18,7 @@ * 3. This notice may not be removed or altered from any source distribution. **/ -#include "wrap_PrismaticJoint.h" +#include "wrap_WheelJoint.h" namespace love { @@ -26,148 +26,122 @@ namespace physics { namespace box2d { - PrismaticJoint * luax_checkprismaticjoint(lua_State * L, int idx) + WheelJoint * luax_checkwheeljoint(lua_State * L, int idx) { - return luax_checktype(L, idx, "PrismaticJoint", PHYSICS_PRISMATIC_JOINT_T); + return luax_checktype(L, idx, "WheelJoint", PHYSICS_WHEEL_JOINT_T); } - int w_PrismaticJoint_getJointTranslation(lua_State * L) + int w_WheelJoint_getJointTranslation(lua_State * L) { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + WheelJoint * t = luax_checkwheeljoint(L, 1); lua_pushnumber(L, t->getJointTranslation()); return 1; } - int w_PrismaticJoint_getJointSpeed(lua_State * L) + int w_WheelJoint_getJointSpeed(lua_State * L) { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + WheelJoint * t = luax_checkwheeljoint(L, 1); lua_pushnumber(L, t->getJointSpeed()); return 1; } - int w_PrismaticJoint_enableMotor(lua_State * L) + int w_WheelJoint_enableMotor(lua_State * L) { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + WheelJoint * t = luax_checkwheeljoint(L, 1); bool arg1 = luax_toboolean(L, 2); t->enableMotor(arg1); return 0; } - int w_PrismaticJoint_isMotorEnabled(lua_State * L) + int w_WheelJoint_isMotorEnabled(lua_State * L) { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + WheelJoint * t = luax_checkwheeljoint(L, 1); luax_pushboolean(L, t->isMotorEnabled()); return 1; } - int w_PrismaticJoint_setMaxMotorForce(lua_State * L) + int w_WheelJoint_setMotorSpeed(lua_State * L) { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); - float arg1 = (float)luaL_checknumber(L, 2); - t->setMaxMotorForce(arg1); - return 0; - } - - int w_PrismaticJoint_setMotorSpeed(lua_State * L) - { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + WheelJoint * t = luax_checkwheeljoint(L, 1); float arg1 = (float)luaL_checknumber(L, 2); t->setMotorSpeed(arg1); return 0; } - int w_PrismaticJoint_getMotorSpeed(lua_State * L) + int w_WheelJoint_getMotorSpeed(lua_State * L) { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + WheelJoint * t = luax_checkwheeljoint(L, 1); lua_pushnumber(L, t->getMotorSpeed()); return 1; } - - int w_PrismaticJoint_getMotorForce(lua_State * L) + + int w_WheelJoint_setMaxMotorTorque(lua_State * L) { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); - lua_pushnumber(L, t->getMotorForce()); - return 1; - } - - int w_PrismaticJoint_enableLimit(lua_State * L) - { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); - bool arg1 = luax_toboolean(L, 2); - t->enableLimit(arg1); - return 0; - } - - int w_PrismaticJoint_isLimitEnabled(lua_State * L) - { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); - luax_pushboolean(L, t->isLimitEnabled()); - return 1; - } - - int w_PrismaticJoint_setUpperLimit(lua_State * L) - { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + WheelJoint * t = luax_checkwheeljoint(L, 1); float arg1 = (float)luaL_checknumber(L, 2); - t->setUpperLimit(arg1); + t->setMaxMotorTorque(arg1); return 0; } - - int w_PrismaticJoint_setLowerLimit(lua_State * L) + + int w_WheelJoint_getMaxMotorTorque(lua_State * L) { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); - float arg1 = (float)luaL_checknumber(L, 2); - t->setLowerLimit(arg1); - return 0; - } - - int w_PrismaticJoint_setLimits(lua_State * L) - { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); - float arg1 = (float)luaL_checknumber(L, 2); - float arg2 = (float)luaL_checknumber(L, 3); - t->setLimits(arg1, arg2); - return 0; - } - - int w_PrismaticJoint_getLowerLimit(lua_State * L) - { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); - lua_pushnumber(L, t->getLowerLimit()); + WheelJoint * t = luax_checkwheeljoint(L, 1); + lua_pushnumber(L, t->getMaxMotorTorque()); return 1; } - - int w_PrismaticJoint_getUpperLimit(lua_State * L) + + int w_WheelJoint_getMotorTorque(lua_State * L) { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); - lua_pushnumber(L, t->getUpperLimit()); + WheelJoint * t = luax_checkwheeljoint(L, 1); + float inv_dt = (float)luaL_checknumber(L, 2); + lua_pushnumber(L, t->getMotorTorque(inv_dt)); return 1; } - - int w_PrismaticJoint_getLimits(lua_State * L) + + int w_WheelJoint_setSpringFrequencyHz(lua_State * L) { - PrismaticJoint * t = luax_checkprismaticjoint(L, 1); - lua_remove(L, 1); - return t->getLimits(L); + WheelJoint * t = luax_checkwheeljoint(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setSpringFrequencyHz(arg1); + return 0; + } + + int w_WheelJoint_getSpringFrequencyHz(lua_State * L) + { + WheelJoint * t = luax_checkwheeljoint(L, 1); + lua_pushnumber(L, t->getSpringFrequencyHz()); + return 1; + } + + int w_WheelJoint_setSpringDampingRatio(lua_State * L) + { + WheelJoint * t = luax_checkwheeljoint(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setSpringDampingRatio(arg1); + return 0; + } + + int w_WheelJoint_getSpringDampingRatio(lua_State * L) + { + WheelJoint * t = luax_checkwheeljoint(L, 1); + lua_pushnumber(L, t->getSpringDampingRatio()); + return 1; } static const luaL_Reg functions[] = { - { "getJointTranslation", w_PrismaticJoint_getJointTranslation }, - { "getJointSpeed", w_PrismaticJoint_getJointSpeed }, - { "enableMotor", w_PrismaticJoint_enableMotor }, - { "isMotorEnabled", w_PrismaticJoint_isMotorEnabled }, - { "setMaxMotorForce", w_PrismaticJoint_setMaxMotorForce }, - { "setMotorSpeed", w_PrismaticJoint_setMotorSpeed }, - { "getMotorSpeed", w_PrismaticJoint_getMotorSpeed }, - { "getMotorForce", w_PrismaticJoint_getMotorForce }, - { "enableLimit", w_PrismaticJoint_enableLimit }, - { "isLimitEnabled", w_PrismaticJoint_isLimitEnabled }, - { "setUpperLimit", w_PrismaticJoint_setUpperLimit }, - { "setLowerLimit", w_PrismaticJoint_setLowerLimit }, - { "setLimits", w_PrismaticJoint_setLimits }, - { "getLowerLimit", w_PrismaticJoint_getLowerLimit }, - { "getUpperLimit", w_PrismaticJoint_getUpperLimit }, - { "getLimits", w_PrismaticJoint_getLimits }, + { "getJointTranslation", w_WheelJoint_getJointTranslation }, + { "getJointSpeed", w_WheelJoint_getJointSpeed }, + { "enableMotor", w_WheelJoint_enableMotor }, + { "isMotorEnabled", w_WheelJoint_isMotorEnabled }, + { "setMotorSpeed", w_WheelJoint_setMotorSpeed }, + { "getMotorSpeed", w_WheelJoint_getMotorSpeed }, + { "setMaxMotorTorque", w_WheelJoint_setMaxMotorTorque }, + { "getMaxMotorTorque", w_WheelJoint_getMaxMotorTorque }, + { "getMotorTorque", w_WheelJoint_getMotorTorque }, + { "setSpringFrequencyHz", w_WheelJoint_setSpringFrequencyHz }, + { "getSpringFrequencyHz", w_WheelJoint_getSpringFrequencyHz }, + { "setSpringDampingRatio", w_WheelJoint_setSpringDampingRatio }, + { "getSpringDampingRatio", w_WheelJoint_getSpringDampingRatio }, // From Joint. { "getType", w_Joint_getType }, { "getAnchors", w_Joint_getAnchors }, @@ -178,9 +152,9 @@ namespace box2d { 0, 0 } }; - int luaopen_prismaticjoint(lua_State * L) + int luaopen_wheeljoint(lua_State * L) { - return luax_register_type(L, "PrismaticJoint", functions); + return luax_register_type(L, "WheelJoint", functions); } } // box2d diff --git a/src/modules/physics/box2d/wrap_WheelJoint.h b/src/modules/physics/box2d/wrap_WheelJoint.h index 203edaea7..b31a5be87 100644 --- a/src/modules/physics/box2d/wrap_WheelJoint.h +++ b/src/modules/physics/box2d/wrap_WheelJoint.h @@ -18,13 +18,13 @@ * 3. This notice may not be removed or altered from any source distribution. **/ -#ifndef LOVE_PHYSICS_BOX2D_WRAP_PRISMATIC_JOINT_H -#define LOVE_PHYSICS_BOX2D_WRAP_PRISMATIC_JOINT_H +#ifndef LOVE_PHYSICS_BOX2D_WRAP_WHEEL_JOINT_H +#define LOVE_PHYSICS_BOX2D_WRAP_WHEEL_JOINT_H // LOVE #include #include "wrap_Joint.h" -#include "PrismaticJoint.h" +#include "WheelJoint.h" namespace love { @@ -32,27 +32,24 @@ namespace physics { namespace box2d { - PrismaticJoint * luax_checkprismaticjoint(lua_State * L, int idx); - int w_PrismaticJoint_getJointTranslation(lua_State * L); - int w_PrismaticJoint_getJointSpeed(lua_State * L); - int w_PrismaticJoint_enableMotor(lua_State * L); - int w_PrismaticJoint_isMotorEnabled(lua_State * L); - int w_PrismaticJoint_setMaxMotorForce(lua_State * L); - int w_PrismaticJoint_setMotorSpeed(lua_State * L); - int w_PrismaticJoint_getMotorSpeed(lua_State * L); - int w_PrismaticJoint_getMotorForce(lua_State * L); - int w_PrismaticJoint_enableLimit(lua_State * L); - int w_PrismaticJoint_isLimitEnabled(lua_State * L); - int w_PrismaticJoint_setUpperLimit(lua_State * L); - int w_PrismaticJoint_setLowerLimit(lua_State * L); - int w_PrismaticJoint_setLimits(lua_State * L); - int w_PrismaticJoint_getLowerLimit(lua_State * L); - int w_PrismaticJoint_getUpperLimit(lua_State * L); - int w_PrismaticJoint_getLimits(lua_State * L); - int luaopen_prismaticjoint(lua_State * L); + WheelJoint * luax_checkwheeljoint(lua_State * L, int idx); + int w_WheelJoint_getJointTranslation(lua_State * L); + int w_WheelJoint_getJointSpeed(lua_State * L); + int w_WheelJoint_enableMotor(lua_State * L); + int w_WheelJoint_isMotorEnabled(lua_State * L); + int w_WheelJoint_setMotorSpeed(lua_State * L); + int w_WheelJoint_getMotorSpeed(lua_State * L); + int w_WheelJoint_setMaxMotorTorque(lua_State * L); + int w_WheelJoint_getMaxMotorTorque(lua_State * L); + int w_WheelJoint_getMotorTorque(lua_State * L); + int w_WheelJoint_setSpringFrequencyHz(lua_State * L); + int w_WheelJoint_getSpringFrequencyHz(lua_State * L); + int w_WheelJoint_setSpringDampingRatio(lua_State * L); + int w_WheelJoint_getSpringDampingRatio(lua_State * L); + int luaopen_wheeljoint(lua_State * L); } // box2d } // physics } // love -#endif // LOVE_PHYSICS_BOX2D_WRAP_PRISMATIC_JOINT_H +#endif // LOVE_PHYSICS_BOX2D_WRAP_WHEEL_JOINT_H From 99660f39ab7e932769f83384eeb3cbace6239af0 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Thu, 15 Sep 2011 12:40:16 -0400 Subject: [PATCH 11/78] Added RopeJoint --HG-- branch : box2d-update --- .../macosx/love.xcodeproj/project.pbxproj | 12 ++++ src/modules/physics/box2d/Physics.cpp | 5 ++ src/modules/physics/box2d/Physics.h | 11 ++++ src/modules/physics/box2d/RopeJoint.cpp | 59 ++++++++++++++++++ src/modules/physics/box2d/RopeJoint.h | 62 +++++++++++++++++++ src/modules/physics/box2d/wrap_Physics.cpp | 17 +++++ src/modules/physics/box2d/wrap_Physics.h | 2 + src/modules/physics/box2d/wrap_RopeJoint.cpp | 60 ++++++++++++++++++ src/modules/physics/box2d/wrap_RopeJoint.h | 43 +++++++++++++ 9 files changed, 271 insertions(+) create mode 100644 src/modules/physics/box2d/RopeJoint.cpp create mode 100644 src/modules/physics/box2d/RopeJoint.h create mode 100644 src/modules/physics/box2d/wrap_RopeJoint.cpp create mode 100644 src/modules/physics/box2d/wrap_RopeJoint.h diff --git a/platform/macosx/love.xcodeproj/project.pbxproj b/platform/macosx/love.xcodeproj/project.pbxproj index 0b351b637..70382453f 100644 --- a/platform/macosx/love.xcodeproj/project.pbxproj +++ b/platform/macosx/love.xcodeproj/project.pbxproj @@ -209,6 +209,8 @@ A9BD60741226C988007DEC63 /* Framebuffer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9BD60701226C988007DEC63 /* Framebuffer.cpp */; }; A9BD60751226C988007DEC63 /* wrap_Framebuffer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9BD60721226C988007DEC63 /* wrap_Framebuffer.cpp */; }; A9CF0E8610B9EB1000E6F37E /* utf8.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9CF0E8510B9EB1000E6F37E /* utf8.cpp */; }; + A9D1D20214224E1300A8BC2F /* RopeJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D1D20114224E1300A8BC2F /* RopeJoint.cpp */; }; + A9D1D2041422578C00A8BC2F /* wrap_RopeJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D1D2031422578A00A8BC2F /* wrap_RopeJoint.cpp */; }; A9D307EA106635C3004FEDF8 /* physfs.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9D307E9106635C3004FEDF8 /* physfs.framework */; }; A9D307F2106635D3004FEDF8 /* physfs.framework in Copy Frameworks */ = {isa = PBXBuildFile; fileRef = A9D307E9106635C3004FEDF8 /* physfs.framework */; }; A9DEC1C11046EFA70049C70C /* Love.icns in Resources */ = {isa = PBXBuildFile; fileRef = A9DEC1BF1046EFA60049C70C /* Love.icns */; }; @@ -669,6 +671,10 @@ A9BFAA851137C1CE005FE0AD /* ThreadModule.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ThreadModule.h; sourceTree = ""; }; A9CF0E8410B9EB1000E6F37E /* utf8.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = utf8.h; sourceTree = ""; }; A9CF0E8510B9EB1000E6F37E /* utf8.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = utf8.cpp; sourceTree = ""; }; + A9D1D20014224DFF00A8BC2F /* RopeJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RopeJoint.h; sourceTree = ""; }; + A9D1D20114224E1300A8BC2F /* RopeJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RopeJoint.cpp; sourceTree = ""; }; + A9D1D2031422578A00A8BC2F /* wrap_RopeJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_RopeJoint.cpp; sourceTree = ""; }; + A9D1D2051422579500A8BC2F /* wrap_RopeJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_RopeJoint.h; sourceTree = ""; }; A9D307E9106635C3004FEDF8 /* physfs.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = physfs.framework; path = /Library/Frameworks/physfs.framework; sourceTree = ""; }; A9DEC1BF1046EFA60049C70C /* Love.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; name = Love.icns; path = icons/Love.icns; sourceTree = ""; }; A9DEC1C01046EFA70049C70C /* LoveDocument.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; name = LoveDocument.icns; path = icons/LoveDocument.icns; sourceTree = ""; }; @@ -1222,6 +1228,8 @@ A93E6B0310420AC8007D418B /* PrismaticJoint.h */, A93E6B0410420AC8007D418B /* PulleyJoint.cpp */, A93E6B0510420AC8007D418B /* PulleyJoint.h */, + A9D1D20114224E1300A8BC2F /* RopeJoint.cpp */, + A9D1D20014224DFF00A8BC2F /* RopeJoint.h */, A93E6B0610420AC8007D418B /* RevoluteJoint.cpp */, A93E6B0710420AC8007D418B /* RevoluteJoint.h */, A93E6B0810420AC8007D418B /* Shape.cpp */, @@ -1260,6 +1268,8 @@ A93E6B6510420ACA007D418B /* wrap_PulleyJoint.h */, A93E6B6610420ACA007D418B /* wrap_RevoluteJoint.cpp */, A93E6B6710420ACA007D418B /* wrap_RevoluteJoint.h */, + A9D1D2031422578A00A8BC2F /* wrap_RopeJoint.cpp */, + A9D1D2051422579500A8BC2F /* wrap_RopeJoint.h */, A93E6B6810420ACA007D418B /* wrap_Shape.cpp */, A93E6B6910420ACA007D418B /* wrap_Shape.h */, A96F41811412AFB70067FE9A /* wrap_WeldJoint.cpp */, @@ -1798,6 +1808,8 @@ A96F418C1412B3AD0067FE9A /* WheelJoint.cpp in Sources */, A96F41A41412C91F0067FE9A /* EdgeShape.cpp in Sources */, A96F41A71412C92B0067FE9A /* wrap_EdgeShape.cpp in Sources */, + A9D1D20214224E1300A8BC2F /* RopeJoint.cpp in Sources */, + A9D1D2041422578C00A8BC2F /* wrap_RopeJoint.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 20a584021..bf43ddb22 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -188,6 +188,11 @@ namespace box2d { return new WheelJoint(body1, body2, x, y, ax, ay); } + + RopeJoint * Physics::newRopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength) + { + return new RopeJoint(body1, body2, x1, y1, x2, y2, maxLength); + } } // box2d } // physics diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index 9e78e14de..94839e865 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -40,6 +40,7 @@ #include "FrictionJoint.h" #include "WeldJoint.h" #include "WheelJoint.h" +#include "RopeJoint.h" namespace love { @@ -222,6 +223,16 @@ namespace box2d * @param ay The y-component of the world-axis. **/ WheelJoint * newWheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay); + + /** + * Creates a new RopeJoint connecting body1 with body2. + * @param x1 Anchor1 along the x-axis. (Local coordinates) + * @param y1 Anchor1 along the y-axis. (Local coordinates) + * @param x2 Anchor2 along the x-axis. (Local coordinates) + * @param y2 Anchor2 along the y-axis. (Local coordinates) + * @param maxLength The maximum distance for the bodies. + **/ + RopeJoint * newRopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength); }; // Physics diff --git a/src/modules/physics/box2d/RopeJoint.cpp b/src/modules/physics/box2d/RopeJoint.cpp new file mode 100644 index 000000000..5cbd26698 --- /dev/null +++ b/src/modules/physics/box2d/RopeJoint.cpp @@ -0,0 +1,59 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#include "RopeJoint.h" + +// Module +#include "Body.h" +#include "World.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + RopeJoint::RopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength) + : Joint(body1, body2), joint(NULL) + { + b2RopeJointDef def; + def.bodyA = body1->body; + def.bodyB = body2->body; + def.localAnchorA = world->scaleDown(b2Vec2(x1,y1)); + def.localAnchorB = world->scaleDown(b2Vec2(x2,y2)); + def.maxLength = world->scaleDown(maxLength); + joint = (b2RopeJoint*)createJoint(&def); + } + + RopeJoint::~RopeJoint() + { + destroyJoint(joint); + joint = 0; + } + + float RopeJoint::getMaxLength() const + { + return world->scaleUp(joint->GetMaxLength()); + } + + +} // box2d +} // physics +} // love diff --git a/src/modules/physics/box2d/RopeJoint.h b/src/modules/physics/box2d/RopeJoint.h new file mode 100644 index 000000000..886f459cd --- /dev/null +++ b/src/modules/physics/box2d/RopeJoint.h @@ -0,0 +1,62 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BOX2D_ROPE_JOINT_H +#define LOVE_PHYSICS_BOX2D_ROPE_JOINT_H + +// Module +#include "Joint.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + /** + * The RopeJoint enforces a maximum distance between two points + * on two bodies. It has no other effect. + **/ + class RopeJoint : public Joint + { + private: + // The Box2D RopeJoint object. + b2RopeJoint * joint; + public: + + /** + * Creates a RopeJoint connecting body1 to body2. + **/ + RopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength); + + virtual ~RopeJoint(); + + /** + * Gets the maximum length of the rope. + **/ + float getMaxLength() const; + + }; + +} // box2d +} // physics +} // love + +#endif // LOVE_PHYSICS_BOX2D_ROPE_JOINT_H diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index 78508fe3c..f72f6f6bd 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -239,6 +239,20 @@ namespace box2d luax_newtype(L, "WheelJoint", PHYSICS_WHEEL_JOINT_T, (void*)j); return 1; } + + int w_newRopeJoint(lua_State * L) + { + Body * body1 = luax_checktype(L, 1, "Body", PHYSICS_BODY_T); + Body * body2 = luax_checktype(L, 2, "Body", PHYSICS_BODY_T); + float x1 = (float)luaL_checknumber(L, 3); + float y1 = (float)luaL_checknumber(L, 4); + float x2 = (float)luaL_checknumber(L, 5); + float y2 = (float)luaL_checknumber(L, 6); + float maxLength = (float)luaL_checknumber(L, 7); + RopeJoint * j = instance->newRopeJoint(body1, body2, x1, y1, x2, y2, maxLength); + luax_newtype(L, "RopeJoint", PHYSICS_ROPE_JOINT_T, (void*)j); + return 1; + } // List of functions to wrap. static const luaL_Reg functions[] = { @@ -257,6 +271,7 @@ namespace box2d { "newFrictionJoint", w_newFrictionJoint }, { "newWeldJoint", w_newWeldJoint }, { "newWheelJoint", w_newWheelJoint }, + { "newRopeJoint", w_newRopeJoint }, { 0, 0 }, }; @@ -277,6 +292,8 @@ namespace box2d luaopen_gearjoint, luaopen_frictionjoint, luaopen_weldjoint, + luaopen_wheeljoint, + luaopen_ropejoint, 0 }; diff --git a/src/modules/physics/box2d/wrap_Physics.h b/src/modules/physics/box2d/wrap_Physics.h index fb715d32b..c87684796 100644 --- a/src/modules/physics/box2d/wrap_Physics.h +++ b/src/modules/physics/box2d/wrap_Physics.h @@ -41,6 +41,7 @@ #include "wrap_FrictionJoint.h" #include "wrap_WeldJoint.h" #include "wrap_WheelJoint.h" +#include "wrap_RopeJoint.h" namespace love { @@ -63,6 +64,7 @@ namespace box2d int w_newFrictionJoint(lua_State * L); int w_newWeldJoint(lua_State * L); int w_newWheelJoint(lua_State * L); + int w_newRopeJoint(lua_State * L); extern "C" LOVE_EXPORT int luaopen_love_physics(lua_State * L); } // box2d diff --git a/src/modules/physics/box2d/wrap_RopeJoint.cpp b/src/modules/physics/box2d/wrap_RopeJoint.cpp new file mode 100644 index 000000000..a86ba666a --- /dev/null +++ b/src/modules/physics/box2d/wrap_RopeJoint.cpp @@ -0,0 +1,60 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#include "wrap_RopeJoint.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + RopeJoint * luax_checkropejoint(lua_State * L, int idx) + { + return luax_checktype(L, idx, "RopeJoint", PHYSICS_ROPE_JOINT_T); + } + + int w_RopeJoint_getMaxLength(lua_State * L) + { + RopeJoint * t = luax_checkropejoint(L, 1); + lua_pushnumber(L, t->getMaxLength()); + return 1; + } + + static const luaL_Reg functions[] = { + { "getMaxLength", w_RopeJoint_getMaxLength }, + // From Joint. + { "getType", w_Joint_getType }, + { "getAnchors", w_Joint_getAnchors }, + { "getReactionForce", w_Joint_getReactionForce }, + { "getReactionTorque", w_Joint_getReactionTorque }, + { "getCollideConnected", w_Joint_getCollideConnected }, + { "destroy", w_Joint_destroy }, + { 0, 0 } + }; + + int luaopen_ropejoint(lua_State * L) + { + return luax_register_type(L, "RopeJoint", functions); + } + +} // box2d +} // physics +} // love diff --git a/src/modules/physics/box2d/wrap_RopeJoint.h b/src/modules/physics/box2d/wrap_RopeJoint.h new file mode 100644 index 000000000..d1cc17ce4 --- /dev/null +++ b/src/modules/physics/box2d/wrap_RopeJoint.h @@ -0,0 +1,43 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BOX2D_WRAP_ROPE_JOINT_H +#define LOVE_PHYSICS_BOX2D_WRAP_ROPE_JOINT_H + +// LOVE +#include +#include "wrap_Joint.h" +#include "RopeJoint.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + RopeJoint * luax_checkropejoint(lua_State * L, int idx); + int w_RopeJoint_getMaxLength(lua_State * L); + int luaopen_ropejoint(lua_State * L); + +} // box2d +} // physics +} // love + +#endif // LOVE_PHYSICS_BOX2D_WRAP_ROPE_JOINT_H From e5fa4c87c63ed575e215e0681c382831b6946c7c Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Thu, 15 Sep 2011 14:28:48 -0400 Subject: [PATCH 12/78] exposed collideConnected flag --HG-- branch : box2d-update --- src/modules/physics/box2d/DistanceJoint.cpp | 3 +- src/modules/physics/box2d/DistanceJoint.h | 2 +- src/modules/physics/box2d/FrictionJoint.cpp | 3 +- src/modules/physics/box2d/FrictionJoint.h | 2 +- src/modules/physics/box2d/GearJoint.cpp | 3 +- src/modules/physics/box2d/GearJoint.h | 2 +- src/modules/physics/box2d/Physics.cpp | 36 ++++++++++---------- src/modules/physics/box2d/Physics.h | 18 +++++----- src/modules/physics/box2d/PrismaticJoint.cpp | 3 +- src/modules/physics/box2d/PrismaticJoint.h | 2 +- src/modules/physics/box2d/PulleyJoint.cpp | 3 +- src/modules/physics/box2d/PulleyJoint.h | 2 +- src/modules/physics/box2d/RevoluteJoint.cpp | 3 +- src/modules/physics/box2d/RevoluteJoint.h | 2 +- src/modules/physics/box2d/RopeJoint.cpp | 3 +- src/modules/physics/box2d/RopeJoint.h | 2 +- src/modules/physics/box2d/WeldJoint.cpp | 3 +- src/modules/physics/box2d/WeldJoint.h | 2 +- src/modules/physics/box2d/WheelJoint.cpp | 3 +- src/modules/physics/box2d/WheelJoint.h | 2 +- src/modules/physics/box2d/wrap_Physics.cpp | 27 ++++++++++----- 21 files changed, 72 insertions(+), 54 deletions(-) diff --git a/src/modules/physics/box2d/DistanceJoint.cpp b/src/modules/physics/box2d/DistanceJoint.cpp index d05ee3883..8ffa8ca9c 100644 --- a/src/modules/physics/box2d/DistanceJoint.cpp +++ b/src/modules/physics/box2d/DistanceJoint.cpp @@ -30,11 +30,12 @@ namespace physics { namespace box2d { - DistanceJoint::DistanceJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2) + DistanceJoint::DistanceJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, bool collideConnected) : Joint(body1, body2), joint(NULL) { b2DistanceJointDef def; def.Initialize(body1->body, body2->body, world->scaleDown(b2Vec2(x1,y1)), world->scaleDown(b2Vec2(x2,y2))); + def.collideConnected = collideConnected; joint = (b2DistanceJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/DistanceJoint.h b/src/modules/physics/box2d/DistanceJoint.h index 2363f1643..19ce1cb19 100644 --- a/src/modules/physics/box2d/DistanceJoint.h +++ b/src/modules/physics/box2d/DistanceJoint.h @@ -44,7 +44,7 @@ namespace box2d /** * Creates a DistanceJoint connecting body1 to body2. **/ - DistanceJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2); + DistanceJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, bool collideConnected); virtual ~DistanceJoint(); diff --git a/src/modules/physics/box2d/FrictionJoint.cpp b/src/modules/physics/box2d/FrictionJoint.cpp index f4d818803..f606199dd 100644 --- a/src/modules/physics/box2d/FrictionJoint.cpp +++ b/src/modules/physics/box2d/FrictionJoint.cpp @@ -32,11 +32,12 @@ namespace physics { namespace box2d { - FrictionJoint::FrictionJoint(Body * body1, Body * body2, float x, float y) + FrictionJoint::FrictionJoint(Body * body1, Body * body2, float x, float y, bool collideConnected) : Joint(body1, body2), joint(NULL) { b2FrictionJointDef def; def.Initialize(body1->body, body2->body, world->scaleDown(b2Vec2(x,y))); + def.collideConnected = collideConnected; joint = (b2FrictionJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/FrictionJoint.h b/src/modules/physics/box2d/FrictionJoint.h index ed4599f68..d334c4799 100644 --- a/src/modules/physics/box2d/FrictionJoint.h +++ b/src/modules/physics/box2d/FrictionJoint.h @@ -45,7 +45,7 @@ namespace box2d /** * Creates a new FrictionJoint connecting body1 and body2. **/ - FrictionJoint(Body * body1, Body * body2, float x, float y); + FrictionJoint(Body * body1, Body * body2, float x, float y, bool collideConnected); virtual ~FrictionJoint(); diff --git a/src/modules/physics/box2d/GearJoint.cpp b/src/modules/physics/box2d/GearJoint.cpp index aad347f45..5fc0f7dc1 100644 --- a/src/modules/physics/box2d/GearJoint.cpp +++ b/src/modules/physics/box2d/GearJoint.cpp @@ -30,7 +30,7 @@ namespace physics { namespace box2d { - GearJoint::GearJoint(Joint * joint1, Joint * joint2, float ratio) + GearJoint::GearJoint(Joint * joint1, Joint * joint2, float ratio, bool collideConnected) : Joint(joint1->body2, joint2->body2), joint(NULL) { b2GearJointDef def; @@ -39,6 +39,7 @@ namespace box2d def.bodyA = joint1->body2->body; def.bodyB = joint2->body2->body; def.ratio = ratio; + def.collideConnected = collideConnected; joint = (b2GearJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/GearJoint.h b/src/modules/physics/box2d/GearJoint.h index 3be2be3af..58eb648be 100644 --- a/src/modules/physics/box2d/GearJoint.h +++ b/src/modules/physics/box2d/GearJoint.h @@ -52,7 +52,7 @@ namespace box2d /** * Creates a GearJoint connecting joint1 to joint2. **/ - GearJoint(Joint * joint1, Joint * joint2, float ratio); + GearJoint(Joint * joint1, Joint * joint2, float ratio, bool collideConnected); virtual ~GearJoint(); diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index bf43ddb22..b8d781eed 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -144,9 +144,9 @@ namespace box2d return 1; } - DistanceJoint * Physics::newDistanceJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2) + DistanceJoint * Physics::newDistanceJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, bool collideConnected) { - return new DistanceJoint(body1, body2, x1, y1, x2, y2); + return new DistanceJoint(body1, body2, x1, y1, x2, y2, collideConnected); } MouseJoint * Physics::newMouseJoint(Body * body, float x, float y) @@ -154,44 +154,44 @@ namespace box2d return new MouseJoint(body, x, y); } - RevoluteJoint * Physics::newRevoluteJoint(Body * body1, Body * body2, float x, float y) + RevoluteJoint * Physics::newRevoluteJoint(Body * body1, Body * body2, float x, float y, bool collideConnected) { - return new RevoluteJoint(body1, body2, x, y); + return new RevoluteJoint(body1, body2, x, y, collideConnected); } - PrismaticJoint * Physics::newPrismaticJoint(Body * body1, Body * body2, float x, float y, float ax, float ay) + PrismaticJoint * Physics::newPrismaticJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected) { - return new PrismaticJoint(body1, body2, x, y, ax, ay); + return new PrismaticJoint(body1, body2, x, y, ax, ay, collideConnected); } - PulleyJoint * Physics::newPulleyJoint(Body * body1, Body * body2, b2Vec2 groundAnchor1, b2Vec2 groundAnchor2, b2Vec2 anchor1, b2Vec2 anchor2, float ratio) + PulleyJoint * Physics::newPulleyJoint(Body * body1, Body * body2, b2Vec2 groundAnchor1, b2Vec2 groundAnchor2, b2Vec2 anchor1, b2Vec2 anchor2, float ratio, bool collideConnected) { - return new PulleyJoint(body1, body2, groundAnchor1, groundAnchor2, anchor1, anchor2, ratio); + return new PulleyJoint(body1, body2, groundAnchor1, groundAnchor2, anchor1, anchor2, ratio, collideConnected); } - GearJoint * Physics::newGearJoint(Joint * joint1, Joint * joint2, float ratio) + GearJoint * Physics::newGearJoint(Joint * joint1, Joint * joint2, float ratio, bool collideConnected) { - return new GearJoint(joint1, joint2, ratio); + return new GearJoint(joint1, joint2, ratio, collideConnected); } - FrictionJoint * Physics::newFrictionJoint(Body * body1, Body * body2, float x, float y) + FrictionJoint * Physics::newFrictionJoint(Body * body1, Body * body2, float x, float y, bool collideConnected) { - return new FrictionJoint(body1, body2, x, y); + return new FrictionJoint(body1, body2, x, y, collideConnected); } - WeldJoint * Physics::newWeldJoint(Body * body1, Body * body2, float x, float y) + WeldJoint * Physics::newWeldJoint(Body * body1, Body * body2, float x, float y, bool collideConnected) { - return new WeldJoint(body1, body2, x, y); + return new WeldJoint(body1, body2, x, y, collideConnected); } - WheelJoint * Physics::newWheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay) + WheelJoint * Physics::newWheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected) { - return new WheelJoint(body1, body2, x, y, ax, ay); + return new WheelJoint(body1, body2, x, y, ax, ay, collideConnected); } - RopeJoint * Physics::newRopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength) + RopeJoint * Physics::newRopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength, bool collideConnected) { - return new RopeJoint(body1, body2, x1, y1, x2, y2, maxLength); + return new RopeJoint(body1, body2, x1, y1, x2, y2, maxLength, collideConnected); } } // box2d diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index 94839e865..267a159de 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -158,7 +158,7 @@ namespace box2d * @param x2 Anchor2 along the x-axis. (World coordinates) * @param y2 Anchor2 along the y-axis. (World coordinates) **/ - DistanceJoint * newDistanceJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2); + DistanceJoint * newDistanceJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, bool collideConnected); /** * Creates a new MouseJoint connecting the body with an arbitrary point. @@ -172,7 +172,7 @@ namespace box2d * @param x Anchor along the x-axis. (World coordinates) * @param y Anchor along the y-axis. (World coordinates) **/ - RevoluteJoint * newRevoluteJoint(Body * body1, Body * body2, float x, float y); + RevoluteJoint * newRevoluteJoint(Body * body1, Body * body2, float x, float y, bool collideConnected); /** * Creates a new PrismaticJoint connecting body1 with body2. @@ -181,7 +181,7 @@ namespace box2d * @param ax The x-component of the world-axis. * @param ay The y-component of the world-axis. **/ - PrismaticJoint * newPrismaticJoint(Body * body1, Body * body2, float x, float y, float ax, float ay); + PrismaticJoint * newPrismaticJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected); /** * Creates a new PulleyJoint connecting body1 with body2. @@ -191,7 +191,7 @@ namespace box2d * @param anchor2 World anchor on body2. * @param ratio The pulley ratio. **/ - PulleyJoint * newPulleyJoint(Body * body1, Body * body2, b2Vec2 groundAnchor1, b2Vec2 groundAnchor2, b2Vec2 anchor1, b2Vec2 anchor2, float ratio); + PulleyJoint * newPulleyJoint(Body * body1, Body * body2, b2Vec2 groundAnchor1, b2Vec2 groundAnchor2, b2Vec2 anchor1, b2Vec2 anchor2, float ratio, bool collideConnected); /** * Creates a new GearJoint connecting joint1 with joint2. @@ -199,21 +199,21 @@ namespace box2d * @param joint2 The second joint. * @param ratio The gear ratio. **/ - GearJoint * newGearJoint(Joint * joint1, Joint * joint2, float ratio); + GearJoint * newGearJoint(Joint * joint1, Joint * joint2, float ratio, bool collideConnected); /** * Creates a new FrictionJoint connecting body1 with body2. * @param x Anchor along the x-axis. (World coordinates) * @param y Anchor along the y-axis. (World coordinates) **/ - FrictionJoint * newFrictionJoint(Body * body1, Body * body2, float x, float y); + FrictionJoint * newFrictionJoint(Body * body1, Body * body2, float x, float y, bool collideConnected); /** * Creates a new WeldJoint connecting body1 with body2. * @param x Anchor along the x-axis. (World coordinates) * @param y Anchor along the y-axis. (World coordinates) **/ - WeldJoint * newWeldJoint(Body * body1, Body * body2, float x, float y); + WeldJoint * newWeldJoint(Body * body1, Body * body2, float x, float y, bool collideConnected); /** * Creates a new WheelJoint connecting body1 with body2. @@ -222,7 +222,7 @@ namespace box2d * @param ax The x-component of the world-axis. * @param ay The y-component of the world-axis. **/ - WheelJoint * newWheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay); + WheelJoint * newWheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected); /** * Creates a new RopeJoint connecting body1 with body2. @@ -232,7 +232,7 @@ namespace box2d * @param y2 Anchor2 along the y-axis. (Local coordinates) * @param maxLength The maximum distance for the bodies. **/ - RopeJoint * newRopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength); + RopeJoint * newRopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength, bool collideConnected); }; // Physics diff --git a/src/modules/physics/box2d/PrismaticJoint.cpp b/src/modules/physics/box2d/PrismaticJoint.cpp index 4556073a7..57ae56b4b 100644 --- a/src/modules/physics/box2d/PrismaticJoint.cpp +++ b/src/modules/physics/box2d/PrismaticJoint.cpp @@ -30,7 +30,7 @@ namespace physics { namespace box2d { - PrismaticJoint::PrismaticJoint(Body * body1, Body * body2, float x, float y, float ax, float ay) + PrismaticJoint::PrismaticJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected) : Joint(body1, body2), joint(NULL) { b2PrismaticJointDef def; @@ -39,6 +39,7 @@ namespace box2d def.lowerTranslation = 0.0f; def.upperTranslation = 100.0f; def.enableLimit = true; + def.collideConnected = collideConnected; joint = (b2PrismaticJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/PrismaticJoint.h b/src/modules/physics/box2d/PrismaticJoint.h index 38b7787e9..5e0c39222 100644 --- a/src/modules/physics/box2d/PrismaticJoint.h +++ b/src/modules/physics/box2d/PrismaticJoint.h @@ -46,7 +46,7 @@ namespace box2d /** * Creates a new PrismaticJoint connecting body1 and body2. **/ - PrismaticJoint(Body * body1, Body * body2, float x, float y, float ax, float ay); + PrismaticJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected); virtual ~PrismaticJoint(); diff --git a/src/modules/physics/box2d/PulleyJoint.cpp b/src/modules/physics/box2d/PulleyJoint.cpp index d45c850da..387a75d41 100644 --- a/src/modules/physics/box2d/PulleyJoint.cpp +++ b/src/modules/physics/box2d/PulleyJoint.cpp @@ -30,12 +30,13 @@ namespace physics { namespace box2d { - PulleyJoint::PulleyJoint(Body * body1, Body * body2, b2Vec2 groundAnchor1, b2Vec2 groundAnchor2, b2Vec2 anchor1, b2Vec2 anchor2, float ratio) + PulleyJoint::PulleyJoint(Body * body1, Body * body2, b2Vec2 groundAnchor1, b2Vec2 groundAnchor2, b2Vec2 anchor1, b2Vec2 anchor2, float ratio, bool collideConnected) : Joint(body1, body2), joint(NULL) { b2PulleyJointDef def; def.Initialize(body1->body, body2->body, world->scaleDown(groundAnchor1), world->scaleDown(groundAnchor2), \ world->scaleDown(anchor1), world->scaleDown(anchor2), ratio); + def.collideConnected = collideConnected; joint = (b2PulleyJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/PulleyJoint.h b/src/modules/physics/box2d/PulleyJoint.h index a352c738a..ba1eb201f 100644 --- a/src/modules/physics/box2d/PulleyJoint.h +++ b/src/modules/physics/box2d/PulleyJoint.h @@ -46,7 +46,7 @@ namespace box2d /** * Creates a PulleyJoint connecting body1 to body2. **/ - PulleyJoint(Body * body1, Body * body2, b2Vec2 groundAnchor1, b2Vec2 groundAnchor2, b2Vec2 anchor1, b2Vec2 anchor2, float ratio); + PulleyJoint(Body * body1, Body * body2, b2Vec2 groundAnchor1, b2Vec2 groundAnchor2, b2Vec2 anchor1, b2Vec2 anchor2, float ratio, bool collideConnected); virtual ~PulleyJoint(); diff --git a/src/modules/physics/box2d/RevoluteJoint.cpp b/src/modules/physics/box2d/RevoluteJoint.cpp index d725efa6e..cf22a195a 100644 --- a/src/modules/physics/box2d/RevoluteJoint.cpp +++ b/src/modules/physics/box2d/RevoluteJoint.cpp @@ -32,11 +32,12 @@ namespace physics { namespace box2d { - RevoluteJoint::RevoluteJoint(Body * body1, Body * body2, float x, float y) + RevoluteJoint::RevoluteJoint(Body * body1, Body * body2, float x, float y, bool collideConnected) : Joint(body1, body2), joint(NULL) { b2RevoluteJointDef def; def.Initialize(body1->body, body2->body, world->scaleDown(b2Vec2(x,y))); + def.collideConnected = collideConnected; joint = (b2RevoluteJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/RevoluteJoint.h b/src/modules/physics/box2d/RevoluteJoint.h index 51acf26fe..4f5a57064 100644 --- a/src/modules/physics/box2d/RevoluteJoint.h +++ b/src/modules/physics/box2d/RevoluteJoint.h @@ -46,7 +46,7 @@ namespace box2d /** * Creates a new RevoluteJoint connecting body1 and body2. **/ - RevoluteJoint(Body * body1, Body * body2, float x, float y); + RevoluteJoint(Body * body1, Body * body2, float x, float y, bool collideConnected); virtual ~RevoluteJoint(); diff --git a/src/modules/physics/box2d/RopeJoint.cpp b/src/modules/physics/box2d/RopeJoint.cpp index 5cbd26698..6becef476 100644 --- a/src/modules/physics/box2d/RopeJoint.cpp +++ b/src/modules/physics/box2d/RopeJoint.cpp @@ -30,7 +30,7 @@ namespace physics { namespace box2d { - RopeJoint::RopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength) + RopeJoint::RopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength, bool collideConnected) : Joint(body1, body2), joint(NULL) { b2RopeJointDef def; @@ -39,6 +39,7 @@ namespace box2d def.localAnchorA = world->scaleDown(b2Vec2(x1,y1)); def.localAnchorB = world->scaleDown(b2Vec2(x2,y2)); def.maxLength = world->scaleDown(maxLength); + def.collideConnected = collideConnected; joint = (b2RopeJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/RopeJoint.h b/src/modules/physics/box2d/RopeJoint.h index 886f459cd..0d3244b1c 100644 --- a/src/modules/physics/box2d/RopeJoint.h +++ b/src/modules/physics/box2d/RopeJoint.h @@ -44,7 +44,7 @@ namespace box2d /** * Creates a RopeJoint connecting body1 to body2. **/ - RopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength); + RopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength, bool collideConnected); virtual ~RopeJoint(); diff --git a/src/modules/physics/box2d/WeldJoint.cpp b/src/modules/physics/box2d/WeldJoint.cpp index 05cb7647f..1b07e04b9 100644 --- a/src/modules/physics/box2d/WeldJoint.cpp +++ b/src/modules/physics/box2d/WeldJoint.cpp @@ -32,11 +32,12 @@ namespace physics { namespace box2d { - WeldJoint::WeldJoint(Body * body1, Body * body2, float x, float y) + WeldJoint::WeldJoint(Body * body1, Body * body2, float x, float y, bool collideConnected) : Joint(body1, body2), joint(NULL) { b2WeldJointDef def; def.Initialize(body1->body, body2->body, world->scaleDown(b2Vec2(x,y))); + def.collideConnected = collideConnected; joint = (b2WeldJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/WeldJoint.h b/src/modules/physics/box2d/WeldJoint.h index ce38a3759..c8bb6856c 100644 --- a/src/modules/physics/box2d/WeldJoint.h +++ b/src/modules/physics/box2d/WeldJoint.h @@ -45,7 +45,7 @@ namespace box2d /** * Creates a new WeldJoint connecting body1 and body2. **/ - WeldJoint(Body * body1, Body * body2, float x, float y); + WeldJoint(Body * body1, Body * body2, float x, float y, bool collideConnected); virtual ~WeldJoint(); diff --git a/src/modules/physics/box2d/WheelJoint.cpp b/src/modules/physics/box2d/WheelJoint.cpp index 01f836338..5ccd7099a 100644 --- a/src/modules/physics/box2d/WheelJoint.cpp +++ b/src/modules/physics/box2d/WheelJoint.cpp @@ -30,12 +30,13 @@ namespace physics { namespace box2d { - WheelJoint::WheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay) + WheelJoint::WheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected) : Joint(body1, body2), joint(NULL) { b2WheelJointDef def; def.Initialize(body1->body, body2->body, world->scaleDown(b2Vec2(x,y)), b2Vec2(ax,ay)); + def.collideConnected = collideConnected; joint = (b2WheelJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/WheelJoint.h b/src/modules/physics/box2d/WheelJoint.h index 431ca6fa7..eb4053636 100644 --- a/src/modules/physics/box2d/WheelJoint.h +++ b/src/modules/physics/box2d/WheelJoint.h @@ -47,7 +47,7 @@ namespace box2d /** * Creates a new WheelJoint connecting body1 and body2. **/ - WheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay); + WheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected); virtual ~WheelJoint(); diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index f72f6f6bd..90c75150e 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -136,7 +136,8 @@ namespace box2d float y1 = (float)luaL_checknumber(L, 4); float x2 = (float)luaL_checknumber(L, 5); float y2 = (float)luaL_checknumber(L, 6); - DistanceJoint * j = instance->newDistanceJoint(body1, body2, x1, y1, x2, y2); + bool collideConnected = luax_optboolean(L, 7, false); + DistanceJoint * j = instance->newDistanceJoint(body1, body2, x1, y1, x2, y2, collideConnected); luax_newtype(L, "DistanceJoint", PHYSICS_DISTANCE_JOINT_T, (void*)j); return 1; } @@ -157,7 +158,8 @@ namespace box2d Body * body2 = luax_checktype(L, 2, "Body", PHYSICS_BODY_T); float x = (float)luaL_checknumber(L, 3); float y = (float)luaL_checknumber(L, 4); - RevoluteJoint * j = instance->newRevoluteJoint(body1, body2, x, y); + bool collideConnected = luax_optboolean(L, 5, false); + RevoluteJoint * j = instance->newRevoluteJoint(body1, body2, x, y, collideConnected); luax_newtype(L, "RevoluteJoint", PHYSICS_REVOLUTE_JOINT_T, (void*)j); return 1; } @@ -170,7 +172,8 @@ namespace box2d float y = (float)luaL_checknumber(L, 4); float ax = (float)luaL_checknumber(L, 5); float ay = (float)luaL_checknumber(L, 6); - PrismaticJoint * j = instance->newPrismaticJoint(body1, body2, x, y, ax, ay); + bool collideConnected = luax_optboolean(L, 7, false); + PrismaticJoint * j = instance->newPrismaticJoint(body1, body2, x, y, ax, ay, collideConnected); luax_newtype(L, "PrismaticJoint", PHYSICS_PRISMATIC_JOINT_T, (void*)j); return 1; } @@ -188,8 +191,9 @@ namespace box2d float x2 = (float)luaL_checknumber(L, 9); float y2 = (float)luaL_checknumber(L, 10); float ratio = (float)luaL_optnumber(L, 11, 1.0); + bool collideConnected = luax_optboolean(L, 12, true); // PulleyJoints default to colliding connected bodies, see b2PulleyJoint.h - PulleyJoint * j = instance->newPulleyJoint(body1, body2, b2Vec2(gx1,gy1), b2Vec2(gx2,gy2), b2Vec2(x1,y1), b2Vec2(x2,y2), ratio); + PulleyJoint * j = instance->newPulleyJoint(body1, body2, b2Vec2(gx1,gy1), b2Vec2(gx2,gy2), b2Vec2(x1,y1), b2Vec2(x2,y2), ratio, collideConnected); luax_newtype(L, "PulleyJoint", PHYSICS_PULLEY_JOINT_T, (void*)j); return 1; } @@ -199,8 +203,9 @@ namespace box2d Joint * joint1 = luax_checktype(L, 1, "Joint", PHYSICS_JOINT_T); Joint * joint2 = luax_checktype(L, 2, "Joint", PHYSICS_JOINT_T); float ratio = (float)luaL_optnumber(L, 3, 1.0); + bool collideConnected = luax_optboolean(L, 4, false); - GearJoint * j = instance->newGearJoint(joint1, joint2, ratio); + GearJoint * j = instance->newGearJoint(joint1, joint2, ratio, collideConnected); luax_newtype(L, "GearJoint", PHYSICS_GEAR_JOINT_T, (void*)j); return 1; } @@ -211,7 +216,8 @@ namespace box2d Body * body2 = luax_checktype(L, 2, "Body", PHYSICS_BODY_T); float x = (float)luaL_checknumber(L, 3); float y = (float)luaL_checknumber(L, 4); - FrictionJoint * j = instance->newFrictionJoint(body1, body2, x, y); + bool collideConnected = luax_optboolean(L, 5, false); + FrictionJoint * j = instance->newFrictionJoint(body1, body2, x, y, collideConnected); luax_newtype(L, "FrictionJoint", PHYSICS_FRICTION_JOINT_T, (void*)j); return 1; } @@ -222,7 +228,8 @@ namespace box2d Body * body2 = luax_checktype(L, 2, "Body", PHYSICS_BODY_T); float x = (float)luaL_checknumber(L, 3); float y = (float)luaL_checknumber(L, 4); - WeldJoint * j = instance->newWeldJoint(body1, body2, x, y); + bool collideConnected = luax_optboolean(L, 5, false); + WeldJoint * j = instance->newWeldJoint(body1, body2, x, y, collideConnected); luax_newtype(L, "WeldJoint", PHYSICS_WELD_JOINT_T, (void*)j); return 1; } @@ -235,7 +242,8 @@ namespace box2d float y = (float)luaL_checknumber(L, 4); float ax = (float)luaL_checknumber(L, 5); float ay = (float)luaL_checknumber(L, 6); - WheelJoint * j = instance->newWheelJoint(body1, body2, x, y, ax, ay); + bool collideConnected = luax_optboolean(L, 7, false); + WheelJoint * j = instance->newWheelJoint(body1, body2, x, y, ax, ay, collideConnected); luax_newtype(L, "WheelJoint", PHYSICS_WHEEL_JOINT_T, (void*)j); return 1; } @@ -249,7 +257,8 @@ namespace box2d float x2 = (float)luaL_checknumber(L, 5); float y2 = (float)luaL_checknumber(L, 6); float maxLength = (float)luaL_checknumber(L, 7); - RopeJoint * j = instance->newRopeJoint(body1, body2, x1, y1, x2, y2, maxLength); + bool collideConnected = luax_optboolean(L, 8, false); + RopeJoint * j = instance->newRopeJoint(body1, body2, x1, y1, x2, y2, maxLength, collideConnected); luax_newtype(L, "RopeJoint", PHYSICS_ROPE_JOINT_T, (void*)j); return 1; } From d8f3db668213b04b380ca41e68ef42859b63536a Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Thu, 15 Sep 2011 15:31:09 -0400 Subject: [PATCH 13/78] exposed new Shape functions --HG-- branch : box2d-update --- src/modules/physics/box2d/Shape.cpp | 75 ++++++++++++++++++- src/modules/physics/box2d/Shape.h | 11 ++- .../physics/box2d/wrap_CircleShape.cpp | 6 ++ src/modules/physics/box2d/wrap_EdgeShape.cpp | 6 ++ .../physics/box2d/wrap_PolygonShape.cpp | 6 ++ src/modules/physics/box2d/wrap_Shape.cpp | 56 ++++++++++++++ src/modules/physics/box2d/wrap_Shape.h | 8 ++ 7 files changed, 165 insertions(+), 3 deletions(-) diff --git a/src/modules/physics/box2d/Shape.cpp b/src/modules/physics/box2d/Shape.cpp index e5ab9f7c7..177ebfad7 100644 --- a/src/modules/physics/box2d/Shape.cpp +++ b/src/modules/physics/box2d/Shape.cpp @@ -33,8 +33,8 @@ namespace physics { namespace box2d { - Shape::Shape() - : shape(NULL) + Shape::Shape(World * world) + : world(world), shape(NULL) { } @@ -59,6 +59,77 @@ namespace box2d return SHAPE_INVALID; } } + + float Shape::getRadius() const + { + return world->scaleUp(shape->m_radius); + } + + int Shape::getChildCount() const + { + return shape->GetChildCount(); + } + + bool Shape::testPoint(float x, float y, float r, float px, float py) const + { + b2Vec2 point(px, py); + b2Transform transform(world->scaleDown(b2Vec2(x, y)), b2Rot(r)); + return shape->TestPoint(transform, world->scaleDown(point)); + } + + int Shape::rayCast(lua_State * L) const + { + float p1x = world->scaleDown((float)luaL_checknumber(L, 1)); + float p1y = world->scaleDown((float)luaL_checknumber(L, 2)); + float p2x = world->scaleDown((float)luaL_checknumber(L, 3)); + float p2y = world->scaleDown((float)luaL_checknumber(L, 4)); + float maxFraction = (float)luaL_checknumber(L, 5); + float x = world->scaleDown((float)luaL_checknumber(L, 6)); + float y = world->scaleDown((float)luaL_checknumber(L, 7)); + float r = (float)luaL_checknumber(L, 8); + int childIndex = (int)luaL_optint(L, 9, 0); + b2RayCastInput input; + input.p1.Set(p1x, p1y); + input.p2.Set(p2x, p2y); + input.maxFraction = maxFraction; + b2Transform transform(b2Vec2(x, y), b2Rot(r)); + b2RayCastOutput output; + shape->RayCast(&output, input, transform, childIndex); + lua_pushnumber(L, world->scaleUp(output.normal.x)); + lua_pushnumber(L, world->scaleUp(output.normal.y)); + lua_pushnumber(L, output.fraction); + return 3; + } + + int Shape::computeAABB(lua_State * L) const + { + float x = world->scaleDown((float)luaL_checknumber(L, 1)); + float y = world->scaleDown((float)luaL_checknumber(L, 2)); + float r = (float)luaL_checknumber(L, 3); + int childIndex = (int)luaL_optint(L, 4, 0); + b2Transform transform(b2Vec2(x, y), b2Rot(r)); + b2AABB box; + shape->ComputeAABB(&box, transform, childIndex); + box = world->scaleUp(box); + lua_pushnumber(L, box.lowerBound.x); + lua_pushnumber(L, box.lowerBound.y); + lua_pushnumber(L, box.upperBound.x); + lua_pushnumber(L, box.upperBound.y); + return 4; + } + + int Shape::computeMass(lua_State * L) const + { + float density = world->scaleDown((float)luaL_checknumber(L, 1)); + b2MassData data; + shape->ComputeMass(&data, density); + b2Vec2 center = world->scaleUp(data.center); + lua_pushnumber(L, center.x); + lua_pushnumber(L, center.y); + lua_pushnumber(L, data.mass); + lua_pushnumber(L, data.I); + return 4; + } } // box2d } // physics diff --git a/src/modules/physics/box2d/Shape.h b/src/modules/physics/box2d/Shape.h index bb77239f3..e89e10d2e 100644 --- a/src/modules/physics/box2d/Shape.h +++ b/src/modules/physics/box2d/Shape.h @@ -44,6 +44,9 @@ namespace box2d **/ class Shape : public love::physics::Shape { + private: + World * world; // We need a reference for scaling up/down + protected: // The Box2D shape. @@ -54,7 +57,7 @@ namespace box2d /** * Creates a Shape. **/ - Shape(); + Shape(World * world); virtual ~Shape(); @@ -63,6 +66,12 @@ namespace box2d * debug drawing. **/ Type getType() const; + float getRadius() const; + int getChildCount() const; + bool testPoint(float x, float y, float r, float px, float py) const; + int rayCast(lua_State * L) const; + int computeAABB(lua_State * L) const; + int computeMass(lua_State * L) const; }; } // box2d diff --git a/src/modules/physics/box2d/wrap_CircleShape.cpp b/src/modules/physics/box2d/wrap_CircleShape.cpp index a17bef0d9..f205dfa5e 100644 --- a/src/modules/physics/box2d/wrap_CircleShape.cpp +++ b/src/modules/physics/box2d/wrap_CircleShape.cpp @@ -51,6 +51,12 @@ namespace box2d { "setRadius", w_CircleShape_setRadius }, // From Shape. { "getType", w_Shape_getType }, + { "getRadius", w_Shape_getRadius }, + { "getChildCount", w_Shape_getChildCount }, + { "testPoint", w_Shape_testPoint }, + { "rayCast", w_Shape_rayCast }, + { "computeAABB", w_Shape_computeAABB }, + { "computeMass", w_Shape_computeMass }, { "destroy", w_Shape_destroy }, { 0, 0 } }; diff --git a/src/modules/physics/box2d/wrap_EdgeShape.cpp b/src/modules/physics/box2d/wrap_EdgeShape.cpp index be64c4feb..3a8f23276 100644 --- a/src/modules/physics/box2d/wrap_EdgeShape.cpp +++ b/src/modules/physics/box2d/wrap_EdgeShape.cpp @@ -34,6 +34,12 @@ namespace box2d static const luaL_Reg functions[] = { // From Shape. { "getType", w_Shape_getType }, + { "getRadius", w_Shape_getRadius }, + { "getChildCount", w_Shape_getChildCount }, + { "testPoint", w_Shape_testPoint }, + { "rayCast", w_Shape_rayCast }, + { "computeAABB", w_Shape_computeAABB }, + { "computeMass", w_Shape_computeMass }, { "destroy", w_Shape_destroy }, { 0, 0 } }; diff --git a/src/modules/physics/box2d/wrap_PolygonShape.cpp b/src/modules/physics/box2d/wrap_PolygonShape.cpp index 8b8a5cc28..e86029fc6 100644 --- a/src/modules/physics/box2d/wrap_PolygonShape.cpp +++ b/src/modules/physics/box2d/wrap_PolygonShape.cpp @@ -42,6 +42,12 @@ namespace box2d { "getPoints", w_PolygonShape_getPoints }, // From Shape. { "getType", w_Shape_getType }, + { "getRadius", w_Shape_getRadius }, + { "getChildCount", w_Shape_getChildCount }, + { "testPoint", w_Shape_testPoint }, + { "rayCast", w_Shape_rayCast }, + { "computeAABB", w_Shape_computeAABB }, + { "computeMass", w_Shape_computeMass }, { "destroy", w_Shape_destroy }, { 0, 0 } }; diff --git a/src/modules/physics/box2d/wrap_Shape.cpp b/src/modules/physics/box2d/wrap_Shape.cpp index 510b75b16..23ebe6284 100644 --- a/src/modules/physics/box2d/wrap_Shape.cpp +++ b/src/modules/physics/box2d/wrap_Shape.cpp @@ -40,6 +40,56 @@ namespace box2d lua_pushstring(L, type); return 1; } + + int w_Shape_getRadius(lua_State * L) + { + Shape * t = luax_checkshape(L, 1); + float radius = t->getRadius(); + lua_pushnumber(L, radius); + return 1; + } + + int w_Shape_getChildCount(lua_State * L) + { + Shape * t = luax_checkshape(L, 1); + int childCount = t->getChildCount(); + lua_pushinteger(L, childCount); + return 1; + } + + int w_Shape_testPoint(lua_State * L) + { + Shape * t = luax_checkshape(L, 1); + float x = (float)luaL_checknumber(L, 1); + float y = (float)luaL_checknumber(L, 2); + float r = (float)luaL_checknumber(L, 3); + float px = (float)luaL_checknumber(L, 4); + float py = (float)luaL_checknumber(L, 5); + bool result = t->testPoint(x, y, r, px, py); + lua_pushboolean(L, result); + return 1; + } + + int w_Shape_rayCast(lua_State * L) + { + Shape * t = luax_checkshape(L, 1); + lua_remove(L, 1); + return t->rayCast(L); + } + + int w_Shape_computeAABB(lua_State * L) + { + Shape * t = luax_checkshape(L, 1); + lua_remove(L, 1); + return t->computeAABB(L); + } + + int w_Shape_computeMass(lua_State * L) + { + Shape * t = luax_checkshape(L, 1); + lua_remove(L, 1); + return t->computeMass(L); + } int w_Shape_destroy(lua_State * L) { @@ -53,6 +103,12 @@ namespace box2d static const luaL_Reg functions[] = { { "getType", w_Shape_getType }, + { "getRadius", w_Shape_getRadius }, + { "getChildCount", w_Shape_getChildCount }, + { "testPoint", w_Shape_testPoint }, + { "rayCast", w_Shape_rayCast }, + { "computeAABB", w_Shape_computeAABB }, + { "computeMass", w_Shape_computeMass }, { "destroy", w_Shape_destroy }, { 0, 0 } }; diff --git a/src/modules/physics/box2d/wrap_Shape.h b/src/modules/physics/box2d/wrap_Shape.h index 02950111d..cc26c5c2b 100644 --- a/src/modules/physics/box2d/wrap_Shape.h +++ b/src/modules/physics/box2d/wrap_Shape.h @@ -33,6 +33,14 @@ namespace box2d { Shape * luax_checkshape(lua_State * L, int idx); int w_Shape_getType(lua_State * L); + int w_Shape_getRadius(lua_State * L); + + int w_Shape_getChildCount(lua_State * L); + int w_Shape_testPoint(lua_State * L); + int w_Shape_rayCast(lua_State * L); + int w_Shape_computeAABB(lua_State * L); + int w_Shape_computeMass(lua_State * L); + int w_Shape_destroy(lua_State * L); int luaopen_shape(lua_State * L); From 1fa99d022a3e25fef336ac7fc0f74b5d4316ec4f Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Thu, 15 Sep 2011 15:35:11 -0400 Subject: [PATCH 14/78] Documented collideConnected flag --HG-- branch : box2d-update --- src/modules/physics/box2d/Physics.h | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index 267a159de..ed2ca3d54 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -157,6 +157,7 @@ namespace box2d * @param y1 Anchor1 along the y-axis. (World coordinates) * @param x2 Anchor2 along the x-axis. (World coordinates) * @param y2 Anchor2 along the y-axis. (World coordinates) + * @param collideConnected Whether the connected bodies should collide with each other. Defaults to false. **/ DistanceJoint * newDistanceJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, bool collideConnected); @@ -171,6 +172,7 @@ namespace box2d * Creates a new RevoluteJoint connecting body1 with body2. * @param x Anchor along the x-axis. (World coordinates) * @param y Anchor along the y-axis. (World coordinates) + * @param collideConnected Whether the connected bodies should collide with each other. Defaults to false. **/ RevoluteJoint * newRevoluteJoint(Body * body1, Body * body2, float x, float y, bool collideConnected); @@ -180,6 +182,7 @@ namespace box2d * @param y World-anchor along the y-axis. * @param ax The x-component of the world-axis. * @param ay The y-component of the world-axis. + * @param collideConnected Whether the connected bodies should collide with each other. Defaults to false. **/ PrismaticJoint * newPrismaticJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected); @@ -190,6 +193,7 @@ namespace box2d * @param anchor1 World anchor on body1. * @param anchor2 World anchor on body2. * @param ratio The pulley ratio. + * @param collideConnected Whether the connected bodies should collide with each other. Defaults to true. **/ PulleyJoint * newPulleyJoint(Body * body1, Body * body2, b2Vec2 groundAnchor1, b2Vec2 groundAnchor2, b2Vec2 anchor1, b2Vec2 anchor2, float ratio, bool collideConnected); @@ -198,6 +202,7 @@ namespace box2d * @param joint1 The first joint. * @param joint2 The second joint. * @param ratio The gear ratio. + * @param collideConnected Whether the connected bodies should collide with each other. Defaults to false. **/ GearJoint * newGearJoint(Joint * joint1, Joint * joint2, float ratio, bool collideConnected); @@ -205,6 +210,7 @@ namespace box2d * Creates a new FrictionJoint connecting body1 with body2. * @param x Anchor along the x-axis. (World coordinates) * @param y Anchor along the y-axis. (World coordinates) + * @param collideConnected Whether the connected bodies should collide with each other. Defaults to false. **/ FrictionJoint * newFrictionJoint(Body * body1, Body * body2, float x, float y, bool collideConnected); @@ -212,6 +218,7 @@ namespace box2d * Creates a new WeldJoint connecting body1 with body2. * @param x Anchor along the x-axis. (World coordinates) * @param y Anchor along the y-axis. (World coordinates) + * @param collideConnected Whether the connected bodies should collide with each other. Defaults to false. **/ WeldJoint * newWeldJoint(Body * body1, Body * body2, float x, float y, bool collideConnected); @@ -221,6 +228,7 @@ namespace box2d * @param y Anchor along the y-axis. (World coordinates) * @param ax The x-component of the world-axis. * @param ay The y-component of the world-axis. + * @param collideConnected Whether the connected bodies should collide with each other. Defaults to false. **/ WheelJoint * newWheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected); @@ -231,6 +239,7 @@ namespace box2d * @param x2 Anchor2 along the x-axis. (Local coordinates) * @param y2 Anchor2 along the y-axis. (Local coordinates) * @param maxLength The maximum distance for the bodies. + * @param collideConnected Whether the connected bodies should collide with each other. Defaults to false. **/ RopeJoint * newRopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength, bool collideConnected); From e69cafe86889a57e270937d895c0d9437b4762e8 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Thu, 15 Sep 2011 16:13:54 -0400 Subject: [PATCH 15/78] Switched get/setMeter from being a World method to a love.physics function --HG-- branch : box2d-update --- src/modules/physics/box2d/Body.cpp | 41 +++++------ src/modules/physics/box2d/Contact.cpp | 15 ++-- src/modules/physics/box2d/DistanceJoint.cpp | 7 +- src/modules/physics/box2d/FrictionJoint.cpp | 3 +- src/modules/physics/box2d/Joint.cpp | 9 +-- src/modules/physics/box2d/MouseJoint.cpp | 9 +-- src/modules/physics/box2d/Physics.cpp | 64 +++++++++++++++++ src/modules/physics/box2d/Physics.h | 73 ++++++++++++++++++++ src/modules/physics/box2d/PrismaticJoint.cpp | 29 ++++---- src/modules/physics/box2d/PulleyJoint.cpp | 17 ++--- src/modules/physics/box2d/RevoluteJoint.cpp | 3 +- src/modules/physics/box2d/RopeJoint.cpp | 9 +-- src/modules/physics/box2d/Shape.cpp | 37 +++++----- src/modules/physics/box2d/Shape.h | 4 +- src/modules/physics/box2d/WeldJoint.cpp | 3 +- src/modules/physics/box2d/WheelJoint.cpp | 25 +++---- src/modules/physics/box2d/World.cpp | 71 ++----------------- src/modules/physics/box2d/World.h | 71 ------------------- src/modules/physics/box2d/wrap_Physics.cpp | 15 ++++ src/modules/physics/box2d/wrap_Physics.h | 2 + src/modules/physics/box2d/wrap_World.cpp | 17 ----- src/modules/physics/box2d/wrap_World.h | 2 - 22 files changed, 270 insertions(+), 256 deletions(-) diff --git a/src/modules/physics/box2d/Body.cpp b/src/modules/physics/box2d/Body.cpp index 5487414c8..4d51f12c3 100644 --- a/src/modules/physics/box2d/Body.cpp +++ b/src/modules/physics/box2d/Body.cpp @@ -23,6 +23,7 @@ #include #include "World.h" +#include "Physics.h" namespace love { @@ -35,7 +36,7 @@ namespace box2d { world->retain(); b2BodyDef def; - def.position = world->scaleDown(p); + def.position = Physics::scaleDown(p); def.massData.mass = m; def.massData.I = i; body = world->world->CreateBody(&def); @@ -50,24 +51,24 @@ namespace box2d float Body::getX() { - return world->scaleUp(body->GetPosition().x); + return Physics::scaleUp(body->GetPosition().x); } float Body::getY() { - return world->scaleUp(body->GetPosition().y); + return Physics::scaleUp(body->GetPosition().y); } void Body::getPosition(float & x_o, float & y_o) { - b2Vec2 v = world->scaleUp(body->GetPosition()); + b2Vec2 v = Physics::scaleUp(body->GetPosition()); x_o = v.x; y_o = v.y; } void Body::getLinearVelocity(float & x_o, float & y_o) { - b2Vec2 v = world->scaleUp(body->GetLinearVelocity()); + b2Vec2 v = Physics::scaleUp(body->GetLinearVelocity()); x_o = v.x; y_o = v.y; } @@ -79,14 +80,14 @@ namespace box2d void Body::getWorldCenter(float & x_o, float & y_o) { - b2Vec2 v = world->scaleUp(body->GetWorldCenter()); + b2Vec2 v = Physics::scaleUp(body->GetWorldCenter()); x_o = v.x; y_o = v.y; } void Body::getLocalCenter(float & x_o, float & y_o) { - b2Vec2 v = world->scaleUp(body->GetLocalCenter()); + b2Vec2 v = Physics::scaleUp(body->GetLocalCenter()); x_o = v.x; y_o = v.y; } @@ -123,7 +124,7 @@ namespace box2d void Body::applyImpulse(float jx, float jy, float rx, float ry) { - body->ApplyImpulse(b2Vec2(jx, jy), world->scaleDown(b2Vec2(rx, ry))); + body->ApplyImpulse(b2Vec2(jx, jy), Physics::scaleDown(b2Vec2(rx, ry))); } void Body::applyTorque(float t) @@ -133,7 +134,7 @@ namespace box2d void Body::applyForce(float fx, float fy, float rx, float ry) { - body->ApplyForce(b2Vec2(fx, fy), world->scaleDown(b2Vec2(rx, ry))); + body->ApplyForce(b2Vec2(fx, fy), Physics::scaleDown(b2Vec2(rx, ry))); } void Body::applyForce(float fx, float fy) @@ -143,17 +144,17 @@ namespace box2d void Body::setX(float x) { - body->SetXForm(world->scaleDown(b2Vec2(x, getY())), getAngle()); + body->SetXForm(Physics::scaleDown(b2Vec2(x, getY())), getAngle()); } void Body::setY(float y) { - body->SetXForm(world->scaleDown(b2Vec2(getX(), y)), getAngle()); + body->SetXForm(Physics::scaleDown(b2Vec2(getX(), y)), getAngle()); } void Body::setLinearVelocity(float x, float y) { - body->SetLinearVelocity(world->scaleDown(b2Vec2(x, y))); + body->SetLinearVelocity(Physics::scaleDown(b2Vec2(x, y))); } void Body::setAngle(float d) @@ -168,7 +169,7 @@ namespace box2d void Body::setPosition(float x, float y) { - body->SetXForm(world->scaleDown(b2Vec2(x, y)), body->GetAngle()); + body->SetXForm(Physics::scaleDown(b2Vec2(x, y)), body->GetAngle()); } void Body::setAngularDamping(float d) @@ -189,7 +190,7 @@ namespace box2d void Body::setMass(float x, float y, float m, float i) { b2MassData massData; - massData.center = world->scaleDown(b2Vec2(x, y)); + massData.center = Physics::scaleDown(b2Vec2(x, y)); massData.mass = m; massData.I = i; body->SetMass(&massData); @@ -206,42 +207,42 @@ namespace box2d void Body::getWorldPoint(float x, float y, float & x_o, float & y_o) { - b2Vec2 v = world->scaleUp(body->GetWorldPoint(world->scaleDown(b2Vec2(x, y)))); + b2Vec2 v = Physics::scaleUp(body->GetWorldPoint(Physics::scaleDown(b2Vec2(x, y)))); x_o = v.x; y_o = v.y; } void Body::getWorldVector(float x, float y, float & x_o, float & y_o) { - b2Vec2 v = world->scaleUp(body->GetWorldVector(world->scaleDown(b2Vec2(x, y)))); + b2Vec2 v = Physics::scaleUp(body->GetWorldVector(Physics::scaleDown(b2Vec2(x, y)))); x_o = v.x; y_o = v.y; } void Body::getLocalPoint(float x, float y, float & x_o, float & y_o) { - b2Vec2 v = world->scaleUp(body->GetLocalPoint(world->scaleDown(b2Vec2(x, y)))); + b2Vec2 v = Physics::scaleUp(body->GetLocalPoint(Physics::scaleDown(b2Vec2(x, y)))); x_o = v.x; y_o = v.y; } void Body::getLocalVector(float x, float y, float & x_o, float & y_o) { - b2Vec2 v = world->scaleUp(body->GetLocalVector(world->scaleDown(b2Vec2(x, y)))); + b2Vec2 v = Physics::scaleUp(body->GetLocalVector(Physics::scaleDown(b2Vec2(x, y)))); x_o = v.x; y_o = v.y; } void Body::getLinearVelocityFromWorldPoint(float x, float y, float & x_o, float & y_o) { - b2Vec2 v = world->scaleUp(body->GetLinearVelocityFromWorldPoint(world->scaleDown(b2Vec2(x, y)))); + b2Vec2 v = Physics::scaleUp(body->GetLinearVelocityFromWorldPoint(Physics::scaleDown(b2Vec2(x, y)))); x_o = v.x; y_o = v.y; } void Body::getLinearVelocityFromLocalPoint(float x, float y, float & x_o, float & y_o) { - b2Vec2 v = world->scaleUp(body->GetLinearVelocityFromLocalPoint(world->scaleDown(b2Vec2(x, y)))); + b2Vec2 v = Physics::scaleUp(body->GetLinearVelocityFromLocalPoint(Physics::scaleDown(b2Vec2(x, y)))); x_o = v.x; y_o = v.y; } diff --git a/src/modules/physics/box2d/Contact.cpp b/src/modules/physics/box2d/Contact.cpp index 8495920be..f048e8c62 100644 --- a/src/modules/physics/box2d/Contact.cpp +++ b/src/modules/physics/box2d/Contact.cpp @@ -20,6 +20,7 @@ #include "Contact.h" #include "World.h" +#include "Physics.h" namespace love { @@ -41,30 +42,30 @@ namespace box2d int Contact::getPosition(lua_State * L) { love::luax_assert_argc(L, 1, 1); - lua_pushnumber(L, world->scaleUp(point.position.x)); - lua_pushnumber(L, world->scaleUp(point.position.y)); + lua_pushnumber(L, Physics::scaleUp(point.position.x)); + lua_pushnumber(L, Physics::scaleUp(point.position.y)); return 2; } int Contact::getVelocity(lua_State * L) { love::luax_assert_argc(L, 1, 1); - lua_pushnumber(L, world->scaleUp(point.velocity.x)); - lua_pushnumber(L, world->scaleUp(point.velocity.y)); + lua_pushnumber(L, Physics::scaleUp(point.velocity.x)); + lua_pushnumber(L, Physics::scaleUp(point.velocity.y)); return 2; } int Contact::getNormal(lua_State * L) { love::luax_assert_argc(L, 1, 1); - lua_pushnumber(L, world->scaleUp(point.normal.x)); - lua_pushnumber(L, world->scaleUp(point.normal.y)); + lua_pushnumber(L, Physics::scaleUp(point.normal.x)); + lua_pushnumber(L, Physics::scaleUp(point.normal.y)); return 2; } float Contact::getSeparation() const { - return world->scaleUp(point.separation); + return Physics::scaleUp(point.separation); } float Contact::getFriction() const diff --git a/src/modules/physics/box2d/DistanceJoint.cpp b/src/modules/physics/box2d/DistanceJoint.cpp index 8ffa8ca9c..3ecd450d8 100644 --- a/src/modules/physics/box2d/DistanceJoint.cpp +++ b/src/modules/physics/box2d/DistanceJoint.cpp @@ -23,6 +23,7 @@ // Module #include "Body.h" #include "World.h" +#include "Physics.h" namespace love { @@ -34,7 +35,7 @@ namespace box2d : Joint(body1, body2), joint(NULL) { b2DistanceJointDef def; - def.Initialize(body1->body, body2->body, world->scaleDown(b2Vec2(x1,y1)), world->scaleDown(b2Vec2(x2,y2))); + def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(x1,y1)), Physics::scaleDown(b2Vec2(x2,y2))); def.collideConnected = collideConnected; joint = (b2DistanceJoint*)createJoint(&def); } @@ -47,12 +48,12 @@ namespace box2d void DistanceJoint::setLength(float length) { - joint->SetLength(world->scaleDown(length)); + joint->SetLength(Physics::scaleDown(length)); } float DistanceJoint::getLength() const { - return world->scaleUp(joint->GetLength()); + return Physics::scaleUp(joint->GetLength()); } void DistanceJoint::setFrequency(float hz) diff --git a/src/modules/physics/box2d/FrictionJoint.cpp b/src/modules/physics/box2d/FrictionJoint.cpp index f606199dd..699bd478a 100644 --- a/src/modules/physics/box2d/FrictionJoint.cpp +++ b/src/modules/physics/box2d/FrictionJoint.cpp @@ -25,6 +25,7 @@ // Module #include "Body.h" #include "World.h" +#include "Physics.h" namespace love { @@ -36,7 +37,7 @@ namespace box2d : Joint(body1, body2), joint(NULL) { b2FrictionJointDef def; - def.Initialize(body1->body, body2->body, world->scaleDown(b2Vec2(x,y))); + def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(x,y))); def.collideConnected = collideConnected; joint = (b2FrictionJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/Joint.cpp b/src/modules/physics/box2d/Joint.cpp index 79cf039f0..1aa48f00d 100644 --- a/src/modules/physics/box2d/Joint.cpp +++ b/src/modules/physics/box2d/Joint.cpp @@ -26,6 +26,7 @@ // Module #include "Body.h" #include "World.h" +#include "Physics.h" namespace love { @@ -87,10 +88,10 @@ namespace box2d int Joint::getAnchors(lua_State * L) { - lua_pushnumber(L, world->scaleUp(joint->GetAnchorA().x)); - lua_pushnumber(L, world->scaleUp(joint->GetAnchorA().y)); - lua_pushnumber(L, world->scaleUp(joint->GetAnchorB().x)); - lua_pushnumber(L, world->scaleUp(joint->GetAnchorB().y)); + lua_pushnumber(L, Physics::scaleUp(joint->GetAnchorA().x)); + lua_pushnumber(L, Physics::scaleUp(joint->GetAnchorA().y)); + lua_pushnumber(L, Physics::scaleUp(joint->GetAnchorB().x)); + lua_pushnumber(L, Physics::scaleUp(joint->GetAnchorB().y)); return 4; } diff --git a/src/modules/physics/box2d/MouseJoint.cpp b/src/modules/physics/box2d/MouseJoint.cpp index 5fee8b23f..9ea217b6f 100644 --- a/src/modules/physics/box2d/MouseJoint.cpp +++ b/src/modules/physics/box2d/MouseJoint.cpp @@ -23,6 +23,7 @@ // Module #include "Body.h" #include "World.h" +#include "Physics.h" namespace love { @@ -38,7 +39,7 @@ namespace box2d def.bodyA = body1->world->getGroundBody(); def.bodyB = body1->body; def.maxForce = 1000.0f * body1->body->GetMass(); - def.target = body1->world->scaleDown(b2Vec2(x,y)); + def.target = Physics::scaleDown(b2Vec2(x,y)); joint = (b2MouseJoint*)createJoint(&def); } @@ -50,13 +51,13 @@ namespace box2d void MouseJoint::setTarget(float x, float y) { - joint->SetTarget(world->scaleDown(b2Vec2(x, y))); + joint->SetTarget(Physics::scaleDown(b2Vec2(x, y))); } int MouseJoint::getTarget(lua_State * L) { - lua_pushnumber(L, world->scaleUp(joint->GetTarget().x)); - lua_pushnumber(L, world->scaleUp(joint->GetTarget().y)); + lua_pushnumber(L, Physics::scaleUp(joint->GetTarget().x)); + lua_pushnumber(L, Physics::scaleUp(joint->GetTarget().y)); return 2; } diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index b8d781eed..6a270036e 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -193,6 +193,70 @@ namespace box2d { return new RopeJoint(body1, body2, x1, y1, x2, y2, maxLength, collideConnected); } + + + + void Physics::setMeter(int meter) + { + Physics::meter = meter; + } + + int Physics::getMeter() + { + return meter; + } + + void Physics::scaleDown(float & x, float & y) + { + x /= (float)meter; + y /= (float)meter; + } + + void Physics::scaleUp(float & x, float & y) + { + x *= (float)meter; + y *= (float)meter; + } + + float Physics::scaleDown(float f) + { + return f/(float)meter; + } + + float Physics::scaleUp(float f) + { + return f*(float)meter; + } + + b2Vec2 Physics::scaleDown(const b2Vec2 & v) + { + b2Vec2 t = v; + scaleDown(t.x, t.y); + return t; + } + + b2Vec2 Physics::scaleUp(const b2Vec2 & v) + { + b2Vec2 t = v; + scaleUp(t.x, t.y); + return t; + } + + b2AABB Physics::scaleDown(const b2AABB & aabb) + { + b2AABB t; + t.lowerBound = scaleDown(aabb.lowerBound); + t.upperBound = scaleDown(aabb.upperBound); + return t; + } + + b2AABB Physics::scaleUp(const b2AABB & aabb) + { + b2AABB t; + t.lowerBound = scaleUp(aabb.lowerBound); + t.upperBound = scaleUp(aabb.upperBound); + return t; + } } // box2d } // physics diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index ed2ca3d54..7dd2c6322 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -50,6 +50,11 @@ namespace box2d { class Physics : public Module { + private: + + // The length of one meter in pixels. + static int meter; + public: // Implements Module. @@ -242,6 +247,74 @@ namespace box2d * @param collideConnected Whether the connected bodies should collide with each other. Defaults to false. **/ RopeJoint * newRopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength, bool collideConnected); + + /** + * Sets the number of pixels in one meter. + * @param pixels The number of pixels in one meter. (1m ~= 3.3ft). + **/ + static void setMeter(int meter); + + /** + * Gets the number of pixels in one meter. + * @param pixels The number of pixels in one meter. (1m ~= 3.3ft). + **/ + static int getMeter(); + + /** + * Scales a value down according to the current meter in pixels. + * @param f The unscaled input value. + **/ + static float scaleDown(float f); + + /** + * Scales a value up according to the current meter in pixels. + * @param f The unscaled input value. + **/ + static float scaleUp(float f); + + /** + * Scales a point down according to the current meter + * in pixels, for instance x = x0/meter, y = x0/meter. + * @param x The x-coordinate of the point to scale. + * @param y The y-coordinate of the point to scale. + **/ + static void scaleDown(float & x, float & y); + + /** + * Scales a point up according to the current meter + * in pixels, for instance x = x0/meter, y = x0/meter. + * @param x The x-coordinate of the point to scale. + * @param y The y-coordinate of the point to scale. + **/ + static void scaleUp(float & x, float & y); + + /** + * Scales a b2Vec2 down according to the current meter in pixels. + * @param v The unscaled input vector. + * @return The scaled vector. + **/ + static b2Vec2 scaleDown(const b2Vec2 & v); + + /** + * Scales a b2Vec up according to the current meter in pixels. + * @param v The unscaled input vector. + * @return The scaled vector. + **/ + static b2Vec2 scaleUp(const b2Vec2 & v); + + /** + * Scales a b2AABB down according to the current meter in pixels. + * @param v The unscaled input AABB. + * @return The scaled AABB. + **/ + static b2AABB scaleDown(const b2AABB & aabb); + + /** + * Scales a b2AABB up according to the current meter in pixels. + * @param v The unscaled input AABB. + * @return The scaled AABB. + **/ + static b2AABB scaleUp(const b2AABB & aabb); }; // Physics diff --git a/src/modules/physics/box2d/PrismaticJoint.cpp b/src/modules/physics/box2d/PrismaticJoint.cpp index 57ae56b4b..17b6b1c7e 100644 --- a/src/modules/physics/box2d/PrismaticJoint.cpp +++ b/src/modules/physics/box2d/PrismaticJoint.cpp @@ -23,6 +23,7 @@ // Module #include "Body.h" #include "World.h" +#include "Physics.h" namespace love { @@ -35,7 +36,7 @@ namespace box2d { b2PrismaticJointDef def; - def.Initialize(body1->body, body2->body, world->scaleDown(b2Vec2(x,y)), b2Vec2(ax,ay)); + def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(x,y)), b2Vec2(ax,ay)); def.lowerTranslation = 0.0f; def.upperTranslation = 100.0f; def.enableLimit = true; @@ -51,12 +52,12 @@ namespace box2d float PrismaticJoint::getJointTranslation() const { - return world->scaleDown(joint->GetJointTranslation()); + return Physics::scaleDown(joint->GetJointTranslation()); } float PrismaticJoint::getJointSpeed() const { - return world->scaleDown(joint->GetJointSpeed()); + return Physics::scaleDown(joint->GetJointSpeed()); } void PrismaticJoint::enableMotor(bool motor) @@ -71,22 +72,22 @@ namespace box2d void PrismaticJoint::setMaxMotorForce(float force) { - joint->SetMaxMotorForce(world->scaleDown(force)); + joint->SetMaxMotorForce(Physics::scaleDown(force)); } void PrismaticJoint::setMotorSpeed(float speed) { - joint->SetMotorSpeed(world->scaleDown(speed)); + joint->SetMotorSpeed(Physics::scaleDown(speed)); } float PrismaticJoint::getMotorSpeed() const { - return world->scaleUp(joint->GetMotorSpeed()); + return Physics::scaleUp(joint->GetMotorSpeed()); } float PrismaticJoint::getMotorForce(float inv_dt) const { - return world->scaleUp(joint->GetMotorForce(inv_dt)); + return Physics::scaleUp(joint->GetMotorForce(inv_dt)); } void PrismaticJoint::enableLimit(bool limit) @@ -101,33 +102,33 @@ namespace box2d void PrismaticJoint::setUpperLimit(float limit) { - joint->SetLimits(joint->GetLowerLimit(), world->scaleDown(limit)); + joint->SetLimits(joint->GetLowerLimit(), Physics::scaleDown(limit)); } void PrismaticJoint::setLowerLimit(float limit) { - joint->SetLimits(world->scaleDown(limit), joint->GetUpperLimit()); + joint->SetLimits(Physics::scaleDown(limit), joint->GetUpperLimit()); } void PrismaticJoint::setLimits(float lower, float upper) { - joint->SetLimits(world->scaleDown(lower), world->scaleDown(upper)); + joint->SetLimits(Physics::scaleDown(lower), Physics::scaleDown(upper)); } float PrismaticJoint::getLowerLimit() const { - return world->scaleUp(joint->GetLowerLimit()); + return Physics::scaleUp(joint->GetLowerLimit()); } float PrismaticJoint::getUpperLimit() const { - return world->scaleUp(joint->GetUpperLimit()); + return Physics::scaleUp(joint->GetUpperLimit()); } int PrismaticJoint::getLimits(lua_State * L) { - lua_pushnumber(L, world->scaleUp(joint->GetLowerLimit())); - lua_pushnumber(L, world->scaleUp(joint->GetUpperLimit())); + lua_pushnumber(L, Physics::scaleUp(joint->GetLowerLimit())); + lua_pushnumber(L, Physics::scaleUp(joint->GetUpperLimit())); return 2; } diff --git a/src/modules/physics/box2d/PulleyJoint.cpp b/src/modules/physics/box2d/PulleyJoint.cpp index 387a75d41..84e449eaf 100644 --- a/src/modules/physics/box2d/PulleyJoint.cpp +++ b/src/modules/physics/box2d/PulleyJoint.cpp @@ -23,6 +23,7 @@ // Module #include "Body.h" #include "World.h" +#include "Physics.h" namespace love { @@ -34,8 +35,8 @@ namespace box2d : Joint(body1, body2), joint(NULL) { b2PulleyJointDef def; - def.Initialize(body1->body, body2->body, world->scaleDown(groundAnchor1), world->scaleDown(groundAnchor2), \ - world->scaleDown(anchor1), world->scaleDown(anchor2), ratio); + def.Initialize(body1->body, body2->body, Physics::scaleDown(groundAnchor1), Physics::scaleDown(groundAnchor2), \ + Physics::scaleDown(anchor1), Physics::scaleDown(anchor2), ratio); def.collideConnected = collideConnected; joint = (b2PulleyJoint*)createJoint(&def); @@ -49,21 +50,21 @@ namespace box2d int PulleyJoint::getGroundAnchors(lua_State * L) { - lua_pushnumber(L, world->scaleUp(joint->GetGroundAnchorA().x)); - lua_pushnumber(L, world->scaleUp(joint->GetGroundAnchorA().y)); - lua_pushnumber(L, world->scaleUp(joint->GetGroundAnchorB().x)); - lua_pushnumber(L, world->scaleUp(joint->GetGroundAnchorB().y)); + lua_pushnumber(L, Physics::scaleUp(joint->GetGroundAnchorA().x)); + lua_pushnumber(L, Physics::scaleUp(joint->GetGroundAnchorA().y)); + lua_pushnumber(L, Physics::scaleUp(joint->GetGroundAnchorB().x)); + lua_pushnumber(L, Physics::scaleUp(joint->GetGroundAnchorB().y)); return 4; } float PulleyJoint::getLength1() const { - return world->scaleUp(joint->GetLength1()); + return Physics::scaleUp(joint->GetLength1()); } float PulleyJoint::getLength2() const { - return world->scaleUp(joint->GetLength2()); + return Physics::scaleUp(joint->GetLength2()); } float PulleyJoint::getRatio() const diff --git a/src/modules/physics/box2d/RevoluteJoint.cpp b/src/modules/physics/box2d/RevoluteJoint.cpp index cf22a195a..1a6251c8d 100644 --- a/src/modules/physics/box2d/RevoluteJoint.cpp +++ b/src/modules/physics/box2d/RevoluteJoint.cpp @@ -25,6 +25,7 @@ // Module #include "Body.h" #include "World.h" +#include "Physics.h" namespace love { @@ -36,7 +37,7 @@ namespace box2d : Joint(body1, body2), joint(NULL) { b2RevoluteJointDef def; - def.Initialize(body1->body, body2->body, world->scaleDown(b2Vec2(x,y))); + def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(x,y))); def.collideConnected = collideConnected; joint = (b2RevoluteJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/RopeJoint.cpp b/src/modules/physics/box2d/RopeJoint.cpp index 6becef476..7516d7311 100644 --- a/src/modules/physics/box2d/RopeJoint.cpp +++ b/src/modules/physics/box2d/RopeJoint.cpp @@ -23,6 +23,7 @@ // Module #include "Body.h" #include "World.h" +#include "Physics.h" namespace love { @@ -36,9 +37,9 @@ namespace box2d b2RopeJointDef def; def.bodyA = body1->body; def.bodyB = body2->body; - def.localAnchorA = world->scaleDown(b2Vec2(x1,y1)); - def.localAnchorB = world->scaleDown(b2Vec2(x2,y2)); - def.maxLength = world->scaleDown(maxLength); + def.localAnchorA = Physics::scaleDown(b2Vec2(x1,y1)); + def.localAnchorB = Physics::scaleDown(b2Vec2(x2,y2)); + def.maxLength = Physics::scaleDown(maxLength); def.collideConnected = collideConnected; joint = (b2RopeJoint*)createJoint(&def); } @@ -51,7 +52,7 @@ namespace box2d float RopeJoint::getMaxLength() const { - return world->scaleUp(joint->GetMaxLength()); + return Physics::scaleUp(joint->GetMaxLength()); } diff --git a/src/modules/physics/box2d/Shape.cpp b/src/modules/physics/box2d/Shape.cpp index 177ebfad7..6b6b99e4e 100644 --- a/src/modules/physics/box2d/Shape.cpp +++ b/src/modules/physics/box2d/Shape.cpp @@ -23,6 +23,7 @@ // Module #include "Body.h" #include "World.h" +#include "Physics.h" // STD #include @@ -33,8 +34,8 @@ namespace physics { namespace box2d { - Shape::Shape(World * world) - : world(world), shape(NULL) + Shape::Shape() + : shape(NULL) { } @@ -62,7 +63,7 @@ namespace box2d float Shape::getRadius() const { - return world->scaleUp(shape->m_radius); + return Physics::scaleUp(shape->m_radius); } int Shape::getChildCount() const @@ -73,19 +74,19 @@ namespace box2d bool Shape::testPoint(float x, float y, float r, float px, float py) const { b2Vec2 point(px, py); - b2Transform transform(world->scaleDown(b2Vec2(x, y)), b2Rot(r)); - return shape->TestPoint(transform, world->scaleDown(point)); + b2Transform transform(Physics::scaleDown(b2Vec2(x, y)), b2Rot(r)); + return shape->TestPoint(transform, Physics::scaleDown(point)); } int Shape::rayCast(lua_State * L) const { - float p1x = world->scaleDown((float)luaL_checknumber(L, 1)); - float p1y = world->scaleDown((float)luaL_checknumber(L, 2)); - float p2x = world->scaleDown((float)luaL_checknumber(L, 3)); - float p2y = world->scaleDown((float)luaL_checknumber(L, 4)); + float p1x = Physics::scaleDown((float)luaL_checknumber(L, 1)); + float p1y = Physics::scaleDown((float)luaL_checknumber(L, 2)); + float p2x = Physics::scaleDown((float)luaL_checknumber(L, 3)); + float p2y = Physics::scaleDown((float)luaL_checknumber(L, 4)); float maxFraction = (float)luaL_checknumber(L, 5); - float x = world->scaleDown((float)luaL_checknumber(L, 6)); - float y = world->scaleDown((float)luaL_checknumber(L, 7)); + float x = Physics::scaleDown((float)luaL_checknumber(L, 6)); + float y = Physics::scaleDown((float)luaL_checknumber(L, 7)); float r = (float)luaL_checknumber(L, 8); int childIndex = (int)luaL_optint(L, 9, 0); b2RayCastInput input; @@ -95,22 +96,22 @@ namespace box2d b2Transform transform(b2Vec2(x, y), b2Rot(r)); b2RayCastOutput output; shape->RayCast(&output, input, transform, childIndex); - lua_pushnumber(L, world->scaleUp(output.normal.x)); - lua_pushnumber(L, world->scaleUp(output.normal.y)); + lua_pushnumber(L, Physics::scaleUp(output.normal.x)); + lua_pushnumber(L, Physics::scaleUp(output.normal.y)); lua_pushnumber(L, output.fraction); return 3; } int Shape::computeAABB(lua_State * L) const { - float x = world->scaleDown((float)luaL_checknumber(L, 1)); - float y = world->scaleDown((float)luaL_checknumber(L, 2)); + float x = Physics::scaleDown((float)luaL_checknumber(L, 1)); + float y = Physics::scaleDown((float)luaL_checknumber(L, 2)); float r = (float)luaL_checknumber(L, 3); int childIndex = (int)luaL_optint(L, 4, 0); b2Transform transform(b2Vec2(x, y), b2Rot(r)); b2AABB box; shape->ComputeAABB(&box, transform, childIndex); - box = world->scaleUp(box); + box = Physics::scaleUp(box); lua_pushnumber(L, box.lowerBound.x); lua_pushnumber(L, box.lowerBound.y); lua_pushnumber(L, box.upperBound.x); @@ -120,10 +121,10 @@ namespace box2d int Shape::computeMass(lua_State * L) const { - float density = world->scaleDown((float)luaL_checknumber(L, 1)); + float density = Physics::scaleDown((float)luaL_checknumber(L, 1)); b2MassData data; shape->ComputeMass(&data, density); - b2Vec2 center = world->scaleUp(data.center); + b2Vec2 center = Physics::scaleUp(data.center); lua_pushnumber(L, center.x); lua_pushnumber(L, center.y); lua_pushnumber(L, data.mass); diff --git a/src/modules/physics/box2d/Shape.h b/src/modules/physics/box2d/Shape.h index e89e10d2e..d388088c3 100644 --- a/src/modules/physics/box2d/Shape.h +++ b/src/modules/physics/box2d/Shape.h @@ -44,8 +44,6 @@ namespace box2d **/ class Shape : public love::physics::Shape { - private: - World * world; // We need a reference for scaling up/down protected: @@ -57,7 +55,7 @@ namespace box2d /** * Creates a Shape. **/ - Shape(World * world); + Shape(); virtual ~Shape(); diff --git a/src/modules/physics/box2d/WeldJoint.cpp b/src/modules/physics/box2d/WeldJoint.cpp index 1b07e04b9..1d1f39494 100644 --- a/src/modules/physics/box2d/WeldJoint.cpp +++ b/src/modules/physics/box2d/WeldJoint.cpp @@ -25,6 +25,7 @@ // Module #include "Body.h" #include "World.h" +#include "Physics.h" namespace love { @@ -36,7 +37,7 @@ namespace box2d : Joint(body1, body2), joint(NULL) { b2WeldJointDef def; - def.Initialize(body1->body, body2->body, world->scaleDown(b2Vec2(x,y))); + def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(x,y))); def.collideConnected = collideConnected; joint = (b2WeldJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/WheelJoint.cpp b/src/modules/physics/box2d/WheelJoint.cpp index 5ccd7099a..93e59a910 100644 --- a/src/modules/physics/box2d/WheelJoint.cpp +++ b/src/modules/physics/box2d/WheelJoint.cpp @@ -23,6 +23,7 @@ // Module #include "Body.h" #include "World.h" +#include "Physics.h" namespace love { @@ -35,7 +36,7 @@ namespace box2d { b2WheelJointDef def; - def.Initialize(body1->body, body2->body, world->scaleDown(b2Vec2(x,y)), b2Vec2(ax,ay)); + def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(x,y)), b2Vec2(ax,ay)); def.collideConnected = collideConnected; joint = (b2WheelJoint*)createJoint(&def); } @@ -48,12 +49,12 @@ namespace box2d float WheelJoint::getJointTranslation() const { - return world->scaleDown(joint->GetJointTranslation()); + return Physics::scaleDown(joint->GetJointTranslation()); } float WheelJoint::getJointSpeed() const { - return world->scaleDown(joint->GetJointSpeed()); + return Physics::scaleDown(joint->GetJointSpeed()); } void WheelJoint::enableMotor(bool motor) @@ -68,47 +69,47 @@ namespace box2d void WheelJoint::setMotorSpeed(float speed) { - joint->SetMotorSpeed(world->scaleDown(speed)); + joint->SetMotorSpeed(Physics::scaleDown(speed)); } float WheelJoint::getMotorSpeed() const { - return world->scaleUp(joint->GetMotorSpeed()); + return Physics::scaleUp(joint->GetMotorSpeed()); } void WheelJoint::setMaxMotorTorque(float torque) { - joint->SetMaxMotorTorque(world->scaleDown(torque)); + joint->SetMaxMotorTorque(Physics::scaleDown(torque)); } float WheelJoint::getMaxMotorTorque() const { - return world->scaleUp(joint->GetMaxMotorTorque()); + return Physics::scaleUp(joint->GetMaxMotorTorque()); } float WheelJoint::getMotorTorque(float inv_dt) const { - return world->scaleUp(joint->getMotorTorque(inv_dt)); + return Physics::scaleUp(joint->GetMotorTorque(inv_dt)); } void WheelJoint::setSpringFrequencyHz(float hz) { - joint->SetSpringFrequencyHz(world->scaleDown(hz)); + joint->SetSpringFrequencyHz(Physics::scaleDown(hz)); } float WheelJoint::getSpringFrequencyHz() const { - return world->scaleUp(joint->GetSpringFrequencyHz()); + return Physics::scaleUp(joint->GetSpringFrequencyHz()); } void WheelJoint::setSpringDampingRatio(float ratio) { - joint->SetSpringDampingRatio(world->scaleDown(ratio)); + joint->SetSpringDampingRatio(Physics::scaleDown(ratio)); } float WheelJoint::getSpringDampingRatio() const { - return world->scaleUp(joint->GetSpringDampingRatio()); + return Physics::scaleUp(joint->GetSpringDampingRatio()); } diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index bcb8582a7..d6de02db0 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -22,6 +22,7 @@ #include "Shape.h" #include "Contact.h" +#include "Physics.h" #include namespace love @@ -98,7 +99,7 @@ namespace box2d World::World(b2AABB aabb) : world(NULL), meter(DEFAULT_METER) { - world = new b2World(scaleDown(aabb), b2Vec2(0,0), true); + world = new b2World(Physics::scaleDown(aabb), b2Vec2(0,0), true); world->SetContactListener(this); b2BodyDef def; groundBody = world->CreateBody(def); @@ -107,7 +108,7 @@ namespace box2d World::World(b2AABB aabb, b2Vec2 gravity, bool sleep, int meter) : world(NULL), meter(meter) { - world = new b2World(scaleDown(aabb), scaleDown(gravity), sleep); + world = new b2World(Physics::scaleDown(aabb), Physics::scaleDown(gravity), sleep); world->SetContactListener(this); } @@ -183,12 +184,12 @@ namespace box2d void World::setGravity(float x, float y) { - world->SetGravity(scaleDown(b2Vec2(x, y))); + world->SetGravity(Physics::scaleDown(b2Vec2(x, y))); } int World::getGravity(lua_State * L) { - b2Vec2 v = scaleUp(world->m_gravity); + b2Vec2 v = Physics::scaleUp(world->m_gravity); lua_pushnumber(L, v.x); lua_pushnumber(L, v.y); return 2; @@ -213,68 +214,6 @@ namespace box2d { return world->GetJointCount(); } - - void World::setMeter(int meter) - { - this->meter = meter; - } - - int World::getMeter() const - { - return this->meter; - } - - void World::scaleDown(float & x, float & y) - { - x /= (float)meter; - y /= (float)meter; - } - - void World::scaleUp(float & x, float & y) - { - x *= (float)meter; - y *= (float)meter; - } - - float World::scaleDown(float f) - { - return f/(float)meter; - } - - float World::scaleUp(float f) - { - return f*(float)meter; - } - - b2Vec2 World::scaleDown(const b2Vec2 & v) - { - b2Vec2 t = v; - scaleDown(t.x, t.y); - return t; - } - - b2Vec2 World::scaleUp(const b2Vec2 & v) - { - b2Vec2 t = v; - scaleUp(t.x, t.y); - return t; - } - - b2AABB World::scaleDown(const b2AABB & aabb) - { - b2AABB t; - t.lowerBound = scaleDown(aabb.lowerBound); - t.upperBound = scaleDown(aabb.upperBound); - return t; - } - - b2AABB World::scaleUp(const b2AABB & aabb) - { - b2AABB t; - t.lowerBound = scaleUp(aabb.lowerBound); - t.upperBound = scaleUp(aabb.upperBound); - return t; - } b2Body * World::getGroundBody() { diff --git a/src/modules/physics/box2d/World.h b/src/modules/physics/box2d/World.h index 68ed12af1..238f19b7f 100644 --- a/src/modules/physics/box2d/World.h +++ b/src/modules/physics/box2d/World.h @@ -84,9 +84,6 @@ namespace box2d // Contact callbacks. ContactCallback add, persist, remove, result; - // The length of one meter in pixels. - int meter; - public: /** @@ -176,74 +173,6 @@ namespace box2d * @return The number of joints. **/ int getJointCount(); - - /** - * Sets the number of pixels in one meter. - * @param pixels The number of pixels in one meter. (1m ~= 3.3ft). - **/ - void setMeter(int meter); - - /** - * Gets the number of pixels in one meter. - * @param pixels The number of pixels in one meter. (1m ~= 3.3ft). - **/ - int getMeter() const; - - /** - * Scales a value down according to the current meter in pixels. - * @param f The unscaled input value. - **/ - float scaleDown(float f); - - /** - * Scales a value up according to the current meter in pixels. - * @param f The unscaled input value. - **/ - float scaleUp(float f); - - /** - * Scales a point down according to the current meter - * in pixels, for instance x = x0/meter, y = x0/meter. - * @param x The x-coordinate of the point to scale. - * @param y The y-coordinate of the point to scale. - **/ - void scaleDown(float & x, float & y); - - /** - * Scales a point up according to the current meter - * in pixels, for instance x = x0/meter, y = x0/meter. - * @param x The x-coordinate of the point to scale. - * @param y The y-coordinate of the point to scale. - **/ - void scaleUp(float & x, float & y); - - /** - * Scales a b2Vec2 down according to the current meter in pixels. - * @param v The unscaled input vector. - * @return The scaled vector. - **/ - b2Vec2 scaleDown(const b2Vec2 & v); - - /** - * Scales a b2Vec up according to the current meter in pixels. - * @param v The unscaled input vector. - * @return The scaled vector. - **/ - b2Vec2 scaleUp(const b2Vec2 & v); - - /** - * Scales a b2AABB down according to the current meter in pixels. - * @param v The unscaled input AABB. - * @return The scaled AABB. - **/ - b2AABB scaleDown(const b2AABB & aabb); - - /** - * Scales a b2AABB up according to the current meter in pixels. - * @param v The unscaled input AABB. - * @return The scaled AABB. - **/ - b2AABB scaleUp(const b2AABB & aabb); /** * Gets the ground body. diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index 90c75150e..ac39f6837 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -262,6 +262,19 @@ namespace box2d luax_newtype(L, "RopeJoint", PHYSICS_ROPE_JOINT_T, (void*)j); return 1; } + + int w_setMeter(lua_State * L) + { + int arg1 = luaL_checkint(L, 1); + Physics::setMeter(arg1); + return 0; + + } + int w_getMeter(lua_State * L) + { + lua_pushinteger(L, Physics::getMeter()); + return 1; + } // List of functions to wrap. static const luaL_Reg functions[] = { @@ -281,6 +294,8 @@ namespace box2d { "newWeldJoint", w_newWeldJoint }, { "newWheelJoint", w_newWheelJoint }, { "newRopeJoint", w_newRopeJoint }, + { "getMeter", w_getMeter }, + { "setMeter", w_setMeter }, { 0, 0 }, }; diff --git a/src/modules/physics/box2d/wrap_Physics.h b/src/modules/physics/box2d/wrap_Physics.h index c87684796..47e291807 100644 --- a/src/modules/physics/box2d/wrap_Physics.h +++ b/src/modules/physics/box2d/wrap_Physics.h @@ -65,6 +65,8 @@ namespace box2d int w_newWeldJoint(lua_State * L); int w_newWheelJoint(lua_State * L); int w_newRopeJoint(lua_State * L); + int w_setMeter(lua_State * L); + int w_getMeter(lua_State * L); extern "C" LOVE_EXPORT int luaopen_love_physics(lua_State * L); } // box2d diff --git a/src/modules/physics/box2d/wrap_World.cpp b/src/modules/physics/box2d/wrap_World.cpp index 457626c4c..7ab9e76de 100644 --- a/src/modules/physics/box2d/wrap_World.cpp +++ b/src/modules/physics/box2d/wrap_World.cpp @@ -98,21 +98,6 @@ namespace box2d lua_pushinteger(L, t->getJointCount()); return 1; } - - int w_World_setMeter(lua_State * L) - { - World * t = luax_checkworld(L, 1); - int arg1 = luaL_checkint(L, 2); - t->setMeter(arg1); - return 0; - - } - int w_World_getMeter(lua_State * L) - { - World * t = luax_checkworld(L, 1); - lua_pushinteger(L, t->getMeter()); - return 1; - } static const luaL_Reg functions[] = { { "update", w_World_update }, @@ -124,8 +109,6 @@ namespace box2d { "isAllowSleep", w_World_isAllowSleep }, { "getBodyCount", w_World_getBodyCount }, { "getJointCount", w_World_getJointCount }, - { "setMeter", w_World_setMeter }, - { "getMeter", w_World_getMeter }, { 0, 0 } }; diff --git a/src/modules/physics/box2d/wrap_World.h b/src/modules/physics/box2d/wrap_World.h index dbe64d913..0ba044d84 100644 --- a/src/modules/physics/box2d/wrap_World.h +++ b/src/modules/physics/box2d/wrap_World.h @@ -41,8 +41,6 @@ namespace box2d int w_World_isAllowSleep(lua_State * L); int w_World_getBodyCount(lua_State * L); int w_World_getJointCount(lua_State * L); - int w_World_setMeter(lua_State * L); - int w_World_getMeter(lua_State * L); int luaopen_world(lua_State * L); } // box2d From a56566818363e2394aac514a8715a260f45a835d Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Thu, 15 Sep 2011 17:17:28 -0400 Subject: [PATCH 16/78] Add ChainShape --HG-- branch : box2d-update --- .../macosx/love.xcodeproj/project.pbxproj | 12 ++ src/modules/physics/box2d/ChainShape.cpp | 95 ++++++++++++++ src/modules/physics/box2d/ChainShape.h | 101 +++++++++++++++ src/modules/physics/box2d/Physics.cpp | 34 ++++- src/modules/physics/box2d/Physics.h | 7 + src/modules/physics/box2d/wrap_ChainShape.cpp | 122 ++++++++++++++++++ src/modules/physics/box2d/wrap_ChainShape.h | 50 +++++++ src/modules/physics/box2d/wrap_Physics.cpp | 7 + src/modules/physics/box2d/wrap_Physics.h | 2 + 9 files changed, 429 insertions(+), 1 deletion(-) create mode 100644 src/modules/physics/box2d/ChainShape.cpp create mode 100644 src/modules/physics/box2d/ChainShape.h create mode 100644 src/modules/physics/box2d/wrap_ChainShape.cpp create mode 100644 src/modules/physics/box2d/wrap_ChainShape.h diff --git a/platform/macosx/love.xcodeproj/project.pbxproj b/platform/macosx/love.xcodeproj/project.pbxproj index 70382453f..befd5e9e1 100644 --- a/platform/macosx/love.xcodeproj/project.pbxproj +++ b/platform/macosx/love.xcodeproj/project.pbxproj @@ -211,6 +211,8 @@ A9CF0E8610B9EB1000E6F37E /* utf8.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9CF0E8510B9EB1000E6F37E /* utf8.cpp */; }; A9D1D20214224E1300A8BC2F /* RopeJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D1D20114224E1300A8BC2F /* RopeJoint.cpp */; }; A9D1D2041422578C00A8BC2F /* wrap_RopeJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D1D2031422578A00A8BC2F /* wrap_RopeJoint.cpp */; }; + A9D1D20A1422959100A8BC2F /* ChainShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D1D2091422959100A8BC2F /* ChainShape.cpp */; }; + A9D1D20D14229B6500A8BC2F /* wrap_ChainShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D1D20C14229B5800A8BC2F /* wrap_ChainShape.cpp */; }; A9D307EA106635C3004FEDF8 /* physfs.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9D307E9106635C3004FEDF8 /* physfs.framework */; }; A9D307F2106635D3004FEDF8 /* physfs.framework in Copy Frameworks */ = {isa = PBXBuildFile; fileRef = A9D307E9106635C3004FEDF8 /* physfs.framework */; }; A9DEC1C11046EFA70049C70C /* Love.icns in Resources */ = {isa = PBXBuildFile; fileRef = A9DEC1BF1046EFA60049C70C /* Love.icns */; }; @@ -675,6 +677,10 @@ A9D1D20114224E1300A8BC2F /* RopeJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RopeJoint.cpp; sourceTree = ""; }; A9D1D2031422578A00A8BC2F /* wrap_RopeJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_RopeJoint.cpp; sourceTree = ""; }; A9D1D2051422579500A8BC2F /* wrap_RopeJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_RopeJoint.h; sourceTree = ""; }; + A9D1D2091422959100A8BC2F /* ChainShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ChainShape.cpp; sourceTree = ""; }; + A9D1D20B142295A800A8BC2F /* ChainShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ChainShape.h; sourceTree = ""; }; + A9D1D20C14229B5800A8BC2F /* wrap_ChainShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_ChainShape.cpp; sourceTree = ""; }; + A9D1D20E14229B7300A8BC2F /* wrap_ChainShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_ChainShape.h; sourceTree = ""; }; A9D307E9106635C3004FEDF8 /* physfs.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = physfs.framework; path = /Library/Frameworks/physfs.framework; sourceTree = ""; }; A9DEC1BF1046EFA60049C70C /* Love.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; name = Love.icns; path = icons/Love.icns; sourceTree = ""; }; A9DEC1C01046EFA70049C70C /* LoveDocument.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; name = LoveDocument.icns; path = icons/LoveDocument.icns; sourceTree = ""; }; @@ -1201,6 +1207,8 @@ A93E6AEB10420AC7007D418B /* Body.cpp */, A93E6AEC10420AC7007D418B /* Body.h */, A986EBC3132CE6D800F048C8 /* Box2D */, + A9D1D2091422959100A8BC2F /* ChainShape.cpp */, + A9D1D20B142295A800A8BC2F /* ChainShape.h */, A93E6AED10420AC7007D418B /* CircleShape.cpp */, A93E6AEE10420AC7007D418B /* CircleShape.h */, A93E6AEF10420AC7007D418B /* Contact.cpp */, @@ -1242,6 +1250,8 @@ A93E6B4F10420ACA007D418B /* World.h */, A93E6B5010420ACA007D418B /* wrap_Body.cpp */, A93E6B5110420ACA007D418B /* wrap_Body.h */, + A9D1D20C14229B5800A8BC2F /* wrap_ChainShape.cpp */, + A9D1D20E14229B7300A8BC2F /* wrap_ChainShape.h */, A93E6B5210420ACA007D418B /* wrap_CircleShape.cpp */, A93E6B5310420ACA007D418B /* wrap_CircleShape.h */, A93E6B5410420ACA007D418B /* wrap_Contact.cpp */, @@ -1810,6 +1820,8 @@ A96F41A71412C92B0067FE9A /* wrap_EdgeShape.cpp in Sources */, A9D1D20214224E1300A8BC2F /* RopeJoint.cpp in Sources */, A9D1D2041422578C00A8BC2F /* wrap_RopeJoint.cpp in Sources */, + A9D1D20A1422959100A8BC2F /* ChainShape.cpp in Sources */, + A9D1D20D14229B6500A8BC2F /* wrap_ChainShape.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/src/modules/physics/box2d/ChainShape.cpp b/src/modules/physics/box2d/ChainShape.cpp new file mode 100644 index 000000000..1e74d5177 --- /dev/null +++ b/src/modules/physics/box2d/ChainShape.cpp @@ -0,0 +1,95 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#include "ChainShape.h" + +// Module +#include "Body.h" +#include "World.h" +#include "Physics.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + ChainShape::ChainShape(b2ChainShape * c, bool loop) + : loop(loop) + { + shape = c; + } + + ChainShape::~ChainShape() + { + } + + void ChainShape::setNextVertex(float x, float y) + { + if (loop) { + throw love::Exception("Physics error: Can't call setNextVertex on a loop ChainShape"); + return; + } + b2Vec2 v(x, y); + b2ChainShape * c = (b2ChainShape *)shape; + c->SetNextVertex(Physics::scaleDown(v)); + } + + void ChainShape::setPrevVertex(float x, float y) + { + if (loop) { + throw love::Exception("Physics error: Can't call setPrevVertex on a loop ChainShape"); + return; + } + b2Vec2 v(x, y); + b2ChainShape * c = (b2ChainShape *)shape; + c->SetNextVertex(Physics::scaleDown(v)); + } + + EdgeShape * ChainShape::getChildEdge(int index) const + { + b2ChainShape * c = (b2ChainShape *)shape; + b2EdgeShape e; + c->GetChildEdge(&e, index); + return new EdgeShape(&e); + } + + int ChainShape::getVertexCount() const + { + b2ChainShape * c = (b2ChainShape *)shape; + return c->GetVertexCount(); + } + + b2Vec2 ChainShape::getVertex(int index) const + { + b2ChainShape * c = (b2ChainShape *)shape; + const b2Vec2 & v = c->GetVertex(index); + return Physics::scaleUp(v); + } + + const b2Vec2 * ChainShape::getVertices() const + { + b2ChainShape * c = (b2ChainShape *)shape; + return c->GetVertices(); + } + +} // box2d +} // physics +} // love diff --git a/src/modules/physics/box2d/ChainShape.h b/src/modules/physics/box2d/ChainShape.h new file mode 100644 index 000000000..c96f4e228 --- /dev/null +++ b/src/modules/physics/box2d/ChainShape.h @@ -0,0 +1,101 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BOX2D_CHAIN_SHAPE_H +#define LOVE_PHYSICS_BOX2D_CHAIN_SHAPE_H + +// Module +#include "Shape.h" +#include "EdgeShape.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + /** + * A ChainShape is a freeform collection of line segments. + **/ + class ChainShape : public Shape + { + private: + // True if this ChainShape is a loop. + bool loop; + + public: + + /** + * Create a new ChainShape from a Box2D chain shape. + * @param c The chain shape. + **/ + ChainShape(b2ChainShape * c, bool loop = false); + + virtual ~ChainShape(); + + /** + * Establish connectivity to a vertex that follows + * the last vertex. Fails if called on a loop. + * @param x The x-coordinate of the vertex. + * @param y The y-coordinate of the vertex. + **/ + void setNextVertex(float x, float y); + + /** + * Establish connectivity to a vertex that precedes + * the first vertex. Fails if called on a loop. + * @param x The x-coordinate of the vertex. + * @param y The y-coordinate of the vertex. + **/ + void setPrevVertex(float x, float y); + + /** + * Returns a child EdgeShape. + * @param index The index of the child shape. + * @returns The specified child. + **/ + EdgeShape * getChildEdge(int index) const; + + /** + * Returns the number of vertices in the shape. + * @returns The number of vertices in the shape. + **/ + int getVertexCount() const; + + /** + * Returns the vertex at the given index. + * @param index The index of the vertex. + * @returns The specified vertex. + **/ + b2Vec2 getVertex(int index) const; + + /** + * Returns all of the vertices. + * @returns The vertices the shape comprises. + **/ + const b2Vec2 * getVertices() const; + + }; + +} // box2d +} // physics +} // love + +#endif // LOVE_PHYSICS_BOX2D_CHAIN_SHAPE_H diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 6a270036e..a9887cf78 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -128,7 +128,7 @@ namespace box2d if(count < 3) return luaL_error(L, "Polygon degenerated to less than three points."); - b2Vec2 vecs[] = new b2vec2[count]; + b2Vec2 * vecs = new b2Vec2[count]; for (int i = 0; i < count; i++) { vecs[i].Set(convex_hull[i].x, convex_hull[i].y); @@ -143,6 +143,38 @@ namespace box2d return 1; } + + int Physics::newChainShape(lua_State * L) + { + int argc = lua_gettop(L)-1; // first argument is looping + int vcount = (int)argc/2; + + b2ChainShape s; + + bool loop = luax_toboolean(L, 1); + + b2Vec2 * vecs = new b2Vec2[vcount]; + + for(int i = 0;i(L, idx, "ChainShape", PHYSICS_CHAIN_SHAPE_T); + } + + int w_ChainShape_setNextVertex(lua_State * L) + { + ChainShape * c = luax_checkchainshape(L, 1); + float x = (float)luaL_checknumber(L, 2); + float y = (float)luaL_checknumber(L, 3); + c->setNextVertex(x, y); + return 0; + } + + int w_ChainShape_setPrevVertex(lua_State * L) + { + ChainShape * c = luax_checkchainshape(L, 1); + float x = (float)luaL_checknumber(L, 2); + float y = (float)luaL_checknumber(L, 3); + c->setPrevVertex(x, y); + return 0; + } + + int w_ChainShape_getChildEdge(lua_State * L) + { + ChainShape * c = luax_checkchainshape(L, 1); + int index = luaL_checkint(L, 2); + EdgeShape * e = c->getChildEdge(index); + luax_newtype(L, "EdgeShape", PHYSICS_EDGE_SHAPE_T, e); + return 1; + } + + int w_ChainShape_getVertexCount(lua_State * L) + { + ChainShape * c = luax_checkchainshape(L, 1); + int count = c->getVertexCount(); + lua_pushinteger(L, count); + return 1; + } + + int w_ChainShape_getVertex(lua_State * L) + { + ChainShape * c = luax_checkchainshape(L, 1); + int index = luaL_checkint(L, 2); + b2Vec2 v = c->getVertex(index); + lua_pushnumber(L, v.x); + lua_pushnumber(L, v.y); + return 2; + } + + int w_ChainShape_getVertices(lua_State * L) + { + ChainShape * c = luax_checkchainshape(L, 1); + const b2Vec2 * verts = c->getVertices(); + int count = c->getVertexCount(); + lua_createtable(L, count*2, 0); + for (int i = 0; i < count; i++) { + b2Vec2 v = Physics::scaleUp(verts[i]); + lua_pushnumber(L, v.x); + lua_rawseti(L, -2, i*2+1); + lua_pushnumber(L, v.y); + lua_rawseti(L, -2, i*2+2); + } + return 1; + } + + static const luaL_Reg functions[] = { + { "setNextVertex", w_ChainShape_setNextVertex }, + { "setPrevVertex", w_ChainShape_setPrevVertex }, + { "getChildEdge", w_ChainShape_getChildEdge }, + { "getVertexCount", w_ChainShape_getVertexCount }, + { "getVertex", w_ChainShape_getVertex }, + { "getVertices", w_ChainShape_getVertices }, + // From Shape. + { "getType", w_Shape_getType }, + { "getRadius", w_Shape_getRadius }, + { "getChildCount", w_Shape_getChildCount }, + { "testPoint", w_Shape_testPoint }, + { "rayCast", w_Shape_rayCast }, + { "computeAABB", w_Shape_computeAABB }, + { "computeMass", w_Shape_computeMass }, + { "destroy", w_Shape_destroy }, + { 0, 0 } + }; + + int luaopen_chainshape(lua_State * L) + { + return luax_register_type(L, "ChainShape", functions); + } + +} // box2d +} // physics +} // love diff --git a/src/modules/physics/box2d/wrap_ChainShape.h b/src/modules/physics/box2d/wrap_ChainShape.h new file mode 100644 index 000000000..88989d063 --- /dev/null +++ b/src/modules/physics/box2d/wrap_ChainShape.h @@ -0,0 +1,50 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BOX2D_WRAP_CHAIN_SHAPE_H +#define LOVE_PHYSICS_BOX2D_WRAP_CHAIN_SHAPE_H + +// LOVE +#include +#include "wrap_Shape.h" +#include "ChainShape.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + ChainShape * luax_checkchainshape(lua_State * L, int idx); + + int w_ChainShape_setNextVertex(lua_State * L); + int w_ChainShape_setPrevVertex(lua_State * L); + int w_ChainShape_getChildEdge(lua_State * L); + int w_ChainShape_getVertexCount(lua_State * L); + int w_ChainShape_getVertex(lua_State * L); + int w_ChainShape_getVertices(lua_State * L); + + int luaopen_chainshape(lua_State * L); + +} // box2d +} // physics +} // love + +#endif // LOVE_PHYSICS_BOX2D_WRAP_CHAIN_SHAPE_H diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index ac39f6837..111a46d39 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -127,6 +127,11 @@ namespace box2d { return instance->newPolygonShape(L); } + + int w_newChainShape(lua_State * L) + { + return instance->newChainShape(L); + } int w_newDistanceJoint(lua_State * L) { @@ -284,6 +289,7 @@ namespace box2d { "newRectangleShape", w_newRectangleShape }, { "newPolygonShape", w_newPolygonShape }, { "newEdgeShape", w_newEdgeShape }, + { "newChainShape", w_newChainShape }, { "newDistanceJoint", w_newDistanceJoint }, { "newMouseJoint", w_newMouseJoint }, { "newRevoluteJoint", w_newRevoluteJoint }, @@ -307,6 +313,7 @@ namespace box2d luaopen_circleshape, luaopen_polygonshape, luaopen_edgeshape, + luaopen_chainshape, luaopen_joint, luaopen_mousejoint, luaopen_distancejoint, diff --git a/src/modules/physics/box2d/wrap_Physics.h b/src/modules/physics/box2d/wrap_Physics.h index 47e291807..29d7e2e58 100644 --- a/src/modules/physics/box2d/wrap_Physics.h +++ b/src/modules/physics/box2d/wrap_Physics.h @@ -31,6 +31,7 @@ #include "wrap_CircleShape.h" #include "wrap_PolygonShape.h" #include "wrap_EdgeShape.h" +#include "wrap_ChainShape.h" #include "wrap_Joint.h" #include "wrap_MouseJoint.h" #include "wrap_DistanceJoint.h" @@ -55,6 +56,7 @@ namespace box2d int w_newRectangleShape(lua_State * L); int w_newPolygonShape(lua_State * L); int w_newEdgeShape(lua_State * L); + int w_newChainShape(lua_State * L); int w_newDistanceJoint(lua_State * L); int w_newMouseJoint(lua_State * L); int w_newRevoluteJoint(lua_State * L); From 3c7310e76d45f9f0a181997b07d3c293b9c09573 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Fri, 23 Sep 2011 16:09:18 -0400 Subject: [PATCH 17/78] Update to Box2D 2.2.1 (stop updating, Erin!) --HG-- branch : box2d-update --- src/modules/physics/box2d/Box2D/Box2D.h | 2 - .../Box2D/Collision/Shapes/b2ChainShape.h | 15 -- .../Box2D/Collision/Shapes/b2EdgeShape.h | 4 + .../box2d/Box2D/Collision/b2Distance.cpp | 10 +- .../physics/box2d/Box2D/Common/b2Math.cpp | 41 ++++ .../physics/box2d/Box2D/Common/b2Math.h | 14 ++ .../physics/box2d/Box2D/Common/b2Settings.cpp | 13 +- .../physics/box2d/Box2D/Common/b2Settings.h | 3 + .../physics/box2d/Box2D/Common/b2Timer.cpp | 4 +- .../physics/box2d/Box2D/Common/b2Timer.h | 2 +- .../Box2D/Dynamics/Joints/b2DistanceJoint.cpp | 26 ++- .../Box2D/Dynamics/Joints/b2DistanceJoint.h | 20 +- .../Box2D/Dynamics/Joints/b2FrictionJoint.cpp | 16 ++ .../Box2D/Dynamics/Joints/b2FrictionJoint.h | 9 + .../Box2D/Dynamics/Joints/b2GearJoint.cpp | 45 +++-- .../box2d/Box2D/Dynamics/Joints/b2GearJoint.h | 12 ++ .../box2d/Box2D/Dynamics/Joints/b2Joint.cpp | 1 + .../box2d/Box2D/Dynamics/Joints/b2Joint.h | 10 +- .../Box2D/Dynamics/Joints/b2MouseJoint.h | 3 + .../Dynamics/Joints/b2PrismaticJoint.cpp | 68 +++++-- .../Box2D/Dynamics/Joints/b2PrismaticJoint.h | 26 ++- .../Box2D/Dynamics/Joints/b2PulleyJoint.cpp | 22 +++ .../Box2D/Dynamics/Joints/b2PulleyJoint.h | 5 + .../Box2D/Dynamics/Joints/b2RevoluteJoint.cpp | 21 ++ .../Box2D/Dynamics/Joints/b2RevoluteJoint.h | 19 +- .../Box2D/Dynamics/Joints/b2RopeJoint.cpp | 15 ++ .../box2d/Box2D/Dynamics/Joints/b2RopeJoint.h | 12 +- .../Box2D/Dynamics/Joints/b2WeldJoint.cpp | 179 ++++++++++++++---- .../box2d/Box2D/Dynamics/Joints/b2WeldJoint.h | 42 +++- .../Box2D/Dynamics/Joints/b2WheelJoint.cpp | 21 +- .../Box2D/Dynamics/Joints/b2WheelJoint.h | 22 ++- .../physics/box2d/Box2D/Dynamics/b2Body.cpp | 30 +++ .../physics/box2d/Box2D/Dynamics/b2Body.h | 5 +- .../box2d/Box2D/Dynamics/b2ContactManager.cpp | 20 +- .../box2d/Box2D/Dynamics/b2Fixture.cpp | 75 ++++++++ .../physics/box2d/Box2D/Dynamics/b2Fixture.h | 13 +- .../physics/box2d/Box2D/Dynamics/b2TimeStep.h | 24 +-- .../physics/box2d/Box2D/Dynamics/b2World.cpp | 85 ++++++++- .../physics/box2d/Box2D/Dynamics/b2World.h | 14 +- 39 files changed, 815 insertions(+), 153 deletions(-) diff --git a/src/modules/physics/box2d/Box2D/Box2D.h b/src/modules/physics/box2d/Box2D/Box2D.h index 817cd1ccf..66d221742 100755 --- a/src/modules/physics/box2d/Box2D/Box2D.h +++ b/src/modules/physics/box2d/Box2D/Box2D.h @@ -64,6 +64,4 @@ For discussion please visit http://box2d.org/forum #include #include -#include - #endif diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.h b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.h index 34593e2b8..6aa41ea41 100755 --- a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.h +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.h @@ -79,21 +79,6 @@ public: /// @see b2Shape::ComputeMass void ComputeMass(b2MassData* massData, float32 density) const; - /// Get the number of vertices. - int32 GetVertexCount() const { return m_count; } - - /// Get the vertices (read-only). - const b2Vec2& GetVertex(int32 index) const - { - b2Assert(0 <= index && index < m_count); - return m_vertices[index]; - } - - /// Get the vertices (read-only). - const b2Vec2* GetVertices() const { return m_vertices; } - -protected: - /// The vertices. Owned by this class. b2Vec2* m_vertices; diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.h b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.h index 780eb2c5c..99f822bec 100755 --- a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.h +++ b/src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.h @@ -63,6 +63,10 @@ inline b2EdgeShape::b2EdgeShape() { m_type = e_edge; m_radius = b2_polygonRadius; + m_vertex0.x = 0.0f; + m_vertex0.y = 0.0f; + m_vertex3.x = 0.0f; + m_vertex3.y = 0.0f; m_hasVertex0 = false; m_hasVertex3 = false; } diff --git a/src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp b/src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp index 2bfb7598a..1010c8c0e 100755 --- a/src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp +++ b/src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp @@ -50,16 +50,16 @@ void b2DistanceProxy::Set(const b2Shape* shape, int32 index) case b2Shape::e_chain: { const b2ChainShape* chain = (b2ChainShape*)shape; - b2Assert(0 <= index && index < chain->GetVertexCount()); + b2Assert(0 <= index && index < chain->m_count); - m_buffer[0] = chain->GetVertex(index); - if (index + 1 < chain->GetVertexCount()) + m_buffer[0] = chain->m_vertices[index]; + if (index + 1 < chain->m_count) { - m_buffer[1] = chain->GetVertex(index + 1); + m_buffer[1] = chain->m_vertices[index + 1]; } else { - m_buffer[1] = chain->GetVertex(0); + m_buffer[1] = chain->m_vertices[0]; } m_vertices = m_buffer; diff --git a/src/modules/physics/box2d/Box2D/Common/b2Math.cpp b/src/modules/physics/box2d/Box2D/Common/b2Math.cpp index b06111dc4..4974fe187 100755 --- a/src/modules/physics/box2d/Box2D/Common/b2Math.cpp +++ b/src/modules/physics/box2d/Box2D/Common/b2Math.cpp @@ -51,3 +51,44 @@ b2Vec2 b2Mat33::Solve22(const b2Vec2& b) const x.y = det * (a11 * b.y - a21 * b.x); return x; } + +/// +void b2Mat33::GetInverse22(b2Mat33* M) const +{ + float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; + float32 det = a * d - b * c; + if (det != 0.0f) + { + det = 1.0f / det; + } + + M->ex.x = det * d; M->ey.x = -det * b; M->ex.z = 0.0f; + M->ex.y = -det * c; M->ey.y = det * a; M->ey.z = 0.0f; + M->ez.x = 0.0f; M->ez.y = 0.0f; M->ez.z = 0.0f; +} + +/// Returns the zero matrix if singular. +void b2Mat33::GetSymInverse33(b2Mat33* M) const +{ + float32 det = b2Dot(ex, b2Cross(ey, ez)); + if (det != 0.0f) + { + det = 1.0f / det; + } + + float32 a11 = ex.x, a12 = ey.x, a13 = ez.x; + float32 a22 = ey.y, a23 = ez.y; + float32 a33 = ez.z; + + M->ex.x = det * (a22 * a33 - a23 * a23); + M->ex.y = det * (a13 * a23 - a12 * a33); + M->ex.z = det * (a12 * a23 - a13 * a22); + + M->ey.x = M->ex.y; + M->ey.y = det * (a11 * a33 - a13 * a13); + M->ey.z = det * (a13 * a12 - a11 * a23); + + M->ez.x = M->ex.z; + M->ez.y = M->ey.z; + M->ez.z = det * (a11 * a22 - a12 * a12); +} diff --git a/src/modules/physics/box2d/Box2D/Common/b2Math.h b/src/modules/physics/box2d/Box2D/Common/b2Math.h index fdcd939de..9808258bf 100755 --- a/src/modules/physics/box2d/Box2D/Common/b2Math.h +++ b/src/modules/physics/box2d/Box2D/Common/b2Math.h @@ -295,6 +295,14 @@ struct b2Mat33 /// 2-by-2 matrix equation. b2Vec2 Solve22(const b2Vec2& b) const; + /// Get the inverse of this matrix as a 2-by-2. + /// Returns the zero matrix if singular. + void GetInverse22(b2Mat33* M) const; + + /// Get the symmetric inverse of this matrix as a 3-by-3. + /// Returns the zero matrix if singular. + void GetSymInverse33(b2Mat33* M) const; + b2Vec3 ex, ey, ez; }; @@ -533,6 +541,12 @@ inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v) return v.x * A.ex + v.y * A.ey + v.z * A.ez; } +/// Multiply a matrix times a vector. +inline b2Vec2 b2Mul22(const b2Mat33& A, const b2Vec2& v) +{ + return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); +} + /// Multiply two rotations: q * r inline b2Rot b2Mul(const b2Rot& q, const b2Rot& r) { diff --git a/src/modules/physics/box2d/Box2D/Common/b2Settings.cpp b/src/modules/physics/box2d/Box2D/Common/b2Settings.cpp index 97f5283f4..05a322305 100755 --- a/src/modules/physics/box2d/Box2D/Common/b2Settings.cpp +++ b/src/modules/physics/box2d/Box2D/Common/b2Settings.cpp @@ -18,8 +18,10 @@ #include #include +#include +#include -b2Version b2_version = {2, 2, 0}; +b2Version b2_version = {2, 2, 1}; // Memory allocators. Modify these to use your own allocator. void* b2Alloc(int32 size) @@ -31,3 +33,12 @@ void b2Free(void* mem) { free(mem); } + +// You can modify this to use your logging facility. +void b2Log(const char* string, ...) +{ + va_list args; + va_start(args, string); + vprintf(string, args); + va_end(args); +} \ No newline at end of file diff --git a/src/modules/physics/box2d/Box2D/Common/b2Settings.h b/src/modules/physics/box2d/Box2D/Common/b2Settings.h index eabc526d0..7e0a165b5 100755 --- a/src/modules/physics/box2d/Box2D/Common/b2Settings.h +++ b/src/modules/physics/box2d/Box2D/Common/b2Settings.h @@ -132,6 +132,9 @@ void* b2Alloc(int32 size); /// If you implement b2Alloc, you should also implement this function. void b2Free(void* mem); +/// Logging function. +void b2Log(const char* string, ...); + /// Version numbering scheme. /// See http://en.wikipedia.org/wiki/Software_versioning struct b2Version diff --git a/src/modules/physics/box2d/Box2D/Common/b2Timer.cpp b/src/modules/physics/box2d/Box2D/Common/b2Timer.cpp index b1863c296..ea3479f11 100755 --- a/src/modules/physics/box2d/Box2D/Common/b2Timer.cpp +++ b/src/modules/physics/box2d/Box2D/Common/b2Timer.cpp @@ -18,11 +18,11 @@ #include -#if defined(WIN32) +#if defined(_WIN32) float64 b2Timer::s_invFrequency = 0.0f; -#include +#include b2Timer::b2Timer() { diff --git a/src/modules/physics/box2d/Box2D/Common/b2Timer.h b/src/modules/physics/box2d/Box2D/Common/b2Timer.h index 678f6ffe4..19bde287f 100755 --- a/src/modules/physics/box2d/Box2D/Common/b2Timer.h +++ b/src/modules/physics/box2d/Box2D/Common/b2Timer.h @@ -35,7 +35,7 @@ public: private: -#if defined(WIN32) +#if defined(_WIN32) float64 m_start; static float64 s_invFrequency; #elif defined(__linux__) || defined (__APPLE__) diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp index 7b0e2a507..1ced7d9de 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp @@ -123,8 +123,13 @@ void b2DistanceJoint::InitVelocityConstraints(const b2SolverData& data) m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; m_bias = C * h * k * m_gamma; - m_mass = invMass + m_gamma; - m_mass = m_mass != 0.0f ? 1.0f / m_mass : 0.0f; + invMass += m_gamma; + m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; + } + else + { + m_gamma = 0.0f; + m_bias = 0.0f; } if (data.step.warmStarting) @@ -236,3 +241,20 @@ float32 b2DistanceJoint::GetReactionTorque(float32 inv_dt) const B2_NOT_USED(inv_dt); return 0.0f; } + +void b2DistanceJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2DistanceJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.length = %.15lef;\n", m_length); + b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); + b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h index a8d35a5e6..9d0528b95 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h @@ -44,16 +44,17 @@ struct b2DistanceJointDef : public b2JointDef void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchorA, const b2Vec2& anchorB); - /// The local anchor point relative to body1's origin. + /// The local anchor point relative to bodyA's origin. b2Vec2 localAnchorA; - /// The local anchor point relative to body2's origin. + /// The local anchor point relative to bodyB's origin. b2Vec2 localAnchorB; /// The natural length between the anchor points. float32 length; - /// The mass-spring-damper frequency in Hertz. + /// The mass-spring-damper frequency in Hertz. A value of 0 + /// disables softness. float32 frequencyHz; /// The damping ratio. 0 = no damping, 1 = critical damping. @@ -78,19 +79,28 @@ public: /// Unit is N*m. This is always zero for a distance joint. float32 GetReactionTorque(float32 inv_dt) const; + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + /// Set/get the natural length. /// Manipulating the length can lead to non-physical behavior when the frequency is zero. void SetLength(float32 length); float32 GetLength() const; - // Set/get frequency in Hz. + /// Set/get frequency in Hz. void SetFrequency(float32 hz); float32 GetFrequency() const; - // Set/get damping ratio. + /// Set/get damping ratio. void SetDampingRatio(float32 ratio); float32 GetDampingRatio() const; + /// Dump joint to dmLog + void Dump(); + protected: friend class b2Joint; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp index 8c363e6a1..075e72bb4 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp @@ -233,3 +233,19 @@ float32 b2FrictionJoint::GetMaxTorque() const { return m_maxTorque; } + +void b2FrictionJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2FrictionJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.maxForce = %.15lef;\n", m_maxForce); + b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h index 3e72be2fe..785d9ac15 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h @@ -61,6 +61,12 @@ public: b2Vec2 GetReactionForce(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const; + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + /// Set the maximum friction force in N. void SetMaxForce(float32 force); @@ -73,6 +79,9 @@ public: /// Get the maximum friction torque in N*m. float32 GetMaxTorque() const; + /// Dump joint to dmLog + void Dump(); + protected: friend class b2Joint; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp index cff95f2bc..201f01233 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp @@ -44,16 +44,21 @@ b2GearJoint::b2GearJoint(const b2GearJointDef* def) : b2Joint(def) { - m_typeA = def->joint1->GetType(); - m_typeB = def->joint2->GetType(); + m_joint1 = def->joint1; + m_joint2 = def->joint2; + + m_typeA = m_joint1->GetType(); + m_typeB = m_joint2->GetType(); b2Assert(m_typeA == e_revoluteJoint || m_typeA == e_prismaticJoint); b2Assert(m_typeB == e_revoluteJoint || m_typeB == e_prismaticJoint); float32 coordinateA, coordinateB; - m_bodyC = def->joint1->GetBodyA(); - m_bodyA = def->joint1->GetBodyB(); + // TODO_ERIN there might be some problem with the joint edges in b2Joint. + + m_bodyC = m_joint1->GetBodyA(); + m_bodyA = m_joint1->GetBodyB(); // Get geometry of joint1 b2Transform xfA = m_bodyA->m_xf; @@ -76,7 +81,7 @@ b2GearJoint::b2GearJoint(const b2GearJointDef* def) b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint1; m_localAnchorC = prismatic->m_localAnchorA; m_localAnchorA = prismatic->m_localAnchorB; - m_referenceAngleA = prismatic->m_refAngle; + m_referenceAngleA = prismatic->m_referenceAngle; m_localAxisC = prismatic->m_localXAxisA; b2Vec2 pC = m_localAnchorC; @@ -84,8 +89,8 @@ b2GearJoint::b2GearJoint(const b2GearJointDef* def) coordinateA = b2Dot(pA - pC, m_localAxisC); } - m_bodyD = def->joint2->GetBodyA(); - m_bodyB = def->joint2->GetBodyB(); + m_bodyD = m_joint2->GetBodyA(); + m_bodyB = m_joint2->GetBodyB(); // Get geometry of joint2 b2Transform xfB = m_bodyB->m_xf; @@ -108,7 +113,7 @@ b2GearJoint::b2GearJoint(const b2GearJointDef* def) b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint2; m_localAnchorD = prismatic->m_localAnchorA; m_localAnchorB = prismatic->m_localAnchorB; - m_referenceAngleB = prismatic->m_refAngle; + m_referenceAngleB = prismatic->m_referenceAngle; m_localAxisD = prismatic->m_localXAxisA; b2Vec2 pD = m_localAnchorD; @@ -315,9 +320,9 @@ bool b2GearJoint::SolvePositionConstraints(const b2SolverData& data) if (m_typeB == e_revoluteJoint) { JvBD.SetZero(); - JwB = 1.0f; - JwD = 1.0f; - mass += m_iB + m_iD; + JwB = m_ratio; + JwD = m_ratio; + mass += m_ratio * m_ratio * (m_iB + m_iD); coordinateB = aB - aD - m_referenceAngleB; } @@ -398,3 +403,21 @@ float32 b2GearJoint::GetRatio() const { return m_ratio; } + +void b2GearJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + int32 index1 = m_joint1->m_index; + int32 index2 = m_joint2->m_index; + + b2Log(" b2GearJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.joint1 = joints[%d];\n", index1); + b2Log(" jd.joint2 = joints[%d];\n", index2); + b2Log(" jd.ratio = %.15lef;\n", m_ratio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.h index 5651d5418..48cdfd886 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.h @@ -62,10 +62,19 @@ public: b2Vec2 GetReactionForce(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const; + /// Get the first joint. + b2Joint* GetJoint1() { return m_joint1; } + + /// Get the second joint. + b2Joint* GetJoint2() { return m_joint2; } + /// Set/Get the gear ratio. void SetRatio(float32 ratio); float32 GetRatio() const; + /// Dump joint to dmLog + void Dump(); + protected: friend class b2Joint; @@ -75,6 +84,9 @@ protected: void SolveVelocityConstraints(const b2SolverData& data); bool SolvePositionConstraints(const b2SolverData& data); + b2Joint* m_joint1; + b2Joint* m_joint2; + b2JointType m_typeA; b2JointType m_typeB; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.cpp index eee195a9d..85322f77c 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.cpp @@ -177,6 +177,7 @@ b2Joint::b2Joint(const b2JointDef* def) m_next = NULL; m_bodyA = def->bodyA; m_bodyB = def->bodyB; + m_index = 0; m_collideConnected = def->collideConnected; m_islandFlag = false; m_userData = def->userData; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.h index ed6ad4103..90154ccb8 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.h @@ -118,10 +118,10 @@ public: /// Get the anchor point on bodyB in world coordinates. virtual b2Vec2 GetAnchorB() const = 0; - /// Get the reaction force on body2 at the joint anchor in Newtons. + /// Get the reaction force on bodyB at the joint anchor in Newtons. virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0; - /// Get the reaction torque on body2 in N*m. + /// Get the reaction torque on bodyB in N*m. virtual float32 GetReactionTorque(float32 inv_dt) const = 0; /// Get the next joint the world joint list. @@ -142,10 +142,14 @@ public: /// the flag is only checked when fixture AABBs begin to overlap. bool GetCollideConnected() const; + /// Dump this joint to the log file. + virtual void Dump() { b2Log("// Dump is not supported for this joint type.\n"); } + protected: friend class b2World; friend class b2Body; friend class b2Island; + friend class b2GearJoint; static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allocator); static void Destroy(b2Joint* joint, b2BlockAllocator* allocator); @@ -167,6 +171,8 @@ protected: b2Body* m_bodyA; b2Body* m_bodyB; + int32 m_index; + bool m_islandFlag; bool m_collideConnected; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.h index 3c90d0161..bb2e28418 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.h @@ -89,6 +89,9 @@ public: void SetDampingRatio(float32 ratio); float32 GetDampingRatio() const; + /// The mouse joint does not support dumping. + void Dump() { b2Log("Mouse joint dumping is not supported.\n"); } + protected: friend class b2Joint; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp index 99f0c7d6f..88a388072 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp @@ -103,8 +103,9 @@ b2PrismaticJoint::b2PrismaticJoint(const b2PrismaticJointDef* def) m_localAnchorA = def->localAnchorA; m_localAnchorB = def->localAnchorB; m_localXAxisA = def->localAxisA; + m_localXAxisA.Normalize(); m_localYAxisA = b2Cross(1.0f, m_localXAxisA); - m_refAngle = def->referenceAngle; + m_referenceAngle = def->referenceAngle; m_impulse.SetZero(); m_motorMass = 0.0; @@ -348,6 +349,17 @@ void b2PrismaticJoint::SolveVelocityConstraints(const b2SolverData& data) vB += mB * P; wB += iB * LB; + + b2Vec2 Cdot10 = Cdot1; + + Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; + Cdot1.y = wB - wA; + + if (b2Abs(Cdot1.x) > 0.01f || b2Abs(Cdot1.y) > 0.01f) + { + b2Vec2 test = b2Mul22(m_K, df); + Cdot1.x += 0.0f; + } } data.velocities[m_indexA].v = vA; @@ -384,7 +396,7 @@ bool b2PrismaticJoint::SolvePositionConstraints(const b2SolverData& data) b2Vec3 impulse; b2Vec2 C1; C1.x = b2Dot(perp, d); - C1.y = aB - aA - m_refAngle; + C1.y = aB - aA - m_referenceAngle; float32 linearError = b2Abs(C1.x); float32 angularError = b2Abs(C1.y); @@ -419,43 +431,45 @@ bool b2PrismaticJoint::SolvePositionConstraints(const b2SolverData& data) if (active) { - float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2; - float32 k12 = iA * m_s1 + iB * m_s2; - float32 k13 = iA * m_s1 * m_a1 + iB * m_s2 * m_a2; + float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; + float32 k12 = iA * s1 + iB * s2; + float32 k13 = iA * s1 * a1 + iB * s2 * a2; float32 k22 = iA + iB; if (k22 == 0.0f) { // For fixed rotation k22 = 1.0f; } - float32 k23 = iA * m_a1 + iB * m_a2; - float32 k33 = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; + float32 k23 = iA * a1 + iB * a2; + float32 k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; - m_K.ex.Set(k11, k12, k13); - m_K.ey.Set(k12, k22, k23); - m_K.ez.Set(k13, k23, k33); + b2Mat33 K; + K.ex.Set(k11, k12, k13); + K.ey.Set(k12, k22, k23); + K.ez.Set(k13, k23, k33); b2Vec3 C; C.x = C1.x; C.y = C1.y; C.z = C2; - impulse = m_K.Solve33(-C); + impulse = K.Solve33(-C); } else { - float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2; - float32 k12 = iA * m_s1 + iB * m_s2; + float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; + float32 k12 = iA * s1 + iB * s2; float32 k22 = iA + iB; if (k22 == 0.0f) { k22 = 1.0f; } - m_K.ex.Set(k11, k12, 0.0f); - m_K.ey.Set(k12, k22, 0.0f); + b2Mat22 K; + K.ex.Set(k11, k12); + K.ey.Set(k12, k22); - b2Vec2 impulse1 = m_K.Solve22(-C1); + b2Vec2 impulse1 = K.Solve(-C1); impulse.x = impulse1.x; impulse.y = impulse1.y; impulse.z = 0.0f; @@ -599,3 +613,25 @@ float32 b2PrismaticJoint::GetMotorForce(float32 inv_dt) const { return inv_dt * m_motorImpulse; } + +void b2PrismaticJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2PrismaticJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); + b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); + b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); + b2Log(" jd.lowerTranslation = %.15lef;\n", m_lowerTranslation); + b2Log(" jd.upperTranslation = %.15lef;\n", m_upperTranslation); + b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); + b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); + b2Log(" jd.maxMotorForce = %.15lef;\n", m_maxMotorForce); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h index f271e7579..8d0f34229 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h @@ -45,16 +45,16 @@ struct b2PrismaticJointDef : public b2JointDef } /// Initialize the bodies, anchors, axis, and reference angle using the world - /// anchor and world axis. + /// anchor and unit world axis. void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); - /// The local anchor point relative to body1's origin. + /// The local anchor point relative to bodyA's origin. b2Vec2 localAnchorA; - /// The local anchor point relative to body2's origin. + /// The local anchor point relative to bodyB's origin. b2Vec2 localAnchorB; - /// The local translation axis in body1. + /// The local translation unit axis in bodyA. b2Vec2 localAxisA; /// The constrained angle between the bodies: bodyB_angle - bodyA_angle. @@ -92,6 +92,18 @@ public: b2Vec2 GetReactionForce(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const; + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// The local joint axis relative to bodyA. + const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } + + /// Get the reference angle. + float32 GetReferenceAngle() const { return m_referenceAngle; } + /// Get the current joint translation, usually in meters. float32 GetJointTranslation() const; @@ -127,10 +139,14 @@ public: /// Set the maximum motor force, usually in N. void SetMaxMotorForce(float32 force); + float32 GetMaxMotorForce() const { return m_maxMotorForce; } /// Get the current motor force given the inverse time step, usually in N. float32 GetMotorForce(float32 inv_dt) const; + /// Dump to b2Log + void Dump(); + protected: friend class b2Joint; friend class b2GearJoint; @@ -145,7 +161,7 @@ protected: b2Vec2 m_localAnchorB; b2Vec2 m_localXAxisA; b2Vec2 m_localYAxisA; - float32 m_refAngle; + float32 m_referenceAngle; b2Vec3 m_impulse; float32 m_motorImpulse; float32 m_lowerTranslation; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp index 1a09d907e..e0bb7da51 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp @@ -59,6 +59,9 @@ b2PulleyJoint::b2PulleyJoint(const b2PulleyJointDef* def) m_localAnchorA = def->localAnchorA; m_localAnchorB = def->localAnchorB; + m_lengthA = def->lengthA; + m_lengthB = def->lengthB; + b2Assert(def->ratio != 0.0f); m_ratio = def->ratio; @@ -308,3 +311,22 @@ float32 b2PulleyJoint::GetRatio() const { return m_ratio; } + +void b2PulleyJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2PulleyJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.groundAnchorA.Set(%.15lef, %.15lef);\n", m_groundAnchorA.x, m_groundAnchorA.y); + b2Log(" jd.groundAnchorB.Set(%.15lef, %.15lef);\n", m_groundAnchorB.x, m_groundAnchorB.y); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.lengthA = %.15lef;\n", m_lengthA); + b2Log(" jd.lengthB = %.15lef;\n", m_lengthB); + b2Log(" jd.ratio = %.15lef;\n", m_ratio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.h index a5269c618..639789f52 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.h @@ -100,6 +100,9 @@ public: /// Get the pulley ratio. float32 GetRatio() const; + /// Dump joint to dmLog + void Dump(); + protected: friend class b2Joint; @@ -111,6 +114,8 @@ protected: b2Vec2 m_groundAnchorA; b2Vec2 m_groundAnchorB; + float32 m_lengthA; + float32 m_lengthB; // Solver shared b2Vec2 m_localAnchorA; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp index 7718f03fc..ffb17252c 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp @@ -481,3 +481,24 @@ void b2RevoluteJoint::SetLimits(float32 lower, float32 upper) m_upperAngle = upper; } } + +void b2RevoluteJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2RevoluteJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); + b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); + b2Log(" jd.lowerAngle = %.15lef;\n", m_lowerAngle); + b2Log(" jd.upperAngle = %.15lef;\n", m_upperAngle); + b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); + b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); + b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h index 03eae0b3a..e62cdbccd 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h @@ -52,13 +52,13 @@ struct b2RevoluteJointDef : public b2JointDef /// anchor point. void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); - /// The local anchor point relative to body1's origin. + /// The local anchor point relative to bodyA's origin. b2Vec2 localAnchorA; - /// The local anchor point relative to body2's origin. + /// The local anchor point relative to bodyB's origin. b2Vec2 localAnchorB; - /// The body2 angle minus body1 angle in the reference state (radians). + /// The bodyB angle minus bodyA angle in the reference state (radians). float32 referenceAngle; /// A flag to enable joint limits. @@ -93,6 +93,15 @@ public: b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorB() const; + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// Get the reference angle. + float32 GetReferenceAngle() const { return m_referenceAngle; } + /// Get the current joint angle in radians. float32 GetJointAngle() const; @@ -128,6 +137,7 @@ public: /// Set the maximum motor torque, usually in N-m. void SetMaxMotorTorque(float32 torque); + float32 GetMaxMotorTorque() const { return m_maxMotorTorque; } /// Get the reaction force given the inverse time step. /// Unit is N. @@ -141,6 +151,9 @@ public: /// Unit is N*m. float32 GetMotorTorque(float32 inv_dt) const; + /// Dump to b2Log. + void Dump(); + protected: friend class b2Joint; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.cpp index 4b1e666c1..107ce1fa5 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.cpp @@ -224,3 +224,18 @@ b2LimitState b2RopeJoint::GetLimitState() const { return m_state; } + +void b2RopeJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2RopeJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.maxLength = %.15lef;\n", m_maxLength); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.h index 660b4ed50..30252460c 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.h @@ -64,11 +64,21 @@ public: b2Vec2 GetReactionForce(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const; - /// Get the maximum length of the rope. + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// Set/Get the maximum length of the rope. + void SetMaxLength(float32 length) { m_maxLength = length; } float32 GetMaxLength() const; b2LimitState GetLimitState() const; + /// Dump joint to dmLog + void Dump(); + protected: friend class b2Joint; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp index 11eb5ec65..9a86686e2 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp @@ -49,6 +49,8 @@ b2WeldJoint::b2WeldJoint(const b2WeldJointDef* def) m_localAnchorA = def->localAnchorA; m_localAnchorB = def->localAnchorB; m_referenceAngle = def->referenceAngle; + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; m_impulse.SetZero(); } @@ -91,15 +93,50 @@ void b2WeldJoint::InitVelocityConstraints(const b2SolverData& data) float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; - m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; - m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; - m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB; - m_mass.ex.y = m_mass.ey.x; - m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; - m_mass.ez.y = m_rA.x * iA + m_rB.x * iB; - m_mass.ex.z = m_mass.ez.x; - m_mass.ey.z = m_mass.ez.y; - m_mass.ez.z = iA + iB; + b2Mat33 K; + K.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; + K.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; + K.ez.x = -m_rA.y * iA - m_rB.y * iB; + K.ex.y = K.ey.x; + K.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; + K.ez.y = m_rA.x * iA + m_rB.x * iB; + K.ex.z = K.ez.x; + K.ey.z = K.ez.y; + K.ez.z = iA + iB; + + if (m_frequencyHz > 0.0f) + { + K.GetInverse22(&m_mass); + + float32 invM = iA + iB; + float32 m = invM > 0.0f ? 1.0f / invM : 0.0f; + + float32 C = aB - aA - m_referenceAngle; + + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; + + // Damping coefficient + float32 d = 2.0f * m * m_dampingRatio * omega; + + // Spring stiffness + float32 k = m * omega * omega; + + // magic formulas + float32 h = data.step.dt; + m_gamma = h * (d + h * k); + m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; + m_bias = C * h * k * m_gamma; + + invM += m_gamma; + m_mass.ez.z = invM != 0.0f ? 1.0f / invM : 0.0f; + } + else + { + K.GetSymInverse33(&m_mass); + m_gamma = 0.0f; + m_bias = 0.0f; + } if (data.step.warmStarting) { @@ -135,20 +172,47 @@ void b2WeldJoint::SolveVelocityConstraints(const b2SolverData& data) float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; - b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - float32 Cdot2 = wB - wA; - b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); + if (m_frequencyHz > 0.0f) + { + float32 Cdot2 = wB - wA; - b2Vec3 impulse = -m_mass.Solve33(Cdot); - m_impulse += impulse; + float32 impulse2 = -m_mass.ez.z * (Cdot2 + m_bias + m_gamma * m_impulse.z); + m_impulse.z += impulse2; - b2Vec2 P(impulse.x, impulse.y); + wA -= iA * impulse2; + wB += iB * impulse2; - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + impulse.z); + b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + impulse.z); + b2Vec2 impulse1 = -b2Mul22(m_mass, Cdot1); + m_impulse.x += impulse1.x; + m_impulse.y += impulse1.y; + + b2Vec2 P = impulse1; + + vA -= mA * P; + wA -= iA * b2Cross(m_rA, P); + + vB += mB * P; + wB += iB * b2Cross(m_rB, P); + } + else + { + b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + float32 Cdot2 = wB - wA; + b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); + + b2Vec3 impulse = -b2Mul(m_mass, Cdot); + m_impulse += impulse; + + b2Vec2 P(impulse.x, impulse.y); + + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + impulse.z); + + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + impulse.z); + } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; @@ -171,33 +235,53 @@ bool b2WeldJoint::SolvePositionConstraints(const b2SolverData& data) b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 C1 = cB + rB - cA - rA; - float32 C2 = aB - aA - m_referenceAngle; + float32 positionError, angularError; - float32 positionError = C1.Length(); - float32 angularError = b2Abs(C2); + b2Mat33 K; + K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; + K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; + K.ez.x = -rA.y * iA - rB.y * iB; + K.ex.y = K.ey.x; + K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; + K.ez.y = rA.x * iA + rB.x * iB; + K.ex.z = K.ez.x; + K.ey.z = K.ez.y; + K.ez.z = iA + iB; - m_mass.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; - m_mass.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; - m_mass.ez.x = -rA.y * iA - rB.y * iB; - m_mass.ex.y = m_mass.ey.x; - m_mass.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; - m_mass.ez.y = rA.x * iA + rB.x * iB; - m_mass.ex.z = m_mass.ez.x; - m_mass.ey.z = m_mass.ez.y; - m_mass.ez.z = iA + iB; + if (m_frequencyHz > 0.0f) + { + b2Vec2 C1 = cB + rB - cA - rA; - b2Vec3 C(C1.x, C1.y, C2); + positionError = C1.Length(); + angularError = 0.0f; - b2Vec3 impulse = -m_mass.Solve33(C); + b2Vec2 P = -K.Solve22(C1); - b2Vec2 P(impulse.x, impulse.y); + cA -= mA * P; + aA -= iA * b2Cross(rA, P); - cA -= mA * P; - aA -= iA * (b2Cross(rA, P) + impulse.z); + cB += mB * P; + aB += iB * b2Cross(rB, P); + } + else + { + b2Vec2 C1 = cB + rB - cA - rA; + float32 C2 = aB - aA - m_referenceAngle; - cB += mB * P; - aB += iB * (b2Cross(rB, P) + impulse.z); + positionError = C1.Length(); + angularError = b2Abs(C2); + + b2Vec3 C(C1.x, C1.y, C2); + + b2Vec3 impulse = -K.Solve33(C); + b2Vec2 P(impulse.x, impulse.y); + + cA -= mA * P; + aA -= iA * (b2Cross(rA, P) + impulse.z); + + cB += mB * P; + aB += iB * (b2Cross(rB, P) + impulse.z); + } data.positions[m_indexA].c = cA; data.positions[m_indexA].a = aA; @@ -227,3 +311,20 @@ float32 b2WeldJoint::GetReactionTorque(float32 inv_dt) const { return inv_dt * m_impulse.z; } + +void b2WeldJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2WeldJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); + b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); + b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h index 51c4b402b..2adfc26ab 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h @@ -32,20 +32,29 @@ struct b2WeldJointDef : public b2JointDef localAnchorA.Set(0.0f, 0.0f); localAnchorB.Set(0.0f, 0.0f); referenceAngle = 0.0f; + frequencyHz = 0.0f; + dampingRatio = 0.0f; } /// Initialize the bodies, anchors, and reference angle using a world /// anchor point. - void Initialize(b2Body* body1, b2Body* body2, const b2Vec2& anchor); + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); - /// The local anchor point relative to body1's origin. + /// The local anchor point relative to bodyA's origin. b2Vec2 localAnchorA; - /// The local anchor point relative to body2's origin. + /// The local anchor point relative to bodyB's origin. b2Vec2 localAnchorB; - /// The body2 angle minus body1 angle in the reference state (radians). + /// The bodyB angle minus bodyA angle in the reference state (radians). float32 referenceAngle; + + /// The mass-spring-damper frequency in Hertz. Rotation only. + /// Disable softness with a value of 0. + float32 frequencyHz; + + /// The damping ratio. 0 = no damping, 1 = critical damping. + float32 dampingRatio; }; /// A weld joint essentially glues two bodies together. A weld joint may @@ -59,6 +68,26 @@ public: b2Vec2 GetReactionForce(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const; + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// Get the reference angle. + float32 GetReferenceAngle() const { return m_referenceAngle; } + + /// Set/get frequency in Hz. + void SetFrequency(float32 hz) { m_frequencyHz = hz; } + float32 GetFrequency() const { return m_frequencyHz; } + + /// Set/get damping ratio. + void SetDampingRatio(float32 ratio) { m_dampingRatio = ratio; } + float32 GetDampingRatio() const { return m_dampingRatio; } + + /// Dump to b2Log + void Dump(); + protected: friend class b2Joint; @@ -69,10 +98,15 @@ protected: void SolveVelocityConstraints(const b2SolverData& data); bool SolvePositionConstraints(const b2SolverData& data); + float32 m_frequencyHz; + float32 m_dampingRatio; + float32 m_bias; + // Solver shared b2Vec2 m_localAnchorA; b2Vec2 m_localAnchorB; float32 m_referenceAngle; + float32 m_gamma; b2Vec3 m_impulse; // Solver temp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.cpp b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.cpp index 826192347..998c627db 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.cpp @@ -398,7 +398,22 @@ float32 b2WheelJoint::GetMotorTorque(float32 inv_dt) const return inv_dt * m_motorImpulse; } +void b2WheelJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; - - - + b2Log(" b2WheelJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); + b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); + b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); + b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); + b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); + b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.h b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.h index 7398d218c..9a8b13639 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.h @@ -46,13 +46,13 @@ struct b2WheelJointDef : public b2JointDef /// anchor and world axis. void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); - /// The local anchor point relative to body1's origin. + /// The local anchor point relative to bodyA's origin. b2Vec2 localAnchorA; - /// The local anchor point relative to body2's origin. + /// The local anchor point relative to bodyB's origin. b2Vec2 localAnchorB; - /// The local translation axis in body1. + /// The local translation axis in bodyA. b2Vec2 localAxisA; /// Enable/disable the joint motor. @@ -72,19 +72,30 @@ struct b2WheelJointDef : public b2JointDef }; /// A wheel joint. This joint provides two degrees of freedom: translation -/// along an axis fixed in body1 and rotation in the plane. You can use a +/// along an axis fixed in bodyA and rotation in the plane. You can use a /// joint limit to restrict the range of motion and a joint motor to drive /// the rotation or to model rotational friction. /// This joint is designed for vehicle suspensions. class b2WheelJoint : public b2Joint { public: + void GetDefinition(b2WheelJointDef* def) const; + b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorB() const; b2Vec2 GetReactionForce(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const; + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// The local joint axis relative to bodyA. + const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } + /// Get the current joint translation, usually in meters. float32 GetJointTranslation() const; @@ -118,6 +129,9 @@ public: void SetSpringDampingRatio(float32 ratio); float32 GetSpringDampingRatio() const; + /// Dump to b2Log + void Dump(); + protected: friend class b2Joint; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp index 858977c81..b50bf45ad 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp @@ -481,4 +481,34 @@ void b2Body::SetActive(bool flag) } m_contactList = NULL; } +} + +void b2Body::Dump() +{ + int32 bodyIndex = m_islandIndex; + + b2Log("{\n"); + b2Log(" b2BodyDef bd;\n"); + b2Log(" bd.type = b2BodyType(%d);\n", m_type); + b2Log(" bd.position.Set(%.15lef, %.15lef);\n", m_xf.p.x, m_xf.p.y); + b2Log(" bd.angle = %.15lef;\n", m_sweep.a); + b2Log(" bd.linearVelocity.Set(%.15lef, %.15lef);\n", m_linearVelocity.x, m_linearVelocity.y); + b2Log(" bd.angularVelocity = %.15lef;\n", m_angularVelocity); + b2Log(" bd.linearDamping = %.15lef;\n", m_linearDamping); + b2Log(" bd.angularDamping = %.15lef;\n", m_angularDamping); + b2Log(" bd.allowSleep = bool(%d);\n", m_flags & e_autoSleepFlag); + b2Log(" bd.awake = bool(%d);\n", m_flags & e_awakeFlag); + b2Log(" bd.fixedRotation = bool(%d);\n", m_flags & e_fixedRotationFlag); + b2Log(" bd.bullet = bool(%d);\n", m_flags & e_bulletFlag); + b2Log(" bd.active = bool(%d);\n", m_flags & e_activeFlag); + b2Log(" bd.gravityScale = %.15lef;\n", m_gravityScale); + b2Log(" bodies[%d] = m_world->CreateBody(&bd);\n", m_islandIndex); + b2Log("\n"); + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + b2Log(" {\n"); + f->Dump(bodyIndex); + b2Log(" }\n"); + } + b2Log("}\n"); } \ No newline at end of file diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Body.h b/src/modules/physics/box2d/Box2D/Dynamics/b2Body.h index 5ebc5ddd1..73f2cb415 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2Body.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Body.h @@ -375,6 +375,9 @@ public: b2World* GetWorld(); const b2World* GetWorld() const; + /// Dump this body to a log file + void Dump(); + private: friend class b2World; @@ -474,7 +477,7 @@ inline const b2Vec2& b2Body::GetPosition() const inline float32 b2Body::GetAngle() const { - return m_xf.q.GetAngle(); + return m_sweep.a; } inline const b2Vec2& b2Body::GetWorldCenter() const diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp index ee12b325e..5ac12b350 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp @@ -115,16 +115,6 @@ void b2ContactManager::Collide() b2Body* bodyA = fixtureA->GetBody(); b2Body* bodyB = fixtureB->GetBody(); - bool activeA = bodyA->IsAwake() && bodyA->m_type != b2_staticBody; - bool activeB = bodyB->IsAwake() && bodyB->m_type != b2_staticBody; - - // At least one body must be awake and it must be dynamic or kinematic. - if (activeA == false && activeB == false) - { - c = c->GetNext(); - continue; - } - // Is this contact flagged for filtering? if (c->m_flags & b2Contact::e_filterFlag) { @@ -150,6 +140,16 @@ void b2ContactManager::Collide() c->m_flags &= ~b2Contact::e_filterFlag; } + bool activeA = bodyA->IsAwake() && bodyA->m_type != b2_staticBody; + bool activeB = bodyB->IsAwake() && bodyB->m_type != b2_staticBody; + + // At least one body must be awake and it must be dynamic or kinematic. + if (activeA == false && activeB == false) + { + c = c->GetNext(); + continue; + } + int32 proxyIdA = fixtureA->m_proxies[indexA].proxyId; int32 proxyIdB = fixtureB->m_proxies[indexB].proxyId; bool overlap = m_broadPhase.TestOverlap(proxyIdA, proxyIdB); diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp index 478088a44..77537b276 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp @@ -226,3 +226,78 @@ void b2Fixture::SetSensor(bool sensor) } } +void b2Fixture::Dump(int32 bodyIndex) +{ + b2Log(" b2FixtureDef fd;\n"); + b2Log(" fd.friction = %.15lef;\n", m_friction); + b2Log(" fd.restitution = %.15lef;\n", m_restitution); + b2Log(" fd.density = %.15lef;\n", m_density); + b2Log(" fd.isSensor = bool(%d);\n", m_isSensor); + b2Log(" fd.filter.categoryBits = uint16(%d);\n", m_filter.categoryBits); + b2Log(" fd.filter.maskBits = uint16(%d);\n", m_filter.maskBits); + b2Log(" fd.filter.groupIndex = int16(%d);\n", m_filter.groupIndex); + + switch (m_shape->m_type) + { + case b2Shape::e_circle: + { + b2CircleShape* s = (b2CircleShape*)m_shape; + b2Log(" b2CircleShape shape;\n"); + b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); + b2Log(" shape.m_p.Set(%.15lef, %.15lef);\n", s->m_p.x, s->m_p.y); + } + break; + + case b2Shape::e_edge: + { + b2EdgeShape* s = (b2EdgeShape*)m_shape; + b2Log(" b2EdgeShape shape;\n"); + b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); + b2Log(" shape.m_vertex0.Set(%.15lef, %.15lef);\n", s->m_vertex0.x, s->m_vertex0.y); + b2Log(" shape.m_vertex1.Set(%.15lef, %.15lef);\n", s->m_vertex1.x, s->m_vertex1.y); + b2Log(" shape.m_vertex2.Set(%.15lef, %.15lef);\n", s->m_vertex2.x, s->m_vertex2.y); + b2Log(" shape.m_vertex3.Set(%.15lef, %.15lef);\n", s->m_vertex3.x, s->m_vertex3.y); + b2Log(" shape.m_hasVertex0 = bool(%d);\n", s->m_hasVertex0); + b2Log(" shape.m_hasVertex3 = bool(%d);\n", s->m_hasVertex3); + } + break; + + case b2Shape::e_polygon: + { + b2PolygonShape* s = (b2PolygonShape*)m_shape; + b2Log(" b2PolygonShape shape;\n"); + b2Log(" b2Vec2 vs[%d];\n", b2_maxPolygonVertices); + for (int32 i = 0; i < s->m_vertexCount; ++i) + { + b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); + } + b2Log(" shape.Set(vs, %d);\n", s->m_vertexCount); + } + break; + + case b2Shape::e_chain: + { + b2ChainShape* s = (b2ChainShape*)m_shape; + b2Log(" b2ChainShape shape;\n"); + b2Log(" b2Vec2 vs[%d];\n", s->m_count); + for (int32 i = 0; i < s->m_count; ++i) + { + b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); + } + b2Log(" shape.CreateChain(vs, %d);\n", s->m_count); + b2Log(" shape.m_prevVertex.Set(%.15lef, %.15lef);\n", s->m_prevVertex.x, s->m_prevVertex.y); + b2Log(" shape.m_nextVertex.Set(%.15lef, %.15lef);\n", s->m_nextVertex.x, s->m_nextVertex.y); + b2Log(" shape.m_hasPrevVertex = bool(%d);\n", s->m_hasPrevVertex); + b2Log(" shape.m_hasNextVertex = bool(%d);\n", s->m_hasNextVertex); + } + break; + + default: + return; + } + + b2Log("\n"); + b2Log(" fd.shape = &shape;\n"); + b2Log("\n"); + b2Log(" bodies[%d]->CreateFixture(&fd);\n", bodyIndex); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h b/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h index a7b5c3428..5ebd0c3fd 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h @@ -31,6 +31,13 @@ class b2Fixture; /// This holds contact filtering data. struct b2Filter { + b2Filter() + { + categoryBits = 0x0001; + maskBits = 0xFFFF; + groupIndex = 0; + } + /// The collision category bits. Normally you would just set one bit. uint16 categoryBits; @@ -56,9 +63,6 @@ struct b2FixtureDef friction = 0.2f; restitution = 0.0f; density = 0.0f; - filter.categoryBits = 0x0001; - filter.maskBits = 0xFFFF; - filter.groupIndex = 0; isSensor = false; } @@ -188,6 +192,9 @@ public: /// the body transform. const b2AABB& GetAABB(int32 childIndex) const; + /// Dump this fixture to the log file. + void Dump(int32 bodyIndex); + protected: friend class b2Body; diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2TimeStep.h b/src/modules/physics/box2d/Box2D/Dynamics/b2TimeStep.h index 80916cb65..abe6fb6e0 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2TimeStep.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2TimeStep.h @@ -21,18 +21,18 @@ #include -/// Profiling data. Times are in milliseconds. -struct b2Profile -{ - float32 step; - float32 collide; - float32 solve; - float32 solveInit; - float32 solveVelocity; - float32 solvePosition; - float32 broadphase; - float32 solveTOI; -}; +/// Profiling data. Times are in milliseconds. +struct b2Profile +{ + float32 step; + float32 collide; + float32 solve; + float32 solveInit; + float32 solveVelocity; + float32 solvePosition; + float32 broadphase; + float32 solveTOI; +}; /// This is an internal structure. struct b2TimeStep diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp b/src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp index 7dcddd03c..baacded4f 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp @@ -34,7 +34,7 @@ #include #include -b2World::b2World(const b2Vec2& gravity, bool doSleep) +b2World::b2World(const b2Vec2& gravity) { m_destructionListener = NULL; m_debugDraw = NULL; @@ -51,7 +51,7 @@ b2World::b2World(const b2Vec2& gravity, bool doSleep) m_stepComplete = true; - m_allowSleep = doSleep; + m_allowSleep = true; m_gravity = gravity; m_flags = e_clearForces; @@ -364,6 +364,24 @@ void b2World::DestroyJoint(b2Joint* j) } } +// +void b2World::SetAllowSleeping(bool flag) +{ + if (flag == m_allowSleep) + { + return; + } + + m_allowSleep = flag; + if (m_allowSleep == false) + { + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->SetAwake(true); + } + } +} + // Find islands, integrate and solve constraints, solve position constraints void b2World::Solve(const b2TimeStep& step) { @@ -1038,8 +1056,8 @@ void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color case b2Shape::e_chain: { b2ChainShape* chain = (b2ChainShape*)fixture->GetShape(); - int32 count = chain->GetVertexCount(); - const b2Vec2* vertices = chain->GetVertices(); + int32 count = chain->m_count; + const b2Vec2* vertices = chain->m_vertices; b2Vec2 v1 = b2Mul(xf, vertices[0]); for (int32 i = 1; i < count; ++i) @@ -1237,3 +1255,62 @@ float32 b2World::GetTreeQuality() const { return m_contactManager.m_broadPhase.GetTreeQuality(); } + +void b2World::Dump() +{ + if ((m_flags & e_locked) == e_locked) + { + return; + } + + b2Log("b2Vec2 g(%.15lef, %.15lef);\n", m_gravity.x, m_gravity.y); + b2Log("m_world->SetGravity(g);\n"); + + b2Log("b2Body** bodies = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount); + b2Log("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount); + int32 i = 0; + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->m_islandIndex = i; + b->Dump(); + ++i; + } + + i = 0; + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + j->m_index = i; + ++i; + } + + // First pass on joints, skip gear joints. + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + if (j->m_type == e_gearJoint) + { + continue; + } + + b2Log("{\n"); + j->Dump(); + b2Log("}\n"); + } + + // Second pass on joints, only gear joints. + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + if (j->m_type != e_gearJoint) + { + continue; + } + + b2Log("{\n"); + j->Dump(); + b2Log("}\n"); + } + + b2Log("b2Free(joints);\n"); + b2Log("b2Free(bodies);\n"); + b2Log("joints = NULL;\n"); + b2Log("bodies = NULL;\n"); +} diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2World.h b/src/modules/physics/box2d/Box2D/Dynamics/b2World.h index 381e1f1ac..eba757276 100755 --- a/src/modules/physics/box2d/Box2D/Dynamics/b2World.h +++ b/src/modules/physics/box2d/Box2D/Dynamics/b2World.h @@ -43,8 +43,7 @@ class b2World public: /// Construct a world object. /// @param gravity the world gravity vector. - /// @param doSleep improve performance by not simulating inactive bodies. - b2World(const b2Vec2& gravity, bool doSleep); + b2World(const b2Vec2& gravity); /// Destruct the world. All physics entities are destroyed and all heap memory is released. ~b2World(); @@ -142,14 +141,21 @@ public: b2Contact* GetContactList(); const b2Contact* GetContactList() const; + /// Enable/disable sleep. + void SetAllowSleeping(bool flag); + bool GetAllowSleeping() const { return m_allowSleep; } + /// Enable/disable warm starting. For testing. void SetWarmStarting(bool flag) { m_warmStarting = flag; } + bool GetWarmStarting() const { return m_warmStarting; } /// Enable/disable continuous physics. For testing. void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; } + bool GetContinuousPhysics() const { return m_continuousPhysics; } /// Enable/disable single stepped continuous physics. For testing. void SetSubStepping(bool flag) { m_subStepping = flag; } + bool GetSubStepping() const { return m_subStepping; } /// Get the number of broad-phase proxies. int32 GetProxyCount() const; @@ -194,6 +200,10 @@ public: /// Get the current profile. const b2Profile& GetProfile() const; + /// Dump the world into the log file. + /// @warning this should be called outside of a time step. + void Dump(); + private: // m_flags From a956f9b0c1febe34ef03b240c41e03c703008636 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Fri, 23 Sep 2011 16:17:29 -0400 Subject: [PATCH 18/78] Update WeldJoint for new soft constraint options --HG-- branch : box2d-update --- src/modules/physics/box2d/WeldJoint.cpp | 20 ++++++++++++ src/modules/physics/box2d/WeldJoint.h | 22 +++++++++++++ src/modules/physics/box2d/wrap_WeldJoint.cpp | 34 ++++++++++++++++++++ src/modules/physics/box2d/wrap_WeldJoint.h | 6 ++++ 4 files changed, 82 insertions(+) diff --git a/src/modules/physics/box2d/WeldJoint.cpp b/src/modules/physics/box2d/WeldJoint.cpp index 1d1f39494..b2882d0be 100644 --- a/src/modules/physics/box2d/WeldJoint.cpp +++ b/src/modules/physics/box2d/WeldJoint.cpp @@ -47,6 +47,26 @@ namespace box2d destroyJoint(joint); joint = 0; } + + void WeldJoint::setFrequency(float hz) + { + joint->SetFrequency(hz); + } + + float WeldJoint::getFrequency() const + { + return joint->GetFrequency(); + } + + void WeldJoint::setDampingRatio(float d) + { + joint->SetDampingRatio(d); + } + + float WeldJoint::getDampingRatio() const + { + return joint->GetDampingRatio(); + } } // box2d } // physics diff --git a/src/modules/physics/box2d/WeldJoint.h b/src/modules/physics/box2d/WeldJoint.h index c8bb6856c..e8469dac2 100644 --- a/src/modules/physics/box2d/WeldJoint.h +++ b/src/modules/physics/box2d/WeldJoint.h @@ -49,6 +49,28 @@ namespace box2d virtual ~WeldJoint(); + /** + * Sets the response speed. + **/ + void setFrequency(float hz); + + /** + * Gets the response speed. + **/ + float getFrequency() const; + + /** + * Sets the damping ratio. + * 0 = no damping, 1 = critical damping. + **/ + void setDampingRatio(float d); + + /** + * Gets the damping ratio. + * 0 = no damping, 1 = critical damping. + **/ + float getDampingRatio() const; + }; } // box2d diff --git a/src/modules/physics/box2d/wrap_WeldJoint.cpp b/src/modules/physics/box2d/wrap_WeldJoint.cpp index 4d0cbc16a..b3229323e 100644 --- a/src/modules/physics/box2d/wrap_WeldJoint.cpp +++ b/src/modules/physics/box2d/wrap_WeldJoint.cpp @@ -31,7 +31,41 @@ namespace box2d return luax_checktype(L, idx, "WeldJoint", PHYSICS_WELD_JOINT_T); } + int w_WeldJoint_setFrequency(lua_State * L) + { + WeldJoint * t = luax_checkweldjoint(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setFrequency(arg1); + return 0; + } + + int w_WeldJoint_getFrequency(lua_State * L) + { + WeldJoint * t = luax_checkweldjoint(L, 1); + lua_pushnumber(L, t->getFrequency()); + return 1; + } + + int w_WeldJoint_setDampingRatio(lua_State * L) + { + WeldJoint * t = luax_checkweldjoint(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setDampingRatio(arg1); + return 0; + } + + int w_WeldJoint_getDampingRatio(lua_State * L) + { + WeldJoint * t = luax_checkweldjoint(L, 1); + lua_pushnumber(L, t->getDampingRatio()); + return 1; + } + static const luaL_Reg functions[] = { + { "setFrequency", w_WeldJoint_setFrequency }, + { "getFrequency", w_WeldJoint_getFrequency }, + { "setDampingRatio", w_WeldJoint_setDampingRatio }, + { "getDampingRatio", w_WeldJoint_getDampingRatio }, // From Joint. { "getType", w_Joint_getType }, { "getAnchors", w_Joint_getAnchors }, diff --git a/src/modules/physics/box2d/wrap_WeldJoint.h b/src/modules/physics/box2d/wrap_WeldJoint.h index bf875e85c..3874897c5 100644 --- a/src/modules/physics/box2d/wrap_WeldJoint.h +++ b/src/modules/physics/box2d/wrap_WeldJoint.h @@ -33,6 +33,12 @@ namespace physics namespace box2d { WeldJoint * luax_checkweldjoint(lua_State * L, int idx); + + int w_WeldJoint_setFrequency(lua_State * L); + int w_WeldJoint_getFrequency(lua_State * L); + int w_WeldJoint_setDampingRatio(lua_State * L); + int w_WeldJoint_getDampingRatio(lua_State * L); + int luaopen_weldjoint(lua_State * L); } // box2d From 4980797afc148c3cc8fdc99d08210affecf9c369 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Fri, 23 Sep 2011 16:27:59 -0400 Subject: [PATCH 19/78] World no longer has an explicit size --HG-- branch : box2d-update --- src/modules/physics/box2d/Physics.cpp | 8 +++----- src/modules/physics/box2d/Physics.h | 11 ++++++----- src/modules/physics/box2d/World.cpp | 12 ++++++------ src/modules/physics/box2d/World.h | 15 ++++----------- src/modules/physics/box2d/wrap_Physics.cpp | 17 +++++------------ 5 files changed, 24 insertions(+), 39 deletions(-) diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index a9887cf78..5c7c59361 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -39,12 +39,10 @@ namespace box2d return "love.physics.box2d"; } - World * Physics::newWorld(float lx, float ly, float ux, float uy, float gx, float gy, bool sleep, int meter) + World * Physics::newWorld(float gx, float gy, bool sleep, int meter) { - b2AABB aabb; - aabb.lowerBound.Set(lx, ly); - aabb.upperBound.Set(ux, uy); - return new World(aabb, b2Vec2(gx, gy), sleep, meter); + Physics::setMeter(meter); + return new World(b2Vec2(gx, gy), sleep); } Body * Physics::newBody(World * world, float x, float y, float mass, float i) diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index d15c1498f..2cca64dec 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -57,22 +57,23 @@ namespace box2d static int meter; public: + + /** + * 30 pixels in one meter by default. + **/ + static const int DEFAULT_METER = 30; // Implements Module. const char * getName() const; /** * Creates a new World. - * @param lx Lower bound on the x-axis. - * @param ly Lower bound on the y-axis. - * @param ux Upper bound on the x-axis. - * @param uy Upper bound on the y-axis. * @param gx Gravity along x-axis. * @param gy Gravity along y-axis. * @param sleep Whether the World allows sleep. * @param meter The scale in px/m. **/ - World * newWorld(float lx, float ly, float ux, float uy, float gx, float gy, bool sleep, int meter); + World * newWorld(float gx, float gy, bool sleep, int meter); /** * Creates a new Body at the specified position. diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index d6de02db0..3cf1c5b86 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -96,19 +96,19 @@ namespace box2d } - World::World(b2AABB aabb) - : world(NULL), meter(DEFAULT_METER) + World::World() + : world(NULL) { - world = new b2World(Physics::scaleDown(aabb), b2Vec2(0,0), true); + world = new b2World(b2Vec2(0,0), true); world->SetContactListener(this); b2BodyDef def; groundBody = world->CreateBody(def); } - World::World(b2AABB aabb, b2Vec2 gravity, bool sleep, int meter) - : world(NULL), meter(meter) + World::World(b2Vec2 gravity, bool sleep) + : world(NULL) { - world = new b2World(Physics::scaleDown(aabb), Physics::scaleDown(gravity), sleep); + world = new b2World(Physics::scaleDown(gravity), sleep); world->SetContactListener(this); } diff --git a/src/modules/physics/box2d/World.h b/src/modules/physics/box2d/World.h index 238f19b7f..fb6447f4d 100644 --- a/src/modules/physics/box2d/World.h +++ b/src/modules/physics/box2d/World.h @@ -87,25 +87,18 @@ namespace box2d public: /** - * 30 pixels in one meter by default. + * Creates a new world. **/ - static const int DEFAULT_METER = 30; + World(); /** - * Creates a new world with the given bounding box. - * @param aabb The bounding box. - **/ - World(b2AABB aabb); - - /** - * Creates a new world with the given bounding box, gravity + * Creates a new world with the given gravity * and whether or not the bodies should sleep when appropriate. - * @param aabb The bounding box. * @param gravity The gravity of the World. * @param sleep True if the bodies should be able to sleep, * false otherwise. **/ - World(b2AABB aabb, b2Vec2 gravity, bool sleep, int meter = DEFAULT_METER); + World(b2Vec2 gravity, bool sleep); virtual ~World(); diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index 111a46d39..e5bab7518 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -31,19 +31,12 @@ namespace box2d int w_newWorld(lua_State * L) { - if (lua_gettop(L) < 4) - return luaL_error(L, "Incorrect number of parameters"); + float gx = (float)luaL_optnumber(L, 1, 0); + float gy = (float)luaL_optnumber(L, 2, 0); + bool sleep = luax_optboolean(L, 3, true); + int meter = (int)luaL_optnumber(L, 4, Physics::DEFAULT_METER); - float lx = (float)luaL_checknumber(L, 1); - float ly = (float)luaL_checknumber(L, 2); - float ux = (float)luaL_checknumber(L, 3); - float uy = (float)luaL_checknumber(L, 4); - float gx = (float)luaL_optnumber(L, 5, 0); - float gy = (float)luaL_optnumber(L, 6, 0); - bool sleep = luax_optboolean(L, 7, true); - int meter = (int)luaL_optnumber(L, 8, World::DEFAULT_METER); - - World * w = instance->newWorld(lx, ly, ux, uy, gx, gy, sleep, meter); + World * w = instance->newWorld(gx, gy, sleep, meter); luax_newtype(L, "World", PHYSICS_WORLD_T, (void*)w); return 1; From 95f60474179a2bef022a4107ac79eb2a05218ef1 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Fri, 23 Sep 2011 17:01:53 -0400 Subject: [PATCH 20/78] Update World contact callback definitions, get ready for collision overhaul --HG-- branch : box2d-update --- src/modules/physics/box2d/Contact.cpp | 4 +- src/modules/physics/box2d/Contact.h | 6 +- src/modules/physics/box2d/World.cpp | 79 ++++++++++++------------ src/modules/physics/box2d/World.h | 22 +++---- src/modules/physics/box2d/wrap_World.cpp | 12 ++-- src/modules/physics/box2d/wrap_World.h | 4 +- 6 files changed, 65 insertions(+), 62 deletions(-) diff --git a/src/modules/physics/box2d/Contact.cpp b/src/modules/physics/box2d/Contact.cpp index f048e8c62..bc9583ab0 100644 --- a/src/modules/physics/box2d/Contact.cpp +++ b/src/modules/physics/box2d/Contact.cpp @@ -28,8 +28,8 @@ namespace physics { namespace box2d { - Contact::Contact(World * world, const b2ContactPoint * point) - : point(*point), world(world) + Contact::Contact(World * world, b2Contact * contact) + : contact(contact), world(world) { world->retain(); } diff --git a/src/modules/physics/box2d/Contact.h b/src/modules/physics/box2d/Contact.h index c5e8aa292..150bfdc91 100644 --- a/src/modules/physics/box2d/Contact.h +++ b/src/modules/physics/box2d/Contact.h @@ -49,8 +49,8 @@ namespace box2d private: - // The Box2D contact point. - b2ContactPoint point; + // The Box2D contact. + b2Contact* contact; // The parent world. Needed for scaling. World * world; @@ -63,7 +63,7 @@ namespace box2d * data pointed to. * @param point Pointer to the Box2D contact. **/ - Contact(World * world, const b2ContactPoint * point); + Contact(World * world, const b2Contact * contact); virtual ~Contact(); diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index 3cf1c5b86..ab3ce8425 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -20,6 +20,7 @@ #include "World.h" +#include "Fixture.h" #include "Shape.h" #include "Contact.h" #include "Physics.h" @@ -43,7 +44,7 @@ namespace box2d delete ref; } - void World::ContactCallback::add(World * world, const b2ContactPoint* point) + void World::ContactCallback::add(World * world, const b2Contact* contact) { /** * We must copy contacts, since we're not allowed to process @@ -52,7 +53,7 @@ namespace box2d **/ if(ref != 0) - contacts.push_back(new Contact(world, point)); + contacts.push_back(new Contact(world, contact)); } void World::ContactCallback::process() @@ -68,16 +69,16 @@ namespace box2d // Push first userdata. { - shapeudata * d = (shapeudata *)(contacts[i]->point.shape1->GetUserData()); + fixtureudata * d = (fixtureudata *)(contacts[i]->contact->GetFixtureA()->GetUserData()); if(d->ref != 0) d->ref->push(); else lua_pushnil(L); } - // Push first userdata. + // Push second userdata. { - shapeudata * d = (shapeudata *)(contacts[i]->point.shape2->GetUserData()); + fixtureudata * d = (fixtureudata *)(contacts[i]->contact->GetFixtureB()->GetUserData()); if(d->ref != 0) d->ref->push(); else @@ -99,16 +100,18 @@ namespace box2d World::World() : world(NULL) { - world = new b2World(b2Vec2(0,0), true); + world = new b2World(b2Vec2(0,0)); + world->SetAllowSleeping(true); world->SetContactListener(this); b2BodyDef def; - groundBody = world->CreateBody(def); + groundBody = world->CreateBody(&def); } World::World(b2Vec2 gravity, bool sleep) : world(NULL) { - world = new b2World(Physics::scaleDown(gravity), sleep); + world = new b2World(Physics::scaleDown(gravity)); + world->SetAllowSleeping(sleep); world->SetContactListener(this); } @@ -120,33 +123,33 @@ namespace box2d void World::update(float dt) { - world->Step(dt, 10); + world->Step(dt, 8, 6); - add.process(); - persist.process(); - remove.process(); - result.process(); + begin.process(); + end.process(); + presolve.process(); + postsolve.process(); } - void World::Add(const b2ContactPoint* point) + void World::BeginContact(b2Contact* contact) { - add.add(this, point); + begin.add(this, contact); } - void World::Persist(const b2ContactPoint* point) + void World::EndContact(b2Contact* contact) { - persist.add(this, point); + end.add(this, contact); } - void World::Remove(const b2ContactPoint* point) + void World::PreSolve(b2Contact* contact, const b2Manifold* oldManifold) { - remove.add(this, point); + presolve.add(this, contact); } - void World::Result(const b2ContactPoint* point) + void World::PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) { - result.add(this, point); + postsolve.add(this, contact); } int World::setCallbacks(lua_State * L) @@ -157,17 +160,17 @@ namespace box2d switch(n) { case 4: - if (result.ref) delete result.ref; - result.ref = luax_refif(L, LUA_TFUNCTION); + if (postsolve.ref) delete postsolve.ref; + postsolve.ref = luax_refif(L, LUA_TFUNCTION); case 3: - if (remove.ref) delete remove.ref; - remove.ref = luax_refif(L, LUA_TFUNCTION); + if (presolve.ref) delete presolve.ref; + presolve.ref = luax_refif(L, LUA_TFUNCTION); case 2: - if (persist.ref) delete persist.ref; - persist.ref = luax_refif(L, LUA_TFUNCTION); + if (end.ref) delete end.ref; + end.ref = luax_refif(L, LUA_TFUNCTION); case 1: - if (add.ref) delete add.ref; - add.ref = luax_refif(L, LUA_TFUNCTION); + if (begin.ref) delete begin.ref; + begin.ref = luax_refif(L, LUA_TFUNCTION); } return 0; @@ -175,10 +178,10 @@ namespace box2d int World::getCallbacks(lua_State * L) { - add.ref ? add.ref->push() : lua_pushnil(L); - persist.ref ? persist.ref->push() : lua_pushnil(L); - remove.ref ? remove.ref->push() : lua_pushnil(L); - result.ref ? result.ref->push() : lua_pushnil(L); + begin.ref ? begin.ref->push() : lua_pushnil(L); + end.ref ? end.ref->push() : lua_pushnil(L); + presolve.ref ? presolve.ref->push() : lua_pushnil(L); + postsolve.ref ? postsolve.ref->push() : lua_pushnil(L); return lua_gettop(L); } @@ -189,20 +192,20 @@ namespace box2d int World::getGravity(lua_State * L) { - b2Vec2 v = Physics::scaleUp(world->m_gravity); + b2Vec2 v = Physics::scaleUp(world->GetGravity()); lua_pushnumber(L, v.x); lua_pushnumber(L, v.y); return 2; } - void World::setAllowSleep(bool allow) + void World::setAllowSleeping(bool allow) { - world->m_allowSleep = allow; + world->SetAllowSleeping(allow); } - bool World::isAllowSleep() const + bool World::getAllowSleeping() const { - return world->m_allowSleep; + return world->GetAllowSleeping(); } int World::getBodyCount() diff --git a/src/modules/physics/box2d/World.h b/src/modules/physics/box2d/World.h index fb6447f4d..21ae6f754 100644 --- a/src/modules/physics/box2d/World.h +++ b/src/modules/physics/box2d/World.h @@ -69,7 +69,7 @@ namespace box2d std::vector contacts; ContactCallback(); ~ContactCallback(); - void add(World * world, const b2ContactPoint* point); + void add(World * world, const b2Contact* contact); void process(); }; @@ -82,7 +82,7 @@ namespace box2d b2Body * groundBody; // Contact callbacks. - ContactCallback add, persist, remove, result; + ContactCallback begin, end, presolve, postsolve; public: @@ -111,16 +111,16 @@ namespace box2d void update(float dt); // From b2ContactListener - void Add(const b2ContactPoint* point); - void Persist(const b2ContactPoint* point); - void Remove(const b2ContactPoint* point); - void Result(const b2ContactPoint* point); + void BeginContact(b2Contact* contact); + void EndContact(b2Contact* contact); + void PreSolve(b2Contact* contact, const b2Manifold* oldManifold); + void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse); /** * Receives up to four Lua functions as arguments. Each function is - * collision callback for the four events (in order): add, persist, - * remove and result. The value "nil" is accepted if one or more events - * are uninteresting. + * collision callback for the four events (in order): begin, end, + * presolve and postsolve. The value "nil" is accepted if one or + * more events are uninteresting. **/ int setCallbacks(lua_State * L); @@ -147,13 +147,13 @@ namespace box2d * Sets whether this World allows sleep. * @param allow True to allow, false to disallow. **/ - void setAllowSleep(bool allow); + void setAllowSleeping(bool allow); /** * Returns whether this World allows sleep. * @return True if allowed, false if disallowed. **/ - bool isAllowSleep() const; + bool getAllowSleeping() const; /** * Get the current body count. diff --git a/src/modules/physics/box2d/wrap_World.cpp b/src/modules/physics/box2d/wrap_World.cpp index 7ab9e76de..4e8f14dc9 100644 --- a/src/modules/physics/box2d/wrap_World.cpp +++ b/src/modules/physics/box2d/wrap_World.cpp @@ -70,18 +70,18 @@ namespace box2d return t->getGravity(L); } - int w_World_setAllowSleep(lua_State * L) + int w_World_setAllowSleeping(lua_State * L) { World * t = luax_checkworld(L, 1); bool b = luax_toboolean(L, 2); - t->setAllowSleep(b); + t->setAllowSleeping(b); return 0; } - int w_World_isAllowSleep(lua_State * L) + int w_World_getAllowSleeping(lua_State * L) { World * t = luax_checkworld(L, 1); - luax_pushboolean(L, t->isAllowSleep()); + luax_pushboolean(L, t->getAllowSleeping()); return 1; } @@ -105,8 +105,8 @@ namespace box2d { "getCallbacks", w_World_getCallbacks }, { "setGravity", w_World_setGravity }, { "getGravity", w_World_getGravity }, - { "setAllowSleep", w_World_setAllowSleep }, - { "isAllowSleep", w_World_isAllowSleep }, + { "setAllowSleeping", w_World_setAllowSleeping }, + { "getAllowSleeping", w_World_getAllowSleeping }, { "getBodyCount", w_World_getBodyCount }, { "getJointCount", w_World_getJointCount }, { 0, 0 } diff --git a/src/modules/physics/box2d/wrap_World.h b/src/modules/physics/box2d/wrap_World.h index 0ba044d84..7f99a7449 100644 --- a/src/modules/physics/box2d/wrap_World.h +++ b/src/modules/physics/box2d/wrap_World.h @@ -37,8 +37,8 @@ namespace box2d int w_World_getCallbacks(lua_State * L); int w_World_setGravity(lua_State * L); int w_World_getGravity(lua_State * L); - int w_World_setAllowSleep(lua_State * L); - int w_World_isAllowSleep(lua_State * L); + int w_World_setAllowSleeping(lua_State * L); + int w_World_getAllowSleeping(lua_State * L); int w_World_getBodyCount(lua_State * L); int w_World_getJointCount(lua_State * L); int luaopen_world(lua_State * L); From 71abae06c74df139cc97cf0c64acd3f81668ad03 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Fri, 23 Sep 2011 18:01:40 -0400 Subject: [PATCH 21/78] Implement Fixture class properly. --HG-- branch : box2d-update --- .../macosx/love.xcodeproj/project.pbxproj | 6 + src/common/types.h | 2 + src/modules/physics/box2d/Fixture.cpp | 295 +++++++++++++++++- src/modules/physics/box2d/Fixture.h | 129 ++++---- src/modules/physics/box2d/Physics.cpp | 5 + src/modules/physics/box2d/Physics.h | 8 + src/modules/physics/box2d/Shape.h | 1 + src/modules/physics/box2d/wrap_Fixture.cpp | 284 +++++++++++++++++ src/modules/physics/box2d/wrap_Fixture.h | 67 ++++ src/modules/physics/box2d/wrap_Physics.cpp | 9 + src/modules/physics/box2d/wrap_Physics.h | 1 + 11 files changed, 745 insertions(+), 62 deletions(-) create mode 100644 src/modules/physics/box2d/wrap_Fixture.cpp create mode 100644 src/modules/physics/box2d/wrap_Fixture.h diff --git a/platform/macosx/love.xcodeproj/project.pbxproj b/platform/macosx/love.xcodeproj/project.pbxproj index befd5e9e1..501020983 100644 --- a/platform/macosx/love.xcodeproj/project.pbxproj +++ b/platform/macosx/love.xcodeproj/project.pbxproj @@ -139,6 +139,7 @@ A946D85510425002002BF36C /* wrap_Timer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B9110420ACC007D418B /* wrap_Timer.cpp */; }; A946D85610425002002BF36C /* Timer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B8F10420ACC007D418B /* Timer.cpp */; }; A95684F7125D3555001B276B /* b64.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A95684F5125D3555001B276B /* b64.cpp */; }; + A958F911142D364C007F320F /* wrap_Fixture.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A958F910142D3627007F320F /* wrap_Fixture.cpp */; }; A968F0CF1083A9A900A895AA /* Event.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0CE1083A9A900A895AA /* Event.cpp */; }; A968F0D11083A9B900A895AA /* File.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0D01083A9B900A895AA /* File.cpp */; }; A968F0D31083A9D400A895AA /* Graphics.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0D21083A9D400A895AA /* Graphics.cpp */; }; @@ -535,6 +536,8 @@ A946D4421176AC42005E1462 /* Font.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Font.h; sourceTree = ""; }; A95684F5125D3555001B276B /* b64.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b64.cpp; sourceTree = ""; }; A95684F6125D3555001B276B /* b64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b64.h; sourceTree = ""; }; + A958F910142D3627007F320F /* wrap_Fixture.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_Fixture.cpp; sourceTree = ""; }; + A958F912142D3687007F320F /* wrap_Fixture.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_Fixture.h; sourceTree = ""; }; A968F0C61083A07B00A895AA /* EnumMap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EnumMap.h; sourceTree = ""; }; A968F0C71083A07C00A895AA /* StringMap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StringMap.h; sourceTree = ""; }; A968F0CE1083A9A900A895AA /* Event.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Event.cpp; sourceTree = ""; }; @@ -1260,6 +1263,8 @@ A93E6B5710420ACA007D418B /* wrap_DistanceJoint.h */, A96F41A51412C92B0067FE9A /* wrap_EdgeShape.cpp */, A96F41A61412C92B0067FE9A /* wrap_EdgeShape.h */, + A958F910142D3627007F320F /* wrap_Fixture.cpp */, + A958F912142D3687007F320F /* wrap_Fixture.h */, A9B6432D13BF87E400DC3C7E /* wrap_FrictionJoint.cpp */, A9B6432E13BF87EA00DC3C7E /* wrap_FrictionJoint.h */, A93E6B5810420ACA007D418B /* wrap_GearJoint.cpp */, @@ -1822,6 +1827,7 @@ A9D1D2041422578C00A8BC2F /* wrap_RopeJoint.cpp in Sources */, A9D1D20A1422959100A8BC2F /* ChainShape.cpp in Sources */, A9D1D20D14229B6500A8BC2F /* wrap_ChainShape.cpp in Sources */, + A958F911142D364C007F320F /* wrap_Fixture.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/src/common/types.h b/src/common/types.h index 567d93744..876aac852 100644 --- a/src/common/types.h +++ b/src/common/types.h @@ -69,6 +69,7 @@ namespace love PHYSICS_WORLD_ID, PHYSICS_CONTACT_ID, PHYSICS_BODY_ID, + PHYSICS_FIXTURE_ID, PHYSICS_SHAPE_ID, PHYSICS_CIRCLE_SHAPE_ID, PHYSICS_POLYGON_SHAPE_ID, @@ -140,6 +141,7 @@ namespace love const bits PHYSICS_WORLD_T = (bits(1) << PHYSICS_WORLD_ID) | OBJECT_T; const bits PHYSICS_CONTACT_T = (bits(1) << PHYSICS_CONTACT_ID) | OBJECT_T; const bits PHYSICS_BODY_T = (bits(1) << PHYSICS_BODY_ID) | OBJECT_T; + const bits PHYSICS_FIXTURE_T = (bits(1) << PHYSICS_FIXTURE_ID) | OBJECT_T; const bits PHYSICS_SHAPE_T = (bits(1) << PHYSICS_SHAPE_ID) | OBJECT_T; const bits PHYSICS_CIRCLE_SHAPE_T = (bits(1) << PHYSICS_CIRCLE_SHAPE_ID) | PHYSICS_SHAPE_T; const bits PHYSICS_POLYGON_SHAPE_T = (bits(1) << PHYSICS_POLYGON_SHAPE_ID) | PHYSICS_SHAPE_T; diff --git a/src/modules/physics/box2d/Fixture.cpp b/src/modules/physics/box2d/Fixture.cpp index fca250b11..47d2461a3 100644 --- a/src/modules/physics/box2d/Fixture.cpp +++ b/src/modules/physics/box2d/Fixture.cpp @@ -1,9 +1,290 @@ -// -// Fixture.cpp -// love -// -// Created by Bill Meltsner on 3/13/11. -// Copyright 2011 Bill Meltsner. All rights reserved. -// +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ #include "Fixture.h" + +// Module +#include "Body.h" +#include "World.h" +#include "Physics.h" + +// STD +#include + +namespace love +{ +namespace physics +{ +namespace box2d +{ + Fixture::Fixture(Body * body, Shape * shape) + : body(body), shape(shape), fixture(NULL) + { + body->retain(); + shape->retain(); + data = new fixtureudata(); + data->ref = 0; + b2FixtureDef def; + def.shape = shape->shape; + def.userData = (void *)data; + fixture = body->body->CreateFixture(&def); + } + + Fixture::~Fixture() + { + if(data->ref != 0) + delete data->ref; + + delete data; + data = 0; + + if (fixture) + body->body->DestroyFixture(fixture); + fixture = 0; + + body->release(); + } + + Shape::Type Fixture::getType() const + { + return shape->getType(); + } + + void Fixture::setFriction(float friction) + { + fixture->SetFriction(friction); + } + + void Fixture::setRestitution(float restitution) + { + fixture->SetRestitution(restitution); + } + + void Fixture::setDensity(float density) + { + fixture->SetDensity(density); + } + + void Fixture::setSensor(bool sensor) + { + fixture->SetSensor(sensor); + } + + float Fixture::getFriction() const + { + return fixture->GetFriction(); + } + + float Fixture::getRestitution() const + { + return fixture->GetRestitution(); + } + + float Fixture::getDensity() const + { + return fixture->GetDensity(); + } + + bool Fixture::isSensor() const + { + return fixture->IsSensor(); + } + + Body * Fixture::getBody() const + { + return body; + } + + Shape * Fixture::getShape() const + { + return shape; + } + + void Fixture::setFilterData(int * v) + { + b2Filter f; + f.categoryBits = (unsigned short)v[0]; + f.maskBits = (unsigned short)v[1]; + f.groupIndex = v[2]; + fixture->SetFilterData(f); + } + + void Fixture::getFilterData(int * v) + { + b2Filter f = fixture->GetFilterData(); + v[0] = (int)f.categoryBits; + v[1] = (int)f.maskBits; + v[2] = f.groupIndex; + } + + int Fixture::setCategory(lua_State * L) + { + b2Filter f = fixture->GetFilterData(); + f.categoryBits = (uint16)getBits(L); + fixture->SetFilterData(f); + return 0; + } + + int Fixture::setMask(lua_State * L) + { + b2Filter f = fixture->GetFilterData(); + f.maskBits = ~(uint16)getBits(L); + fixture->SetFilterData(f); + return 0; + } + + void Fixture::setGroupIndex(int index) + { + b2Filter f = fixture->GetFilterData(); + f.groupIndex = (uint16)index; + fixture->SetFilterData(f); + } + + int Fixture::getGroupIndex() const + { + b2Filter f = fixture->GetFilterData(); + return f.groupIndex; + } + + int Fixture::getCategory(lua_State * L) + { + return pushBits(L, fixture->GetFilterData().categoryBits); + } + + int Fixture::getMask(lua_State * L) + { + return pushBits(L, ~(fixture->GetFilterData().maskBits)); + } + + uint16 Fixture::getBits(lua_State * L) + { + // Get number of args. + int argc = lua_gettop(L); + + // The new bitset. + std::bitset<16> b; + + for(int i = 1;i<=argc;i++) + { + size_t bpos = (size_t)(lua_tointeger(L, i)-1); + if(bpos > 16) + return luaL_error(L, "Values must be in range 1-16."); + b.set(bpos, true); + } + + return (uint16)b.to_ulong(); + } + + int Fixture::pushBits(lua_State * L, uint16 bits) + { + // Create a bitset. + std::bitset<16> b((int)bits); + + // Push all set bits. + for(int i = 0;i<16;i++) + if(b.test(i)) + lua_pushinteger(L, i+1); + + // Count number of set bits. + return (int)b.count(); + } + + int Fixture::setUserData(lua_State * L) + { + love::luax_assert_argc(L, 1, 1); + + if(data->ref != 0) + { + delete data->ref; + data->ref = 0; + } + + data->ref = new Reference(L); + return 0; + } + + int Fixture::getUserData(lua_State * L) + { + love::luax_assert_argc(L, 0, 0); + if(data->ref != 0) + data->ref->push(); + else + lua_pushnil(L); + + return 1; + } + + bool Fixture::testPoint(float x, float y) const + { + return fixture->TestPoint(Physics::scaleDown(b2Vec2(x, y))); + } + + int Fixture::rayCast(lua_State * L) const + { + float p1x = Physics::scaleDown((float)luaL_checknumber(L, 1)); + float p1y = Physics::scaleDown((float)luaL_checknumber(L, 2)); + float p2x = Physics::scaleDown((float)luaL_checknumber(L, 3)); + float p2y = Physics::scaleDown((float)luaL_checknumber(L, 4)); + float maxFraction = (float)luaL_checknumber(L, 5); + float x = Physics::scaleDown((float)luaL_checknumber(L, 6)); + float y = Physics::scaleDown((float)luaL_checknumber(L, 7)); + float r = (float)luaL_checknumber(L, 8); + int childIndex = (int)luaL_optint(L, 9, 0); + b2RayCastInput input; + input.p1.Set(p1x, p1y); + input.p2.Set(p2x, p2y); + input.maxFraction = maxFraction; + b2Transform transform(b2Vec2(x, y), b2Rot(r)); + b2RayCastOutput output; + fixture->RayCast(&output, input, childIndex); + lua_pushnumber(L, Physics::scaleUp(output.normal.x)); + lua_pushnumber(L, Physics::scaleUp(output.normal.y)); + lua_pushnumber(L, output.fraction); + return 3; + } + + int Fixture::getBoundingBox(lua_State * L) const + { + int childIndex = (int)luaL_optint(L, 1, 0); + b2AABB box = fixture->GetAABB(childIndex); + box = Physics::scaleUp(box); + lua_pushnumber(L, box.lowerBound.x); + lua_pushnumber(L, box.lowerBound.y); + lua_pushnumber(L, box.upperBound.x); + lua_pushnumber(L, box.upperBound.y); + return 4; + } + + int Fixture::getMassData(lua_State * L) const + { + b2MassData data; + fixture->GetMassData(&data); + b2Vec2 center = Physics::scaleUp(data.center); + lua_pushnumber(L, center.x); + lua_pushnumber(L, center.y); + lua_pushnumber(L, data.mass); + lua_pushnumber(L, data.I); + return 4; + } + + +} // box2d +} // physics +} // love diff --git a/src/modules/physics/box2d/Fixture.h b/src/modules/physics/box2d/Fixture.h index 76760b5d7..c06d9d8ca 100644 --- a/src/modules/physics/box2d/Fixture.h +++ b/src/modules/physics/box2d/Fixture.h @@ -59,6 +59,8 @@ namespace box2d { protected: + Body * body; + Shape * shape; b2Fixture * fixture; fixtureudata * data; @@ -76,6 +78,64 @@ namespace box2d * debug drawing. **/ Shape::Type getType() const; + + /** + * Gets the Shape attached to this Fixture. + **/ + Shape * getShape() const; + + /** + * Checks whether this Fixture acts as a sensor. + * @return True if sensor, false otherwise. + **/ + bool isSensor() const; + + /** + * Set whether this Fixture should be a sensor or not. + * @param sensor True if sensor, false if not. + **/ + void setSensor(bool sensor); + + /** + * Gets the Body this Fixture is attached to. + **/ + Body * getBody() const; + + /** + * Gets the next Fixture attached to the parent Body. + **/ + Fixture * getNext() const; + + + + /** + * Sets the filter data. An integer array is used even though the + * first two elements are unsigned shorts. The elements are: + * category (16-bits), mask (16-bits) and group (32-bits/int). + **/ + void setFilterData(int * v); + + /** + * Gets the filter data. An integer array is used even though the + * first two elements are unsigned shorts. The elements are: + * category (16-bits), mask (16-bits) and group (32-bits/int). + **/ + void getFilterData(int * v); + + /** + * This function stores an in-C reference to + * arbitrary Lua data in the Box2D Fixture object. + * + * The data set here will be passed to the collision + * handler when collisions occur. + **/ + int setUserData(lua_State * L); + + /** + * Gets the data set with setData. If no + * data is set, nil is returned. + **/ + int getUserData(lua_State * L); /** * Sets the friction of the Fixture. @@ -95,12 +155,6 @@ namespace box2d **/ void setDensity(float density); - /** - * Set whether this Fixture should be a sensor or not. - * @param sensor True if sensor, false if not. - **/ - void setSensor(bool sensor); - /** * Gets the friction of the Fixture. * @returns The friction. @@ -118,45 +172,19 @@ namespace box2d * @return The density. **/ float getDensity() const; - - /** - * Checks whether this Fixture acts as a sensor. - * @return True if sensor, false otherwise. - **/ - bool isSensor() const; - - /** - * Get the body attatched to this Fixture. - * @return The parent Body. - **/ - Body * getBody() const; - + /** * Checks if a point is inside the Fixture. - * @param x The x-component of the Fixture. - * @param y The y-component of the Fixture. + * @param x The x-component of the point. + * @param y The y-component of the point. **/ bool testPoint(float x, float y) const; - + /** - * Tests whether a line segment intersects a Fixture. + * Cast a ray against this Fixture. **/ - int testSegment(lua_State * L); - - /** - * Sets the filter data. An integer array is used even though the - * first two elements are unsigned shorts. The elements are: - * category (16-bits), mask (16-bits) and group (32-bits/int). - **/ - void setFilterData(int * v); - - /** - * Gets the filter data. An integer array is used even though the - * first two elements are unsigned shorts. The elements are: - * category (16-bits), mask (16-bits) and group (32-bits/int). - **/ - void getFilterData(int * v); - + int rayCast(lua_State * L) const; + void setGroupIndex(int index); int getGroupIndex() const; @@ -167,27 +195,18 @@ namespace box2d uint16 getBits(lua_State * L); int pushBits(lua_State * L, uint16 bits); - /** - * This function stores an in-C reference to - * arbitrary Lua data in the Box2D Fixture object. - * - * The data set here will be passed to the collision - * handler when collisions occur. - **/ - int setData(lua_State * L); - - /** - * Gets the data set with setData. If no - * data is set, nil is returned. - **/ - int getData(lua_State * L); - /** * Gets the bounding box for this Fixture. * The function returns eight values which can be * passed directly to love.graphics.polygon. **/ - int getBoundingBox(lua_State * L); + int getBoundingBox(lua_State * L) const; + + /** + * Gets the mass data for this Fixture. + * This operation may be expensive. + **/ + int getMassData(lua_State * L) const; }; } // box2d diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 5c7c59361..3aee9e050 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -59,6 +59,11 @@ namespace box2d { return new Body(world, b2Vec2(0, 0), 1, 1); } + + Fixture * Physics::newFixture(Body * body, Shape * shape) + { + return new Fixture(body, shape); + } CircleShape * Physics::newCircleShape(float radius) { diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index 2cca64dec..342eae8de 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -26,6 +26,7 @@ #include "World.h" #include "Contact.h" #include "Body.h" +#include "Fixture.h" #include "Shape.h" #include "CircleShape.h" #include "PolygonShape.h" @@ -98,6 +99,13 @@ namespace box2d * @param world The world to create the Body in. **/ Body * newBody(World * world); + + /** + * Creates a new Fixture. + * @param body The body to attach the Fixture to. + * @param shape The shape to attach to the Fixture. + **/ + Fixture * newFixture(Body * body, Shape * shape); /** * Creates a new CircleShape at (0, 0). diff --git a/src/modules/physics/box2d/Shape.h b/src/modules/physics/box2d/Shape.h index d388088c3..78334a6f7 100644 --- a/src/modules/physics/box2d/Shape.h +++ b/src/modules/physics/box2d/Shape.h @@ -44,6 +44,7 @@ namespace box2d **/ class Shape : public love::physics::Shape { + friend class Fixture; protected: diff --git a/src/modules/physics/box2d/wrap_Fixture.cpp b/src/modules/physics/box2d/wrap_Fixture.cpp new file mode 100644 index 000000000..bc758f4db --- /dev/null +++ b/src/modules/physics/box2d/wrap_Fixture.cpp @@ -0,0 +1,284 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#include "wrap_Fixture.h" +#include + +namespace love +{ +namespace physics +{ +namespace box2d +{ + Fixture * luax_checkfixture(lua_State * L, int idx) + { + return luax_checktype(L, idx, "Fixture", PHYSICS_FIXTURE_T); + } + + int w_Fixture_getType(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + const char * type = ""; + Shape::getConstant(t->getType(), type); + lua_pushstring(L, type); + return 1; + } + + int w_Fixture_setFriction(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setFriction(arg1); + return 0; + } + + int w_Fixture_setRestitution(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setRestitution(arg1); + return 0; + } + + int w_Fixture_setDensity(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setDensity(arg1); + return 0; + } + + int w_Fixture_setSensor(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + bool arg1 = luax_toboolean(L, 2); + t->setSensor(arg1); + return 0; + } + + int w_Fixture_getFriction(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + lua_pushnumber(L, t->getFriction()); + return 1; + } + + int w_Fixture_getRestitution(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + lua_pushnumber(L, t->getRestitution()); + return 1; + } + + int w_Fixture_getDensity(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + lua_pushnumber(L, t->getDensity()); + return 1; + } + + int w_Fixture_isSensor(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + luax_pushboolean(L, t->isSensor()); + return 1; + } + + int w_Fixture_getBody(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + Body * body = t->getBody(); + if(body == 0) + return 0; + body->retain(); + luax_newtype(L, "Body", PHYSICS_BODY_T, (void*)body); + return 1; + } + + int w_Fixture_getShape(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + Shape * shape = t->getShape(); + if(shape == 0) + return 0; + shape->retain(); + luax_newtype(L, "Shape", PHYSICS_SHAPE_T, (void*)shape); + return 1; + } + + int w_Fixture_testPoint(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + float x = (float)luaL_checknumber(L, 2); + float y = (float)luaL_checknumber(L, 3); + luax_pushboolean(L, t->testPoint(x, y)); + return 1; + } + + int w_Fixture_rayCast(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + lua_remove(L, 1); + return t->rayCast(L); + } + + int w_Fixture_setFilterData(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + int v[3]; + v[0] = luaL_checkint(L, 2); + v[1] = luaL_checkint(L, 3); + v[2] = luaL_checkint(L, 4); + t->setFilterData(v); + return 0; + } + + int w_Fixture_getFilterData(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + int v[3]; + t->getFilterData(v); + lua_pushinteger(L, v[0]); + lua_pushinteger(L, v[1]); + lua_pushinteger(L, v[2]); + return 3; + } + + int w_Fixture_setCategory(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + lua_remove(L, 1); + return t->setCategory(L); + } + + int w_Fixture_getCategory(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + lua_remove(L, 1); + return t->getCategory(L); + } + + int w_Fixture_setMask(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + lua_remove(L, 1); + return t->setMask(L); + } + + int w_Fixture_getMask(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + lua_remove(L, 1); + return t->getMask(L); + } + + int w_Fixture_setUserData(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + lua_remove(L, 1); + return t->setUserData(L); + } + + int w_Fixture_getUserData(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + lua_remove(L, 1); + return t->getUserData(L); + } + + int w_Fixture_getBoundingBox(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + lua_remove(L, 1); + return t->getBoundingBox(L); + } + + int w_Fixture_getMassData(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + lua_remove(L, 1); + return t->getMassData(L); + } + + int w_Fixture_getGroupIndex(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + int i = t->getGroupIndex(); + lua_pushinteger(L, i); + return 1; + } + + int w_Fixture_setGroupIndex(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + int i = luaL_checkint(L, 2); + t->setGroupIndex(i); + return 0; + } + + int w_Fixture_destroy(lua_State * L) + { + Proxy * p = (Proxy *)lua_touserdata(L, 1); + p->own = false; + + Fixture * t = (Fixture *)p->data; + t->release(); + return 0; + } + + static const luaL_Reg functions[] = { + { "getType", w_Fixture_getType }, + { "setFriction", w_Fixture_setFriction }, + { "setRestitution", w_Fixture_setRestitution }, + { "setDensity", w_Fixture_setDensity }, + { "setSensor", w_Fixture_setSensor }, + { "getFriction", w_Fixture_getFriction }, + { "getRestitution", w_Fixture_getRestitution }, + { "getDensity", w_Fixture_getDensity }, + { "getBody", w_Fixture_getBody }, + { "getShape", w_Fixture_getShape }, + { "isSensor", w_Fixture_isSensor }, + { "testPoint", w_Fixture_testPoint }, + { "rayCast", w_Fixture_rayCast }, + { "setFilterData", w_Fixture_setFilterData }, + { "getFilterData", w_Fixture_getFilterData }, + { "setCategory", w_Fixture_setCategory }, + { "getCategory", w_Fixture_getCategory }, + { "setMask", w_Fixture_setMask }, + { "getMask", w_Fixture_getMask }, + { "setUserData", w_Fixture_setUserData }, + { "getUserData", w_Fixture_getUserData }, + { "getBoundingBox", w_Fixture_getBoundingBox }, + { "getMassData", w_Fixture_getMassData }, + { "getGroupIndex", w_Fixture_getGroupIndex }, + { "setGroupIndex", w_Fixture_setGroupIndex }, + { "destroy", w_Fixture_destroy }, + { 0, 0 } + }; + + int luaopen_fixture(lua_State * L) + { + return luax_register_type(L, "Fixture", functions); + } + +} // box2d +} // physics +} // love + diff --git a/src/modules/physics/box2d/wrap_Fixture.h b/src/modules/physics/box2d/wrap_Fixture.h new file mode 100644 index 000000000..d41f6b25a --- /dev/null +++ b/src/modules/physics/box2d/wrap_Fixture.h @@ -0,0 +1,67 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BOX2D_WRAP_FIXTURE_H +#define LOVE_PHYSICS_BOX2D_WRAP_FIXTURE_H + +// LOVE +#include +#include "Fixture.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + Fixture * luax_checkfixture(lua_State * L, int idx); + int w_Fixture_getType(lua_State * L); + int w_Fixture_setFriction(lua_State * L); + int w_Fixture_setRestitution(lua_State * L); + int w_Fixture_setDensity(lua_State * L); + int w_Fixture_setSensor(lua_State * L); + int w_Fixture_getFriction(lua_State * L); + int w_Fixture_getRestitution(lua_State * L); + int w_Fixture_getDensity(lua_State * L); + int w_Fixture_isSensor(lua_State * L); + int w_Fixture_getBody(lua_State * L); + int w_Fixture_getShape(lua_State * L); + int w_Fixture_testPoint(lua_State * L); + int w_Fixture_rayCast(lua_State * L); + int w_Fixture_setFilterData(lua_State * L); + int w_Fixture_getFilterData(lua_State * L); + int w_Fixture_setCategory(lua_State * L); + int w_Fixture_getCategory(lua_State * L); + int w_Fixture_setMask(lua_State * L); + int w_Fixture_getMask(lua_State * L); + int w_Fixture_setUserData(lua_State * L); + int w_Fixture_getUserData(lua_State * L); + int w_Fixture_getBoundingBox(lua_State * L); + int w_Fixture_getMassData(lua_State * L); + int w_Fixture_getGroupIndex(lua_State * L); + int w_Fixture_setGroupIndex(lua_State * L); + int w_Fixture_destroy(lua_State * L); + int luaopen_fixture(lua_State * L); + +} // box2d +} // physics +} // love + +#endif // LOVE_PHYSICS_BOX2D_WRAP_FIXTURE_H diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index e5bab7518..928706dde 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -53,6 +53,15 @@ namespace box2d luax_newtype(L, "Body", PHYSICS_BODY_T, (void*)body); return 1; } + + int w_newFixture(lua_State * L) + { + Body * body = luax_checkbody(L, 1); + Shape * shape = luax_checkshape(L, 2); + Fixture * fixture = instance->newFixture(body, shape); + luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)fixture); + return 1; + } int w_newCircleShape(lua_State * L) { diff --git a/src/modules/physics/box2d/wrap_Physics.h b/src/modules/physics/box2d/wrap_Physics.h index 29d7e2e58..09cf0b4cf 100644 --- a/src/modules/physics/box2d/wrap_Physics.h +++ b/src/modules/physics/box2d/wrap_Physics.h @@ -52,6 +52,7 @@ namespace box2d { int w_newWorld(lua_State * L); int w_newBody(lua_State * L); + int w_newFixture(lua_State * L); int w_newCircleShape(lua_State * L); int w_newRectangleShape(lua_State * L); int w_newPolygonShape(lua_State * L); From 0678eac4531a547e2d366937df0ecc08febd3ae2 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Fri, 23 Sep 2011 21:25:41 -0400 Subject: [PATCH 22/78] A first attempt at overhauling collision. New everything. --HG-- branch : box2d-update --- src/modules/physics/box2d/Contact.cpp | 78 +++++++++++++------- src/modules/physics/box2d/Contact.h | 67 ++++++++++++------ src/modules/physics/box2d/World.cpp | 36 +++++++--- src/modules/physics/box2d/World.h | 8 ++- src/modules/physics/box2d/wrap_Contact.cpp | 82 +++++++++++++++++----- src/modules/physics/box2d/wrap_Contact.h | 11 ++- 6 files changed, 203 insertions(+), 79 deletions(-) diff --git a/src/modules/physics/box2d/Contact.cpp b/src/modules/physics/box2d/Contact.cpp index bc9583ab0..7a1b9ffa8 100644 --- a/src/modules/physics/box2d/Contact.cpp +++ b/src/modules/physics/box2d/Contact.cpp @@ -28,54 +28,82 @@ namespace physics { namespace box2d { - Contact::Contact(World * world, b2Contact * contact) - : contact(contact), world(world) + Contact::Contact(b2Contact * contact) + : contact(contact) { - world->retain(); } Contact::~Contact() { - world->release(); } - int Contact::getPosition(lua_State * L) + int Contact::getPositions(lua_State * L) { love::luax_assert_argc(L, 1, 1); - lua_pushnumber(L, Physics::scaleUp(point.position.x)); - lua_pushnumber(L, Physics::scaleUp(point.position.y)); - return 2; - } - - int Contact::getVelocity(lua_State * L) - { - love::luax_assert_argc(L, 1, 1); - lua_pushnumber(L, Physics::scaleUp(point.velocity.x)); - lua_pushnumber(L, Physics::scaleUp(point.velocity.y)); - return 2; + b2WorldManifold manifold; + contact->GetWorldManifold(&manifold); + int points = contact->GetManifold()->pointCount; + for (int i = 0; i < points; i++) { + b2Vec2 position = Physics::scaleUp(manifold.points[i]); + lua_pushnumber(L, position.x); + lua_pushnumber(L, position.y); + } + return points*2; } int Contact::getNormal(lua_State * L) { love::luax_assert_argc(L, 1, 1); - lua_pushnumber(L, Physics::scaleUp(point.normal.x)); - lua_pushnumber(L, Physics::scaleUp(point.normal.y)); + b2WorldManifold manifold; + contact->GetWorldManifold(&manifold); + lua_pushnumber(L, Physics::scaleUp(manifold.normal.x)); + lua_pushnumber(L, Physics::scaleUp(manifold.normal.y)); return 2; } - float Contact::getSeparation() const - { - return Physics::scaleUp(point.separation); - } - float Contact::getFriction() const { - return point.friction; + return contact->GetFriction(); } float Contact::getRestitution() const { - return point.restitution; + return contact->GetRestitution(); + } + + bool Contact::isEnabled() const + { + return contact->IsEnabled(); + } + + bool Contact::isTouching() const + { + return contact->IsTouching(); + } + + void Contact::setFriction(float friction) + { + contact->SetFriction(friction); + } + + void Contact::setRestitution(float restitution) + { + contact->SetRestitution(restitution); + } + + void Contact::setEnabled(bool enabled) + { + contact->SetEnabled(enabled); + } + + void Contact::resetFriction() + { + contact->ResetFriction(); + } + + void Contact::resetRestitution() + { + contact->ResetRestitution(); } } // box2d diff --git a/src/modules/physics/box2d/Contact.h b/src/modules/physics/box2d/Contact.h index 150bfdc91..8db2f5233 100644 --- a/src/modules/physics/box2d/Contact.h +++ b/src/modules/physics/box2d/Contact.h @@ -51,10 +51,7 @@ namespace box2d // The Box2D contact. b2Contact* contact; - - // The parent world. Needed for scaling. - World * world; - + public: /** @@ -63,23 +60,16 @@ namespace box2d * data pointed to. * @param point Pointer to the Box2D contact. **/ - Contact(World * world, const b2Contact * contact); + Contact(b2Contact * contact); virtual ~Contact(); /** - * Gets the position of the Contact. + * Gets the position of each point of contact. * @return The position along the x-axis. * @return The position along the y-axis. **/ - int getPosition(lua_State * L); - - /** - * Gets the linear impact velocity. - * @return The velocity along the x-axis. - * @return The velocity along the y-axis. - **/ - int getVelocity(lua_State * L); + int getPositions(lua_State * L); /** * Gets the collision normal. @@ -89,22 +79,55 @@ namespace box2d int getNormal(lua_State * L); /** - * How far apart the shapes are. If they are intersecting - * this value is negative. - **/ - float getSeparation() const; - - /** - * The mixed friction between the two shapes at + * The mixed friction between the two fixtures at * the point of impact. **/ float getFriction() const; /** - * The mixed restitution of the two shapes + * The mixed restitution of the two fixtures * at the point of impact. **/ float getRestitution() const; + + /** + * Check if the contact is enabled. + **/ + bool isEnabled() const; + + /** + * Check if the contact is touching. + **/ + bool isTouching() const; + + // Only call the setters in PreSolve + + /** + * Override the default friction mixture. + **/ + void setFriction(float friction); + + /** + * Override the default restitution mixture. + **/ + void setRestitution(float restitution); + + /** + * Enable/disable this contact. + **/ + void setEnabled(bool enabled); + + /** + * Reset the friction mixture to the default + * value. + **/ + void resetFriction(); + + /** + * Reset the restitution mixture to the default + * value. + **/ + void resetRestitution(); }; diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index ab3ce8425..9649d9f8a 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -44,7 +44,7 @@ namespace box2d delete ref; } - void World::ContactCallback::add(World * world, const b2Contact* contact) + void World::ContactCallback::add(b2Contact* contact) { /** * We must copy contacts, since we're not allowed to process @@ -53,7 +53,15 @@ namespace box2d **/ if(ref != 0) - contacts.push_back(new Contact(world, contact)); + contacts.push_back(new Contact(contact)); + } + + void World::ContactCallback::add(b2Contact* contact, const b2ContactImpulse* impulse) + { + if(ref != 0) { + contacts.push_back(new Contact(contact)); + impulses.push_back(impulse); + } } void World::ContactCallback::process() @@ -86,13 +94,25 @@ namespace box2d } luax_newtype(L, "Contact", (PHYSICS_CONTACT_T), (void*)contacts[i], false); - lua_call(L, 3, 0); + + int args = 3; + if ((int)impulses.size() > i) { + const b2ContactImpulse * impulse = impulses[i]; + for (int c = 0; c < impulse->count; c++) { + lua_pushnumber(L, Physics::scaleUp(impulse->normalImpulses[c])); + lua_pushnumber(L, Physics::scaleUp(impulse->tangentImpulses[c])); + args += 2; + } + } + lua_call(L, args, 0); } // Clear contacts. for(int i = 0;i<(int)contacts.size();i++) delete contacts[i]; contacts.clear(); + // Clear impulses. + impulses.clear(); } } @@ -134,22 +154,22 @@ namespace box2d void World::BeginContact(b2Contact* contact) { - begin.add(this, contact); + begin.add(contact); } void World::EndContact(b2Contact* contact) { - end.add(this, contact); + end.add(contact); } - void World::PreSolve(b2Contact* contact, const b2Manifold* oldManifold) + void World::PreSolve(b2Contact* contact) { - presolve.add(this, contact); + presolve.add(contact); } void World::PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) { - postsolve.add(this, contact); + postsolve.add(contact, impulse); } int World::setCallbacks(lua_State * L) diff --git a/src/modules/physics/box2d/World.h b/src/modules/physics/box2d/World.h index 21ae6f754..25ae32b2c 100644 --- a/src/modules/physics/box2d/World.h +++ b/src/modules/physics/box2d/World.h @@ -67,9 +67,13 @@ namespace box2d public: Reference * ref; std::vector contacts; + std::vector impulses; + b2Manifold* oldManifold; + b2ContactImpulse* impulse; ContactCallback(); ~ContactCallback(); - void add(World * world, const b2Contact* contact); + void add(b2Contact* contact); + void add(b2Contact* contact, const b2ContactImpulse* impulse); void process(); }; @@ -113,7 +117,7 @@ namespace box2d // From b2ContactListener void BeginContact(b2Contact* contact); void EndContact(b2Contact* contact); - void PreSolve(b2Contact* contact, const b2Manifold* oldManifold); + void PreSolve(b2Contact* contact); void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse); /** diff --git a/src/modules/physics/box2d/wrap_Contact.cpp b/src/modules/physics/box2d/wrap_Contact.cpp index 16eefa818..71997d790 100644 --- a/src/modules/physics/box2d/wrap_Contact.cpp +++ b/src/modules/physics/box2d/wrap_Contact.cpp @@ -32,31 +32,18 @@ namespace box2d return luax_checktype(L, idx, "Contact", PHYSICS_CONTACT_T); } - int w_Contact_getPosition(lua_State * L) + int w_Contact_getPositions(lua_State * L) { Contact * t = luax_checkcontact(L, 1); - return t->getPosition(L); + return t->getPositions(L); } - - int w_Contact_getVelocity(lua_State * L) - { - Contact * t = luax_checkcontact(L, 1); - return t->getVelocity(L); - } - + int w_Contact_getNormal(lua_State * L) { Contact * t = luax_checkcontact(L, 1); return t->getNormal(L); } - int w_Contact_getSeparation(lua_State * L) - { - Contact * t = luax_checkcontact(L, 1); - lua_pushnumber(L, t->getSeparation()); - return 1; - } - int w_Contact_getFriction(lua_State * L) { Contact * t = luax_checkcontact(L, 1); @@ -70,16 +57,73 @@ namespace box2d lua_pushnumber(L, t->getRestitution()); return 1; } + + int w_Contact_isEnabled(lua_State * L) + { + Contact * t = luax_checkcontact(L, 1); + lua_pushboolean(L, t->isEnabled()); + return 1; + } + + int w_Contact_isTouching(lua_State * L) + { + Contact * t = luax_checkcontact(L, 1); + lua_pushboolean(L, t->isTouching()); + return 1; + } + + int w_Contact_setFriction(lua_State * L) + { + Contact * t = luax_checkcontact(L, 1); + float f = (float)luaL_checknumber(L, 2); + t->setFriction(f); + return 0; + } + + int w_Contact_setRestitution(lua_State * L) + { + Contact * t = luax_checkcontact(L, 1); + float r = (float)luaL_checknumber(L, 2); + t->setRestitution(r); + return 0; + } + + int w_Contact_setEnabled(lua_State * L) + { + Contact * t = luax_checkcontact(L, 1); + bool e = luax_toboolean(L, 2); + t->setEnabled(e); + return 0; + } + + int w_Contact_resetFriction(lua_State * L) + { + Contact * t = luax_checkcontact(L, 1); + t->resetFriction(); + return 0; + } + + int w_Contact_resetRestitution(lua_State * L) + { + Contact * t = luax_checkcontact(L, 1); + t->resetRestitution(); + return 0; + } int luaopen_contact(lua_State * L) { static const luaL_Reg functions[] = { - { "getPosition", w_Contact_getPosition }, - { "getVelocity", w_Contact_getVelocity }, + { "getPositions", w_Contact_getPositions }, { "getNormal", w_Contact_getNormal }, - { "getSeparation", w_Contact_getSeparation }, { "getFriction", w_Contact_getFriction }, { "getRestitution", w_Contact_getRestitution }, + { "isEnabled", w_Contact_isEnabled }, + { "isTouching", w_Contact_isTouching }, + { "setFriction", w_Contact_setFriction }, + { "setRestitution", w_Contact_setRestitution }, + { "setEnabled", w_Contact_setEnabled }, + { "resetFriction", w_Contact_resetFriction }, + { "resetRestitution", w_Contact_resetRestitution }, { 0, 0 } }; diff --git a/src/modules/physics/box2d/wrap_Contact.h b/src/modules/physics/box2d/wrap_Contact.h index 2e261a8f3..3c0c906a8 100644 --- a/src/modules/physics/box2d/wrap_Contact.h +++ b/src/modules/physics/box2d/wrap_Contact.h @@ -32,12 +32,17 @@ namespace physics namespace box2d { Contact * luax_checkcontact(lua_State * L, int idx); - int w_Contact_getPosition(lua_State * L); - int w_Contact_getVelocity(lua_State * L); + int w_Contact_getPositions(lua_State * L); int w_Contact_getNormal(lua_State * L); - int w_Contact_getSeparation(lua_State * L); int w_Contact_getFriction(lua_State * L); int w_Contact_getRestitution(lua_State * L); + int w_Contact_isEnabled(lua_State * L); + int w_Contact_isTouching(lua_State * L); + int w_Contact_setFriction(lua_State * L); + int w_Contact_setRestitution(lua_State * L); + int w_Contact_setEnabled(lua_State * L); + int w_Contact_resetFriction(lua_State * L); + int w_Contact_resetRestitution(lua_State * L); int luaopen_contact(lua_State * L); } // box2d From 367dbc2ecccde8465e2775a40497ef71394403bd Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Fri, 23 Sep 2011 22:21:14 -0400 Subject: [PATCH 23/78] Update Body API. --HG-- branch : box2d-update --- .../macosx/love.xcodeproj/project.pbxproj | 6 + src/modules/physics/Body.cpp | 51 ++++++ src/modules/physics/Body.h | 59 +++++++ src/modules/physics/box2d/Body.cpp | 161 ++++++++++++------ src/modules/physics/box2d/Body.h | 91 ++++++---- src/modules/physics/box2d/Fixture.h | 7 - src/modules/physics/box2d/Physics.cpp | 14 +- src/modules/physics/box2d/Physics.h | 17 -- src/modules/physics/box2d/World.cpp | 3 +- src/modules/physics/box2d/World.h | 2 +- src/modules/physics/box2d/wrap_Body.cpp | 154 ++++++++++++----- src/modules/physics/box2d/wrap_Body.h | 32 ++-- src/modules/physics/box2d/wrap_Physics.cpp | 13 +- src/modules/physics/box2d/wrap_Physics.h | 1 - 14 files changed, 416 insertions(+), 195 deletions(-) create mode 100644 src/modules/physics/Body.cpp create mode 100644 src/modules/physics/Body.h diff --git a/platform/macosx/love.xcodeproj/project.pbxproj b/platform/macosx/love.xcodeproj/project.pbxproj index 501020983..7e081e935 100644 --- a/platform/macosx/love.xcodeproj/project.pbxproj +++ b/platform/macosx/love.xcodeproj/project.pbxproj @@ -140,6 +140,7 @@ A946D85610425002002BF36C /* Timer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B8F10420ACC007D418B /* Timer.cpp */; }; A95684F7125D3555001B276B /* b64.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A95684F5125D3555001B276B /* b64.cpp */; }; A958F911142D364C007F320F /* wrap_Fixture.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A958F910142D3627007F320F /* wrap_Fixture.cpp */; }; + A958F917142D6B3A007F320F /* Body.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A958F916142D6B37007F320F /* Body.cpp */; }; A968F0CF1083A9A900A895AA /* Event.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0CE1083A9A900A895AA /* Event.cpp */; }; A968F0D11083A9B900A895AA /* File.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0D01083A9B900A895AA /* File.cpp */; }; A968F0D31083A9D400A895AA /* Graphics.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0D21083A9D400A895AA /* Graphics.cpp */; }; @@ -538,6 +539,8 @@ A95684F6125D3555001B276B /* b64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b64.h; sourceTree = ""; }; A958F910142D3627007F320F /* wrap_Fixture.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_Fixture.cpp; sourceTree = ""; }; A958F912142D3687007F320F /* wrap_Fixture.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_Fixture.h; sourceTree = ""; }; + A958F916142D6B37007F320F /* Body.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Body.cpp; sourceTree = ""; }; + A958F918142D6B60007F320F /* Body.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Body.h; sourceTree = ""; }; A968F0C61083A07B00A895AA /* EnumMap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EnumMap.h; sourceTree = ""; }; A968F0C71083A07C00A895AA /* StringMap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StringMap.h; sourceTree = ""; }; A968F0CE1083A9A900A895AA /* Event.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Event.cpp; sourceTree = ""; }; @@ -1195,6 +1198,8 @@ A93E6AE910420AC7007D418B /* physics */ = { isa = PBXGroup; children = ( + A958F916142D6B37007F320F /* Body.cpp */, + A958F918142D6B60007F320F /* Body.h */, A93E6AEA10420AC7007D418B /* box2d */, A968F0DC1083AA6600A895AA /* Joint.cpp */, A93E6B6C10420ACB007D418B /* Joint.h */, @@ -1828,6 +1833,7 @@ A9D1D20A1422959100A8BC2F /* ChainShape.cpp in Sources */, A9D1D20D14229B6500A8BC2F /* wrap_ChainShape.cpp in Sources */, A958F911142D364C007F320F /* wrap_Fixture.cpp in Sources */, + A958F917142D6B3A007F320F /* Body.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/src/modules/physics/Body.cpp b/src/modules/physics/Body.cpp new file mode 100644 index 000000000..eef9d6e98 --- /dev/null +++ b/src/modules/physics/Body.cpp @@ -0,0 +1,51 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#include "Body.h" + +namespace love +{ +namespace physics +{ + Body::~Body() + { + } + + bool Body::getConstant(const char * in, Type & out) + { + return types.find(in, out); + } + + bool Body::getConstant(Type in, const char *& out) + { + return types.find(in, out); + } + + StringMap::Entry Body::typeEntries[] = + { + {"static", Body::BODY_STATIC}, + {"dynamic", Body::BODY_DYNAMIC}, + {"kinematic", Body::BODY_KINEMATIC}, + }; + + StringMap Body::types(Body::typeEntries, sizeof(Body::typeEntries)); + +} // physics +} // love diff --git a/src/modules/physics/Body.h b/src/modules/physics/Body.h new file mode 100644 index 000000000..6dc55a83c --- /dev/null +++ b/src/modules/physics/Body.h @@ -0,0 +1,59 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_PHYSICS_BODY_H +#define LOVE_PHYSICS_BODY_H + +// LOVE +#include +#include + +namespace love +{ +namespace physics +{ + class Body : public Object + { + public: + + enum Type + { + BODY_INVALID, + BODY_STATIC, + BODY_DYNAMIC, + BODY_KINEMATIC, + BODY_MAX_ENUM + }; + + virtual ~Body(); + + static bool getConstant(const char * in, Type & out); + static bool getConstant(Type in, const char *& out); + + private: + + static StringMap::Entry typeEntries[]; + static StringMap types; + }; + +} // physics +} // love + +#endif // LOVE_PHYSICS_BODY_H diff --git a/src/modules/physics/box2d/Body.cpp b/src/modules/physics/box2d/Body.cpp index 4d51f12c3..4ab323538 100644 --- a/src/modules/physics/box2d/Body.cpp +++ b/src/modules/physics/box2d/Body.cpp @@ -22,6 +22,8 @@ #include +#include "Shape.h" +#include "Fixture.h" #include "World.h" #include "Physics.h" @@ -31,14 +33,12 @@ namespace physics { namespace box2d { - Body::Body(World * world, b2Vec2 p, float m, float i) + Body::Body(World * world, b2Vec2 p) : world(world) { world->retain(); b2BodyDef def; def.position = Physics::scaleDown(p); - def.massData.mass = m; - def.massData.I = i; body = world->world->CreateBody(&def); } @@ -106,25 +106,65 @@ namespace box2d { return body->GetInertia(); } + + int Body::getMassData(lua_State * L) + { + b2MassData data; + body->GetMassData(&data); + b2Vec2 center = Physics::scaleUp(data.center); + lua_pushnumber(L, center.x); + lua_pushnumber(L, center.y); + lua_pushnumber(L, data.mass); + lua_pushnumber(L, data.I); + return 4; + } float Body::getAngularDamping() const { - return body->m_angularDamping; + return body->GetAngularDamping(); } float Body::getLinearDamping() const { - return body->m_linearDamping; + return body->GetLinearDamping(); + } + + float Body::getGravityScale() const + { + return body->GetGravityScale(); + } + + Body::Type Body::getType() const + { + switch (body->GetType()) { + case b2_staticBody: + return BODY_STATIC; + break; + case b2_dynamicBody: + return BODY_DYNAMIC; + break; + case b2_kinematicBody: + return BODY_KINEMATIC; + break; + default: + return BODY_INVALID; + break; + } } - void Body::applyImpulse(float jx, float jy) + void Body::applyLinearImpulse(float jx, float jy) { - body->ApplyImpulse(b2Vec2(jx, jy), body->GetWorldCenter()); + body->ApplyLinearImpulse(Physics::scaleDown(b2Vec2(jx, jy)), body->GetWorldCenter()); } - void Body::applyImpulse(float jx, float jy, float rx, float ry) + void Body::applyLinearImpulse(float jx, float jy, float rx, float ry) { - body->ApplyImpulse(b2Vec2(jx, jy), Physics::scaleDown(b2Vec2(rx, ry))); + body->ApplyLinearImpulse(Physics::scaleDown(b2Vec2(jx, jy)), Physics::scaleDown(b2Vec2(rx, ry))); + } + + void Body::applyAngularImpulse(float impulse) + { + body->ApplyAngularImpulse(Physics::scaleDown(impulse)); } void Body::applyTorque(float t) @@ -144,12 +184,12 @@ namespace box2d void Body::setX(float x) { - body->SetXForm(Physics::scaleDown(b2Vec2(x, getY())), getAngle()); + body->SetTransform(Physics::scaleDown(b2Vec2(x, getY())), getAngle()); } void Body::setY(float y) { - body->SetXForm(Physics::scaleDown(b2Vec2(getX(), y)), getAngle()); + body->SetTransform(Physics::scaleDown(b2Vec2(getX(), y)), getAngle()); } void Body::setLinearVelocity(float x, float y) @@ -159,7 +199,7 @@ namespace box2d void Body::setAngle(float d) { - body->SetXForm(body->GetPosition(), d); + body->SetTransform(body->GetPosition(), d); } void Body::setAngularVelocity(float r) @@ -169,31 +209,31 @@ namespace box2d void Body::setPosition(float x, float y) { - body->SetXForm(Physics::scaleDown(b2Vec2(x, y)), body->GetAngle()); + body->SetTransform(Physics::scaleDown(b2Vec2(x, y)), body->GetAngle()); } void Body::setAngularDamping(float d) { - body->m_angularDamping = d; + body->SetAngularDamping(d); } void Body::setLinearDamping(float d) { - body->m_linearDamping = d; + body->SetLinearDamping(d); } - void Body::setMassFromShapes() + void Body::resetMassData() { - body->SetMassFromShapes(); + body->ResetMassData(); } - void Body::setMass(float x, float y, float m, float i) + void Body::setMassData(float x, float y, float m, float i) { b2MassData massData; massData.center = Physics::scaleDown(b2Vec2(x, y)); massData.mass = m; massData.I = i; - body->SetMass(&massData); + body->SetMassData(&massData); } void Body::setInertia(float i) @@ -202,7 +242,29 @@ namespace box2d massData.center = body->GetLocalCenter(); massData.mass = body->GetMass(); massData.I = i; - body->SetMass(&massData); + body->SetMassData(&massData); + } + + void Body::setGravityScale(float scale) + { + body->SetGravityScale(scale); + } + + void Body::setType(Body::Type type) + { + switch (type) { + case Body::BODY_STATIC: + body->SetType(b2_staticBody); + break; + case Body::BODY_DYNAMIC: + body->SetType(b2_dynamicBody); + break; + case Body::BODY_KINEMATIC: + body->SetType(b2_kinematicBody); + break; + default: + break; + } } void Body::getWorldPoint(float x, float y, float & x_o, float & y_o) @@ -257,63 +319,60 @@ namespace box2d return body->SetBullet(bullet); } - bool Body::isStatic() const + bool Body::isActive() const { - return body->IsStatic(); + return body->IsActive(); } - bool Body::isDynamic() const + bool Body::isAwake() const { - return body->IsDynamic(); + return body->IsAwake(); } - bool Body::isFrozen() const + void Body::setSleepingAllowed(bool allow) { - return body->IsFrozen(); + body->SetSleepingAllowed(allow); } - bool Body::isSleeping() const + bool Body::isSleepingAllowed() const { - return body->IsSleeping(); + return body->IsSleepingAllowed(); + } + + void Body::setActive(bool active) + { + body->SetActive(active); } - void Body::setAllowSleeping(bool allow) + void Body::setAwake(bool awake) { - body->AllowSleeping(allow); - } - - bool Body::getAllowSleeping() - { - return (body->m_flags & b2Body::e_allowSleepFlag) != 0; - } - - void Body::putToSleep() - { - body->PutToSleep(); - } - - void Body::wakeUp() - { - body->WakeUp(); + body->SetAwake(awake); } void Body::setFixedRotation(bool fixed) { - if(fixed) - body->m_flags |= b2Body::e_fixedRotationFlag; - else - body->m_flags &= ~(b2Body::e_fixedRotationFlag); + body->SetFixedRotation(fixed); } - bool Body::getFixedRotation() const + bool Body::isFixedRotation() const { - return (body->m_flags & b2Body::e_fixedRotationFlag) != 0; + return body->IsFixedRotation(); } World * Body::getWorld() const { return world; } + + Fixture * Body::createFixture(Shape * shape) + { + return new Fixture(this, shape); + } + + void Body::destroyFixture(Fixture * fixture) + { + fixture->release(); + } b2Vec2 Body::getVector(lua_State * L) { diff --git a/src/modules/physics/box2d/Body.h b/src/modules/physics/box2d/Body.h index 83996e17c..ddc5023cf 100644 --- a/src/modules/physics/box2d/Body.h +++ b/src/modules/physics/box2d/Body.h @@ -25,7 +25,7 @@ #include #include #include - +#include // Box2D #include @@ -38,6 +38,8 @@ namespace box2d { // Forward declarations. class World; + class Shape; + class Fixture; /** * A Body is an entity which has position and orientation @@ -45,7 +47,7 @@ namespace box2d * by itself, but depend on an arbitrary number of child Shape objects * which together constitute the final geometry for the Body. **/ - class Body : public Object + class Body : public love::physics::Body { // Friends. friend class Joint; @@ -73,7 +75,7 @@ namespace box2d /** * Create a Body at position p. **/ - Body(World * world, b2Vec2 p, float m, float i); + Body(World * world, b2Vec2 p); virtual ~Body(); @@ -134,6 +136,11 @@ namespace box2d * Gets the Body's intertia. **/ float getInertia() const; + + /** + * Gets mass properties. + **/ + int getMassData(lua_State * L); /** * Gets the Body's angular damping. @@ -144,16 +151,31 @@ namespace box2d * Gets the Body's linear damping. **/ float getLinearDamping() const; + + /** + * Gets the Body's gravity scale. + **/ + float getGravityScale() const; + + /** + * Gets the type of body this is. + **/ + Type getType() const; /** * Apply an impulse (jx, jy) with offset (0, 0). **/ - void applyImpulse(float jx, float jy); + void applyLinearImpulse(float jx, float jy); /** * Apply an impulse (jx, jy) with offset (rx, ry). **/ - void applyImpulse(float jx, float jy, float rx, float ry); + void applyLinearImpulse(float jx, float jy, float rx, float ry); + + /** + * Apply an angular impulse to the body. + **/ + void applyAngularImpulse(float impulse); /** * Apply torque (t). @@ -203,7 +225,7 @@ namespace box2d /** * Sets the mass from the currently attatched shapes. **/ - void setMassFromShapes(); + void resetMassData(); /** * Sets mass properties. @@ -212,7 +234,7 @@ namespace box2d * @param m The mass. * @param i The inertia. **/ - void setMass(float x, float y, float m, float i); + void setMassData(float x, float y, float m, float i); /** * Sets the inertia while keeping the other properties @@ -230,6 +252,16 @@ namespace box2d * Sets the Body's linear damping. **/ void setLinearDamping(float d); + + /** + * Sets the Body's gravity scale. + **/ + void setGravityScale(float scale); + + /** + * Sets the type of body this is. + **/ + void setType(Type type); /** * Transforms a point (x, y) from local coordinates @@ -301,51 +333,44 @@ namespace box2d void setBullet(bool bullet); /** - * Checks whether a Body is static or not, i.e. terrain - * or not. + * Checks whether a Body is active or not. An inactive body + * cannot be interacted with. **/ - bool isStatic() const; + bool isActive() const; /** - * The opposite of isStatic. - **/ - bool isDynamic() const; - - /** - * Checks whether a Body is frozen or not. - * A Body will freeze if hits the world bounding box. - **/ - bool isFrozen() const; - - /** - * Checks whether a Body is sleeping or nor. A Body + * Checks whether a Body is awake or not. A Body * will fall to sleep if nothing happens to it for while. **/ - bool isSleeping() const; + bool isAwake() const; /** * Controls whether this Body should be allowed to sleep. **/ - void setAllowSleeping(bool allow); - bool getAllowSleeping(); + void setSleepingAllowed(bool allow); + bool isSleepingAllowed() const; + + /** + * Changes the body's active state. + **/ + void setActive(bool active); /** - * Puts the body to sleep. + * Changes the body's sleep state. **/ - void putToSleep(); - - /** - * Wakes the Body up. - **/ - void wakeUp(); + void setAwake(bool awake); void setFixedRotation(bool fixed); - bool getFixedRotation() const; + bool isFixedRotation() const; /** * Get the World this Body resides in. */ World * getWorld() const; + + Fixture * createFixture(Shape * shape); + + void destroyFixture(Fixture * fixture); private: /** diff --git a/src/modules/physics/box2d/Fixture.h b/src/modules/physics/box2d/Fixture.h index c06d9d8ca..17dc831f3 100644 --- a/src/modules/physics/box2d/Fixture.h +++ b/src/modules/physics/box2d/Fixture.h @@ -101,13 +101,6 @@ namespace box2d **/ Body * getBody() const; - /** - * Gets the next Fixture attached to the parent Body. - **/ - Fixture * getNext() const; - - - /** * Sets the filter data. An integer array is used even though the * first two elements are unsigned shorts. The elements are: diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 3aee9e050..cdf9fc07e 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -45,26 +45,16 @@ namespace box2d return new World(b2Vec2(gx, gy), sleep); } - Body * Physics::newBody(World * world, float x, float y, float mass, float i) - { - return new Body(world, b2Vec2(x, y), mass, i); - } - Body * Physics::newBody(World * world, float x, float y) { - return new Body(world, b2Vec2(x, y), 1, 1); + return new Body(world, b2Vec2(x, y)); } Body * Physics::newBody(World * world) { - return new Body(world, b2Vec2(0, 0), 1, 1); + return new Body(world, b2Vec2(0, 0)); } - Fixture * Physics::newFixture(Body * body, Shape * shape) - { - return new Fixture(body, shape); - } - CircleShape * Physics::newCircleShape(float radius) { return newCircleShape(0, 0, radius); diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index 342eae8de..a51677ae0 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -76,16 +76,6 @@ namespace box2d **/ World * newWorld(float gx, float gy, bool sleep, int meter); - /** - * Creates a new Body at the specified position. - * @param world The world to create the Body in. - * @param x The position along the x-axis. - * @param x The position along the y-axis. - * @param m The mass. - * @param i The rotational inertia. - **/ - Body * newBody(World * world, float x, float y, float m, float i); - /** * Creates a new Body at the specified position. * @param world The world to create the Body in. @@ -99,13 +89,6 @@ namespace box2d * @param world The world to create the Body in. **/ Body * newBody(World * world); - - /** - * Creates a new Fixture. - * @param body The body to attach the Fixture to. - * @param shape The shape to attach to the Fixture. - **/ - Fixture * newFixture(Body * body, Shape * shape); /** * Creates a new CircleShape at (0, 0). diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index 9649d9f8a..206206696 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -162,8 +162,9 @@ namespace box2d end.add(contact); } - void World::PreSolve(b2Contact* contact) + void World::PreSolve(b2Contact* contact, const b2Manifold* oldManifold) { + B2_NOT_USED(oldManifold); // not sure what to do with this presolve.add(contact); } diff --git a/src/modules/physics/box2d/World.h b/src/modules/physics/box2d/World.h index 25ae32b2c..b76eee41c 100644 --- a/src/modules/physics/box2d/World.h +++ b/src/modules/physics/box2d/World.h @@ -117,7 +117,7 @@ namespace box2d // From b2ContactListener void BeginContact(b2Contact* contact); void EndContact(b2Contact* contact); - void PreSolve(b2Contact* contact); + void PreSolve(b2Contact* contact, const b2Manifold* oldManifold); void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse); /** diff --git a/src/modules/physics/box2d/wrap_Body.cpp b/src/modules/physics/box2d/wrap_Body.cpp index 2d97f4c74..40fa1b463 100644 --- a/src/modules/physics/box2d/wrap_Body.cpp +++ b/src/modules/physics/box2d/wrap_Body.cpp @@ -120,6 +120,13 @@ namespace box2d lua_pushnumber(L, t->getInertia()); return 1; } + + int w_Body_getMassData(lua_State * L) + { + Body * t = luax_checkbody(L, 1); + lua_remove(L, 1); + return t->getMassData(L); + } int w_Body_getAngularDamping(lua_State * L) { @@ -134,8 +141,24 @@ namespace box2d lua_pushnumber(L, t->getLinearDamping()); return 1; } + + int w_Body_getGravityScale(lua_State * L) + { + Body * t = luax_checkbody(L, 1); + lua_pushnumber(L, t->getGravityScale()); + return 1; + } + + int w_Body_getType(lua_State * L) + { + Body * t = luax_checkbody(L, 1); + const char * type = ""; + Body::getConstant(t->getType(), type); + lua_pushstring(L, type); + return 1; + } - int w_Body_applyImpulse(lua_State * L) + int w_Body_applyLinearImpulse(lua_State * L) { Body * t = luax_checkbody(L, 1); float jx = (float)luaL_checknumber(L, 2); @@ -143,13 +166,13 @@ namespace box2d if(lua_gettop(L) == 3) { - t->applyImpulse(jx, jy); + t->applyLinearImpulse(jx, jy); } else if(lua_gettop(L) == 5) { float rx = (float)luaL_checknumber(L, 4); float ry = (float)luaL_checknumber(L, 5); - t->applyImpulse(jx, jy, rx, ry); + t->applyLinearImpulse(jx, jy, rx, ry); } else { @@ -158,6 +181,14 @@ namespace box2d return 0; } + + int w_Body_applyAngularImpulse(lua_State * L) + { + Body * t = luax_checkbody(L, 1); + float i = (float)luaL_checknumber(L, 2); + t->applyAngularImpulse(i); + return 0; + } int w_Body_applyTorque(lua_State * L) { @@ -242,21 +273,21 @@ namespace box2d return 0; } - int w_Body_setMassFromShapes(lua_State * L) + int w_Body_resetMassData(lua_State * L) { Body * t = luax_checkbody(L, 1); - t->setMassFromShapes(); + t->resetMassData(); return 0; } - int w_Body_setMass(lua_State * L) + int w_Body_setMassData(lua_State * L) { Body * t = luax_checkbody(L, 1); float x = (float)luaL_checknumber(L, 2); float y = (float)luaL_checknumber(L, 3); float m = (float)luaL_checknumber(L, 4); float i = (float)luaL_checknumber(L, 5); - t->setMass(x, y, m, i); + t->setMassData(x, y, m, i); return 0; } @@ -283,6 +314,24 @@ namespace box2d t->setLinearDamping(arg1); return 0; } + + int w_Body_setGravityScale(lua_State * L) + { + Body * t = luax_checkbody(L, 1); + float arg1 = (float)luaL_checknumber(L, 2); + t->setGravityScale(arg1); + return 0; + } + + int w_Body_setType(lua_State * L) + { + Body * t = luax_checkbody(L, 1); + const char * typeStr = luaL_checkstring(L, 2); + Body::Type type; + Body::getConstant(typeStr, type); + t->setType(type); + return 0; + } int w_Body_getWorldPoint(lua_State * L) { @@ -383,60 +432,48 @@ namespace box2d return 0; } - int w_Body_isStatic(lua_State * L) + int w_Body_isActive(lua_State * L) { Body * t = luax_checkbody(L, 1); - luax_pushboolean(L, t->isStatic()); + luax_pushboolean(L, t->isActive()); return 1; } - int w_Body_isDynamic(lua_State * L) + int w_Body_isAwake(lua_State * L) { Body * t = luax_checkbody(L, 1); - luax_pushboolean(L, t->isDynamic()); + luax_pushboolean(L, t->isAwake()); return 1; } - int w_Body_isFrozen(lua_State * L) - { - Body * t = luax_checkbody(L, 1); - luax_pushboolean(L, t->isFrozen()); - return 1; - } - - int w_Body_isSleeping(lua_State * L) - { - Body * t = luax_checkbody(L, 1); - luax_pushboolean(L, t->isSleeping()); - return 1; - } - - int w_Body_setAllowSleeping(lua_State * L) + int w_Body_setSleepingAllowed(lua_State * L) { Body * t = luax_checkbody(L, 1); bool b = luax_toboolean(L, 2); - t->setAllowSleeping(b); + t->setSleepingAllowed(b); return 0; } - int w_Body_getAllowSleeping(lua_State * L) + int w_Body_isSleepingAllowed(lua_State * L) { Body * t = luax_checkbody(L, 1); - lua_pushboolean(L, t->getAllowSleeping()); + lua_pushboolean(L, t->isSleepingAllowed()); return 1; } - int w_Body_putToSleep(lua_State * L) + int w_Body_setActive(lua_State * L) { Body * t = luax_checkbody(L, 1); - t->putToSleep(); + bool b = luax_toboolean(L, 2); + t->setActive(b); return 0; } - int w_Body_wakeUp(lua_State * L) + int w_Body_setAwake(lua_State * L) { Body * t = luax_checkbody(L, 1); - t->wakeUp(); + bool b = luax_toboolean(L, 2); + t->setAwake(b); return 0; } @@ -448,13 +485,30 @@ namespace box2d return 0; } - int w_Body_getFixedRotation(lua_State * L) + int w_Body_isFixedRotation(lua_State * L) { Body * t = luax_checkbody(L, 1); - bool b = t->getFixedRotation(); + bool b = t->isFixedRotation(); luax_pushboolean(L, b); return 1; } + + int w_Body_createFixture(lua_State * L) + { + Body * t = luax_checkbody(L, 1); + Shape * s = luax_checktype(L, 2, "Shape", PHYSICS_SHAPE_T); + Fixture * f = t->createFixture(s); + luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)f); + return 1; + } + + int w_Body_destroyFixture(lua_State * L) + { + Body * t = luax_checkbody(L, 1); + Fixture * f = luax_checktype(L, 2, "Fixture", PHYSICS_FIXTURE_T); + t->destroyFixture(f); + return 0; + } int w_Body_destroy(lua_State * L) { @@ -478,9 +532,13 @@ namespace box2d { "getAngularVelocity", w_Body_getAngularVelocity }, { "getMass", w_Body_getMass }, { "getInertia", w_Body_getInertia }, + { "getMassData", w_Body_getMassData }, { "getAngularDamping", w_Body_getAngularDamping }, { "getLinearDamping", w_Body_getLinearDamping }, - { "applyImpulse", w_Body_applyImpulse }, + { "getGravityScale", w_Body_getGravityScale }, + { "getType", w_Body_getType }, + { "applyLinearImpulse", w_Body_applyLinearImpulse }, + { "applyAngularImpulse", w_Body_applyAngularImpulse }, { "applyTorque", w_Body_applyTorque }, { "applyForce", w_Body_applyForce }, { "setX", w_Body_setX }, @@ -489,11 +547,13 @@ namespace box2d { "setAngle", w_Body_setAngle }, { "setAngularVelocity", w_Body_setAngularVelocity }, { "setPosition", w_Body_setPosition }, - { "setMassFromShapes", w_Body_setMassFromShapes }, - { "setMass", w_Body_setMass }, + { "resetMassData", w_Body_resetMassData }, + { "setMassData", w_Body_setMassData }, { "setInertia", w_Body_setInertia }, { "setAngularDamping", w_Body_setAngularDamping }, { "setLinearDamping", w_Body_setLinearDamping }, + { "setGravityScale", w_Body_setGravityScale }, + { "setType", w_Body_setType }, { "getWorldPoint", w_Body_getWorldPoint }, { "getWorldVector", w_Body_getWorldVector }, { "getLocalPoint", w_Body_getLocalPoint }, @@ -502,16 +562,16 @@ namespace box2d { "getLinearVelocityFromLocalPoint", w_Body_getLinearVelocityFromLocalPoint }, { "isBullet", w_Body_isBullet }, { "setBullet", w_Body_setBullet }, - { "isStatic", w_Body_isStatic }, - { "isDynamic", w_Body_isDynamic }, - { "isFrozen", w_Body_isFrozen }, - { "isSleeping", w_Body_isSleeping }, - { "setAllowSleeping", w_Body_setAllowSleeping }, - { "getAllowSleeping", w_Body_getAllowSleeping }, - { "putToSleep", w_Body_putToSleep }, - { "wakeUp", w_Body_wakeUp }, + { "isActive", w_Body_isActive }, + { "isAwake", w_Body_isAwake }, + { "setSleepingAllowed", w_Body_setSleepingAllowed }, + { "isSleepingAllowde", w_Body_isSleepingAllowed }, + { "setActive", w_Body_setActive }, + { "setAwake", w_Body_setAwake }, { "setFixedRotation", w_Body_setFixedRotation }, - { "getFixedRotation", w_Body_getFixedRotation }, + { "isFixedRotation", w_Body_isFixedRotation }, + { "createFixture", w_Body_createFixture }, + { "destroyFixture", w_Body_destroyFixture }, { "destroy", w_Body_destroy }, { 0, 0 } }; diff --git a/src/modules/physics/box2d/wrap_Body.h b/src/modules/physics/box2d/wrap_Body.h index 9be3fc1b1..b4f58d2cd 100644 --- a/src/modules/physics/box2d/wrap_Body.h +++ b/src/modules/physics/box2d/wrap_Body.h @@ -43,22 +43,28 @@ namespace box2d int w_Body_getAngularVelocity(lua_State * L); int w_Body_getMass(lua_State * L); int w_Body_getInertia(lua_State * L); + int w_Body_getMassData(lua_State * L); int w_Body_getAngularDamping(lua_State * L); int w_Body_getLinearDamping(lua_State * L); - int w_Body_applyImpulse(lua_State * L); + int w_Body_getGravityScale(lua_State * L); + int w_Body_getType(lua_State * L); + int w_Body_applyLinearImpulse(lua_State * L); + int w_Body_applyAngularImpulse(lua_State * L); int w_Body_applyTorque(lua_State * L); int w_Body_applyForce(lua_State * L); int w_Body_setX(lua_State * L); int w_Body_setY(lua_State * L); - int w_Body_setVelocity(lua_State * L); + int w_Body_setLinearVelocity(lua_State * L); int w_Body_setAngle(lua_State * L); int w_Body_setAngularVelocity(lua_State * L); int w_Body_setPosition(lua_State * L); - int w_Body_setMassFromShapes(lua_State * L); - int w_Body_setMass(lua_State * L); + int w_Body_resetMassData(lua_State * L); + int w_Body_setMassData(lua_State * L); int w_Body_setInertia(lua_State * L); int w_Body_setAngularDamping(lua_State * L); int w_Body_setLinearDamping(lua_State * L); + int w_Body_setGravityScale(lua_State * L); + int w_Body_setType(lua_State * L); int w_Body_getWorldPoint(lua_State * L); int w_Body_getWorldVector(lua_State * L); int w_Body_getLocalPoint(lua_State * L); @@ -67,16 +73,16 @@ namespace box2d int w_Body_getLinearVelocityFromLocalPoint(lua_State * L); int w_Body_isBullet(lua_State * L); int w_Body_setBullet(lua_State * L); - int w_Body_isStatic(lua_State * L); - int w_Body_isDynamic(lua_State * L); - int w_Body_isFrozen(lua_State * L); - int w_Body_isSleeping(lua_State * L); - int w_Body_setAllowSleeping(lua_State * L); - int w_Body_getAllowSleeping(lua_State * L); - int w_Body_putToSleep(lua_State * L); - int w_Body_wakeUp(lua_State * L); + int w_Body_isActive(lua_State * L); + int w_Body_isAwake(lua_State * L); + int w_Body_setSleepingAllowed(lua_State * L); + int w_Body_isSleepingAllowed(lua_State * L); + int w_Body_setActive(lua_State * L); + int w_Body_setAwake(lua_State * L); int w_Body_setFixedRotation(lua_State * L); - int w_Body_getFixedRotation(lua_State * L); + int w_Body_isFixedRotation(lua_State * L); + int w_Body_createFixture(lua_State * L); + int w_Body_destroyFixture(lua_State * L); int w_Body_destroy(lua_State * L); int luaopen_body(lua_State * L); diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index 928706dde..343907016 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -47,21 +47,10 @@ namespace box2d World * world = luax_checktype(L, 1, "World", PHYSICS_WORLD_T); float x = (float)luaL_optnumber(L, 2, 0.0); float y = (float)luaL_optnumber(L, 3, 0.0); - float m = (float)luaL_optnumber(L, 4, 0.0); - float i = (float)luaL_optnumber(L, 5, 0.0); - Body * body = instance->newBody(world, x, y, m, i); + Body * body = instance->newBody(world, x, y); luax_newtype(L, "Body", PHYSICS_BODY_T, (void*)body); return 1; } - - int w_newFixture(lua_State * L) - { - Body * body = luax_checkbody(L, 1); - Shape * shape = luax_checkshape(L, 2); - Fixture * fixture = instance->newFixture(body, shape); - luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)fixture); - return 1; - } int w_newCircleShape(lua_State * L) { diff --git a/src/modules/physics/box2d/wrap_Physics.h b/src/modules/physics/box2d/wrap_Physics.h index 09cf0b4cf..29d7e2e58 100644 --- a/src/modules/physics/box2d/wrap_Physics.h +++ b/src/modules/physics/box2d/wrap_Physics.h @@ -52,7 +52,6 @@ namespace box2d { int w_newWorld(lua_State * L); int w_newBody(lua_State * L); - int w_newFixture(lua_State * L); int w_newCircleShape(lua_State * L); int w_newRectangleShape(lua_State * L); int w_newPolygonShape(lua_State * L); From 6e7d83d7eae60d155761bf9c7ab44c1f34e86b1a Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Fri, 23 Sep 2011 22:32:39 -0400 Subject: [PATCH 24/78] Update ChainShape API --HG-- branch : box2d-update --- src/modules/physics/box2d/ChainShape.cpp | 12 +++++++++--- src/modules/physics/box2d/ChainShape.h | 5 +++++ src/modules/physics/box2d/wrap_ChainShape.cpp | 8 ++++++++ src/modules/physics/box2d/wrap_ChainShape.h | 1 + 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/modules/physics/box2d/ChainShape.cpp b/src/modules/physics/box2d/ChainShape.cpp index 1e74d5177..693719a67 100644 --- a/src/modules/physics/box2d/ChainShape.cpp +++ b/src/modules/physics/box2d/ChainShape.cpp @@ -71,23 +71,29 @@ namespace box2d return new EdgeShape(&e); } + int ChainShape::getChildCount() const + { + b2ChainShape * c = (b2ChainShape *)shape; + return c->GetChildCount(); + } + int ChainShape::getVertexCount() const { b2ChainShape * c = (b2ChainShape *)shape; - return c->GetVertexCount(); + return c->m_count; } b2Vec2 ChainShape::getVertex(int index) const { b2ChainShape * c = (b2ChainShape *)shape; - const b2Vec2 & v = c->GetVertex(index); + const b2Vec2 & v = c->m_vertices[index]; return Physics::scaleUp(v); } const b2Vec2 * ChainShape::getVertices() const { b2ChainShape * c = (b2ChainShape *)shape; - return c->GetVertices(); + return c->m_vertices; } } // box2d diff --git a/src/modules/physics/box2d/ChainShape.h b/src/modules/physics/box2d/ChainShape.h index c96f4e228..ccabc2e08 100644 --- a/src/modules/physics/box2d/ChainShape.h +++ b/src/modules/physics/box2d/ChainShape.h @@ -66,6 +66,11 @@ namespace box2d **/ void setPrevVertex(float x, float y); + /** + * Gets the number of children shapes. + **/ + int getChildCount() const; + /** * Returns a child EdgeShape. * @param index The index of the child shape. diff --git a/src/modules/physics/box2d/wrap_ChainShape.cpp b/src/modules/physics/box2d/wrap_ChainShape.cpp index 8db43e3cc..ef5195cfe 100644 --- a/src/modules/physics/box2d/wrap_ChainShape.cpp +++ b/src/modules/physics/box2d/wrap_ChainShape.cpp @@ -50,6 +50,13 @@ namespace box2d return 0; } + int w_ChainShape_getChildCount(lua_State * L) + { + ChainShape * c = luax_checkchainshape(L, 1); + lua_pushinteger(L, c->getChildCount()); + return 1; + } + int w_ChainShape_getChildEdge(lua_State * L) { ChainShape * c = luax_checkchainshape(L, 1); @@ -96,6 +103,7 @@ namespace box2d static const luaL_Reg functions[] = { { "setNextVertex", w_ChainShape_setNextVertex }, { "setPrevVertex", w_ChainShape_setPrevVertex }, + { "getChildCount", w_ChainShape_getChildCount }, { "getChildEdge", w_ChainShape_getChildEdge }, { "getVertexCount", w_ChainShape_getVertexCount }, { "getVertex", w_ChainShape_getVertex }, diff --git a/src/modules/physics/box2d/wrap_ChainShape.h b/src/modules/physics/box2d/wrap_ChainShape.h index 88989d063..ae81e4ba8 100644 --- a/src/modules/physics/box2d/wrap_ChainShape.h +++ b/src/modules/physics/box2d/wrap_ChainShape.h @@ -36,6 +36,7 @@ namespace box2d int w_ChainShape_setNextVertex(lua_State * L); int w_ChainShape_setPrevVertex(lua_State * L); + int w_ChainShape_getChildCount(lua_State * L); int w_ChainShape_getChildEdge(lua_State * L); int w_ChainShape_getVertexCount(lua_State * L); int w_ChainShape_getVertex(lua_State * L); From de170c02c835072f98cc7347f64f74b143280c56 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Fri, 23 Sep 2011 22:32:49 -0400 Subject: [PATCH 25/78] Update Joint APIs --HG-- branch : box2d-update --- src/modules/physics/box2d/PulleyJoint.cpp | 16 ++++++++-------- src/modules/physics/box2d/PulleyJoint.h | 12 ++++++------ src/modules/physics/box2d/RevoluteJoint.cpp | 4 ++-- src/modules/physics/box2d/RevoluteJoint.h | 3 ++- src/modules/physics/box2d/wrap_Joint.cpp | 3 ++- .../physics/box2d/wrap_PrismaticJoint.cpp | 3 ++- src/modules/physics/box2d/wrap_PulleyJoint.cpp | 12 ++++++------ src/modules/physics/box2d/wrap_PulleyJoint.h | 4 ++-- src/modules/physics/box2d/wrap_RevoluteJoint.cpp | 3 ++- 9 files changed, 32 insertions(+), 28 deletions(-) diff --git a/src/modules/physics/box2d/PulleyJoint.cpp b/src/modules/physics/box2d/PulleyJoint.cpp index 84e449eaf..a4ce4d08b 100644 --- a/src/modules/physics/box2d/PulleyJoint.cpp +++ b/src/modules/physics/box2d/PulleyJoint.cpp @@ -31,12 +31,12 @@ namespace physics { namespace box2d { - PulleyJoint::PulleyJoint(Body * body1, Body * body2, b2Vec2 groundAnchor1, b2Vec2 groundAnchor2, b2Vec2 anchor1, b2Vec2 anchor2, float ratio, bool collideConnected) - : Joint(body1, body2), joint(NULL) + PulleyJoint::PulleyJoint(Body * bodyA, Body * bodyB, b2Vec2 groundAnchorA, b2Vec2 groundAnchorB, b2Vec2 anchorA, b2Vec2 anchorB, float ratio, bool collideConnected) + : Joint(bodyA, bodyB), joint(NULL) { b2PulleyJointDef def; - def.Initialize(body1->body, body2->body, Physics::scaleDown(groundAnchor1), Physics::scaleDown(groundAnchor2), \ - Physics::scaleDown(anchor1), Physics::scaleDown(anchor2), ratio); + def.Initialize(bodyA->body, bodyB->body, Physics::scaleDown(groundAnchorA), Physics::scaleDown(groundAnchorB), \ + Physics::scaleDown(anchorA), Physics::scaleDown(anchorB), ratio); def.collideConnected = collideConnected; joint = (b2PulleyJoint*)createJoint(&def); @@ -57,14 +57,14 @@ namespace box2d return 4; } - float PulleyJoint::getLength1() const + float PulleyJoint::getLengthA() const { - return Physics::scaleUp(joint->GetLength1()); + return Physics::scaleUp(joint->GetLengthA()); } - float PulleyJoint::getLength2() const + float PulleyJoint::getLengthB() const { - return Physics::scaleUp(joint->GetLength2()); + return Physics::scaleUp(joint->GetLengthB()); } float PulleyJoint::getRatio() const diff --git a/src/modules/physics/box2d/PulleyJoint.h b/src/modules/physics/box2d/PulleyJoint.h index ba1eb201f..fcf5e7349 100644 --- a/src/modules/physics/box2d/PulleyJoint.h +++ b/src/modules/physics/box2d/PulleyJoint.h @@ -44,9 +44,9 @@ namespace box2d public: /** - * Creates a PulleyJoint connecting body1 to body2. + * Creates a PulleyJoint connecting bodyA to bodyB. **/ - PulleyJoint(Body * body1, Body * body2, b2Vec2 groundAnchor1, b2Vec2 groundAnchor2, b2Vec2 anchor1, b2Vec2 anchor2, float ratio, bool collideConnected); + PulleyJoint(Body * bodyA, Body * bodyB, b2Vec2 groundAnchorA, b2Vec2 groundAnchorB, b2Vec2 anchorA, b2Vec2 anchorB, float ratio, bool collideConnected); virtual ~PulleyJoint(); @@ -57,14 +57,14 @@ namespace box2d int getGroundAnchors(lua_State * L); /** - * Gets the current length of the segment attached to body1. + * Gets the current length of the segment attached to bodyA. **/ - float getLength1() const; + float getLengthA() const; /** - * Gets the current length of the segment attached to body2. + * Gets the current length of the segment attached to bodyB. **/ - float getLength2() const; + float getLengthB() const; /** * Gets the pulley ratio. diff --git a/src/modules/physics/box2d/RevoluteJoint.cpp b/src/modules/physics/box2d/RevoluteJoint.cpp index 1a6251c8d..a80ffe303 100644 --- a/src/modules/physics/box2d/RevoluteJoint.cpp +++ b/src/modules/physics/box2d/RevoluteJoint.cpp @@ -83,9 +83,9 @@ namespace box2d return joint->GetMotorSpeed(); } - float RevoluteJoint::getMotorTorque() const + float RevoluteJoint::getMotorTorque(float inv_dt) const { - return joint->GetMotorTorque(); + return joint->GetMotorTorque(inv_dt); } void RevoluteJoint::enableLimit(bool limit) diff --git a/src/modules/physics/box2d/RevoluteJoint.h b/src/modules/physics/box2d/RevoluteJoint.h index 4f5a57064..c5b255e23 100644 --- a/src/modules/physics/box2d/RevoluteJoint.h +++ b/src/modules/physics/box2d/RevoluteJoint.h @@ -87,8 +87,9 @@ namespace box2d /** * Get the current motor torque, usually in N-m. + * @param inv_dt The inverse timestep. **/ - float getMotorTorque() const; + float getMotorTorque(float inv_dt) const; /** * Enable/disable the joint limit. diff --git a/src/modules/physics/box2d/wrap_Joint.cpp b/src/modules/physics/box2d/wrap_Joint.cpp index f71885202..3054e58d2 100644 --- a/src/modules/physics/box2d/wrap_Joint.cpp +++ b/src/modules/physics/box2d/wrap_Joint.cpp @@ -59,7 +59,8 @@ namespace box2d int w_Joint_getReactionTorque(lua_State * L) { Joint * t = luax_checkjoint(L, 1); - lua_pushnumber(L, t->getReactionTorque()); + float inv_dt = (float)luaL_checknumber(L, 2); + lua_pushnumber(L, t->getReactionTorque(inv_dt)); return 1; } diff --git a/src/modules/physics/box2d/wrap_PrismaticJoint.cpp b/src/modules/physics/box2d/wrap_PrismaticJoint.cpp index bffd37a56..a09344a06 100644 --- a/src/modules/physics/box2d/wrap_PrismaticJoint.cpp +++ b/src/modules/physics/box2d/wrap_PrismaticJoint.cpp @@ -86,7 +86,8 @@ namespace box2d int w_PrismaticJoint_getMotorForce(lua_State * L) { PrismaticJoint * t = luax_checkprismaticjoint(L, 1); - lua_pushnumber(L, t->getMotorForce()); + float inv_dt = (float)luaL_checknumber(L, 2); + lua_pushnumber(L, t->getMotorForce(inv_dt)); return 1; } diff --git a/src/modules/physics/box2d/wrap_PulleyJoint.cpp b/src/modules/physics/box2d/wrap_PulleyJoint.cpp index d6a4984fb..111d74822 100644 --- a/src/modules/physics/box2d/wrap_PulleyJoint.cpp +++ b/src/modules/physics/box2d/wrap_PulleyJoint.cpp @@ -38,17 +38,17 @@ namespace box2d return t->getGroundAnchors(L); } - int w_PulleyJoint_getLength1(lua_State * L) + int w_PulleyJoint_getLengthA(lua_State * L) { PulleyJoint * t = luax_checkpulleyjoint(L, 1); - lua_pushnumber(L, t->getLength1()); + lua_pushnumber(L, t->getLengthA()); return 1; } - int w_PulleyJoint_getLength2(lua_State * L) + int w_PulleyJoint_getLengthB(lua_State * L) { PulleyJoint * t = luax_checkpulleyjoint(L, 1); - lua_pushnumber(L, t->getLength2()); + lua_pushnumber(L, t->getLengthB()); return 1; } @@ -61,8 +61,8 @@ namespace box2d static const luaL_Reg functions[] = { { "getGroundAnchors", w_PulleyJoint_getGroundAnchors }, - { "getLength1", w_PulleyJoint_getLength1 }, - { "getLength2", w_PulleyJoint_getLength2 }, + { "getLengthA", w_PulleyJoint_getLengthA }, + { "getLengthB", w_PulleyJoint_getLengthB }, { "getRatio", w_PulleyJoint_getRatio }, // From Joint. { "getType", w_Joint_getType }, diff --git a/src/modules/physics/box2d/wrap_PulleyJoint.h b/src/modules/physics/box2d/wrap_PulleyJoint.h index 6001a5f85..0f68ba7f1 100644 --- a/src/modules/physics/box2d/wrap_PulleyJoint.h +++ b/src/modules/physics/box2d/wrap_PulleyJoint.h @@ -34,8 +34,8 @@ namespace box2d { PulleyJoint * luax_checkpulleyjoint(lua_State * L, int idx); int w_PulleyJoint_getGroundAnchors(lua_State * L); - int w_PulleyJoint_getLength1(lua_State * L); - int w_PulleyJoint_getLength2(lua_State * L); + int w_PulleyJoint_getLengthA(lua_State * L); + int w_PulleyJoint_getLengthB(lua_State * L); int w_PulleyJoint_getRatio(lua_State * L); int luaopen_pulleyjoint(lua_State * L); diff --git a/src/modules/physics/box2d/wrap_RevoluteJoint.cpp b/src/modules/physics/box2d/wrap_RevoluteJoint.cpp index d770e03a4..d6517e687 100644 --- a/src/modules/physics/box2d/wrap_RevoluteJoint.cpp +++ b/src/modules/physics/box2d/wrap_RevoluteJoint.cpp @@ -86,7 +86,8 @@ namespace box2d int w_RevoluteJoint_getMotorTorque(lua_State * L) { RevoluteJoint * t = luax_checkrevolutejoint(L, 1); - lua_pushnumber(L, t->getMotorTorque()); + float inv_dt = (float)luaL_checknumber(L, 2); + lua_pushnumber(L, t->getMotorTorque(inv_dt)); return 1; } From de90c5e0d51467f5ec4e0fdf4ae2d0c24cdb2dee Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Fri, 23 Sep 2011 22:54:29 -0400 Subject: [PATCH 26/78] Fix Physics linker error --HG-- branch : box2d-update --- src/modules/physics/box2d/Physics.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index cdf9fc07e..51b3c0443 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -33,6 +33,8 @@ namespace physics { namespace box2d { + + int Physics::meter = Physics::DEFAULT_METER; const char * Physics::getName() const { @@ -219,8 +221,6 @@ namespace box2d return new RopeJoint(body1, body2, x1, y1, x2, y2, maxLength, collideConnected); } - - void Physics::setMeter(int meter) { Physics::meter = meter; From 0ee4bbc0bd270bb556cc53bdf5246bdb22f05bc2 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Fri, 23 Sep 2011 23:05:08 -0400 Subject: [PATCH 27/78] Make Xcode less stupid and use the right files for b2RopeJoint and b2WheelJoint. This is the first time this branch has successfully compiled since it started. Holy shit. --HG-- branch : box2d-update --- platform/macosx/love.xcodeproj/project.pbxproj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/platform/macosx/love.xcodeproj/project.pbxproj b/platform/macosx/love.xcodeproj/project.pbxproj index 7e081e935..7c15c274f 100644 --- a/platform/macosx/love.xcodeproj/project.pbxproj +++ b/platform/macosx/love.xcodeproj/project.pbxproj @@ -551,10 +551,10 @@ A968F0D81083A9FC00A895AA /* Mouse.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Mouse.cpp; sourceTree = ""; }; A968F0DB1083AA6600A895AA /* Shape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Shape.cpp; sourceTree = ""; }; A968F0DC1083AA6600A895AA /* Joint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Joint.cpp; sourceTree = ""; }; - A96F415C14127E310067FE9A /* b2RopeJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2RopeJoint.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Joints/b2RopeJoint.cpp; sourceTree = ""; }; - A96F415D14127E320067FE9A /* b2RopeJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2RopeJoint.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Joints/b2RopeJoint.h; sourceTree = ""; }; - A96F415E14127E320067FE9A /* b2WheelJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2WheelJoint.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Joints/b2WheelJoint.cpp; sourceTree = ""; }; - A96F415F14127E320067FE9A /* b2WheelJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2WheelJoint.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Joints/b2WheelJoint.h; sourceTree = ""; }; + A96F415C14127E310067FE9A /* b2RopeJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2RopeJoint.cpp; sourceTree = ""; }; + A96F415D14127E320067FE9A /* b2RopeJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2RopeJoint.h; sourceTree = ""; }; + A96F415E14127E320067FE9A /* b2WheelJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2WheelJoint.cpp; sourceTree = ""; }; + A96F415F14127E320067FE9A /* b2WheelJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2WheelJoint.h; sourceTree = ""; }; A96F416314127E720067FE9A /* b2Rope.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Rope.cpp; sourceTree = ""; }; A96F416414127E720067FE9A /* b2Rope.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Rope.h; sourceTree = ""; }; A96F416614127E9C0067FE9A /* b2Draw.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2Draw.cpp; path = ../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Common/b2Draw.cpp; sourceTree = ""; }; From dc5cfc928c66d49108510e6dad4ec500eb94a3a2 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Fri, 23 Sep 2011 23:40:04 -0400 Subject: [PATCH 28/78] Make Xcode even more less stupid. --HG-- branch : box2d-update --- .../macosx/love.xcodeproj/project.pbxproj | 39 +++++++++---------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/platform/macosx/love.xcodeproj/project.pbxproj b/platform/macosx/love.xcodeproj/project.pbxproj index 7c15c274f..58ee87fcf 100644 --- a/platform/macosx/love.xcodeproj/project.pbxproj +++ b/platform/macosx/love.xcodeproj/project.pbxproj @@ -557,24 +557,24 @@ A96F415F14127E320067FE9A /* b2WheelJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2WheelJoint.h; sourceTree = ""; }; A96F416314127E720067FE9A /* b2Rope.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Rope.cpp; sourceTree = ""; }; A96F416414127E720067FE9A /* b2Rope.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Rope.h; sourceTree = ""; }; - A96F416614127E9C0067FE9A /* b2Draw.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2Draw.cpp; path = ../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Common/b2Draw.cpp; sourceTree = ""; }; - A96F416714127E9C0067FE9A /* b2Draw.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2Draw.h; path = ../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Common/b2Draw.h; sourceTree = ""; }; - A96F416814127E9C0067FE9A /* b2GrowableStack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2GrowableStack.h; path = ../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Common/b2GrowableStack.h; sourceTree = ""; }; - A96F416914127E9C0067FE9A /* b2Timer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2Timer.cpp; path = ../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Common/b2Timer.cpp; sourceTree = ""; }; - A96F416A14127E9C0067FE9A /* b2Timer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2Timer.h; path = ../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Common/b2Timer.h; sourceTree = ""; }; - A96F416D14127EB20067FE9A /* b2CollideEdge.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2CollideEdge.cpp; path = ../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Collision/b2CollideEdge.cpp; sourceTree = ""; }; - A96F416F14127EC00067FE9A /* b2ChainShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2ChainShape.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Collision/Shapes/b2ChainShape.cpp; sourceTree = ""; }; - A96F417014127EC00067FE9A /* b2ChainShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2ChainShape.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Collision/Shapes/b2ChainShape.h; sourceTree = ""; }; - A96F417214127EE70067FE9A /* b2ChainAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2ChainAndCircleContact.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp; sourceTree = ""; }; - A96F417314127EE70067FE9A /* b2ChainAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2ChainAndCircleContact.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h; sourceTree = ""; }; - A96F417414127EE70067FE9A /* b2ChainAndPolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2ChainAndPolygonContact.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp; sourceTree = ""; }; - A96F417514127EE70067FE9A /* b2ChainAndPolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2ChainAndPolygonContact.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h; sourceTree = ""; }; - A96F417814127EFD0067FE9A /* b2EdgeAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2EdgeAndCircleContact.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp; sourceTree = ""; }; - A96F417914127EFD0067FE9A /* b2EdgeAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2EdgeAndCircleContact.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h; sourceTree = ""; }; - A96F417A14127EFD0067FE9A /* b2EdgeAndPolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2EdgeAndPolygonContact.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp; sourceTree = ""; }; - A96F417B14127EFD0067FE9A /* b2EdgeAndPolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2EdgeAndPolygonContact.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h; sourceTree = ""; }; - A96F417E14127FC20067FE9A /* b2EdgeShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = b2EdgeShape.cpp; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Collision/Shapes/b2EdgeShape.cpp; sourceTree = ""; }; - A96F417F14127FC20067FE9A /* b2EdgeShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = b2EdgeShape.h; path = ../../../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Collision/Shapes/b2EdgeShape.h; sourceTree = ""; }; + A96F416614127E9C0067FE9A /* b2Draw.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Draw.cpp; sourceTree = ""; }; + A96F416714127E9C0067FE9A /* b2Draw.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Draw.h; sourceTree = ""; }; + A96F416814127E9C0067FE9A /* b2GrowableStack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2GrowableStack.h; sourceTree = ""; }; + A96F416914127E9C0067FE9A /* b2Timer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Timer.cpp; sourceTree = ""; }; + A96F416A14127E9C0067FE9A /* b2Timer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Timer.h; sourceTree = ""; }; + A96F416D14127EB20067FE9A /* b2CollideEdge.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CollideEdge.cpp; sourceTree = ""; }; + A96F416F14127EC00067FE9A /* b2ChainShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ChainShape.cpp; sourceTree = ""; }; + A96F417014127EC00067FE9A /* b2ChainShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ChainShape.h; sourceTree = ""; }; + A96F417214127EE70067FE9A /* b2ChainAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ChainAndCircleContact.cpp; sourceTree = ""; }; + A96F417314127EE70067FE9A /* b2ChainAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ChainAndCircleContact.h; sourceTree = ""; }; + A96F417414127EE70067FE9A /* b2ChainAndPolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ChainAndPolygonContact.cpp; sourceTree = ""; }; + A96F417514127EE70067FE9A /* b2ChainAndPolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ChainAndPolygonContact.h; sourceTree = ""; }; + A96F417814127EFD0067FE9A /* b2EdgeAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2EdgeAndCircleContact.cpp; sourceTree = ""; }; + A96F417914127EFD0067FE9A /* b2EdgeAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2EdgeAndCircleContact.h; sourceTree = ""; }; + A96F417A14127EFD0067FE9A /* b2EdgeAndPolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2EdgeAndPolygonContact.cpp; sourceTree = ""; }; + A96F417B14127EFD0067FE9A /* b2EdgeAndPolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; path = b2EdgeAndPolygonContact.h; sourceTree = ""; }; + A96F417E14127FC20067FE9A /* b2EdgeShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2EdgeShape.cpp; sourceTree = ""; }; + A96F417F14127FC20067FE9A /* b2EdgeShape.h */ = {isa = PBXFileReference; fileEncoding = 4; path = b2EdgeShape.h; sourceTree = ""; }; A96F41811412AFB70067FE9A /* wrap_WeldJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_WeldJoint.cpp; sourceTree = ""; }; A96F41821412AFC60067FE9A /* wrap_WeldJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_WeldJoint.h; sourceTree = ""; }; A96F41841412AFEB0067FE9A /* WeldJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WeldJoint.cpp; sourceTree = ""; }; @@ -1406,8 +1406,7 @@ A96F416314127E720067FE9A /* b2Rope.cpp */, A96F416414127E720067FE9A /* b2Rope.h */, ); - name = Rope; - path = ../../../../../../Downloads/Box2D_v2.2.0/Box2D/Box2D/Rope; + path = Rope; sourceTree = ""; }; A986DEAF113249A700810279 /* thread */ = { From a446ddacc4ba7309b2d78814c0978e9fec3daf50 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 00:41:42 -0400 Subject: [PATCH 29/78] Fix Shape memory management --HG-- branch : box2d-update --- src/modules/physics/box2d/ChainShape.cpp | 2 ++ src/modules/physics/box2d/CircleShape.cpp | 1 + src/modules/physics/box2d/EdgeShape.cpp | 2 ++ src/modules/physics/box2d/Physics.cpp | 36 +++++++++++----------- src/modules/physics/box2d/PolygonShape.cpp | 2 ++ 5 files changed, 25 insertions(+), 18 deletions(-) diff --git a/src/modules/physics/box2d/ChainShape.cpp b/src/modules/physics/box2d/ChainShape.cpp index 693719a67..2a0af58b5 100644 --- a/src/modules/physics/box2d/ChainShape.cpp +++ b/src/modules/physics/box2d/ChainShape.cpp @@ -39,6 +39,8 @@ namespace box2d ChainShape::~ChainShape() { + delete shape; + shape = NULL; } void ChainShape::setNextVertex(float x, float y) diff --git a/src/modules/physics/box2d/CircleShape.cpp b/src/modules/physics/box2d/CircleShape.cpp index d8b619799..614f04621 100644 --- a/src/modules/physics/box2d/CircleShape.cpp +++ b/src/modules/physics/box2d/CircleShape.cpp @@ -37,6 +37,7 @@ namespace box2d CircleShape::~CircleShape() { + delete shape; shape = NULL; } diff --git a/src/modules/physics/box2d/EdgeShape.cpp b/src/modules/physics/box2d/EdgeShape.cpp index 196ea9940..3d0c6a8d5 100644 --- a/src/modules/physics/box2d/EdgeShape.cpp +++ b/src/modules/physics/box2d/EdgeShape.cpp @@ -37,6 +37,8 @@ namespace box2d EdgeShape::~EdgeShape() { + delete shape; + shape = NULL; } } // box2d diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 51b3c0443..cd3c8ba94 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -64,10 +64,10 @@ namespace box2d CircleShape * Physics::newCircleShape(float x, float y, float radius) { - b2CircleShape s; - s.m_p = b2Vec2(x, y); - s.m_radius = radius; - return new CircleShape(&s); + b2CircleShape *s = new b2CircleShape(); + s->m_p = b2Vec2(x, y); + s->m_radius = radius; + return new CircleShape(s); } PolygonShape * Physics::newRectangleShape(float w, float h) @@ -82,16 +82,16 @@ namespace box2d PolygonShape * Physics::newRectangleShape(float x, float y, float w, float h, float angle) { - b2PolygonShape s; - s.SetAsBox(w/2.0f, h/2.0f, b2Vec2(x, y), angle); - return new PolygonShape(&s); + b2PolygonShape* s = new b2PolygonShape(); + s->SetAsBox(w/2.0f, h/2.0f, b2Vec2(x, y), angle); + return new PolygonShape(s); } EdgeShape * Physics::newEdgeShape(float x1, float y1, float x2, float y2) { - b2EdgeShape s; - s.Set(b2Vec2(x1, y1), b2Vec2(x2, y2)); - return new EdgeShape(&s); + b2EdgeShape* s = new b2EdgeShape(); + s->Set(b2Vec2(x1, y1), b2Vec2(x2, y2)); + return new EdgeShape(s); } int Physics::newPolygonShape(lua_State * L) @@ -101,9 +101,9 @@ namespace box2d // 3 vertices love::luax_assert_argc(L, 2 * 3); - b2PolygonShape s; + b2PolygonShape* s = new b2PolygonShape(); - std::vector points(s.m_vertexCount); + std::vector points(s->m_vertexCount); std::vector convex_hull; for(int i = 0;iSet(vecs, count); - PolygonShape * p = new PolygonShape(&s); + PolygonShape * p = new PolygonShape(s); delete[] vecs; luax_newtype(L, "PolygonShape", PHYSICS_POLYGON_SHAPE_T, (void*)p); @@ -144,7 +144,7 @@ namespace box2d int argc = lua_gettop(L)-1; // first argument is looping int vcount = (int)argc/2; - b2ChainShape s; + b2ChainShape* s = new b2ChainShape(); bool loop = luax_toboolean(L, 1); @@ -159,11 +159,11 @@ namespace box2d } if (loop) - s.CreateLoop(vecs, vcount); + s->CreateLoop(vecs, vcount); else - s.CreateChain(vecs, vcount); + s->CreateChain(vecs, vcount); - ChainShape * c = new ChainShape(&s); + ChainShape * c = new ChainShape(s); delete[] vecs; luax_newtype(L, "ChainShape", PHYSICS_CHAIN_SHAPE_T, (void*)c); diff --git a/src/modules/physics/box2d/PolygonShape.cpp b/src/modules/physics/box2d/PolygonShape.cpp index ec3ba787e..84feefbe1 100644 --- a/src/modules/physics/box2d/PolygonShape.cpp +++ b/src/modules/physics/box2d/PolygonShape.cpp @@ -37,6 +37,8 @@ namespace box2d PolygonShape::~PolygonShape() { + delete shape; + shape = NULL; } int PolygonShape::getPoints(lua_State * L) From 2c761fc7017f730b45f755a3c21800afb7b21047 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 00:47:54 -0400 Subject: [PATCH 30/78] Actually load Fixture Lua functions --HG-- branch : box2d-update --- src/modules/physics/box2d/wrap_Physics.cpp | 1 + src/modules/physics/box2d/wrap_Physics.h | 1 + 2 files changed, 2 insertions(+) diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index 343907016..976db1980 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -300,6 +300,7 @@ namespace box2d luaopen_world, luaopen_contact, luaopen_body, + luaopen_fixture, luaopen_shape, luaopen_circleshape, luaopen_polygonshape, diff --git a/src/modules/physics/box2d/wrap_Physics.h b/src/modules/physics/box2d/wrap_Physics.h index 29d7e2e58..47fde7933 100644 --- a/src/modules/physics/box2d/wrap_Physics.h +++ b/src/modules/physics/box2d/wrap_Physics.h @@ -27,6 +27,7 @@ #include "wrap_World.h" #include "wrap_Contact.h" #include "wrap_Body.h" +#include "wrap_Fixture.h" #include "wrap_Shape.h" #include "wrap_CircleShape.h" #include "wrap_PolygonShape.h" From 542ae2f7367dc1ab73ba1ecb967b7bb0a978fa74 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 01:16:34 -0400 Subject: [PATCH 31/78] Actually create groundBody when creating a World with gravity (i.e. all the time) --HG-- branch : box2d-update --- src/modules/physics/box2d/World.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index 206206696..956c13a7a 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -133,6 +133,8 @@ namespace box2d world = new b2World(Physics::scaleDown(gravity)); world->SetAllowSleeping(sleep); world->SetContactListener(this); + b2BodyDef def; + groundBody = world->CreateBody(&def); } World::~World() From 5f4b4c8838c83ddaeaec42d455228800a71924b7 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 01:55:15 -0400 Subject: [PATCH 32/78] Forgot scaling when creating shapes and in PolygonShape::getPoints() --HG-- branch : box2d-update --- src/modules/physics/box2d/Physics.cpp | 8 +++++--- src/modules/physics/box2d/PolygonShape.cpp | 3 ++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index cd3c8ba94..8f3d8aac5 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -65,7 +65,7 @@ namespace box2d CircleShape * Physics::newCircleShape(float x, float y, float radius) { b2CircleShape *s = new b2CircleShape(); - s->m_p = b2Vec2(x, y); + s->m_p = Physics::scaleDown(b2Vec2(x, y)); s->m_radius = radius; return new CircleShape(s); } @@ -83,14 +83,14 @@ namespace box2d PolygonShape * Physics::newRectangleShape(float x, float y, float w, float h, float angle) { b2PolygonShape* s = new b2PolygonShape(); - s->SetAsBox(w/2.0f, h/2.0f, b2Vec2(x, y), angle); + s->SetAsBox(Physics::scaleDown(w/2.0f), Physics::scaleDown(h/2.0f), Physics::scaleDown(b2Vec2(x, y)), angle); return new PolygonShape(s); } EdgeShape * Physics::newEdgeShape(float x1, float y1, float x2, float y2) { b2EdgeShape* s = new b2EdgeShape(); - s->Set(b2Vec2(x1, y1), b2Vec2(x2, y2)); + s->Set(Physics::scaleDown(b2Vec2(x1, y1)), Physics::scaleDown(b2Vec2(x2, y2))); return new EdgeShape(s); } @@ -127,6 +127,7 @@ namespace box2d for (int i = 0; i < count; i++) { vecs[i].Set(convex_hull[i].x, convex_hull[i].y); + vecs[i] = Physics::scaleDown(vecs[i]); } s->Set(vecs, count); @@ -155,6 +156,7 @@ namespace box2d float x = (float)lua_tonumber(L, -2); float y = (float)lua_tonumber(L, -1); vecs[i].Set(x, y); + vecs[i] = Physics::scaleDown(vecs[i]); lua_pop(L, 2); } diff --git a/src/modules/physics/box2d/PolygonShape.cpp b/src/modules/physics/box2d/PolygonShape.cpp index 84feefbe1..e9d04d701 100644 --- a/src/modules/physics/box2d/PolygonShape.cpp +++ b/src/modules/physics/box2d/PolygonShape.cpp @@ -23,6 +23,7 @@ // Module #include "Body.h" #include "World.h" +#include "Physics.h" namespace love { @@ -48,7 +49,7 @@ namespace box2d int count = p->GetVertexCount(); for(int i = 0;iGetVertex(i); + b2Vec2 v = Physics::scaleUp(p->GetVertex(i)); lua_pushnumber(L, v.x); lua_pushnumber(L, v.y); } From 8592b98525e67059f426acb31c7dac2170775f57 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 02:15:46 -0400 Subject: [PATCH 33/78] Add type to Body constructor (defaults to "static") --HG-- branch : box2d-update --- src/modules/physics/box2d/Body.cpp | 3 ++- src/modules/physics/box2d/Body.h | 2 +- src/modules/physics/box2d/Physics.cpp | 8 ++++---- src/modules/physics/box2d/Physics.h | 6 ++++-- src/modules/physics/box2d/wrap_Physics.cpp | 5 ++++- 5 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/modules/physics/box2d/Body.cpp b/src/modules/physics/box2d/Body.cpp index 4ab323538..bae447523 100644 --- a/src/modules/physics/box2d/Body.cpp +++ b/src/modules/physics/box2d/Body.cpp @@ -33,13 +33,14 @@ namespace physics { namespace box2d { - Body::Body(World * world, b2Vec2 p) + Body::Body(World * world, b2Vec2 p, Body::Type type) : world(world) { world->retain(); b2BodyDef def; def.position = Physics::scaleDown(p); body = world->world->CreateBody(&def); + this->setType(type); } Body::~Body() diff --git a/src/modules/physics/box2d/Body.h b/src/modules/physics/box2d/Body.h index ddc5023cf..3898956c1 100644 --- a/src/modules/physics/box2d/Body.h +++ b/src/modules/physics/box2d/Body.h @@ -75,7 +75,7 @@ namespace box2d /** * Create a Body at position p. **/ - Body(World * world, b2Vec2 p); + Body(World * world, b2Vec2 p, Type type); virtual ~Body(); diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 8f3d8aac5..3c4d83e00 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -47,14 +47,14 @@ namespace box2d return new World(b2Vec2(gx, gy), sleep); } - Body * Physics::newBody(World * world, float x, float y) + Body * Physics::newBody(World * world, float x, float y, Body::Type type) { - return new Body(world, b2Vec2(x, y)); + return new Body(world, b2Vec2(x, y), type); } - Body * Physics::newBody(World * world) + Body * Physics::newBody(World * world, Body::Type type) { - return new Body(world, b2Vec2(0, 0)); + return new Body(world, b2Vec2(0, 0), type); } CircleShape * Physics::newCircleShape(float radius) diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index a51677ae0..9fa58876b 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -81,14 +81,16 @@ namespace box2d * @param world The world to create the Body in. * @param x The position along the x-axis. * @param x The position along the y-axis. + * @param type The type of body to create. **/ - Body * newBody(World * world, float x, float y); + Body * newBody(World * world, float x, float y, Body::Type type); /** * Creates a new Body at (0, 0) * @param world The world to create the Body in. + * @param type The type of Body to create. **/ - Body * newBody(World * world); + Body * newBody(World * world, Body::Type type); /** * Creates a new CircleShape at (0, 0). diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index 976db1980..e5557b0d8 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -47,7 +47,10 @@ namespace box2d World * world = luax_checktype(L, 1, "World", PHYSICS_WORLD_T); float x = (float)luaL_optnumber(L, 2, 0.0); float y = (float)luaL_optnumber(L, 3, 0.0); - Body * body = instance->newBody(world, x, y); + const char * type = luaL_optstring(L, 4, "static"); + Body::Type bodyType; + Body::getConstant(type, bodyType); + Body * body = instance->newBody(world, x, y, bodyType); luax_newtype(L, "Body", PHYSICS_BODY_T, (void*)body); return 1; } From 0d4569d28b915311c7b931cbae0371729ac47a26 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 02:34:27 -0400 Subject: [PATCH 34/78] Add mandatory density argument to Body:createFixture --HG-- branch : box2d-update --- src/modules/physics/box2d/Body.cpp | 4 ++-- src/modules/physics/box2d/Body.h | 2 +- src/modules/physics/box2d/Fixture.cpp | 3 ++- src/modules/physics/box2d/Fixture.h | 2 +- src/modules/physics/box2d/wrap_Body.cpp | 3 ++- 5 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/modules/physics/box2d/Body.cpp b/src/modules/physics/box2d/Body.cpp index bae447523..c689099d8 100644 --- a/src/modules/physics/box2d/Body.cpp +++ b/src/modules/physics/box2d/Body.cpp @@ -365,9 +365,9 @@ namespace box2d return world; } - Fixture * Body::createFixture(Shape * shape) + Fixture * Body::createFixture(Shape * shape, float density) { - return new Fixture(this, shape); + return new Fixture(this, shape, density); } void Body::destroyFixture(Fixture * fixture) diff --git a/src/modules/physics/box2d/Body.h b/src/modules/physics/box2d/Body.h index 3898956c1..581d42d36 100644 --- a/src/modules/physics/box2d/Body.h +++ b/src/modules/physics/box2d/Body.h @@ -368,7 +368,7 @@ namespace box2d */ World * getWorld() const; - Fixture * createFixture(Shape * shape); + Fixture * createFixture(Shape * shape, float density); void destroyFixture(Fixture * fixture); private: diff --git a/src/modules/physics/box2d/Fixture.cpp b/src/modules/physics/box2d/Fixture.cpp index 47d2461a3..38b927559 100644 --- a/src/modules/physics/box2d/Fixture.cpp +++ b/src/modules/physics/box2d/Fixture.cpp @@ -34,7 +34,7 @@ namespace physics { namespace box2d { - Fixture::Fixture(Body * body, Shape * shape) + Fixture::Fixture(Body * body, Shape * shape, float density) : body(body), shape(shape), fixture(NULL) { body->retain(); @@ -44,6 +44,7 @@ namespace box2d b2FixtureDef def; def.shape = shape->shape; def.userData = (void *)data; + def.density = density; fixture = body->body->CreateFixture(&def); } diff --git a/src/modules/physics/box2d/Fixture.h b/src/modules/physics/box2d/Fixture.h index 17dc831f3..23c312676 100644 --- a/src/modules/physics/box2d/Fixture.h +++ b/src/modules/physics/box2d/Fixture.h @@ -69,7 +69,7 @@ namespace box2d /** * Creates a Fixture. **/ - Fixture(Body * body, Shape * shape); + Fixture(Body * body, Shape * shape, float density); virtual ~Fixture(); diff --git a/src/modules/physics/box2d/wrap_Body.cpp b/src/modules/physics/box2d/wrap_Body.cpp index 40fa1b463..71e0fb3cc 100644 --- a/src/modules/physics/box2d/wrap_Body.cpp +++ b/src/modules/physics/box2d/wrap_Body.cpp @@ -497,7 +497,8 @@ namespace box2d { Body * t = luax_checkbody(L, 1); Shape * s = luax_checktype(L, 2, "Shape", PHYSICS_SHAPE_T); - Fixture * f = t->createFixture(s); + float d = (float)luaL_checknumber(L, 3); + Fixture * f = t->createFixture(s, d); luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)f); return 1; } From 08f894a98e286fc2b237e758a7097124854dffdc Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 03:10:19 -0400 Subject: [PATCH 35/78] Box2D implemented its own convex hull algorithm, Graham just messes things up --HG-- branch : box2d-update --- .../macosx/love.xcodeproj/project.pbxproj | 18 +-- src/modules/physics/box2d/Physics.cpp | 28 +--- .../box2d/graham/GrahamScanConvexHull.cpp | 123 ---------------- .../box2d/graham/GrahamScanConvexHull.h | 137 ------------------ 4 files changed, 6 insertions(+), 300 deletions(-) delete mode 100644 src/modules/physics/box2d/graham/GrahamScanConvexHull.cpp delete mode 100644 src/modules/physics/box2d/graham/GrahamScanConvexHull.h diff --git a/platform/macosx/love.xcodeproj/project.pbxproj b/platform/macosx/love.xcodeproj/project.pbxproj index 58ee87fcf..0c982c59d 100644 --- a/platform/macosx/love.xcodeproj/project.pbxproj +++ b/platform/macosx/love.xcodeproj/project.pbxproj @@ -115,7 +115,6 @@ A946D7F910424E57002BF36C /* wrap_World.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B6A10420ACA007D418B /* wrap_World.cpp */; }; A946D7FA10424E57002BF36C /* wrap_RevoluteJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B6610420ACA007D418B /* wrap_RevoluteJoint.cpp */; }; A946D7FB10424E57002BF36C /* wrap_PrismaticJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B6210420ACA007D418B /* wrap_PrismaticJoint.cpp */; }; - A946D7FC10424E57002BF36C /* GrahamScanConvexHull.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6AF610420AC7007D418B /* GrahamScanConvexHull.cpp */; }; A946D7FE10424E57002BF36C /* wrap_MouseJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B5C10420ACA007D418B /* wrap_MouseJoint.cpp */; }; A946D7FF10424E57002BF36C /* wrap_Physics.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B5E10420ACA007D418B /* wrap_Physics.cpp */; }; A946D80210424E57002BF36C /* PrismaticJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A93E6B0210420AC8007D418B /* PrismaticJoint.cpp */; }; @@ -442,8 +441,6 @@ A93E6AF210420AC7007D418B /* DistanceJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DistanceJoint.h; sourceTree = ""; }; A93E6AF310420AC7007D418B /* GearJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GearJoint.cpp; sourceTree = ""; }; A93E6AF410420AC7007D418B /* GearJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GearJoint.h; sourceTree = ""; }; - A93E6AF610420AC7007D418B /* GrahamScanConvexHull.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GrahamScanConvexHull.cpp; sourceTree = ""; }; - A93E6AF710420AC8007D418B /* GrahamScanConvexHull.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GrahamScanConvexHull.h; sourceTree = ""; }; A93E6AFA10420AC8007D418B /* Joint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Joint.cpp; sourceTree = ""; }; A93E6AFB10420AC8007D418B /* Joint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Joint.h; sourceTree = ""; }; A93E6AFC10420AC8007D418B /* MouseJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MouseJoint.cpp; sourceTree = ""; }; @@ -572,9 +569,9 @@ A96F417814127EFD0067FE9A /* b2EdgeAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2EdgeAndCircleContact.cpp; sourceTree = ""; }; A96F417914127EFD0067FE9A /* b2EdgeAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2EdgeAndCircleContact.h; sourceTree = ""; }; A96F417A14127EFD0067FE9A /* b2EdgeAndPolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2EdgeAndPolygonContact.cpp; sourceTree = ""; }; - A96F417B14127EFD0067FE9A /* b2EdgeAndPolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; path = b2EdgeAndPolygonContact.h; sourceTree = ""; }; + A96F417B14127EFD0067FE9A /* b2EdgeAndPolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2EdgeAndPolygonContact.h; sourceTree = ""; }; A96F417E14127FC20067FE9A /* b2EdgeShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2EdgeShape.cpp; sourceTree = ""; }; - A96F417F14127FC20067FE9A /* b2EdgeShape.h */ = {isa = PBXFileReference; fileEncoding = 4; path = b2EdgeShape.h; sourceTree = ""; }; + A96F417F14127FC20067FE9A /* b2EdgeShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2EdgeShape.h; sourceTree = ""; }; A96F41811412AFB70067FE9A /* wrap_WeldJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_WeldJoint.cpp; sourceTree = ""; }; A96F41821412AFC60067FE9A /* wrap_WeldJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_WeldJoint.h; sourceTree = ""; }; A96F41841412AFEB0067FE9A /* WeldJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WeldJoint.cpp; sourceTree = ""; }; @@ -1231,7 +1228,6 @@ A9B6432B13BF837800DC3C7E /* FrictionJoint.h */, A93E6AF310420AC7007D418B /* GearJoint.cpp */, A93E6AF410420AC7007D418B /* GearJoint.h */, - A93E6AF510420AC7007D418B /* graham */, A93E6AFA10420AC8007D418B /* Joint.cpp */, A93E6AFB10420AC8007D418B /* Joint.h */, A93E6AFC10420AC8007D418B /* MouseJoint.cpp */, @@ -1302,15 +1298,6 @@ path = box2d; sourceTree = ""; }; - A93E6AF510420AC7007D418B /* graham */ = { - isa = PBXGroup; - children = ( - A93E6AF610420AC7007D418B /* GrahamScanConvexHull.cpp */, - A93E6AF710420AC8007D418B /* GrahamScanConvexHull.h */, - ); - path = graham; - sourceTree = ""; - }; A93E6B7410420ACB007D418B /* sound */ = { isa = PBXGroup; children = ( @@ -1730,7 +1717,6 @@ A946D7F910424E57002BF36C /* wrap_World.cpp in Sources */, A946D7FA10424E57002BF36C /* wrap_RevoluteJoint.cpp in Sources */, A946D7FB10424E57002BF36C /* wrap_PrismaticJoint.cpp in Sources */, - A946D7FC10424E57002BF36C /* GrahamScanConvexHull.cpp in Sources */, A946D7FE10424E57002BF36C /* wrap_MouseJoint.cpp in Sources */, A946D7FF10424E57002BF36C /* wrap_Physics.cpp in Sources */, A946D80210424E57002BF36C /* PrismaticJoint.cpp in Sources */, diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 3c4d83e00..e6dcabae0 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -20,9 +20,6 @@ #include "Physics.h" -// Convex Hull Scan -#include "graham/GrahamScanConvexHull.h" - // LOVE #include #include "wrap_Body.h" @@ -102,35 +99,18 @@ namespace box2d love::luax_assert_argc(L, 2 * 3); b2PolygonShape* s = new b2PolygonShape(); - - std::vector points(s->m_vertexCount); - std::vector convex_hull; + + b2Vec2 * vecs = new b2Vec2[vcount]; for(int i = 0;iSet(vecs, count); + s->Set(vecs, vcount); PolygonShape * p = new PolygonShape(s); delete[] vecs; diff --git a/src/modules/physics/box2d/graham/GrahamScanConvexHull.cpp b/src/modules/physics/box2d/graham/GrahamScanConvexHull.cpp deleted file mode 100644 index e22b21d1a..000000000 --- a/src/modules/physics/box2d/graham/GrahamScanConvexHull.cpp +++ /dev/null @@ -1,123 +0,0 @@ -#include "GrahamScanConvexHull.h" - -#include -#include - -bool GrahamScanConvexHull::operator()(const std::vector < point2d >& pnt, std::vector< point2d >& final_hull) -{ - final_hull.clear(); - - if (pnt.size() <= 3) - { - std::copy(pnt.begin(), pnt.end(), std::back_inserter(final_hull)); - return true; - } - - unsigned int j = 0; - gs_point2d tmp_pnt; - - for(unsigned int i = 0; i < pnt.size(); i++) - { - point.push_back(gs_point2d(pnt[i].x,pnt[i].y,0.0)); - - if (point[i].y < point[j].y) - j = i; - else if (point[i].y == point[j].y) - if (point[i].x < point[j].x) - j = i; - } - - tmp_pnt = point[0]; - point[0] = point[j]; - point[j] = tmp_pnt; - - anchor = point[0]; - - for (unsigned int i = 1; i < point.size(); i++) - { - point[i].angle = cartesian_angle(point[i].x - anchor.x, point[i].y - anchor.y); - } - - sort(++point.begin(),point.end(),GSPoint2DCompare(&anchor)); - - graham_scan(final_hull); - - return true; -} - - -void GrahamScanConvexHull::graham_scan(std::vector< point2d >& final_hull) -{ - const std::size_t HEAD = 0; - const std::size_t PRE_HEAD = 1; - - std::deque pnt_queue; - - pnt_queue.push_front(point[0]); - pnt_queue.push_front(point[1]); - - unsigned int i = 2; - - while(i < point.size()) - { - if (pnt_queue.size() > 1) - { - if (orientation(pnt_queue[PRE_HEAD],pnt_queue[HEAD],point[i]) == counter_clock_wise) - pnt_queue.push_front(point[i++]); - else - pnt_queue.pop_front(); - } - else - pnt_queue.push_front(point[i++]); - } - - for(std::deque::iterator it = pnt_queue.begin(); it != pnt_queue.end(); it++) - { - final_hull.push_back(point2d((*it).x, (*it).y)); - } -} - - -inline double GrahamScanConvexHull::cartesian_angle(double x, double y) -{ - if ((x > 0.0) && (y > 0.0)) return (atan( y / x) * _180DivPI); - else if ((x < 0.0) && (y > 0.0)) return (atan(-x / y) * _180DivPI) + 90.0; - else if ((x < 0.0) && (y < 0.0)) return (atan( y / x) * _180DivPI) + 180.0; - else if ((x > 0.0) && (y < 0.0)) return (atan(-x / y) * _180DivPI) + 270.0; - else if ((x == 0.0) && (y > 0.0)) return 90.0; - else if ((x < 0.0) && (y == 0.0)) return 180.0; - else if ((x == 0.0) && (y < 0.0)) return 270.0; - else - return 0.0; -} - - -inline int GrahamScanConvexHull::orientation(const gs_point2d& p1, const gs_point2d& p2, const gs_point2d& p3) -{ - return orientation(p1.x,p1.y,p2.x,p2.y,p3.x,p3.y); -} - - -inline int GrahamScanConvexHull::orientation(const double x1, const double y1, - const double x2, const double y2, - const double px, const double py) -{ - double orin = (x2 - x1) * (py - y1) - (px - x1) * (y2 - y1); - - if (is_equal(orin,0.0)) - return 0; /* Orientaion is neutral aka collinear */ - else if (orin < 0.0) - return -1; /* Orientaion is to the right-hand side */ - else - return +1; /* Orientaion is to the left-hand side */ - -} - - -inline bool GrahamScanConvexHull::is_equal(const double v1, const double& v2, const double epsilon) -{ - double diff = v1 - v2; - return (-epsilon <= diff) && (diff <= epsilon); -} - - diff --git a/src/modules/physics/box2d/graham/GrahamScanConvexHull.h b/src/modules/physics/box2d/graham/GrahamScanConvexHull.h deleted file mode 100644 index 76167e2e0..000000000 --- a/src/modules/physics/box2d/graham/GrahamScanConvexHull.h +++ /dev/null @@ -1,137 +0,0 @@ -/* - ************************************************************************** - * Class: Graham Scan Convex Hull * - * By Arash Partow - 2001 * - * URL: http://www.partow.net * - * * - * Copyright Notice: * - * Free use of this library is permitted under the guidelines and * - * in accordance with the most current version of the Common Public * - * License. * - * http://www.opensource.org/licenses/cpl.php * - * * - ************************************************************************** -*/ - - -#ifndef INCLUDE_GRAHAMSCANCONVEXHULL_H -#define INCLUDE_GRAHAMSCANCONVEXHULL_H - -#include -#include -#include -#include -#include - -#include - - -struct point2d -{ - point2d(double _x = 0.0 , double _y = 0.0) : x(_x), y(_y){} - double x; - double y; -}; - -class ConvexHull -{ - public: - - virtual ~ConvexHull(){}; - virtual bool operator()(const std::vector& pnt, std::vector& final_hull) = 0; - -}; - - - - - -struct gs_point2d -{ -public: - gs_point2d(double _x = 0.0, double _y = 0.0, double _angle = 0.0) : x(_x), y(_y), angle(_angle){} - double x; - double y; - double angle; -}; - -const double _180DivPI = 57.295779513082320876798154814105000; -const int counter_clock_wise = +1; -const int clock_wise = -1; - - -class GSPoint2DCompare -{ -public: - - GSPoint2DCompare(gs_point2d* _anchor):anchor(_anchor){}; - - bool operator()(const gs_point2d& p1, const gs_point2d& p2) - { - if (p1.angle < p2.angle) return true; - else if (p1.angle > p2.angle) return false; - else if (is_equal(p1,p2)) return false; - else if (lay_distance(anchor->x, anchor->y, p1.x, p1.y) < lay_distance(anchor->x, anchor->y, p2.x, p2.y)) - return true; - else - return false; - } - -private: - - inline bool is_equal(const gs_point2d p1, gs_point2d p2) - { - return is_equal(p1.x,p2.x) && is_equal(p1.y,p2.y); - } - - inline bool is_equal(const double v1, const double& v2, const double epsilon = 1.0e-12) - { - double diff = v1 - v2; - return (-epsilon <= diff) && (diff <= epsilon); - } - - inline double lay_distance(const double& x1, const double& y1, const double& x2, const double& y2) - { - double dx = (x1 - x2); - double dy = (y1 - y2); - return (dx * dx + dy * dy); - } - - gs_point2d* anchor; - -}; - - -class GrahamScanConvexHull : public ConvexHull -{ -public: - - GrahamScanConvexHull(){}; - ~GrahamScanConvexHull(){}; - - virtual bool operator()(const std::vector < point2d >& pnt, std::vector< point2d >& final_hull); - -private: - - void graham_scan(std::vector< point2d >& final_hull); - - inline double cartesian_angle(double x, double y); - - inline int orientation(const gs_point2d& p1, - const gs_point2d& p2, - const gs_point2d& p3); - - inline int orientation(const double x1, const double y1, - const double x2, const double y2, - const double px, const double py); - - inline bool is_equal(const double v1, const double& v2, const double epsilon = 1.0e-12); - - std::vector point; - gs_point2d anchor; - -}; - - - -#endif From a0c0fd8387a0927a563ea373455f58798484782a Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 03:39:21 -0400 Subject: [PATCH 36/78] Add Body:getWorldPoints, basically for use with PolygonShape:getPoints to facilitate easier drawing --HG-- branch : box2d-update --- src/modules/physics/box2d/Body.cpp | 19 +++++++++++++++++++ src/modules/physics/box2d/Body.h | 6 ++++++ src/modules/physics/box2d/wrap_Body.cpp | 8 ++++++++ src/modules/physics/box2d/wrap_Body.h | 1 + 4 files changed, 34 insertions(+) diff --git a/src/modules/physics/box2d/Body.cpp b/src/modules/physics/box2d/Body.cpp index c689099d8..110b95642 100644 --- a/src/modules/physics/box2d/Body.cpp +++ b/src/modules/physics/box2d/Body.cpp @@ -281,6 +281,25 @@ namespace box2d x_o = v.x; y_o = v.y; } + + int Body::getWorldPoints(lua_State * L) + { + int argc = lua_gettop(L); + int vcount = (int)argc/2; + // at least one point + love::luax_assert_argc(L, 2); + + for(int i = 0;iGetWorldPoint(Physics::scaleDown(b2Vec2(x, y)))); + lua_pushnumber(L, point.x); + lua_pushnumber(L, point.y); + } + + return argc; + } void Body::getLocalPoint(float x, float y, float & x_o, float & y_o) { diff --git a/src/modules/physics/box2d/Body.h b/src/modules/physics/box2d/Body.h index 581d42d36..416dc926a 100644 --- a/src/modules/physics/box2d/Body.h +++ b/src/modules/physics/box2d/Body.h @@ -282,6 +282,12 @@ namespace box2d * @returns The y-coordinate of the vector in world coordinates. **/ void getWorldVector(float x, float y, float & x_o, float & y_o); + + /** + * Transforms a series of points (x, y) from local coordinates + * to world coordinates. + **/ + int getWorldPoints(lua_State * L); /** * Transforms a point (x, y) from world coordinates diff --git a/src/modules/physics/box2d/wrap_Body.cpp b/src/modules/physics/box2d/wrap_Body.cpp index 71e0fb3cc..bc7883394 100644 --- a/src/modules/physics/box2d/wrap_Body.cpp +++ b/src/modules/physics/box2d/wrap_Body.cpp @@ -360,6 +360,13 @@ namespace box2d return 2; } + + int w_Body_getWorldPoints(lua_State * L) + { + Body * t = luax_checkbody(L, 1); + lua_remove(L, 1); + return t->getWorldPoints(L); + } int w_Body_getLocalPoint(lua_State * L) { @@ -557,6 +564,7 @@ namespace box2d { "setType", w_Body_setType }, { "getWorldPoint", w_Body_getWorldPoint }, { "getWorldVector", w_Body_getWorldVector }, + { "getWorldPoints", w_Body_getWorldPoints }, { "getLocalPoint", w_Body_getLocalPoint }, { "getLocalVector", w_Body_getLocalVector }, { "getLinearVelocityFromWorldPoint", w_Body_getLinearVelocityFromWorldPoint }, diff --git a/src/modules/physics/box2d/wrap_Body.h b/src/modules/physics/box2d/wrap_Body.h index b4f58d2cd..bbee3e6b6 100644 --- a/src/modules/physics/box2d/wrap_Body.h +++ b/src/modules/physics/box2d/wrap_Body.h @@ -67,6 +67,7 @@ namespace box2d int w_Body_setType(lua_State * L); int w_Body_getWorldPoint(lua_State * L); int w_Body_getWorldVector(lua_State * L); + int w_Body_getWorldPoints(lua_State * L); int w_Body_getLocalPoint(lua_State * L); int w_Body_getLocalVector(lua_State * L); int w_Body_getLinearVelocityFromWorldPoint(lua_State * L); From b36ff409aa7a77c0131d2d49416459b44ec01408 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 09:27:39 -0400 Subject: [PATCH 37/78] Make Fixture creation API more lovely --HG-- branch : box2d-update --- src/modules/physics/box2d/Body.cpp | 10 --- src/modules/physics/box2d/Body.h | 4 - src/modules/physics/box2d/Physics.cpp | 5 ++ src/modules/physics/box2d/Physics.h | 86 ++++++++++++---------- src/modules/physics/box2d/wrap_Body.cpp | 20 ----- src/modules/physics/box2d/wrap_Body.h | 2 - src/modules/physics/box2d/wrap_Physics.cpp | 11 +++ src/modules/physics/box2d/wrap_Physics.h | 1 + 8 files changed, 64 insertions(+), 75 deletions(-) diff --git a/src/modules/physics/box2d/Body.cpp b/src/modules/physics/box2d/Body.cpp index 110b95642..a471a1738 100644 --- a/src/modules/physics/box2d/Body.cpp +++ b/src/modules/physics/box2d/Body.cpp @@ -383,16 +383,6 @@ namespace box2d { return world; } - - Fixture * Body::createFixture(Shape * shape, float density) - { - return new Fixture(this, shape, density); - } - - void Body::destroyFixture(Fixture * fixture) - { - fixture->release(); - } b2Vec2 Body::getVector(lua_State * L) { diff --git a/src/modules/physics/box2d/Body.h b/src/modules/physics/box2d/Body.h index 416dc926a..d14a00e2f 100644 --- a/src/modules/physics/box2d/Body.h +++ b/src/modules/physics/box2d/Body.h @@ -373,10 +373,6 @@ namespace box2d * Get the World this Body resides in. */ World * getWorld() const; - - Fixture * createFixture(Shape * shape, float density); - - void destroyFixture(Fixture * fixture); private: /** diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index e6dcabae0..9c76a7ff0 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -203,6 +203,11 @@ namespace box2d return new RopeJoint(body1, body2, x1, y1, x2, y2, maxLength, collideConnected); } + Fixture * Physics::newFixture(Body * body, Shape * shape, float density) + { + return new Fixture(body, shape, density); + } + void Physics::setMeter(int meter) { Physics::meter = meter; diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index 9fa58876b..b26f61e42 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -250,74 +250,82 @@ namespace box2d RopeJoint * newRopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength, bool collideConnected); /** - * Sets the number of pixels in one meter. - * @param pixels The number of pixels in one meter. (1m ~= 3.3ft). - **/ + * Creates a new Fixture attaching shape to body. + * @param body The body to attach the Fixture to. + * @param shape The shape to attach to the Fixture, + * @param density The density of the Fixture. + **/ + + Fixture * newFixture(Body * body, Shape * shape, float density); + + /** + * Sets the number of pixels in one meter. + * @param pixels The number of pixels in one meter. (1m ~= 3.3ft). + **/ static void setMeter(int meter); /** - * Gets the number of pixels in one meter. - * @param pixels The number of pixels in one meter. (1m ~= 3.3ft). - **/ + * Gets the number of pixels in one meter. + * @param pixels The number of pixels in one meter. (1m ~= 3.3ft). + **/ static int getMeter(); /** - * Scales a value down according to the current meter in pixels. - * @param f The unscaled input value. - **/ + * Scales a value down according to the current meter in pixels. + * @param f The unscaled input value. + **/ static float scaleDown(float f); /** - * Scales a value up according to the current meter in pixels. - * @param f The unscaled input value. - **/ + * Scales a value up according to the current meter in pixels. + * @param f The unscaled input value. + **/ static float scaleUp(float f); /** - * Scales a point down according to the current meter - * in pixels, for instance x = x0/meter, y = x0/meter. - * @param x The x-coordinate of the point to scale. - * @param y The y-coordinate of the point to scale. - **/ + * Scales a point down according to the current meter + * in pixels, for instance x = x0/meter, y = x0/meter. + * @param x The x-coordinate of the point to scale. + * @param y The y-coordinate of the point to scale. + **/ static void scaleDown(float & x, float & y); /** - * Scales a point up according to the current meter - * in pixels, for instance x = x0/meter, y = x0/meter. - * @param x The x-coordinate of the point to scale. - * @param y The y-coordinate of the point to scale. - **/ + * Scales a point up according to the current meter + * in pixels, for instance x = x0/meter, y = x0/meter. + * @param x The x-coordinate of the point to scale. + * @param y The y-coordinate of the point to scale. + **/ static void scaleUp(float & x, float & y); /** - * Scales a b2Vec2 down according to the current meter in pixels. - * @param v The unscaled input vector. - * @return The scaled vector. - **/ + * Scales a b2Vec2 down according to the current meter in pixels. + * @param v The unscaled input vector. + * @return The scaled vector. + **/ static b2Vec2 scaleDown(const b2Vec2 & v); /** - * Scales a b2Vec up according to the current meter in pixels. - * @param v The unscaled input vector. - * @return The scaled vector. - **/ + * Scales a b2Vec up according to the current meter in pixels. + * @param v The unscaled input vector. + * @return The scaled vector. + **/ static b2Vec2 scaleUp(const b2Vec2 & v); /** - * Scales a b2AABB down according to the current meter in pixels. - * @param v The unscaled input AABB. - * @return The scaled AABB. - **/ + * Scales a b2AABB down according to the current meter in pixels. + * @param v The unscaled input AABB. + * @return The scaled AABB. + **/ static b2AABB scaleDown(const b2AABB & aabb); /** - * Scales a b2AABB up according to the current meter in pixels. - * @param v The unscaled input AABB. - * @return The scaled AABB. - **/ + * Scales a b2AABB up according to the current meter in pixels. + * @param v The unscaled input AABB. + * @return The scaled AABB. + **/ static b2AABB scaleUp(const b2AABB & aabb); - }; // Physics } // box2d diff --git a/src/modules/physics/box2d/wrap_Body.cpp b/src/modules/physics/box2d/wrap_Body.cpp index bc7883394..110dfacd3 100644 --- a/src/modules/physics/box2d/wrap_Body.cpp +++ b/src/modules/physics/box2d/wrap_Body.cpp @@ -499,24 +499,6 @@ namespace box2d luax_pushboolean(L, b); return 1; } - - int w_Body_createFixture(lua_State * L) - { - Body * t = luax_checkbody(L, 1); - Shape * s = luax_checktype(L, 2, "Shape", PHYSICS_SHAPE_T); - float d = (float)luaL_checknumber(L, 3); - Fixture * f = t->createFixture(s, d); - luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)f); - return 1; - } - - int w_Body_destroyFixture(lua_State * L) - { - Body * t = luax_checkbody(L, 1); - Fixture * f = luax_checktype(L, 2, "Fixture", PHYSICS_FIXTURE_T); - t->destroyFixture(f); - return 0; - } int w_Body_destroy(lua_State * L) { @@ -579,8 +561,6 @@ namespace box2d { "setAwake", w_Body_setAwake }, { "setFixedRotation", w_Body_setFixedRotation }, { "isFixedRotation", w_Body_isFixedRotation }, - { "createFixture", w_Body_createFixture }, - { "destroyFixture", w_Body_destroyFixture }, { "destroy", w_Body_destroy }, { 0, 0 } }; diff --git a/src/modules/physics/box2d/wrap_Body.h b/src/modules/physics/box2d/wrap_Body.h index bbee3e6b6..e7a8fe6e2 100644 --- a/src/modules/physics/box2d/wrap_Body.h +++ b/src/modules/physics/box2d/wrap_Body.h @@ -82,8 +82,6 @@ namespace box2d int w_Body_setAwake(lua_State * L); int w_Body_setFixedRotation(lua_State * L); int w_Body_isFixedRotation(lua_State * L); - int w_Body_createFixture(lua_State * L); - int w_Body_destroyFixture(lua_State * L); int w_Body_destroy(lua_State * L); int luaopen_body(lua_State * L); diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index e5557b0d8..e84839187 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -54,6 +54,16 @@ namespace box2d luax_newtype(L, "Body", PHYSICS_BODY_T, (void*)body); return 1; } + + int w_newFixture(lua_State * L) + { + Body * body = luax_checkbody(L, 1); + Shape * shape = luax_checkshape(L, 2); + float density = (float)luaL_checknumber(L, 3); + Fixture * fixture = instance->newFixture(body, shape, density); + luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)fixture); + return 1; + } int w_newCircleShape(lua_State * L) { @@ -279,6 +289,7 @@ namespace box2d static const luaL_Reg functions[] = { { "newWorld", w_newWorld }, { "newBody", w_newBody }, + { "newFixture", w_newFixture }, { "newCircleShape", w_newCircleShape }, { "newRectangleShape", w_newRectangleShape }, { "newPolygonShape", w_newPolygonShape }, diff --git a/src/modules/physics/box2d/wrap_Physics.h b/src/modules/physics/box2d/wrap_Physics.h index 47fde7933..8de805600 100644 --- a/src/modules/physics/box2d/wrap_Physics.h +++ b/src/modules/physics/box2d/wrap_Physics.h @@ -53,6 +53,7 @@ namespace box2d { int w_newWorld(lua_State * L); int w_newBody(lua_State * L); + int w_newFixture(lua_State * L); int w_newCircleShape(lua_State * L); int w_newRectangleShape(lua_State * L); int w_newPolygonShape(lua_State * L); From 2e1b941bd61b8b5f23ebfdf339348255087b667a Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 11:51:06 -0400 Subject: [PATCH 38/78] Add Memoizer class --HG-- branch : box2d-update --- .../macosx/love.xcodeproj/project.pbxproj | 6 +++ src/common/Memoizer.cpp | 43 +++++++++++++++++ src/common/Memoizer.h | 46 +++++++++++++++++++ 3 files changed, 95 insertions(+) create mode 100644 src/common/Memoizer.cpp create mode 100644 src/common/Memoizer.h diff --git a/platform/macosx/love.xcodeproj/project.pbxproj b/platform/macosx/love.xcodeproj/project.pbxproj index 0c982c59d..543bcfdca 100644 --- a/platform/macosx/love.xcodeproj/project.pbxproj +++ b/platform/macosx/love.xcodeproj/project.pbxproj @@ -216,6 +216,7 @@ A9D1D20D14229B6500A8BC2F /* wrap_ChainShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D1D20C14229B5800A8BC2F /* wrap_ChainShape.cpp */; }; A9D307EA106635C3004FEDF8 /* physfs.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9D307E9106635C3004FEDF8 /* physfs.framework */; }; A9D307F2106635D3004FEDF8 /* physfs.framework in Copy Frameworks */ = {isa = PBXBuildFile; fileRef = A9D307E9106635C3004FEDF8 /* physfs.framework */; }; + A9D5C47D142E32EE0044ECF7 /* Memoizer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C47C142E32ED0044ECF7 /* Memoizer.cpp */; }; A9DEC1C11046EFA70049C70C /* Love.icns in Resources */ = {isa = PBXBuildFile; fileRef = A9DEC1BF1046EFA60049C70C /* Love.icns */; }; A9DEC1C21046EFA70049C70C /* LoveDocument.icns in Resources */ = {isa = PBXBuildFile; fileRef = A9DEC1C01046EFA70049C70C /* LoveDocument.icns */; }; A9F16927109E7BAD00FC83D1 /* libmodplug.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9F16926109E7BAD00FC83D1 /* libmodplug.framework */; }; @@ -685,6 +686,8 @@ A9D1D20C14229B5800A8BC2F /* wrap_ChainShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_ChainShape.cpp; sourceTree = ""; }; A9D1D20E14229B7300A8BC2F /* wrap_ChainShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_ChainShape.h; sourceTree = ""; }; A9D307E9106635C3004FEDF8 /* physfs.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = physfs.framework; path = /Library/Frameworks/physfs.framework; sourceTree = ""; }; + A9D5C47B142E31350044ECF7 /* Memoizer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Memoizer.h; sourceTree = ""; }; + A9D5C47C142E32ED0044ECF7 /* Memoizer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Memoizer.cpp; sourceTree = ""; }; A9DEC1BF1046EFA60049C70C /* Love.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; name = Love.icns; path = icons/Love.icns; sourceTree = ""; }; A9DEC1C01046EFA70049C70C /* LoveDocument.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; name = LoveDocument.icns; path = icons/LoveDocument.icns; sourceTree = ""; }; A9F16926109E7BAD00FC83D1 /* libmodplug.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = libmodplug.framework; path = /Library/Frameworks/libmodplug.framework; sourceTree = ""; }; @@ -810,6 +813,8 @@ A93E69E210420ABF007D418B /* math.h */, A93E69E310420ABF007D418B /* Matrix.cpp */, A93E69E410420ABF007D418B /* Matrix.h */, + A9D5C47C142E32ED0044ECF7 /* Memoizer.cpp */, + A9D5C47B142E31350044ECF7 /* Memoizer.h */, A93E69E510420ABF007D418B /* MemoryData.cpp */, A93E69E610420ABF007D418B /* MemoryData.h */, A93E69E710420ABF007D418B /* Module.h */, @@ -1819,6 +1824,7 @@ A9D1D20D14229B6500A8BC2F /* wrap_ChainShape.cpp in Sources */, A958F911142D364C007F320F /* wrap_Fixture.cpp in Sources */, A958F917142D6B3A007F320F /* Body.cpp in Sources */, + A9D5C47D142E32EE0044ECF7 /* Memoizer.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/src/common/Memoizer.cpp b/src/common/Memoizer.cpp new file mode 100644 index 000000000..792c2c13f --- /dev/null +++ b/src/common/Memoizer.cpp @@ -0,0 +1,43 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ +#include "Memoizer.h" + +namespace love +{ + + std::map Memoizer::objectMap; + + void Memoizer::add(void * key, void * val) + { + objectMap[key] = val; + } + + void Memoizer::remove(void * key) + { + objectMap.erase(key); + } + + void * Memoizer::find(void * key) + { + if (objectMap.count(key)) return objectMap[key]; + return NULL; + } + +} // love diff --git a/src/common/Memoizer.h b/src/common/Memoizer.h new file mode 100644 index 000000000..36abe61de --- /dev/null +++ b/src/common/Memoizer.h @@ -0,0 +1,46 @@ +/** +* Copyright (c) 2006-2011 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#ifndef LOVE_MEMOIZER_H +#define LOVE_MEMOIZER_H + +#include + +namespace love +{ + class Memoizer + { + private: + + static std::map objectMap; + + public: + + static void add(void * key, void * val); + + static void remove(void * key); + + static void * find(void * key); + + }; // Memoizer + +} // love + +#endif // LOVE_MEMOIZER_H From d35dbaa28bc633eea9ec08b1467e29be75b32e9d Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 11:58:24 -0400 Subject: [PATCH 39/78] Add __eq metamethod to all objects (checks to see if the Proxy data they represent are equal) --HG-- branch : box2d-update --- src/common/runtime.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/common/runtime.cpp b/src/common/runtime.cpp index 67614966a..cb2482922 100644 --- a/src/common/runtime.cpp +++ b/src/common/runtime.cpp @@ -74,6 +74,14 @@ namespace love luax_pushboolean(L, p->flags[t]); return 1; } + + static int w__eq(lua_State * L) + { + Proxy * p1 = (Proxy *)lua_touserdata(L, 1); + Proxy * p2 = (Proxy *)lua_touserdata(L, 2); + luax_pushboolean(L, p1->data == p2->data); + return 1; + } Reference * luax_refif(lua_State * L, int type) { @@ -197,6 +205,10 @@ namespace love // setup gc lua_pushcfunction(L, w__gc); lua_setfield(L, -2, "__gc"); + + // Add equality + lua_pushcfunction(L, w__eq); + lua_setfield(L, -2, "__eq"); // Add tostring function. lua_pushstring(L, tname); From c70506359709cf90959b95dd2b9afe88dab34ad2 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 12:20:59 -0400 Subject: [PATCH 40/78] First attempt at implementing Memoization for certain Box2D objects --HG-- branch : box2d-update --- src/modules/physics/box2d/Body.cpp | 11 +++++++++++ src/modules/physics/box2d/Body.h | 5 +++++ src/modules/physics/box2d/ChainShape.cpp | 4 ++++ src/modules/physics/box2d/CircleShape.cpp | 4 ++++ src/modules/physics/box2d/EdgeShape.cpp | 4 ++++ src/modules/physics/box2d/Fixture.cpp | 16 ++++++++++++++++ src/modules/physics/box2d/Fixture.h | 5 +++++ src/modules/physics/box2d/PolygonShape.cpp | 4 ++++ src/modules/physics/box2d/Shape.cpp | 11 +++++++++++ src/modules/physics/box2d/Shape.h | 1 + src/modules/physics/box2d/World.cpp | 4 ++++ 11 files changed, 69 insertions(+) diff --git a/src/modules/physics/box2d/Body.cpp b/src/modules/physics/box2d/Body.cpp index a471a1738..a5cba16ca 100644 --- a/src/modules/physics/box2d/Body.cpp +++ b/src/modules/physics/box2d/Body.cpp @@ -21,6 +21,7 @@ #include "Body.h" #include +#include #include "Shape.h" #include "Fixture.h" @@ -41,10 +42,20 @@ namespace box2d def.position = Physics::scaleDown(p); body = world->world->CreateBody(&def); this->setType(type); + Memoizer::add(body, this); + } + + Body::Body(b2Body * b) + : body(b) + { + world = (World *)Memoizer::find(b->GetWorld()); + world->retain(); + Memoizer::add(body, this); } Body::~Body() { + Memoizer::remove(body); world->world->DestroyBody(body); world->release(); body = 0; diff --git a/src/modules/physics/box2d/Body.h b/src/modules/physics/box2d/Body.h index d14a00e2f..07c181365 100644 --- a/src/modules/physics/box2d/Body.h +++ b/src/modules/physics/box2d/Body.h @@ -76,6 +76,11 @@ namespace box2d * Create a Body at position p. **/ Body(World * world, b2Vec2 p, Type type); + + /** + * Create a Body from an extant b2Body. + **/ + Body(b2Body * b); virtual ~Body(); diff --git a/src/modules/physics/box2d/ChainShape.cpp b/src/modules/physics/box2d/ChainShape.cpp index 2a0af58b5..f127be479 100644 --- a/src/modules/physics/box2d/ChainShape.cpp +++ b/src/modules/physics/box2d/ChainShape.cpp @@ -25,6 +25,8 @@ #include "World.h" #include "Physics.h" +#include + namespace love { namespace physics @@ -35,10 +37,12 @@ namespace box2d : loop(loop) { shape = c; + Memoizer::add(shape, this); } ChainShape::~ChainShape() { + Memoizer::remove(shape); delete shape; shape = NULL; } diff --git a/src/modules/physics/box2d/CircleShape.cpp b/src/modules/physics/box2d/CircleShape.cpp index 614f04621..752f2f94d 100644 --- a/src/modules/physics/box2d/CircleShape.cpp +++ b/src/modules/physics/box2d/CircleShape.cpp @@ -24,6 +24,8 @@ #include "Body.h" #include "World.h" +#include + namespace love { namespace physics @@ -33,10 +35,12 @@ namespace box2d CircleShape::CircleShape(b2CircleShape * c) { shape = c; + Memoizer::add(shape, this); } CircleShape::~CircleShape() { + Memoizer::remove(shape); delete shape; shape = NULL; } diff --git a/src/modules/physics/box2d/EdgeShape.cpp b/src/modules/physics/box2d/EdgeShape.cpp index 3d0c6a8d5..1e90db188 100644 --- a/src/modules/physics/box2d/EdgeShape.cpp +++ b/src/modules/physics/box2d/EdgeShape.cpp @@ -24,6 +24,8 @@ #include "Body.h" #include "World.h" +#include + namespace love { namespace physics @@ -33,10 +35,12 @@ namespace box2d EdgeShape::EdgeShape(b2EdgeShape * e) { shape = e; + Memoizer::add(shape, this); } EdgeShape::~EdgeShape() { + Memoizer::remove(shape); delete shape; shape = NULL; } diff --git a/src/modules/physics/box2d/Fixture.cpp b/src/modules/physics/box2d/Fixture.cpp index 38b927559..f8968fe80 100644 --- a/src/modules/physics/box2d/Fixture.cpp +++ b/src/modules/physics/box2d/Fixture.cpp @@ -25,6 +25,8 @@ #include "World.h" #include "Physics.h" +#include + // STD #include @@ -46,6 +48,20 @@ namespace box2d def.userData = (void *)data; def.density = density; fixture = body->body->CreateFixture(&def); + Memoizer::add(fixture, this); + } + + Fixture::Fixture(b2Fixture * f) + : fixture(f) + { + data = (fixtureudata *)f->GetUserData(); + body = (Body *)Memoizer::find(f->GetBody()); + if (!body) body = new Body(f->GetBody()); + body->retain(); + shape = (Shape *)Memoizer::find(f->GetShape()); + if (!shape) shape = new Shape(f->GetShape()); + shape->retain(); + Memoizer::add(fixture, this); } Fixture::~Fixture() diff --git a/src/modules/physics/box2d/Fixture.h b/src/modules/physics/box2d/Fixture.h index 23c312676..856628858 100644 --- a/src/modules/physics/box2d/Fixture.h +++ b/src/modules/physics/box2d/Fixture.h @@ -70,6 +70,11 @@ namespace box2d * Creates a Fixture. **/ Fixture(Body * body, Shape * shape, float density); + + /** + * Creates a Fixture. + **/ + Fixture(b2Fixture * f); virtual ~Fixture(); diff --git a/src/modules/physics/box2d/PolygonShape.cpp b/src/modules/physics/box2d/PolygonShape.cpp index e9d04d701..62c1a80d2 100644 --- a/src/modules/physics/box2d/PolygonShape.cpp +++ b/src/modules/physics/box2d/PolygonShape.cpp @@ -25,6 +25,8 @@ #include "World.h" #include "Physics.h" +#include + namespace love { namespace physics @@ -34,10 +36,12 @@ namespace box2d PolygonShape::PolygonShape(b2PolygonShape * p) { shape = p; + Memoizer::add(shape, this); } PolygonShape::~PolygonShape() { + Memoizer::remove(shape); delete shape; shape = NULL; } diff --git a/src/modules/physics/box2d/Shape.cpp b/src/modules/physics/box2d/Shape.cpp index 6b6b99e4e..0de9c7c44 100644 --- a/src/modules/physics/box2d/Shape.cpp +++ b/src/modules/physics/box2d/Shape.cpp @@ -25,6 +25,8 @@ #include "World.h" #include "Physics.h" +#include + // STD #include @@ -38,9 +40,18 @@ namespace box2d : shape(NULL) { } + Shape::Shape(b2Shape * shape) + : shape(shape) + { + Memoizer::add(shape, this); + } Shape::~Shape() { + if (shape) { + Memoizer::remove(shape); + delete shape; + } shape = 0; } diff --git a/src/modules/physics/box2d/Shape.h b/src/modules/physics/box2d/Shape.h index 78334a6f7..beb94c37c 100644 --- a/src/modules/physics/box2d/Shape.h +++ b/src/modules/physics/box2d/Shape.h @@ -57,6 +57,7 @@ namespace box2d * Creates a Shape. **/ Shape(); + Shape(b2Shape * shape); virtual ~Shape(); diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index 956c13a7a..d7423e9f9 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -24,6 +24,7 @@ #include "Shape.h" #include "Contact.h" #include "Physics.h" +#include #include namespace love @@ -125,6 +126,7 @@ namespace box2d world->SetContactListener(this); b2BodyDef def; groundBody = world->CreateBody(&def); + Memoizer::add(world, this); } World::World(b2Vec2 gravity, bool sleep) @@ -135,11 +137,13 @@ namespace box2d world->SetContactListener(this); b2BodyDef def; groundBody = world->CreateBody(&def); + Memoizer::add(world, this); } World::~World() { world->DestroyBody(groundBody); + Memoizer::remove(world); delete world; } From e962891ba20116162cb112efe6548549e55c09e1 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 12:32:28 -0400 Subject: [PATCH 41/78] Add Fixture:getNext() --HG-- branch : box2d-update --- src/modules/physics/box2d/Fixture.cpp | 9 +++++++++ src/modules/physics/box2d/Fixture.h | 5 +++++ src/modules/physics/box2d/wrap_Fixture.cpp | 11 +++++++++++ src/modules/physics/box2d/wrap_Fixture.h | 1 + 4 files changed, 26 insertions(+) diff --git a/src/modules/physics/box2d/Fixture.cpp b/src/modules/physics/box2d/Fixture.cpp index f8968fe80..ea7838db4 100644 --- a/src/modules/physics/box2d/Fixture.cpp +++ b/src/modules/physics/box2d/Fixture.cpp @@ -133,6 +133,15 @@ namespace box2d { return shape; } + + Fixture * Fixture::getNext() const + { + b2Fixture * f = fixture->GetNext(); + if (!f) return NULL; + Fixture * fix = (Fixture *)Memoizer::find(f); + if (!fix) fix = new Fixture(f); + return fix; + } void Fixture::setFilterData(int * v) { diff --git a/src/modules/physics/box2d/Fixture.h b/src/modules/physics/box2d/Fixture.h index 856628858..574d17b24 100644 --- a/src/modules/physics/box2d/Fixture.h +++ b/src/modules/physics/box2d/Fixture.h @@ -106,6 +106,11 @@ namespace box2d **/ Body * getBody() const; + /** + * Gets the next Fixture attached to the parent Body. + **/ + Fixture * getNext() const; + /** * Sets the filter data. An integer array is used even though the * first two elements are unsigned shorts. The elements are: diff --git a/src/modules/physics/box2d/wrap_Fixture.cpp b/src/modules/physics/box2d/wrap_Fixture.cpp index bc758f4db..c420f38e6 100644 --- a/src/modules/physics/box2d/wrap_Fixture.cpp +++ b/src/modules/physics/box2d/wrap_Fixture.cpp @@ -122,6 +122,16 @@ namespace box2d luax_newtype(L, "Shape", PHYSICS_SHAPE_T, (void*)shape); return 1; } + + int w_Fixture_getNext(lua_State * L) + { + Fixture * t = luax_checkfixture(L, 1); + Fixture * f = t->getNext(); + if (f == 0) return 0; + f->retain(); + luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)f); + return 1; + } int w_Fixture_testPoint(lua_State * L) { @@ -254,6 +264,7 @@ namespace box2d { "getDensity", w_Fixture_getDensity }, { "getBody", w_Fixture_getBody }, { "getShape", w_Fixture_getShape }, + { "getNext", w_Fixture_getNext }, { "isSensor", w_Fixture_isSensor }, { "testPoint", w_Fixture_testPoint }, { "rayCast", w_Fixture_rayCast }, diff --git a/src/modules/physics/box2d/wrap_Fixture.h b/src/modules/physics/box2d/wrap_Fixture.h index d41f6b25a..675ab7342 100644 --- a/src/modules/physics/box2d/wrap_Fixture.h +++ b/src/modules/physics/box2d/wrap_Fixture.h @@ -43,6 +43,7 @@ namespace box2d int w_Fixture_isSensor(lua_State * L); int w_Fixture_getBody(lua_State * L); int w_Fixture_getShape(lua_State * L); + int w_Fixture_getNext(lua_State * L); int w_Fixture_testPoint(lua_State * L); int w_Fixture_rayCast(lua_State * L); int w_Fixture_setFilterData(lua_State * L); From 06820210eb22490f9ea1923b2a1b50aba5e0ec7f Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 13:21:50 -0400 Subject: [PATCH 42/78] better Fixture Shape management --HG-- branch : box2d-update --- src/modules/physics/box2d/Fixture.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/modules/physics/box2d/Fixture.cpp b/src/modules/physics/box2d/Fixture.cpp index ea7838db4..01f704597 100644 --- a/src/modules/physics/box2d/Fixture.cpp +++ b/src/modules/physics/box2d/Fixture.cpp @@ -37,10 +37,9 @@ namespace physics namespace box2d { Fixture::Fixture(Body * body, Shape * shape, float density) - : body(body), shape(shape), fixture(NULL) + : body(body), fixture(NULL) { body->retain(); - shape->retain(); data = new fixtureudata(); data->ref = 0; b2FixtureDef def; @@ -48,6 +47,7 @@ namespace box2d def.userData = (void *)data; def.density = density; fixture = body->body->CreateFixture(&def); + shape = new Shape(fixture->GetShape()); Memoizer::add(fixture, this); } @@ -60,7 +60,7 @@ namespace box2d body->retain(); shape = (Shape *)Memoizer::find(f->GetShape()); if (!shape) shape = new Shape(f->GetShape()); - shape->retain(); + else shape->retain(); Memoizer::add(fixture, this); } @@ -77,6 +77,7 @@ namespace box2d fixture = 0; body->release(); + shape->release(); } Shape::Type Fixture::getType() const From 1b14dcaeb863b1af118a393efad24c320c534689 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 13:22:05 -0400 Subject: [PATCH 43/78] cleaning up *Shape constructors --HG-- branch : box2d-update --- src/modules/physics/box2d/ChainShape.cpp | 4 +--- src/modules/physics/box2d/CircleShape.cpp | 3 +-- src/modules/physics/box2d/EdgeShape.cpp | 3 +-- src/modules/physics/box2d/PolygonShape.cpp | 3 +-- 4 files changed, 4 insertions(+), 9 deletions(-) diff --git a/src/modules/physics/box2d/ChainShape.cpp b/src/modules/physics/box2d/ChainShape.cpp index f127be479..2f3a3a1ec 100644 --- a/src/modules/physics/box2d/ChainShape.cpp +++ b/src/modules/physics/box2d/ChainShape.cpp @@ -34,10 +34,8 @@ namespace physics namespace box2d { ChainShape::ChainShape(b2ChainShape * c, bool loop) - : loop(loop) + : Shape(c), loop(loop) { - shape = c; - Memoizer::add(shape, this); } ChainShape::~ChainShape() diff --git a/src/modules/physics/box2d/CircleShape.cpp b/src/modules/physics/box2d/CircleShape.cpp index 752f2f94d..a9123a3b9 100644 --- a/src/modules/physics/box2d/CircleShape.cpp +++ b/src/modules/physics/box2d/CircleShape.cpp @@ -33,9 +33,8 @@ namespace physics namespace box2d { CircleShape::CircleShape(b2CircleShape * c) + : Shape(c) { - shape = c; - Memoizer::add(shape, this); } CircleShape::~CircleShape() diff --git a/src/modules/physics/box2d/EdgeShape.cpp b/src/modules/physics/box2d/EdgeShape.cpp index 1e90db188..1416419b1 100644 --- a/src/modules/physics/box2d/EdgeShape.cpp +++ b/src/modules/physics/box2d/EdgeShape.cpp @@ -33,9 +33,8 @@ namespace physics namespace box2d { EdgeShape::EdgeShape(b2EdgeShape * e) + : Shape(e) { - shape = e; - Memoizer::add(shape, this); } EdgeShape::~EdgeShape() diff --git a/src/modules/physics/box2d/PolygonShape.cpp b/src/modules/physics/box2d/PolygonShape.cpp index 62c1a80d2..c77e0106b 100644 --- a/src/modules/physics/box2d/PolygonShape.cpp +++ b/src/modules/physics/box2d/PolygonShape.cpp @@ -34,9 +34,8 @@ namespace physics namespace box2d { PolygonShape::PolygonShape(b2PolygonShape * p) + : Shape(p) { - shape = p; - Memoizer::add(shape, this); } PolygonShape::~PolygonShape() From 7e039dd1efca02868bfc95f786cb3d3d6f856d17 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 13:45:24 -0400 Subject: [PATCH 44/78] Add ContactFilter callback to World --HG-- branch : box2d-update --- src/modules/physics/box2d/World.cpp | 49 ++++++++++++++++++++++++ src/modules/physics/box2d/World.h | 26 ++++++++++++- src/modules/physics/box2d/wrap_World.cpp | 16 ++++++++ src/modules/physics/box2d/wrap_World.h | 2 + 4 files changed, 92 insertions(+), 1 deletion(-) diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index d7423e9f9..dc368517f 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -117,6 +117,31 @@ namespace box2d } } + + World::ContactFilter::ContactFilter() + : ref(0) + { + } + + World::ContactFilter::~ContactFilter() + { + if(ref != 0) + delete ref; + } + + bool World::ContactFilter::process(Fixture * a, Fixture * b) + { + if (ref != 0) + { + lua_State * L = ref->getL(); + ref->push(); + luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)a); + luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)b); + lua_call(L, 2, 1); + return luax_toboolean(L, -1); + } + return true; + } World::World() : world(NULL) @@ -178,6 +203,16 @@ namespace box2d { postsolve.add(contact, impulse); } + + bool World::ShouldCollide(b2Fixture * fixtureA, b2Fixture * fixtureB) + { + // Fixtures should be memoized, if we created them + Fixture * a = (Fixture *)Memoizer::find(fixtureA); + if (!a) throw love::Exception("A fixture has escaped Memoizer!"); + Fixture * b = (Fixture *)Memoizer::find(fixtureB); + if (!b) throw love::Exception("A fixture has escaped Memoizer!"); + return filter.process(a, b); + } int World::setCallbacks(lua_State * L) { @@ -211,6 +246,20 @@ namespace box2d postsolve.ref ? postsolve.ref->push() : lua_pushnil(L); return lua_gettop(L); } + + int World::setContactFilter(lua_State * L) + { + luax_assert_argc(L, 1); + if (filter.ref) delete filter.ref; + filter.ref = luax_refif(L, LUA_TFUNCTION); + return 0; + } + + int World::getContactFilter(lua_State * L) + { + filter.ref ? filter.ref->push() : lua_pushnil(L); + return lua_gettop(L); + } void World::setGravity(float x, float y) { diff --git a/src/modules/physics/box2d/World.h b/src/modules/physics/box2d/World.h index b76eee41c..1798372af 100644 --- a/src/modules/physics/box2d/World.h +++ b/src/modules/physics/box2d/World.h @@ -40,6 +40,7 @@ namespace box2d { class Contact; + class Fixture; /** * The World is the "God" container class, @@ -52,7 +53,7 @@ namespace box2d * The world also controls global parameters, like * gravity. **/ - class World : public Object, public b2ContactListener + class World : public Object, public b2ContactListener, public b2ContactFilter { // Friends. friend class Joint; @@ -76,6 +77,15 @@ namespace box2d void add(b2Contact* contact, const b2ContactImpulse* impulse); void process(); }; + + class ContactFilter + { + public: + Reference * ref; + ContactFilter(); + ~ContactFilter(); + bool process(Fixture * a, Fixture * b); + }; private: @@ -87,6 +97,7 @@ namespace box2d // Contact callbacks. ContactCallback begin, end, presolve, postsolve; + ContactFilter filter; public: @@ -119,6 +130,9 @@ namespace box2d void EndContact(b2Contact* contact); void PreSolve(b2Contact* contact, const b2Manifold* oldManifold); void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse); + + // From b2ContactFilter + bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB); /** * Receives up to four Lua functions as arguments. Each function is @@ -132,6 +146,16 @@ namespace box2d * Returns the functions previously set by setCallbacks. **/ int getCallbacks(lua_State * L); + + /** + * Sets the ContactFilter callback. + **/ + int setContactFilter(lua_State * L); + + /** + * Gets the ContactFilter callback. + **/ + int getContactFilter(lua_State * L); /** * Sets the current gravity of the World. diff --git a/src/modules/physics/box2d/wrap_World.cpp b/src/modules/physics/box2d/wrap_World.cpp index 4e8f14dc9..febfcfcb4 100644 --- a/src/modules/physics/box2d/wrap_World.cpp +++ b/src/modules/physics/box2d/wrap_World.cpp @@ -53,6 +53,20 @@ namespace box2d lua_remove(L, 1); return t->getCallbacks(L); } + + int w_World_setContactFilter(lua_State * L) + { + World * t = luax_checkworld(L, 1); + lua_remove(L, 1); + return t->setContactFilter(L); + } + + int w_World_getContactFilter(lua_State * L) + { + World * t = luax_checkworld(L, 1); + lua_remove(L, 1); + return t->getContactFilter(L); + } int w_World_setGravity(lua_State * L) { @@ -103,6 +117,8 @@ namespace box2d { "update", w_World_update }, { "setCallbacks", w_World_setCallbacks }, { "getCallbacks", w_World_getCallbacks }, + { "setContactFilter", w_World_setContactFilter }, + { "getContactFilter", w_World_getContactFilter }, { "setGravity", w_World_setGravity }, { "getGravity", w_World_getGravity }, { "setAllowSleeping", w_World_setAllowSleeping }, diff --git a/src/modules/physics/box2d/wrap_World.h b/src/modules/physics/box2d/wrap_World.h index 7f99a7449..372928c22 100644 --- a/src/modules/physics/box2d/wrap_World.h +++ b/src/modules/physics/box2d/wrap_World.h @@ -35,6 +35,8 @@ namespace box2d int w_World_update(lua_State * L); int w_World_setCallbacks(lua_State * L); int w_World_getCallbacks(lua_State * L); + int w_World_setContactFilter(lua_State * L); + int w_World_getContactFilter(lua_State * L); int w_World_setGravity(lua_State * L); int w_World_getGravity(lua_State * L); int w_World_setAllowSleeping(lua_State * L); From c233ab3d50f9761cac61cfcfd4602bc1efef0085 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 13:45:40 -0400 Subject: [PATCH 45/78] isSleepingAllowde -> isSleepingAllowed --HG-- branch : box2d-update --- src/modules/physics/box2d/wrap_Body.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/modules/physics/box2d/wrap_Body.cpp b/src/modules/physics/box2d/wrap_Body.cpp index 110dfacd3..909f5e429 100644 --- a/src/modules/physics/box2d/wrap_Body.cpp +++ b/src/modules/physics/box2d/wrap_Body.cpp @@ -556,7 +556,7 @@ namespace box2d { "isActive", w_Body_isActive }, { "isAwake", w_Body_isAwake }, { "setSleepingAllowed", w_Body_setSleepingAllowed }, - { "isSleepingAllowde", w_Body_isSleepingAllowed }, + { "isSleepingAllowed", w_Body_isSleepingAllowed }, { "setActive", w_Body_setActive }, { "setAwake", w_Body_setAwake }, { "setFixedRotation", w_Body_setFixedRotation }, From 055238659b42e8b6b29d71aea2b46de2dba24ce8 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 13:51:11 -0400 Subject: [PATCH 46/78] Change Contact callbacks to pass the actual Fixtures instead of just the userdata --HG-- branch : box2d-update --- src/modules/physics/box2d/World.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index dc368517f..110a1b80a 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -76,22 +76,22 @@ namespace box2d // Push the function. ref->push(); - // Push first userdata. + // Push first fixture. { - fixtureudata * d = (fixtureudata *)(contacts[i]->contact->GetFixtureA()->GetUserData()); - if(d->ref != 0) - d->ref->push(); + Fixture * a = (Fixture *)Memoizer::find(contacts[i]->contact->GetFixtureA()); + if(a != 0) + luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)a); else - lua_pushnil(L); + throw love::Exception("A fixture has escaped Memoizer!"); } // Push second userdata. { - fixtureudata * d = (fixtureudata *)(contacts[i]->contact->GetFixtureB()->GetUserData()); - if(d->ref != 0) - d->ref->push(); + Fixture * b = (Fixture *)Memoizer::find(contacts[i]->contact->GetFixtureB()); + if(b != 0) + luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)b); else - lua_pushnil(L); + throw love::Exception("A fixture has escaped Memoizer!"); } luax_newtype(L, "Contact", (PHYSICS_CONTACT_T), (void*)contacts[i], false); From 8ae43be1feac2014a06975e2a15df22a518d9055 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 14:54:06 -0400 Subject: [PATCH 47/78] Fix Fixture memory management issues --HG-- branch : box2d-update --- src/modules/physics/box2d/Fixture.cpp | 14 ++++++-------- src/modules/physics/box2d/Fixture.h | 1 - 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/modules/physics/box2d/Fixture.cpp b/src/modules/physics/box2d/Fixture.cpp index 01f704597..b07b98092 100644 --- a/src/modules/physics/box2d/Fixture.cpp +++ b/src/modules/physics/box2d/Fixture.cpp @@ -47,7 +47,6 @@ namespace box2d def.userData = (void *)data; def.density = density; fixture = body->body->CreateFixture(&def); - shape = new Shape(fixture->GetShape()); Memoizer::add(fixture, this); } @@ -57,10 +56,7 @@ namespace box2d data = (fixtureudata *)f->GetUserData(); body = (Body *)Memoizer::find(f->GetBody()); if (!body) body = new Body(f->GetBody()); - body->retain(); - shape = (Shape *)Memoizer::find(f->GetShape()); - if (!shape) shape = new Shape(f->GetShape()); - else shape->retain(); + else body->retain(); Memoizer::add(fixture, this); } @@ -77,12 +73,11 @@ namespace box2d fixture = 0; body->release(); - shape->release(); } Shape::Type Fixture::getType() const { - return shape->getType(); + return Shape(fixture->GetShape()).getType(); } void Fixture::setFriction(float friction) @@ -132,7 +127,10 @@ namespace box2d Shape * Fixture::getShape() const { - return shape; + if (!fixture->GetShape()) return NULL; + Shape * s = (Shape *)Memoizer::find(fixture->GetShape()); + if (!s) s = new Shape(fixture->GetShape()); + return s; } Fixture * Fixture::getNext() const diff --git a/src/modules/physics/box2d/Fixture.h b/src/modules/physics/box2d/Fixture.h index 574d17b24..69734d770 100644 --- a/src/modules/physics/box2d/Fixture.h +++ b/src/modules/physics/box2d/Fixture.h @@ -60,7 +60,6 @@ namespace box2d protected: Body * body; - Shape * shape; b2Fixture * fixture; fixtureudata * data; From e984bc084d2defb56a553e5f207f01540c878e3a Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 15:34:28 -0400 Subject: [PATCH 48/78] Move Box2D from modules/physics/box2d to libraries --HG-- branch : box2d-update --- .../macosx/love.xcodeproj/project.pbxproj | 620 +++++++++--------- .../physics/box2d => libraries}/Box2D/Box2D.h | 0 .../Box2D/Collision/Shapes/b2ChainShape.cpp | 0 .../Box2D/Collision/Shapes/b2ChainShape.h | 0 .../Box2D/Collision/Shapes/b2CircleShape.cpp | 0 .../Box2D/Collision/Shapes/b2CircleShape.h | 0 .../Box2D/Collision/Shapes/b2EdgeShape.cpp | 0 .../Box2D/Collision/Shapes/b2EdgeShape.h | 0 .../Box2D/Collision/Shapes/b2PolygonShape.cpp | 0 .../Box2D/Collision/Shapes/b2PolygonShape.h | 0 .../Box2D/Collision/Shapes/b2Shape.h | 0 .../Box2D/Collision/b2BroadPhase.cpp | 0 .../Box2D/Collision/b2BroadPhase.h | 0 .../Box2D/Collision/b2CollideCircle.cpp | 0 .../Box2D/Collision/b2CollideEdge.cpp | 0 .../Box2D/Collision/b2CollidePolygon.cpp | 0 .../Box2D/Collision/b2Collision.cpp | 0 .../Box2D/Collision/b2Collision.h | 0 .../Box2D/Collision/b2Distance.cpp | 0 .../Box2D/Collision/b2Distance.h | 0 .../Box2D/Collision/b2DynamicTree.cpp | 0 .../Box2D/Collision/b2DynamicTree.h | 0 .../Box2D/Collision/b2TimeOfImpact.cpp | 0 .../Box2D/Collision/b2TimeOfImpact.h | 0 .../Box2D/Common/b2BlockAllocator.cpp | 0 .../Box2D/Common/b2BlockAllocator.h | 0 .../Box2D/Common/b2Draw.cpp | 0 .../box2d => libraries}/Box2D/Common/b2Draw.h | 0 .../Box2D/Common/b2GrowableStack.h | 0 .../Box2D/Common/b2Math.cpp | 0 .../box2d => libraries}/Box2D/Common/b2Math.h | 0 .../Box2D/Common/b2Settings.cpp | 0 .../Box2D/Common/b2Settings.h | 0 .../Box2D/Common/b2StackAllocator.cpp | 0 .../Box2D/Common/b2StackAllocator.h | 0 .../Box2D/Common/b2Timer.cpp | 0 .../Box2D/Common/b2Timer.h | 0 .../Contacts/b2ChainAndCircleContact.cpp | 0 .../Contacts/b2ChainAndCircleContact.h | 0 .../Contacts/b2ChainAndPolygonContact.cpp | 0 .../Contacts/b2ChainAndPolygonContact.h | 0 .../Dynamics/Contacts/b2CircleContact.cpp | 0 .../Box2D/Dynamics/Contacts/b2CircleContact.h | 0 .../Box2D/Dynamics/Contacts/b2Contact.cpp | 0 .../Box2D/Dynamics/Contacts/b2Contact.h | 0 .../Dynamics/Contacts/b2ContactSolver.cpp | 0 .../Box2D/Dynamics/Contacts/b2ContactSolver.h | 0 .../Contacts/b2EdgeAndCircleContact.cpp | 0 .../Contacts/b2EdgeAndCircleContact.h | 0 .../Contacts/b2EdgeAndPolygonContact.cpp | 0 .../Contacts/b2EdgeAndPolygonContact.h | 0 .../Contacts/b2PolygonAndCircleContact.cpp | 0 .../Contacts/b2PolygonAndCircleContact.h | 0 .../Dynamics/Contacts/b2PolygonContact.cpp | 0 .../Dynamics/Contacts/b2PolygonContact.h | 0 .../Box2D/Dynamics/Joints/b2DistanceJoint.cpp | 0 .../Box2D/Dynamics/Joints/b2DistanceJoint.h | 0 .../Box2D/Dynamics/Joints/b2FrictionJoint.cpp | 0 .../Box2D/Dynamics/Joints/b2FrictionJoint.h | 0 .../Box2D/Dynamics/Joints/b2GearJoint.cpp | 0 .../Box2D/Dynamics/Joints/b2GearJoint.h | 0 .../Box2D/Dynamics/Joints/b2Joint.cpp | 0 .../Box2D/Dynamics/Joints/b2Joint.h | 0 .../Box2D/Dynamics/Joints/b2MouseJoint.cpp | 0 .../Box2D/Dynamics/Joints/b2MouseJoint.h | 0 .../Dynamics/Joints/b2PrismaticJoint.cpp | 0 .../Box2D/Dynamics/Joints/b2PrismaticJoint.h | 0 .../Box2D/Dynamics/Joints/b2PulleyJoint.cpp | 0 .../Box2D/Dynamics/Joints/b2PulleyJoint.h | 0 .../Box2D/Dynamics/Joints/b2RevoluteJoint.cpp | 0 .../Box2D/Dynamics/Joints/b2RevoluteJoint.h | 0 .../Box2D/Dynamics/Joints/b2RopeJoint.cpp | 0 .../Box2D/Dynamics/Joints/b2RopeJoint.h | 0 .../Box2D/Dynamics/Joints/b2WeldJoint.cpp | 0 .../Box2D/Dynamics/Joints/b2WeldJoint.h | 0 .../Box2D/Dynamics/Joints/b2WheelJoint.cpp | 0 .../Box2D/Dynamics/Joints/b2WheelJoint.h | 0 .../Box2D/Dynamics/b2Body.cpp | 0 .../Box2D/Dynamics/b2Body.h | 0 .../Box2D/Dynamics/b2ContactManager.cpp | 0 .../Box2D/Dynamics/b2ContactManager.h | 0 .../Box2D/Dynamics/b2Fixture.cpp | 0 .../Box2D/Dynamics/b2Fixture.h | 0 .../Box2D/Dynamics/b2Island.cpp | 0 .../Box2D/Dynamics/b2Island.h | 0 .../Box2D/Dynamics/b2TimeStep.h | 0 .../Box2D/Dynamics/b2World.cpp | 0 .../Box2D/Dynamics/b2World.h | 0 .../Box2D/Dynamics/b2WorldCallbacks.cpp | 0 .../Box2D/Dynamics/b2WorldCallbacks.h | 0 .../box2d => libraries}/Box2D/Rope/b2Rope.cpp | 0 .../box2d => libraries}/Box2D/Rope/b2Rope.h | 0 92 files changed, 306 insertions(+), 314 deletions(-) rename src/{modules/physics/box2d => libraries}/Box2D/Box2D.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/Shapes/b2ChainShape.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/Shapes/b2ChainShape.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/Shapes/b2CircleShape.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/Shapes/b2CircleShape.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/Shapes/b2EdgeShape.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/Shapes/b2EdgeShape.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/Shapes/b2PolygonShape.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/Shapes/b2PolygonShape.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/Shapes/b2Shape.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/b2BroadPhase.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/b2BroadPhase.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/b2CollideCircle.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/b2CollideEdge.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/b2CollidePolygon.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/b2Collision.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/b2Collision.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/b2Distance.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/b2Distance.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/b2DynamicTree.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/b2DynamicTree.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/b2TimeOfImpact.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Collision/b2TimeOfImpact.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Common/b2BlockAllocator.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Common/b2BlockAllocator.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Common/b2Draw.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Common/b2Draw.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Common/b2GrowableStack.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Common/b2Math.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Common/b2Math.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Common/b2Settings.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Common/b2Settings.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Common/b2StackAllocator.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Common/b2StackAllocator.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Common/b2Timer.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Common/b2Timer.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2CircleContact.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2CircleContact.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2Contact.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2Contact.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2ContactSolver.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2ContactSolver.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2PolygonContact.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Contacts/b2PolygonContact.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2DistanceJoint.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2DistanceJoint.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2FrictionJoint.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2FrictionJoint.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2GearJoint.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2GearJoint.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2Joint.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2Joint.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2MouseJoint.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2MouseJoint.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2PrismaticJoint.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2PulleyJoint.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2PulleyJoint.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2RevoluteJoint.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2RopeJoint.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2RopeJoint.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2WeldJoint.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2WeldJoint.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2WheelJoint.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/Joints/b2WheelJoint.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/b2Body.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/b2Body.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/b2ContactManager.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/b2ContactManager.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/b2Fixture.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/b2Fixture.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/b2Island.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/b2Island.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/b2TimeStep.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/b2World.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/b2World.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/b2WorldCallbacks.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Dynamics/b2WorldCallbacks.h (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Rope/b2Rope.cpp (100%) rename src/{modules/physics/box2d => libraries}/Box2D/Rope/b2Rope.h (100%) diff --git a/platform/macosx/love.xcodeproj/project.pbxproj b/platform/macosx/love.xcodeproj/project.pbxproj index 543bcfdca..f01fe2b23 100644 --- a/platform/macosx/love.xcodeproj/project.pbxproj +++ b/platform/macosx/love.xcodeproj/project.pbxproj @@ -148,18 +148,6 @@ A968F0D91083A9FC00A895AA /* Mouse.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0D81083A9FC00A895AA /* Mouse.cpp */; }; A968F0DD1083AA6600A895AA /* Shape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0DB1083AA6600A895AA /* Shape.cpp */; }; A968F0DE1083AA6600A895AA /* Joint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A968F0DC1083AA6600A895AA /* Joint.cpp */; }; - A96F416014127E340067FE9A /* b2RopeJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F415C14127E310067FE9A /* b2RopeJoint.cpp */; }; - A96F416114127E340067FE9A /* b2WheelJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F415E14127E320067FE9A /* b2WheelJoint.cpp */; }; - A96F416514127E720067FE9A /* b2Rope.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F416314127E720067FE9A /* b2Rope.cpp */; }; - A96F416B14127E9C0067FE9A /* b2Draw.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F416614127E9C0067FE9A /* b2Draw.cpp */; }; - A96F416C14127E9C0067FE9A /* b2Timer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F416914127E9C0067FE9A /* b2Timer.cpp */; }; - A96F416E14127EB20067FE9A /* b2CollideEdge.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F416D14127EB20067FE9A /* b2CollideEdge.cpp */; }; - A96F417114127EC00067FE9A /* b2ChainShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F416F14127EC00067FE9A /* b2ChainShape.cpp */; }; - A96F417614127EE70067FE9A /* b2ChainAndCircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F417214127EE70067FE9A /* b2ChainAndCircleContact.cpp */; }; - A96F417714127EE70067FE9A /* b2ChainAndPolygonContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F417414127EE70067FE9A /* b2ChainAndPolygonContact.cpp */; }; - A96F417C14127EFD0067FE9A /* b2EdgeAndCircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F417814127EFD0067FE9A /* b2EdgeAndCircleContact.cpp */; }; - A96F417D14127EFD0067FE9A /* b2EdgeAndPolygonContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F417A14127EFD0067FE9A /* b2EdgeAndPolygonContact.cpp */; }; - A96F418014127FC20067FE9A /* b2EdgeShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F417E14127FC20067FE9A /* b2EdgeShape.cpp */; }; A96F41831412AFE20067FE9A /* wrap_WeldJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F41811412AFB70067FE9A /* wrap_WeldJoint.cpp */; }; A96F41861412AFF80067FE9A /* WeldJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F41841412AFEB0067FE9A /* WeldJoint.cpp */; }; A96F41891412B36D0067FE9A /* wrap_WheelJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F41871412B35B0067FE9A /* wrap_WheelJoint.cpp */; }; @@ -168,39 +156,6 @@ A96F41A71412C92B0067FE9A /* wrap_EdgeShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A96F41A51412C92B0067FE9A /* wrap_EdgeShape.cpp */; }; A986DEB5113249A800810279 /* Thread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986DEB1113249A800810279 /* Thread.cpp */; }; A986DEB6113249A800810279 /* wrap_Thread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986DEB3113249A800810279 /* wrap_Thread.cpp */; }; - A986EC64132CE6DB00F048C8 /* b2BroadPhase.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBC8132CE6D800F048C8 /* b2BroadPhase.cpp */; }; - A986EC65132CE6DB00F048C8 /* b2CollideCircle.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBCA132CE6D800F048C8 /* b2CollideCircle.cpp */; }; - A986EC66132CE6DB00F048C8 /* b2CollidePolygon.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBCB132CE6D800F048C8 /* b2CollidePolygon.cpp */; }; - A986EC67132CE6DB00F048C8 /* b2Collision.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBCC132CE6D800F048C8 /* b2Collision.cpp */; }; - A986EC68132CE6DB00F048C8 /* b2Distance.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBCE132CE6D800F048C8 /* b2Distance.cpp */; }; - A986EC69132CE6DB00F048C8 /* b2DynamicTree.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBD0132CE6D800F048C8 /* b2DynamicTree.cpp */; }; - A986EC6A132CE6DB00F048C8 /* b2TimeOfImpact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBD2132CE6D800F048C8 /* b2TimeOfImpact.cpp */; }; - A986EC6B132CE6DB00F048C8 /* b2CircleShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBD5132CE6D800F048C8 /* b2CircleShape.cpp */; }; - A986EC6C132CE6DB00F048C8 /* b2PolygonShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBD7132CE6D800F048C8 /* b2PolygonShape.cpp */; }; - A986EC6D132CE6DB00F048C8 /* b2BlockAllocator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBDB132CE6D800F048C8 /* b2BlockAllocator.cpp */; }; - A986EC6E132CE6DB00F048C8 /* b2Math.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBDD132CE6D800F048C8 /* b2Math.cpp */; }; - A986EC6F132CE6DB00F048C8 /* b2Settings.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBDF132CE6D800F048C8 /* b2Settings.cpp */; }; - A986EC70132CE6DB00F048C8 /* b2StackAllocator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBE1132CE6D800F048C8 /* b2StackAllocator.cpp */; }; - A986EC71132CE6DB00F048C8 /* b2Body.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBE4132CE6D800F048C8 /* b2Body.cpp */; }; - A986EC72132CE6DB00F048C8 /* b2ContactManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBE6132CE6D800F048C8 /* b2ContactManager.cpp */; }; - A986EC73132CE6DB00F048C8 /* b2Fixture.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBE8132CE6D800F048C8 /* b2Fixture.cpp */; }; - A986EC74132CE6DB00F048C8 /* b2Island.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBEA132CE6D800F048C8 /* b2Island.cpp */; }; - A986EC75132CE6DB00F048C8 /* b2World.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBED132CE6D800F048C8 /* b2World.cpp */; }; - A986EC76132CE6DB00F048C8 /* b2WorldCallbacks.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBEF132CE6D800F048C8 /* b2WorldCallbacks.cpp */; }; - A986EC77132CE6DB00F048C8 /* b2CircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBF2132CE6D800F048C8 /* b2CircleContact.cpp */; }; - A986EC78132CE6DB00F048C8 /* b2Contact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBF4132CE6D800F048C8 /* b2Contact.cpp */; }; - A986EC79132CE6DB00F048C8 /* b2ContactSolver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBF6132CE6D800F048C8 /* b2ContactSolver.cpp */; }; - A986EC7A132CE6DB00F048C8 /* b2PolygonAndCircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBF8132CE6D800F048C8 /* b2PolygonAndCircleContact.cpp */; }; - A986EC7B132CE6DB00F048C8 /* b2PolygonContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBFA132CE6D800F048C8 /* b2PolygonContact.cpp */; }; - A986EC7D132CE6DB00F048C8 /* b2DistanceJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EBFF132CE6D800F048C8 /* b2DistanceJoint.cpp */; }; - A986EC7E132CE6DB00F048C8 /* b2FrictionJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC01132CE6D800F048C8 /* b2FrictionJoint.cpp */; }; - A986EC7F132CE6DB00F048C8 /* b2GearJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC03132CE6D800F048C8 /* b2GearJoint.cpp */; }; - A986EC80132CE6DB00F048C8 /* b2Joint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC05132CE6D800F048C8 /* b2Joint.cpp */; }; - A986EC82132CE6DB00F048C8 /* b2MouseJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC09132CE6D800F048C8 /* b2MouseJoint.cpp */; }; - A986EC83132CE6DB00F048C8 /* b2PrismaticJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC0B132CE6D800F048C8 /* b2PrismaticJoint.cpp */; }; - A986EC84132CE6DB00F048C8 /* b2PulleyJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC0D132CE6D800F048C8 /* b2PulleyJoint.cpp */; }; - A986EC85132CE6DB00F048C8 /* b2RevoluteJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC0F132CE6D800F048C8 /* b2RevoluteJoint.cpp */; }; - A986EC86132CE6DB00F048C8 /* b2WeldJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986EC11132CE6D800F048C8 /* b2WeldJoint.cpp */; }; A986ECAF132CEBB000F048C8 /* Fixture.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A986ECAD132CEB9300F048C8 /* Fixture.cpp */; }; A98D914410507C97008E03F2 /* EncodedImageData.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A98D914310507C97008E03F2 /* EncodedImageData.cpp */; }; A9B4BA9C1045937F001DBC80 /* ParticleSystem.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9B4BA9A1045937F001DBC80 /* ParticleSystem.cpp */; }; @@ -217,6 +172,52 @@ A9D307EA106635C3004FEDF8 /* physfs.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9D307E9106635C3004FEDF8 /* physfs.framework */; }; A9D307F2106635D3004FEDF8 /* physfs.framework in Copy Frameworks */ = {isa = PBXBuildFile; fileRef = A9D307E9106635C3004FEDF8 /* physfs.framework */; }; A9D5C47D142E32EE0044ECF7 /* Memoizer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C47C142E32ED0044ECF7 /* Memoizer.cpp */; }; + A9D5C4E8142E5F7F0044ECF7 /* b2BroadPhase.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C487142E5F7F0044ECF7 /* b2BroadPhase.cpp */; }; + A9D5C4E9142E5F7F0044ECF7 /* b2CollideCircle.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C489142E5F7F0044ECF7 /* b2CollideCircle.cpp */; }; + A9D5C4EA142E5F7F0044ECF7 /* b2CollideEdge.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C48A142E5F7F0044ECF7 /* b2CollideEdge.cpp */; }; + A9D5C4EB142E5F7F0044ECF7 /* b2CollidePolygon.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C48B142E5F7F0044ECF7 /* b2CollidePolygon.cpp */; }; + A9D5C4EC142E5F7F0044ECF7 /* b2Collision.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C48C142E5F7F0044ECF7 /* b2Collision.cpp */; }; + A9D5C4ED142E5F7F0044ECF7 /* b2Distance.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C48E142E5F7F0044ECF7 /* b2Distance.cpp */; }; + A9D5C4EE142E5F7F0044ECF7 /* b2DynamicTree.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C490142E5F7F0044ECF7 /* b2DynamicTree.cpp */; }; + A9D5C4EF142E5F7F0044ECF7 /* b2TimeOfImpact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C492142E5F7F0044ECF7 /* b2TimeOfImpact.cpp */; }; + A9D5C4F0142E5F7F0044ECF7 /* b2ChainShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C495142E5F7F0044ECF7 /* b2ChainShape.cpp */; }; + A9D5C4F1142E5F7F0044ECF7 /* b2CircleShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C497142E5F7F0044ECF7 /* b2CircleShape.cpp */; }; + A9D5C4F2142E5F7F0044ECF7 /* b2EdgeShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C499142E5F7F0044ECF7 /* b2EdgeShape.cpp */; }; + A9D5C4F3142E5F7F0044ECF7 /* b2PolygonShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C49B142E5F7F0044ECF7 /* b2PolygonShape.cpp */; }; + A9D5C4F4142E5F7F0044ECF7 /* b2PolygonShape.cpp.orig in Resources */ = {isa = PBXBuildFile; fileRef = A9D5C49C142E5F7F0044ECF7 /* b2PolygonShape.cpp.orig */; }; + A9D5C4F5142E5F7F0044ECF7 /* b2BlockAllocator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4A0142E5F7F0044ECF7 /* b2BlockAllocator.cpp */; }; + A9D5C4F6142E5F7F0044ECF7 /* b2Draw.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4A2142E5F7F0044ECF7 /* b2Draw.cpp */; }; + A9D5C4F7142E5F7F0044ECF7 /* b2Math.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4A5142E5F7F0044ECF7 /* b2Math.cpp */; }; + A9D5C4F8142E5F7F0044ECF7 /* b2Settings.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4A7142E5F7F0044ECF7 /* b2Settings.cpp */; }; + A9D5C4F9142E5F7F0044ECF7 /* b2StackAllocator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4A9142E5F7F0044ECF7 /* b2StackAllocator.cpp */; }; + A9D5C4FA142E5F7F0044ECF7 /* b2Timer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4AB142E5F7F0044ECF7 /* b2Timer.cpp */; }; + A9D5C4FB142E5F7F0044ECF7 /* b2Body.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4AE142E5F7F0044ECF7 /* b2Body.cpp */; }; + A9D5C4FC142E5F7F0044ECF7 /* b2ContactManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4B0142E5F7F0044ECF7 /* b2ContactManager.cpp */; }; + A9D5C4FD142E5F7F0044ECF7 /* b2Fixture.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4B2142E5F7F0044ECF7 /* b2Fixture.cpp */; }; + A9D5C4FE142E5F7F0044ECF7 /* b2Island.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4B4142E5F7F0044ECF7 /* b2Island.cpp */; }; + A9D5C4FF142E5F7F0044ECF7 /* b2World.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4B7142E5F7F0044ECF7 /* b2World.cpp */; }; + A9D5C500142E5F7F0044ECF7 /* b2WorldCallbacks.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4B9142E5F7F0044ECF7 /* b2WorldCallbacks.cpp */; }; + A9D5C501142E5F7F0044ECF7 /* b2ChainAndCircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4BC142E5F7F0044ECF7 /* b2ChainAndCircleContact.cpp */; }; + A9D5C502142E5F7F0044ECF7 /* b2ChainAndPolygonContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4BE142E5F7F0044ECF7 /* b2ChainAndPolygonContact.cpp */; }; + A9D5C503142E5F7F0044ECF7 /* b2CircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4C0142E5F7F0044ECF7 /* b2CircleContact.cpp */; }; + A9D5C504142E5F7F0044ECF7 /* b2Contact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4C2142E5F7F0044ECF7 /* b2Contact.cpp */; }; + A9D5C505142E5F7F0044ECF7 /* b2ContactSolver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4C4142E5F7F0044ECF7 /* b2ContactSolver.cpp */; }; + A9D5C506142E5F7F0044ECF7 /* b2EdgeAndCircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4C6142E5F7F0044ECF7 /* b2EdgeAndCircleContact.cpp */; }; + A9D5C507142E5F7F0044ECF7 /* b2EdgeAndPolygonContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4C8142E5F7F0044ECF7 /* b2EdgeAndPolygonContact.cpp */; }; + A9D5C508142E5F7F0044ECF7 /* b2PolygonAndCircleContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4CA142E5F7F0044ECF7 /* b2PolygonAndCircleContact.cpp */; }; + A9D5C509142E5F7F0044ECF7 /* b2PolygonContact.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4CC142E5F7F0044ECF7 /* b2PolygonContact.cpp */; }; + A9D5C50A142E5F7F0044ECF7 /* b2DistanceJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4CF142E5F7F0044ECF7 /* b2DistanceJoint.cpp */; }; + A9D5C50B142E5F7F0044ECF7 /* b2FrictionJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4D1142E5F7F0044ECF7 /* b2FrictionJoint.cpp */; }; + A9D5C50C142E5F7F0044ECF7 /* b2GearJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4D3142E5F7F0044ECF7 /* b2GearJoint.cpp */; }; + A9D5C50D142E5F7F0044ECF7 /* b2Joint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4D5142E5F7F0044ECF7 /* b2Joint.cpp */; }; + A9D5C50E142E5F7F0044ECF7 /* b2MouseJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4D7142E5F7F0044ECF7 /* b2MouseJoint.cpp */; }; + A9D5C50F142E5F7F0044ECF7 /* b2PrismaticJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4D9142E5F7F0044ECF7 /* b2PrismaticJoint.cpp */; }; + A9D5C510142E5F7F0044ECF7 /* b2PulleyJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4DB142E5F7F0044ECF7 /* b2PulleyJoint.cpp */; }; + A9D5C511142E5F7F0044ECF7 /* b2RevoluteJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4DD142E5F7F0044ECF7 /* b2RevoluteJoint.cpp */; }; + A9D5C512142E5F7F0044ECF7 /* b2RopeJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4DF142E5F7F0044ECF7 /* b2RopeJoint.cpp */; }; + A9D5C513142E5F7F0044ECF7 /* b2WeldJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4E1142E5F7F0044ECF7 /* b2WeldJoint.cpp */; }; + A9D5C514142E5F7F0044ECF7 /* b2WheelJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4E3142E5F7F0044ECF7 /* b2WheelJoint.cpp */; }; + A9D5C515142E5F7F0044ECF7 /* b2Rope.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9D5C4E6142E5F7F0044ECF7 /* b2Rope.cpp */; }; A9DEC1C11046EFA70049C70C /* Love.icns in Resources */ = {isa = PBXBuildFile; fileRef = A9DEC1BF1046EFA60049C70C /* Love.icns */; }; A9DEC1C21046EFA70049C70C /* LoveDocument.icns in Resources */ = {isa = PBXBuildFile; fileRef = A9DEC1C01046EFA70049C70C /* LoveDocument.icns */; }; A9F16927109E7BAD00FC83D1 /* libmodplug.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9F16926109E7BAD00FC83D1 /* libmodplug.framework */; }; @@ -549,30 +550,6 @@ A968F0D81083A9FC00A895AA /* Mouse.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Mouse.cpp; sourceTree = ""; }; A968F0DB1083AA6600A895AA /* Shape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Shape.cpp; sourceTree = ""; }; A968F0DC1083AA6600A895AA /* Joint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Joint.cpp; sourceTree = ""; }; - A96F415C14127E310067FE9A /* b2RopeJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2RopeJoint.cpp; sourceTree = ""; }; - A96F415D14127E320067FE9A /* b2RopeJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2RopeJoint.h; sourceTree = ""; }; - A96F415E14127E320067FE9A /* b2WheelJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2WheelJoint.cpp; sourceTree = ""; }; - A96F415F14127E320067FE9A /* b2WheelJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2WheelJoint.h; sourceTree = ""; }; - A96F416314127E720067FE9A /* b2Rope.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Rope.cpp; sourceTree = ""; }; - A96F416414127E720067FE9A /* b2Rope.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Rope.h; sourceTree = ""; }; - A96F416614127E9C0067FE9A /* b2Draw.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Draw.cpp; sourceTree = ""; }; - A96F416714127E9C0067FE9A /* b2Draw.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Draw.h; sourceTree = ""; }; - A96F416814127E9C0067FE9A /* b2GrowableStack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2GrowableStack.h; sourceTree = ""; }; - A96F416914127E9C0067FE9A /* b2Timer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Timer.cpp; sourceTree = ""; }; - A96F416A14127E9C0067FE9A /* b2Timer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Timer.h; sourceTree = ""; }; - A96F416D14127EB20067FE9A /* b2CollideEdge.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CollideEdge.cpp; sourceTree = ""; }; - A96F416F14127EC00067FE9A /* b2ChainShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ChainShape.cpp; sourceTree = ""; }; - A96F417014127EC00067FE9A /* b2ChainShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ChainShape.h; sourceTree = ""; }; - A96F417214127EE70067FE9A /* b2ChainAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ChainAndCircleContact.cpp; sourceTree = ""; }; - A96F417314127EE70067FE9A /* b2ChainAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ChainAndCircleContact.h; sourceTree = ""; }; - A96F417414127EE70067FE9A /* b2ChainAndPolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ChainAndPolygonContact.cpp; sourceTree = ""; }; - A96F417514127EE70067FE9A /* b2ChainAndPolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ChainAndPolygonContact.h; sourceTree = ""; }; - A96F417814127EFD0067FE9A /* b2EdgeAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2EdgeAndCircleContact.cpp; sourceTree = ""; }; - A96F417914127EFD0067FE9A /* b2EdgeAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2EdgeAndCircleContact.h; sourceTree = ""; }; - A96F417A14127EFD0067FE9A /* b2EdgeAndPolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2EdgeAndPolygonContact.cpp; sourceTree = ""; }; - A96F417B14127EFD0067FE9A /* b2EdgeAndPolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2EdgeAndPolygonContact.h; sourceTree = ""; }; - A96F417E14127FC20067FE9A /* b2EdgeShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2EdgeShape.cpp; sourceTree = ""; }; - A96F417F14127FC20067FE9A /* b2EdgeShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2EdgeShape.h; sourceTree = ""; }; A96F41811412AFB70067FE9A /* wrap_WeldJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_WeldJoint.cpp; sourceTree = ""; }; A96F41821412AFC60067FE9A /* wrap_WeldJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_WeldJoint.h; sourceTree = ""; }; A96F41841412AFEB0067FE9A /* WeldJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WeldJoint.cpp; sourceTree = ""; }; @@ -590,73 +567,6 @@ A986DEB2113249A800810279 /* Thread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Thread.h; sourceTree = ""; }; A986DEB3113249A800810279 /* wrap_Thread.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wrap_Thread.cpp; sourceTree = ""; }; A986DEB4113249A800810279 /* wrap_Thread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wrap_Thread.h; sourceTree = ""; }; - A986EBC8132CE6D800F048C8 /* b2BroadPhase.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2BroadPhase.cpp; sourceTree = ""; }; - A986EBC9132CE6D800F048C8 /* b2BroadPhase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2BroadPhase.h; sourceTree = ""; }; - A986EBCA132CE6D800F048C8 /* b2CollideCircle.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CollideCircle.cpp; sourceTree = ""; }; - A986EBCB132CE6D800F048C8 /* b2CollidePolygon.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CollidePolygon.cpp; sourceTree = ""; }; - A986EBCC132CE6D800F048C8 /* b2Collision.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Collision.cpp; sourceTree = ""; }; - A986EBCD132CE6D800F048C8 /* b2Collision.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Collision.h; sourceTree = ""; }; - A986EBCE132CE6D800F048C8 /* b2Distance.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Distance.cpp; sourceTree = ""; }; - A986EBCF132CE6D800F048C8 /* b2Distance.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Distance.h; sourceTree = ""; }; - A986EBD0132CE6D800F048C8 /* b2DynamicTree.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2DynamicTree.cpp; sourceTree = ""; }; - A986EBD1132CE6D800F048C8 /* b2DynamicTree.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2DynamicTree.h; sourceTree = ""; }; - A986EBD2132CE6D800F048C8 /* b2TimeOfImpact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2TimeOfImpact.cpp; sourceTree = ""; }; - A986EBD3132CE6D800F048C8 /* b2TimeOfImpact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2TimeOfImpact.h; sourceTree = ""; }; - A986EBD5132CE6D800F048C8 /* b2CircleShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CircleShape.cpp; sourceTree = ""; }; - A986EBD6132CE6D800F048C8 /* b2CircleShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2CircleShape.h; sourceTree = ""; }; - A986EBD7132CE6D800F048C8 /* b2PolygonShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PolygonShape.cpp; sourceTree = ""; }; - A986EBD8132CE6D800F048C8 /* b2PolygonShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PolygonShape.h; sourceTree = ""; }; - A986EBD9132CE6D800F048C8 /* b2Shape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Shape.h; sourceTree = ""; }; - A986EBDB132CE6D800F048C8 /* b2BlockAllocator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2BlockAllocator.cpp; sourceTree = ""; }; - A986EBDC132CE6D800F048C8 /* b2BlockAllocator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2BlockAllocator.h; sourceTree = ""; }; - A986EBDD132CE6D800F048C8 /* b2Math.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Math.cpp; sourceTree = ""; }; - A986EBDE132CE6D800F048C8 /* b2Math.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Math.h; sourceTree = ""; }; - A986EBDF132CE6D800F048C8 /* b2Settings.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Settings.cpp; sourceTree = ""; }; - A986EBE0132CE6D800F048C8 /* b2Settings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Settings.h; sourceTree = ""; }; - A986EBE1132CE6D800F048C8 /* b2StackAllocator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2StackAllocator.cpp; sourceTree = ""; }; - A986EBE2132CE6D800F048C8 /* b2StackAllocator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2StackAllocator.h; sourceTree = ""; }; - A986EBE4132CE6D800F048C8 /* b2Body.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Body.cpp; sourceTree = ""; }; - A986EBE5132CE6D800F048C8 /* b2Body.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Body.h; sourceTree = ""; }; - A986EBE6132CE6D800F048C8 /* b2ContactManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ContactManager.cpp; sourceTree = ""; }; - A986EBE7132CE6D800F048C8 /* b2ContactManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ContactManager.h; sourceTree = ""; }; - A986EBE8132CE6D800F048C8 /* b2Fixture.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Fixture.cpp; sourceTree = ""; }; - A986EBE9132CE6D800F048C8 /* b2Fixture.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Fixture.h; sourceTree = ""; }; - A986EBEA132CE6D800F048C8 /* b2Island.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Island.cpp; sourceTree = ""; }; - A986EBEB132CE6D800F048C8 /* b2Island.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Island.h; sourceTree = ""; }; - A986EBEC132CE6D800F048C8 /* b2TimeStep.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2TimeStep.h; sourceTree = ""; }; - A986EBED132CE6D800F048C8 /* b2World.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2World.cpp; sourceTree = ""; }; - A986EBEE132CE6D800F048C8 /* b2World.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2World.h; sourceTree = ""; }; - A986EBEF132CE6D800F048C8 /* b2WorldCallbacks.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2WorldCallbacks.cpp; sourceTree = ""; }; - A986EBF0132CE6D800F048C8 /* b2WorldCallbacks.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2WorldCallbacks.h; sourceTree = ""; }; - A986EBF2132CE6D800F048C8 /* b2CircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CircleContact.cpp; sourceTree = ""; }; - A986EBF3132CE6D800F048C8 /* b2CircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2CircleContact.h; sourceTree = ""; }; - A986EBF4132CE6D800F048C8 /* b2Contact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Contact.cpp; sourceTree = ""; }; - A986EBF5132CE6D800F048C8 /* b2Contact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Contact.h; sourceTree = ""; }; - A986EBF6132CE6D800F048C8 /* b2ContactSolver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ContactSolver.cpp; sourceTree = ""; }; - A986EBF7132CE6D800F048C8 /* b2ContactSolver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ContactSolver.h; sourceTree = ""; }; - A986EBF8132CE6D800F048C8 /* b2PolygonAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PolygonAndCircleContact.cpp; sourceTree = ""; }; - A986EBF9132CE6D800F048C8 /* b2PolygonAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PolygonAndCircleContact.h; sourceTree = ""; }; - A986EBFA132CE6D800F048C8 /* b2PolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PolygonContact.cpp; sourceTree = ""; }; - A986EBFB132CE6D800F048C8 /* b2PolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PolygonContact.h; sourceTree = ""; }; - A986EBFF132CE6D800F048C8 /* b2DistanceJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2DistanceJoint.cpp; sourceTree = ""; }; - A986EC00132CE6D800F048C8 /* b2DistanceJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2DistanceJoint.h; sourceTree = ""; }; - A986EC01132CE6D800F048C8 /* b2FrictionJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2FrictionJoint.cpp; sourceTree = ""; }; - A986EC02132CE6D800F048C8 /* b2FrictionJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2FrictionJoint.h; sourceTree = ""; }; - A986EC03132CE6D800F048C8 /* b2GearJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2GearJoint.cpp; sourceTree = ""; }; - A986EC04132CE6D800F048C8 /* b2GearJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2GearJoint.h; sourceTree = ""; }; - A986EC05132CE6D800F048C8 /* b2Joint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Joint.cpp; sourceTree = ""; }; - A986EC06132CE6D800F048C8 /* b2Joint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Joint.h; sourceTree = ""; }; - A986EC09132CE6D800F048C8 /* b2MouseJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2MouseJoint.cpp; sourceTree = ""; }; - A986EC0A132CE6D800F048C8 /* b2MouseJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2MouseJoint.h; sourceTree = ""; }; - A986EC0B132CE6D800F048C8 /* b2PrismaticJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PrismaticJoint.cpp; sourceTree = ""; }; - A986EC0C132CE6D800F048C8 /* b2PrismaticJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PrismaticJoint.h; sourceTree = ""; }; - A986EC0D132CE6D800F048C8 /* b2PulleyJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PulleyJoint.cpp; sourceTree = ""; }; - A986EC0E132CE6D800F048C8 /* b2PulleyJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PulleyJoint.h; sourceTree = ""; }; - A986EC0F132CE6D800F048C8 /* b2RevoluteJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2RevoluteJoint.cpp; sourceTree = ""; }; - A986EC10132CE6D800F048C8 /* b2RevoluteJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2RevoluteJoint.h; sourceTree = ""; }; - A986EC11132CE6D800F048C8 /* b2WeldJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2WeldJoint.cpp; sourceTree = ""; }; - A986EC12132CE6D800F048C8 /* b2WeldJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2WeldJoint.h; sourceTree = ""; }; - A986ECAC132CE82F00F048C8 /* Box2D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Box2D.h; sourceTree = ""; }; A986ECAD132CEB9300F048C8 /* Fixture.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Fixture.cpp; sourceTree = ""; }; A986ECAE132CEB9B00F048C8 /* Fixture.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Fixture.h; sourceTree = ""; }; A98D913E10507BF9008E03F2 /* EncodedImageData.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EncodedImageData.h; sourceTree = ""; }; @@ -688,6 +598,98 @@ A9D307E9106635C3004FEDF8 /* physfs.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = physfs.framework; path = /Library/Frameworks/physfs.framework; sourceTree = ""; }; A9D5C47B142E31350044ECF7 /* Memoizer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Memoizer.h; sourceTree = ""; }; A9D5C47C142E32ED0044ECF7 /* Memoizer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Memoizer.cpp; sourceTree = ""; }; + A9D5C485142E5F7F0044ECF7 /* Box2D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Box2D.h; sourceTree = ""; }; + A9D5C487142E5F7F0044ECF7 /* b2BroadPhase.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2BroadPhase.cpp; sourceTree = ""; }; + A9D5C488142E5F7F0044ECF7 /* b2BroadPhase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2BroadPhase.h; sourceTree = ""; }; + A9D5C489142E5F7F0044ECF7 /* b2CollideCircle.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CollideCircle.cpp; sourceTree = ""; }; + A9D5C48A142E5F7F0044ECF7 /* b2CollideEdge.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CollideEdge.cpp; sourceTree = ""; }; + A9D5C48B142E5F7F0044ECF7 /* b2CollidePolygon.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CollidePolygon.cpp; sourceTree = ""; }; + A9D5C48C142E5F7F0044ECF7 /* b2Collision.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Collision.cpp; sourceTree = ""; }; + A9D5C48D142E5F7F0044ECF7 /* b2Collision.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Collision.h; sourceTree = ""; }; + A9D5C48E142E5F7F0044ECF7 /* b2Distance.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Distance.cpp; sourceTree = ""; }; + A9D5C48F142E5F7F0044ECF7 /* b2Distance.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Distance.h; sourceTree = ""; }; + A9D5C490142E5F7F0044ECF7 /* b2DynamicTree.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2DynamicTree.cpp; sourceTree = ""; }; + A9D5C491142E5F7F0044ECF7 /* b2DynamicTree.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2DynamicTree.h; sourceTree = ""; }; + A9D5C492142E5F7F0044ECF7 /* b2TimeOfImpact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2TimeOfImpact.cpp; sourceTree = ""; }; + A9D5C493142E5F7F0044ECF7 /* b2TimeOfImpact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2TimeOfImpact.h; sourceTree = ""; }; + A9D5C495142E5F7F0044ECF7 /* b2ChainShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ChainShape.cpp; sourceTree = ""; }; + A9D5C496142E5F7F0044ECF7 /* b2ChainShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ChainShape.h; sourceTree = ""; }; + A9D5C497142E5F7F0044ECF7 /* b2CircleShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CircleShape.cpp; sourceTree = ""; }; + A9D5C498142E5F7F0044ECF7 /* b2CircleShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2CircleShape.h; sourceTree = ""; }; + A9D5C499142E5F7F0044ECF7 /* b2EdgeShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2EdgeShape.cpp; sourceTree = ""; }; + A9D5C49A142E5F7F0044ECF7 /* b2EdgeShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2EdgeShape.h; sourceTree = ""; }; + A9D5C49B142E5F7F0044ECF7 /* b2PolygonShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PolygonShape.cpp; sourceTree = ""; }; + A9D5C49C142E5F7F0044ECF7 /* b2PolygonShape.cpp.orig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = b2PolygonShape.cpp.orig; sourceTree = ""; }; + A9D5C49D142E5F7F0044ECF7 /* b2PolygonShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PolygonShape.h; sourceTree = ""; }; + A9D5C49E142E5F7F0044ECF7 /* b2Shape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Shape.h; sourceTree = ""; }; + A9D5C4A0142E5F7F0044ECF7 /* b2BlockAllocator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2BlockAllocator.cpp; sourceTree = ""; }; + A9D5C4A1142E5F7F0044ECF7 /* b2BlockAllocator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2BlockAllocator.h; sourceTree = ""; }; + A9D5C4A2142E5F7F0044ECF7 /* b2Draw.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Draw.cpp; sourceTree = ""; }; + A9D5C4A3142E5F7F0044ECF7 /* b2Draw.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Draw.h; sourceTree = ""; }; + A9D5C4A4142E5F7F0044ECF7 /* b2GrowableStack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2GrowableStack.h; sourceTree = ""; }; + A9D5C4A5142E5F7F0044ECF7 /* b2Math.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Math.cpp; sourceTree = ""; }; + A9D5C4A6142E5F7F0044ECF7 /* b2Math.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Math.h; sourceTree = ""; }; + A9D5C4A7142E5F7F0044ECF7 /* b2Settings.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Settings.cpp; sourceTree = ""; }; + A9D5C4A8142E5F7F0044ECF7 /* b2Settings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Settings.h; sourceTree = ""; }; + A9D5C4A9142E5F7F0044ECF7 /* b2StackAllocator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2StackAllocator.cpp; sourceTree = ""; }; + A9D5C4AA142E5F7F0044ECF7 /* b2StackAllocator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2StackAllocator.h; sourceTree = ""; }; + A9D5C4AB142E5F7F0044ECF7 /* b2Timer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Timer.cpp; sourceTree = ""; }; + A9D5C4AC142E5F7F0044ECF7 /* b2Timer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Timer.h; sourceTree = ""; }; + A9D5C4AE142E5F7F0044ECF7 /* b2Body.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Body.cpp; sourceTree = ""; }; + A9D5C4AF142E5F7F0044ECF7 /* b2Body.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Body.h; sourceTree = ""; }; + A9D5C4B0142E5F7F0044ECF7 /* b2ContactManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ContactManager.cpp; sourceTree = ""; }; + A9D5C4B1142E5F7F0044ECF7 /* b2ContactManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ContactManager.h; sourceTree = ""; }; + A9D5C4B2142E5F7F0044ECF7 /* b2Fixture.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Fixture.cpp; sourceTree = ""; }; + A9D5C4B3142E5F7F0044ECF7 /* b2Fixture.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Fixture.h; sourceTree = ""; }; + A9D5C4B4142E5F7F0044ECF7 /* b2Island.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Island.cpp; sourceTree = ""; }; + A9D5C4B5142E5F7F0044ECF7 /* b2Island.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Island.h; sourceTree = ""; }; + A9D5C4B6142E5F7F0044ECF7 /* b2TimeStep.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2TimeStep.h; sourceTree = ""; }; + A9D5C4B7142E5F7F0044ECF7 /* b2World.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2World.cpp; sourceTree = ""; }; + A9D5C4B8142E5F7F0044ECF7 /* b2World.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2World.h; sourceTree = ""; }; + A9D5C4B9142E5F7F0044ECF7 /* b2WorldCallbacks.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2WorldCallbacks.cpp; sourceTree = ""; }; + A9D5C4BA142E5F7F0044ECF7 /* b2WorldCallbacks.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2WorldCallbacks.h; sourceTree = ""; }; + A9D5C4BC142E5F7F0044ECF7 /* b2ChainAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ChainAndCircleContact.cpp; sourceTree = ""; }; + A9D5C4BD142E5F7F0044ECF7 /* b2ChainAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ChainAndCircleContact.h; sourceTree = ""; }; + A9D5C4BE142E5F7F0044ECF7 /* b2ChainAndPolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ChainAndPolygonContact.cpp; sourceTree = ""; }; + A9D5C4BF142E5F7F0044ECF7 /* b2ChainAndPolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ChainAndPolygonContact.h; sourceTree = ""; }; + A9D5C4C0142E5F7F0044ECF7 /* b2CircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2CircleContact.cpp; sourceTree = ""; }; + A9D5C4C1142E5F7F0044ECF7 /* b2CircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2CircleContact.h; sourceTree = ""; }; + A9D5C4C2142E5F7F0044ECF7 /* b2Contact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Contact.cpp; sourceTree = ""; }; + A9D5C4C3142E5F7F0044ECF7 /* b2Contact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Contact.h; sourceTree = ""; }; + A9D5C4C4142E5F7F0044ECF7 /* b2ContactSolver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2ContactSolver.cpp; sourceTree = ""; }; + A9D5C4C5142E5F7F0044ECF7 /* b2ContactSolver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2ContactSolver.h; sourceTree = ""; }; + A9D5C4C6142E5F7F0044ECF7 /* b2EdgeAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2EdgeAndCircleContact.cpp; sourceTree = ""; }; + A9D5C4C7142E5F7F0044ECF7 /* b2EdgeAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2EdgeAndCircleContact.h; sourceTree = ""; }; + A9D5C4C8142E5F7F0044ECF7 /* b2EdgeAndPolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2EdgeAndPolygonContact.cpp; sourceTree = ""; }; + A9D5C4C9142E5F7F0044ECF7 /* b2EdgeAndPolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2EdgeAndPolygonContact.h; sourceTree = ""; }; + A9D5C4CA142E5F7F0044ECF7 /* b2PolygonAndCircleContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PolygonAndCircleContact.cpp; sourceTree = ""; }; + A9D5C4CB142E5F7F0044ECF7 /* b2PolygonAndCircleContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PolygonAndCircleContact.h; sourceTree = ""; }; + A9D5C4CC142E5F7F0044ECF7 /* b2PolygonContact.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PolygonContact.cpp; sourceTree = ""; }; + A9D5C4CD142E5F7F0044ECF7 /* b2PolygonContact.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PolygonContact.h; sourceTree = ""; }; + A9D5C4CF142E5F7F0044ECF7 /* b2DistanceJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2DistanceJoint.cpp; sourceTree = ""; }; + A9D5C4D0142E5F7F0044ECF7 /* b2DistanceJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2DistanceJoint.h; sourceTree = ""; }; + A9D5C4D1142E5F7F0044ECF7 /* b2FrictionJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2FrictionJoint.cpp; sourceTree = ""; }; + A9D5C4D2142E5F7F0044ECF7 /* b2FrictionJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2FrictionJoint.h; sourceTree = ""; }; + A9D5C4D3142E5F7F0044ECF7 /* b2GearJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2GearJoint.cpp; sourceTree = ""; }; + A9D5C4D4142E5F7F0044ECF7 /* b2GearJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2GearJoint.h; sourceTree = ""; }; + A9D5C4D5142E5F7F0044ECF7 /* b2Joint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Joint.cpp; sourceTree = ""; }; + A9D5C4D6142E5F7F0044ECF7 /* b2Joint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Joint.h; sourceTree = ""; }; + A9D5C4D7142E5F7F0044ECF7 /* b2MouseJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2MouseJoint.cpp; sourceTree = ""; }; + A9D5C4D8142E5F7F0044ECF7 /* b2MouseJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2MouseJoint.h; sourceTree = ""; }; + A9D5C4D9142E5F7F0044ECF7 /* b2PrismaticJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PrismaticJoint.cpp; sourceTree = ""; }; + A9D5C4DA142E5F7F0044ECF7 /* b2PrismaticJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PrismaticJoint.h; sourceTree = ""; }; + A9D5C4DB142E5F7F0044ECF7 /* b2PulleyJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2PulleyJoint.cpp; sourceTree = ""; }; + A9D5C4DC142E5F7F0044ECF7 /* b2PulleyJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2PulleyJoint.h; sourceTree = ""; }; + A9D5C4DD142E5F7F0044ECF7 /* b2RevoluteJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2RevoluteJoint.cpp; sourceTree = ""; }; + A9D5C4DE142E5F7F0044ECF7 /* b2RevoluteJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2RevoluteJoint.h; sourceTree = ""; }; + A9D5C4DF142E5F7F0044ECF7 /* b2RopeJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2RopeJoint.cpp; sourceTree = ""; }; + A9D5C4E0142E5F7F0044ECF7 /* b2RopeJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2RopeJoint.h; sourceTree = ""; }; + A9D5C4E1142E5F7F0044ECF7 /* b2WeldJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2WeldJoint.cpp; sourceTree = ""; }; + A9D5C4E2142E5F7F0044ECF7 /* b2WeldJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2WeldJoint.h; sourceTree = ""; }; + A9D5C4E3142E5F7F0044ECF7 /* b2WheelJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2WheelJoint.cpp; sourceTree = ""; }; + A9D5C4E4142E5F7F0044ECF7 /* b2WheelJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2WheelJoint.h; sourceTree = ""; }; + A9D5C4E6142E5F7F0044ECF7 /* b2Rope.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2Rope.cpp; sourceTree = ""; }; + A9D5C4E7142E5F7F0044ECF7 /* b2Rope.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2Rope.h; sourceTree = ""; }; A9DEC1BF1046EFA60049C70C /* Love.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; name = Love.icns; path = icons/Love.icns; sourceTree = ""; }; A9DEC1C01046EFA70049C70C /* LoveDocument.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; name = LoveDocument.icns; path = icons/LoveDocument.icns; sourceTree = ""; }; A9F16926109E7BAD00FC83D1 /* libmodplug.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = libmodplug.framework; path = /Library/Frameworks/libmodplug.framework; sourceTree = ""; }; @@ -840,6 +842,7 @@ A93E69F410420ABF007D418B /* libraries */ = { isa = PBXGroup; children = ( + A9D5C484142E5F7F0044ECF7 /* Box2D */, A93E6A0210420ABF007D418B /* luasocket */, A944D58A13244E5D0039937C /* utf8 */, ); @@ -1216,7 +1219,6 @@ children = ( A93E6AEB10420AC7007D418B /* Body.cpp */, A93E6AEC10420AC7007D418B /* Body.h */, - A986EBC3132CE6D800F048C8 /* Box2D */, A9D1D2091422959100A8BC2F /* ChainShape.cpp */, A9D1D20B142295A800A8BC2F /* ChainShape.h */, A93E6AED10420AC7007D418B /* CircleShape.cpp */, @@ -1392,15 +1394,6 @@ path = utf8; sourceTree = ""; }; - A96F416214127E720067FE9A /* Rope */ = { - isa = PBXGroup; - children = ( - A96F416314127E720067FE9A /* b2Rope.cpp */, - A96F416414127E720067FE9A /* b2Rope.h */, - ); - path = Rope; - sourceTree = ""; - }; A986DEAF113249A700810279 /* thread */ = { isa = PBXGroup; children = ( @@ -1421,151 +1414,161 @@ path = sdl; sourceTree = ""; }; - A986EBC3132CE6D800F048C8 /* Box2D */ = { + A9D5C484142E5F7F0044ECF7 /* Box2D */ = { isa = PBXGroup; children = ( - A986ECAC132CE82F00F048C8 /* Box2D.h */, - A986EBC7132CE6D800F048C8 /* Collision */, - A986EBDA132CE6D800F048C8 /* Common */, - A986EBE3132CE6D800F048C8 /* Dynamics */, - A96F416214127E720067FE9A /* Rope */, + A9D5C485142E5F7F0044ECF7 /* Box2D.h */, + A9D5C486142E5F7F0044ECF7 /* Collision */, + A9D5C49F142E5F7F0044ECF7 /* Common */, + A9D5C4AD142E5F7F0044ECF7 /* Dynamics */, + A9D5C4E5142E5F7F0044ECF7 /* Rope */, ); path = Box2D; sourceTree = ""; }; - A986EBC7132CE6D800F048C8 /* Collision */ = { + A9D5C486142E5F7F0044ECF7 /* Collision */ = { isa = PBXGroup; children = ( - A986EBC8132CE6D800F048C8 /* b2BroadPhase.cpp */, - A986EBC9132CE6D800F048C8 /* b2BroadPhase.h */, - A986EBCA132CE6D800F048C8 /* b2CollideCircle.cpp */, - A96F416D14127EB20067FE9A /* b2CollideEdge.cpp */, - A986EBCB132CE6D800F048C8 /* b2CollidePolygon.cpp */, - A986EBCC132CE6D800F048C8 /* b2Collision.cpp */, - A986EBCD132CE6D800F048C8 /* b2Collision.h */, - A986EBCE132CE6D800F048C8 /* b2Distance.cpp */, - A986EBCF132CE6D800F048C8 /* b2Distance.h */, - A986EBD0132CE6D800F048C8 /* b2DynamicTree.cpp */, - A986EBD1132CE6D800F048C8 /* b2DynamicTree.h */, - A986EBD2132CE6D800F048C8 /* b2TimeOfImpact.cpp */, - A986EBD3132CE6D800F048C8 /* b2TimeOfImpact.h */, - A986EBD4132CE6D800F048C8 /* Shapes */, + A9D5C487142E5F7F0044ECF7 /* b2BroadPhase.cpp */, + A9D5C488142E5F7F0044ECF7 /* b2BroadPhase.h */, + A9D5C489142E5F7F0044ECF7 /* b2CollideCircle.cpp */, + A9D5C48A142E5F7F0044ECF7 /* b2CollideEdge.cpp */, + A9D5C48B142E5F7F0044ECF7 /* b2CollidePolygon.cpp */, + A9D5C48C142E5F7F0044ECF7 /* b2Collision.cpp */, + A9D5C48D142E5F7F0044ECF7 /* b2Collision.h */, + A9D5C48E142E5F7F0044ECF7 /* b2Distance.cpp */, + A9D5C48F142E5F7F0044ECF7 /* b2Distance.h */, + A9D5C490142E5F7F0044ECF7 /* b2DynamicTree.cpp */, + A9D5C491142E5F7F0044ECF7 /* b2DynamicTree.h */, + A9D5C492142E5F7F0044ECF7 /* b2TimeOfImpact.cpp */, + A9D5C493142E5F7F0044ECF7 /* b2TimeOfImpact.h */, + A9D5C494142E5F7F0044ECF7 /* Shapes */, ); path = Collision; sourceTree = ""; }; - A986EBD4132CE6D800F048C8 /* Shapes */ = { + A9D5C494142E5F7F0044ECF7 /* Shapes */ = { isa = PBXGroup; children = ( - A96F416F14127EC00067FE9A /* b2ChainShape.cpp */, - A96F417014127EC00067FE9A /* b2ChainShape.h */, - A986EBD5132CE6D800F048C8 /* b2CircleShape.cpp */, - A986EBD6132CE6D800F048C8 /* b2CircleShape.h */, - A96F417E14127FC20067FE9A /* b2EdgeShape.cpp */, - A96F417F14127FC20067FE9A /* b2EdgeShape.h */, - A986EBD7132CE6D800F048C8 /* b2PolygonShape.cpp */, - A986EBD8132CE6D800F048C8 /* b2PolygonShape.h */, - A986EBD9132CE6D800F048C8 /* b2Shape.h */, + A9D5C495142E5F7F0044ECF7 /* b2ChainShape.cpp */, + A9D5C496142E5F7F0044ECF7 /* b2ChainShape.h */, + A9D5C497142E5F7F0044ECF7 /* b2CircleShape.cpp */, + A9D5C498142E5F7F0044ECF7 /* b2CircleShape.h */, + A9D5C499142E5F7F0044ECF7 /* b2EdgeShape.cpp */, + A9D5C49A142E5F7F0044ECF7 /* b2EdgeShape.h */, + A9D5C49B142E5F7F0044ECF7 /* b2PolygonShape.cpp */, + A9D5C49C142E5F7F0044ECF7 /* b2PolygonShape.cpp.orig */, + A9D5C49D142E5F7F0044ECF7 /* b2PolygonShape.h */, + A9D5C49E142E5F7F0044ECF7 /* b2Shape.h */, ); path = Shapes; sourceTree = ""; }; - A986EBDA132CE6D800F048C8 /* Common */ = { + A9D5C49F142E5F7F0044ECF7 /* Common */ = { isa = PBXGroup; children = ( - A986EBDB132CE6D800F048C8 /* b2BlockAllocator.cpp */, - A986EBDC132CE6D800F048C8 /* b2BlockAllocator.h */, - A96F416614127E9C0067FE9A /* b2Draw.cpp */, - A96F416714127E9C0067FE9A /* b2Draw.h */, - A96F416814127E9C0067FE9A /* b2GrowableStack.h */, - A986EBDD132CE6D800F048C8 /* b2Math.cpp */, - A986EBDE132CE6D800F048C8 /* b2Math.h */, - A986EBDF132CE6D800F048C8 /* b2Settings.cpp */, - A986EBE0132CE6D800F048C8 /* b2Settings.h */, - A986EBE1132CE6D800F048C8 /* b2StackAllocator.cpp */, - A986EBE2132CE6D800F048C8 /* b2StackAllocator.h */, - A96F416914127E9C0067FE9A /* b2Timer.cpp */, - A96F416A14127E9C0067FE9A /* b2Timer.h */, + A9D5C4A0142E5F7F0044ECF7 /* b2BlockAllocator.cpp */, + A9D5C4A1142E5F7F0044ECF7 /* b2BlockAllocator.h */, + A9D5C4A2142E5F7F0044ECF7 /* b2Draw.cpp */, + A9D5C4A3142E5F7F0044ECF7 /* b2Draw.h */, + A9D5C4A4142E5F7F0044ECF7 /* b2GrowableStack.h */, + A9D5C4A5142E5F7F0044ECF7 /* b2Math.cpp */, + A9D5C4A6142E5F7F0044ECF7 /* b2Math.h */, + A9D5C4A7142E5F7F0044ECF7 /* b2Settings.cpp */, + A9D5C4A8142E5F7F0044ECF7 /* b2Settings.h */, + A9D5C4A9142E5F7F0044ECF7 /* b2StackAllocator.cpp */, + A9D5C4AA142E5F7F0044ECF7 /* b2StackAllocator.h */, + A9D5C4AB142E5F7F0044ECF7 /* b2Timer.cpp */, + A9D5C4AC142E5F7F0044ECF7 /* b2Timer.h */, ); path = Common; sourceTree = ""; }; - A986EBE3132CE6D800F048C8 /* Dynamics */ = { + A9D5C4AD142E5F7F0044ECF7 /* Dynamics */ = { isa = PBXGroup; children = ( - A986EBE4132CE6D800F048C8 /* b2Body.cpp */, - A986EBE5132CE6D800F048C8 /* b2Body.h */, - A986EBE6132CE6D800F048C8 /* b2ContactManager.cpp */, - A986EBE7132CE6D800F048C8 /* b2ContactManager.h */, - A986EBE8132CE6D800F048C8 /* b2Fixture.cpp */, - A986EBE9132CE6D800F048C8 /* b2Fixture.h */, - A986EBEA132CE6D800F048C8 /* b2Island.cpp */, - A986EBEB132CE6D800F048C8 /* b2Island.h */, - A986EBEC132CE6D800F048C8 /* b2TimeStep.h */, - A986EBED132CE6D800F048C8 /* b2World.cpp */, - A986EBEE132CE6D800F048C8 /* b2World.h */, - A986EBEF132CE6D800F048C8 /* b2WorldCallbacks.cpp */, - A986EBF0132CE6D800F048C8 /* b2WorldCallbacks.h */, - A986EBF1132CE6D800F048C8 /* Contacts */, - A986EBFE132CE6D800F048C8 /* Joints */, + A9D5C4AE142E5F7F0044ECF7 /* b2Body.cpp */, + A9D5C4AF142E5F7F0044ECF7 /* b2Body.h */, + A9D5C4B0142E5F7F0044ECF7 /* b2ContactManager.cpp */, + A9D5C4B1142E5F7F0044ECF7 /* b2ContactManager.h */, + A9D5C4B2142E5F7F0044ECF7 /* b2Fixture.cpp */, + A9D5C4B3142E5F7F0044ECF7 /* b2Fixture.h */, + A9D5C4B4142E5F7F0044ECF7 /* b2Island.cpp */, + A9D5C4B5142E5F7F0044ECF7 /* b2Island.h */, + A9D5C4B6142E5F7F0044ECF7 /* b2TimeStep.h */, + A9D5C4B7142E5F7F0044ECF7 /* b2World.cpp */, + A9D5C4B8142E5F7F0044ECF7 /* b2World.h */, + A9D5C4B9142E5F7F0044ECF7 /* b2WorldCallbacks.cpp */, + A9D5C4BA142E5F7F0044ECF7 /* b2WorldCallbacks.h */, + A9D5C4BB142E5F7F0044ECF7 /* Contacts */, + A9D5C4CE142E5F7F0044ECF7 /* Joints */, ); path = Dynamics; sourceTree = ""; }; - A986EBF1132CE6D800F048C8 /* Contacts */ = { + A9D5C4BB142E5F7F0044ECF7 /* Contacts */ = { isa = PBXGroup; children = ( - A96F417214127EE70067FE9A /* b2ChainAndCircleContact.cpp */, - A96F417314127EE70067FE9A /* b2ChainAndCircleContact.h */, - A96F417414127EE70067FE9A /* b2ChainAndPolygonContact.cpp */, - A96F417514127EE70067FE9A /* b2ChainAndPolygonContact.h */, - A986EBF2132CE6D800F048C8 /* b2CircleContact.cpp */, - A986EBF3132CE6D800F048C8 /* b2CircleContact.h */, - A986EBF4132CE6D800F048C8 /* b2Contact.cpp */, - A986EBF5132CE6D800F048C8 /* b2Contact.h */, - A986EBF6132CE6D800F048C8 /* b2ContactSolver.cpp */, - A986EBF7132CE6D800F048C8 /* b2ContactSolver.h */, - A96F417814127EFD0067FE9A /* b2EdgeAndCircleContact.cpp */, - A96F417914127EFD0067FE9A /* b2EdgeAndCircleContact.h */, - A96F417A14127EFD0067FE9A /* b2EdgeAndPolygonContact.cpp */, - A96F417B14127EFD0067FE9A /* b2EdgeAndPolygonContact.h */, - A986EBF8132CE6D800F048C8 /* b2PolygonAndCircleContact.cpp */, - A986EBF9132CE6D800F048C8 /* b2PolygonAndCircleContact.h */, - A986EBFA132CE6D800F048C8 /* b2PolygonContact.cpp */, - A986EBFB132CE6D800F048C8 /* b2PolygonContact.h */, + A9D5C4BC142E5F7F0044ECF7 /* b2ChainAndCircleContact.cpp */, + A9D5C4BD142E5F7F0044ECF7 /* b2ChainAndCircleContact.h */, + A9D5C4BE142E5F7F0044ECF7 /* b2ChainAndPolygonContact.cpp */, + A9D5C4BF142E5F7F0044ECF7 /* b2ChainAndPolygonContact.h */, + A9D5C4C0142E5F7F0044ECF7 /* b2CircleContact.cpp */, + A9D5C4C1142E5F7F0044ECF7 /* b2CircleContact.h */, + A9D5C4C2142E5F7F0044ECF7 /* b2Contact.cpp */, + A9D5C4C3142E5F7F0044ECF7 /* b2Contact.h */, + A9D5C4C4142E5F7F0044ECF7 /* b2ContactSolver.cpp */, + A9D5C4C5142E5F7F0044ECF7 /* b2ContactSolver.h */, + A9D5C4C6142E5F7F0044ECF7 /* b2EdgeAndCircleContact.cpp */, + A9D5C4C7142E5F7F0044ECF7 /* b2EdgeAndCircleContact.h */, + A9D5C4C8142E5F7F0044ECF7 /* b2EdgeAndPolygonContact.cpp */, + A9D5C4C9142E5F7F0044ECF7 /* b2EdgeAndPolygonContact.h */, + A9D5C4CA142E5F7F0044ECF7 /* b2PolygonAndCircleContact.cpp */, + A9D5C4CB142E5F7F0044ECF7 /* b2PolygonAndCircleContact.h */, + A9D5C4CC142E5F7F0044ECF7 /* b2PolygonContact.cpp */, + A9D5C4CD142E5F7F0044ECF7 /* b2PolygonContact.h */, ); path = Contacts; sourceTree = ""; }; - A986EBFE132CE6D800F048C8 /* Joints */ = { + A9D5C4CE142E5F7F0044ECF7 /* Joints */ = { isa = PBXGroup; children = ( - A986EBFF132CE6D800F048C8 /* b2DistanceJoint.cpp */, - A986EC00132CE6D800F048C8 /* b2DistanceJoint.h */, - A986EC01132CE6D800F048C8 /* b2FrictionJoint.cpp */, - A986EC02132CE6D800F048C8 /* b2FrictionJoint.h */, - A986EC03132CE6D800F048C8 /* b2GearJoint.cpp */, - A986EC04132CE6D800F048C8 /* b2GearJoint.h */, - A986EC05132CE6D800F048C8 /* b2Joint.cpp */, - A986EC06132CE6D800F048C8 /* b2Joint.h */, - A986EC09132CE6D800F048C8 /* b2MouseJoint.cpp */, - A986EC0A132CE6D800F048C8 /* b2MouseJoint.h */, - A986EC0B132CE6D800F048C8 /* b2PrismaticJoint.cpp */, - A986EC0C132CE6D800F048C8 /* b2PrismaticJoint.h */, - A986EC0D132CE6D800F048C8 /* b2PulleyJoint.cpp */, - A986EC0E132CE6D800F048C8 /* b2PulleyJoint.h */, - A986EC0F132CE6D800F048C8 /* b2RevoluteJoint.cpp */, - A986EC10132CE6D800F048C8 /* b2RevoluteJoint.h */, - A96F415C14127E310067FE9A /* b2RopeJoint.cpp */, - A96F415D14127E320067FE9A /* b2RopeJoint.h */, - A986EC11132CE6D800F048C8 /* b2WeldJoint.cpp */, - A986EC12132CE6D800F048C8 /* b2WeldJoint.h */, - A96F415E14127E320067FE9A /* b2WheelJoint.cpp */, - A96F415F14127E320067FE9A /* b2WheelJoint.h */, + A9D5C4CF142E5F7F0044ECF7 /* b2DistanceJoint.cpp */, + A9D5C4D0142E5F7F0044ECF7 /* b2DistanceJoint.h */, + A9D5C4D1142E5F7F0044ECF7 /* b2FrictionJoint.cpp */, + A9D5C4D2142E5F7F0044ECF7 /* b2FrictionJoint.h */, + A9D5C4D3142E5F7F0044ECF7 /* b2GearJoint.cpp */, + A9D5C4D4142E5F7F0044ECF7 /* b2GearJoint.h */, + A9D5C4D5142E5F7F0044ECF7 /* b2Joint.cpp */, + A9D5C4D6142E5F7F0044ECF7 /* b2Joint.h */, + A9D5C4D7142E5F7F0044ECF7 /* b2MouseJoint.cpp */, + A9D5C4D8142E5F7F0044ECF7 /* b2MouseJoint.h */, + A9D5C4D9142E5F7F0044ECF7 /* b2PrismaticJoint.cpp */, + A9D5C4DA142E5F7F0044ECF7 /* b2PrismaticJoint.h */, + A9D5C4DB142E5F7F0044ECF7 /* b2PulleyJoint.cpp */, + A9D5C4DC142E5F7F0044ECF7 /* b2PulleyJoint.h */, + A9D5C4DD142E5F7F0044ECF7 /* b2RevoluteJoint.cpp */, + A9D5C4DE142E5F7F0044ECF7 /* b2RevoluteJoint.h */, + A9D5C4DF142E5F7F0044ECF7 /* b2RopeJoint.cpp */, + A9D5C4E0142E5F7F0044ECF7 /* b2RopeJoint.h */, + A9D5C4E1142E5F7F0044ECF7 /* b2WeldJoint.cpp */, + A9D5C4E2142E5F7F0044ECF7 /* b2WeldJoint.h */, + A9D5C4E3142E5F7F0044ECF7 /* b2WheelJoint.cpp */, + A9D5C4E4142E5F7F0044ECF7 /* b2WheelJoint.h */, ); path = Joints; sourceTree = ""; }; + A9D5C4E5142E5F7F0044ECF7 /* Rope */ = { + isa = PBXGroup; + children = ( + A9D5C4E6142E5F7F0044ECF7 /* b2Rope.cpp */, + A9D5C4E7142E5F7F0044ECF7 /* b2Rope.h */, + ); + path = Rope; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -1622,6 +1625,7 @@ files = ( A9DEC1C11046EFA70049C70C /* Love.icns in Resources */, A9DEC1C21046EFA70049C70C /* LoveDocument.icns in Resources */, + A9D5C4F4142E5F7F0044ECF7 /* b2PolygonShape.cpp.orig in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1764,54 +1768,9 @@ A9BD60741226C988007DEC63 /* Framebuffer.cpp in Sources */, A9BD60751226C988007DEC63 /* wrap_Framebuffer.cpp in Sources */, A95684F7125D3555001B276B /* b64.cpp in Sources */, - A986EC64132CE6DB00F048C8 /* b2BroadPhase.cpp in Sources */, - A986EC65132CE6DB00F048C8 /* b2CollideCircle.cpp in Sources */, - A986EC66132CE6DB00F048C8 /* b2CollidePolygon.cpp in Sources */, - A986EC67132CE6DB00F048C8 /* b2Collision.cpp in Sources */, - A986EC68132CE6DB00F048C8 /* b2Distance.cpp in Sources */, - A986EC69132CE6DB00F048C8 /* b2DynamicTree.cpp in Sources */, - A986EC6A132CE6DB00F048C8 /* b2TimeOfImpact.cpp in Sources */, - A986EC6B132CE6DB00F048C8 /* b2CircleShape.cpp in Sources */, - A986EC6C132CE6DB00F048C8 /* b2PolygonShape.cpp in Sources */, - A986EC6D132CE6DB00F048C8 /* b2BlockAllocator.cpp in Sources */, - A986EC6E132CE6DB00F048C8 /* b2Math.cpp in Sources */, - A986EC6F132CE6DB00F048C8 /* b2Settings.cpp in Sources */, - A986EC70132CE6DB00F048C8 /* b2StackAllocator.cpp in Sources */, - A986EC71132CE6DB00F048C8 /* b2Body.cpp in Sources */, - A986EC72132CE6DB00F048C8 /* b2ContactManager.cpp in Sources */, - A986EC73132CE6DB00F048C8 /* b2Fixture.cpp in Sources */, - A986EC74132CE6DB00F048C8 /* b2Island.cpp in Sources */, - A986EC75132CE6DB00F048C8 /* b2World.cpp in Sources */, - A986EC76132CE6DB00F048C8 /* b2WorldCallbacks.cpp in Sources */, - A986EC77132CE6DB00F048C8 /* b2CircleContact.cpp in Sources */, - A986EC78132CE6DB00F048C8 /* b2Contact.cpp in Sources */, - A986EC79132CE6DB00F048C8 /* b2ContactSolver.cpp in Sources */, - A986EC7A132CE6DB00F048C8 /* b2PolygonAndCircleContact.cpp in Sources */, - A986EC7B132CE6DB00F048C8 /* b2PolygonContact.cpp in Sources */, - A986EC7D132CE6DB00F048C8 /* b2DistanceJoint.cpp in Sources */, - A986EC7E132CE6DB00F048C8 /* b2FrictionJoint.cpp in Sources */, - A986EC7F132CE6DB00F048C8 /* b2GearJoint.cpp in Sources */, - A986EC80132CE6DB00F048C8 /* b2Joint.cpp in Sources */, - A986EC82132CE6DB00F048C8 /* b2MouseJoint.cpp in Sources */, - A986EC83132CE6DB00F048C8 /* b2PrismaticJoint.cpp in Sources */, - A986EC84132CE6DB00F048C8 /* b2PulleyJoint.cpp in Sources */, - A986EC85132CE6DB00F048C8 /* b2RevoluteJoint.cpp in Sources */, - A986EC86132CE6DB00F048C8 /* b2WeldJoint.cpp in Sources */, A986ECAF132CEBB000F048C8 /* Fixture.cpp in Sources */, A9B6432C13BF83AB00DC3C7E /* FrictionJoint.cpp in Sources */, A9B6432F13BF87F100DC3C7E /* wrap_FrictionJoint.cpp in Sources */, - A96F416014127E340067FE9A /* b2RopeJoint.cpp in Sources */, - A96F416114127E340067FE9A /* b2WheelJoint.cpp in Sources */, - A96F416514127E720067FE9A /* b2Rope.cpp in Sources */, - A96F416B14127E9C0067FE9A /* b2Draw.cpp in Sources */, - A96F416C14127E9C0067FE9A /* b2Timer.cpp in Sources */, - A96F416E14127EB20067FE9A /* b2CollideEdge.cpp in Sources */, - A96F417114127EC00067FE9A /* b2ChainShape.cpp in Sources */, - A96F417614127EE70067FE9A /* b2ChainAndCircleContact.cpp in Sources */, - A96F417714127EE70067FE9A /* b2ChainAndPolygonContact.cpp in Sources */, - A96F417C14127EFD0067FE9A /* b2EdgeAndCircleContact.cpp in Sources */, - A96F417D14127EFD0067FE9A /* b2EdgeAndPolygonContact.cpp in Sources */, - A96F418014127FC20067FE9A /* b2EdgeShape.cpp in Sources */, A96F41831412AFE20067FE9A /* wrap_WeldJoint.cpp in Sources */, A96F41861412AFF80067FE9A /* WeldJoint.cpp in Sources */, A96F41891412B36D0067FE9A /* wrap_WheelJoint.cpp in Sources */, @@ -1825,6 +1784,51 @@ A958F911142D364C007F320F /* wrap_Fixture.cpp in Sources */, A958F917142D6B3A007F320F /* Body.cpp in Sources */, A9D5C47D142E32EE0044ECF7 /* Memoizer.cpp in Sources */, + A9D5C4E8142E5F7F0044ECF7 /* b2BroadPhase.cpp in Sources */, + A9D5C4E9142E5F7F0044ECF7 /* b2CollideCircle.cpp in Sources */, + A9D5C4EA142E5F7F0044ECF7 /* b2CollideEdge.cpp in Sources */, + A9D5C4EB142E5F7F0044ECF7 /* b2CollidePolygon.cpp in Sources */, + A9D5C4EC142E5F7F0044ECF7 /* b2Collision.cpp in Sources */, + A9D5C4ED142E5F7F0044ECF7 /* b2Distance.cpp in Sources */, + A9D5C4EE142E5F7F0044ECF7 /* b2DynamicTree.cpp in Sources */, + A9D5C4EF142E5F7F0044ECF7 /* b2TimeOfImpact.cpp in Sources */, + A9D5C4F0142E5F7F0044ECF7 /* b2ChainShape.cpp in Sources */, + A9D5C4F1142E5F7F0044ECF7 /* b2CircleShape.cpp in Sources */, + A9D5C4F2142E5F7F0044ECF7 /* b2EdgeShape.cpp in Sources */, + A9D5C4F3142E5F7F0044ECF7 /* b2PolygonShape.cpp in Sources */, + A9D5C4F5142E5F7F0044ECF7 /* b2BlockAllocator.cpp in Sources */, + A9D5C4F6142E5F7F0044ECF7 /* b2Draw.cpp in Sources */, + A9D5C4F7142E5F7F0044ECF7 /* b2Math.cpp in Sources */, + A9D5C4F8142E5F7F0044ECF7 /* b2Settings.cpp in Sources */, + A9D5C4F9142E5F7F0044ECF7 /* b2StackAllocator.cpp in Sources */, + A9D5C4FA142E5F7F0044ECF7 /* b2Timer.cpp in Sources */, + A9D5C4FB142E5F7F0044ECF7 /* b2Body.cpp in Sources */, + A9D5C4FC142E5F7F0044ECF7 /* b2ContactManager.cpp in Sources */, + A9D5C4FD142E5F7F0044ECF7 /* b2Fixture.cpp in Sources */, + A9D5C4FE142E5F7F0044ECF7 /* b2Island.cpp in Sources */, + A9D5C4FF142E5F7F0044ECF7 /* b2World.cpp in Sources */, + A9D5C500142E5F7F0044ECF7 /* b2WorldCallbacks.cpp in Sources */, + A9D5C501142E5F7F0044ECF7 /* b2ChainAndCircleContact.cpp in Sources */, + A9D5C502142E5F7F0044ECF7 /* b2ChainAndPolygonContact.cpp in Sources */, + A9D5C503142E5F7F0044ECF7 /* b2CircleContact.cpp in Sources */, + A9D5C504142E5F7F0044ECF7 /* b2Contact.cpp in Sources */, + A9D5C505142E5F7F0044ECF7 /* b2ContactSolver.cpp in Sources */, + A9D5C506142E5F7F0044ECF7 /* b2EdgeAndCircleContact.cpp in Sources */, + A9D5C507142E5F7F0044ECF7 /* b2EdgeAndPolygonContact.cpp in Sources */, + A9D5C508142E5F7F0044ECF7 /* b2PolygonAndCircleContact.cpp in Sources */, + A9D5C509142E5F7F0044ECF7 /* b2PolygonContact.cpp in Sources */, + A9D5C50A142E5F7F0044ECF7 /* b2DistanceJoint.cpp in Sources */, + A9D5C50B142E5F7F0044ECF7 /* b2FrictionJoint.cpp in Sources */, + A9D5C50C142E5F7F0044ECF7 /* b2GearJoint.cpp in Sources */, + A9D5C50D142E5F7F0044ECF7 /* b2Joint.cpp in Sources */, + A9D5C50E142E5F7F0044ECF7 /* b2MouseJoint.cpp in Sources */, + A9D5C50F142E5F7F0044ECF7 /* b2PrismaticJoint.cpp in Sources */, + A9D5C510142E5F7F0044ECF7 /* b2PulleyJoint.cpp in Sources */, + A9D5C511142E5F7F0044ECF7 /* b2RevoluteJoint.cpp in Sources */, + A9D5C512142E5F7F0044ECF7 /* b2RopeJoint.cpp in Sources */, + A9D5C513142E5F7F0044ECF7 /* b2WeldJoint.cpp in Sources */, + A9D5C514142E5F7F0044ECF7 /* b2WheelJoint.cpp in Sources */, + A9D5C515142E5F7F0044ECF7 /* b2Rope.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1846,14 +1850,6 @@ GCC_OPTIMIZATION_LEVEL = 0; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = love_Prefix.pch; - HEADER_SEARCH_PATHS = ( - /Library/Frameworks/Lua.framework/Headers, - /Library/Frameworks/FreeType.framework/Headers, - /Library/Frameworks/SDL.framework/Headers, - ../../src, - ../../src/modules, - ../../src/modules/physics/box2d, - ); INSTALL_PATH = "$(HOME)/Applications"; LIBRARY_SEARCH_PATHS = ( "$(inherited)", @@ -1875,14 +1871,6 @@ GCC_MODEL_TUNING = G5; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = love_Prefix.pch; - HEADER_SEARCH_PATHS = ( - /Library/Frameworks/Lua.framework/Headers, - /Library/Frameworks/FreeType.framework/Headers, - /Library/Frameworks/SDL.framework/Headers, - ../../src, - ../../src/modules, - ../../src/modules/physics/box2d, - ); INSTALL_PATH = "$(HOME)/Applications"; LIBRARY_SEARCH_PATHS = ( "$(inherited)", @@ -1897,6 +1885,7 @@ C01FCF4F08A954540054247B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; ARCHS = "$(ARCHS_STANDARD_32_BIT)"; FRAMEWORK_SEARCH_PATHS = ""; GCC_C_LANGUAGE_STANDARD = c99; @@ -1924,11 +1913,12 @@ GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = NO; GCC_WARN_UNUSED_VARIABLE = YES; HEADER_SEARCH_PATHS = ( + "\"$(SRCROOT)/../../src\"", + "\"$(SRCROOT)/../../src/libraries\"", + "\"$(SRCROOT)/../../src/modules\"", /Library/Frameworks/Lua.framework/Headers, /Library/Frameworks/FreeType.framework/Headers, /Library/Frameworks/SDL.framework/Headers, - ../../src, - ../../src/modules, ); INFOPLIST_FILE = "love-Info.plist"; LIBRARY_SEARCH_PATHS = ""; @@ -1949,6 +1939,7 @@ C01FCF5008A954540054247B /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; ARCHS = "$(ARCHS_STANDARD_32_BIT)"; DEPLOYMENT_POSTPROCESSING = NO; FRAMEWORK_SEARCH_PATHS = ""; @@ -1978,11 +1969,12 @@ GCC_WARN_UNUSED_VALUE = NO; GCC_WARN_UNUSED_VARIABLE = YES; HEADER_SEARCH_PATHS = ( + "\"$(SRCROOT)/../../src\"", + "\"$(SRCROOT)/../../src/libraries\"", + "\"$(SRCROOT)/../../src/modules\"", /Library/Frameworks/Lua.framework/Headers, /Library/Frameworks/FreeType.framework/Headers, /Library/Frameworks/SDL.framework/Headers, - ../../src, - ../../src/modules, ); INFOPLIST_FILE = "love-Info.plist"; LD_RUNPATH_SEARCH_PATHS = "@loader_path/../Frameworks"; diff --git a/src/modules/physics/box2d/Box2D/Box2D.h b/src/libraries/Box2D/Box2D.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Box2D.h rename to src/libraries/Box2D/Box2D.h diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.cpp b/src/libraries/Box2D/Collision/Shapes/b2ChainShape.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.cpp rename to src/libraries/Box2D/Collision/Shapes/b2ChainShape.cpp diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.h b/src/libraries/Box2D/Collision/Shapes/b2ChainShape.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/Shapes/b2ChainShape.h rename to src/libraries/Box2D/Collision/Shapes/b2ChainShape.h diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.cpp b/src/libraries/Box2D/Collision/Shapes/b2CircleShape.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.cpp rename to src/libraries/Box2D/Collision/Shapes/b2CircleShape.cpp diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.h b/src/libraries/Box2D/Collision/Shapes/b2CircleShape.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/Shapes/b2CircleShape.h rename to src/libraries/Box2D/Collision/Shapes/b2CircleShape.h diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.cpp b/src/libraries/Box2D/Collision/Shapes/b2EdgeShape.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.cpp rename to src/libraries/Box2D/Collision/Shapes/b2EdgeShape.cpp diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.h b/src/libraries/Box2D/Collision/Shapes/b2EdgeShape.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/Shapes/b2EdgeShape.h rename to src/libraries/Box2D/Collision/Shapes/b2EdgeShape.h diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp b/src/libraries/Box2D/Collision/Shapes/b2PolygonShape.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp rename to src/libraries/Box2D/Collision/Shapes/b2PolygonShape.cpp diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.h b/src/libraries/Box2D/Collision/Shapes/b2PolygonShape.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/Shapes/b2PolygonShape.h rename to src/libraries/Box2D/Collision/Shapes/b2PolygonShape.h diff --git a/src/modules/physics/box2d/Box2D/Collision/Shapes/b2Shape.h b/src/libraries/Box2D/Collision/Shapes/b2Shape.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/Shapes/b2Shape.h rename to src/libraries/Box2D/Collision/Shapes/b2Shape.h diff --git a/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.cpp b/src/libraries/Box2D/Collision/b2BroadPhase.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.cpp rename to src/libraries/Box2D/Collision/b2BroadPhase.cpp diff --git a/src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.h b/src/libraries/Box2D/Collision/b2BroadPhase.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/b2BroadPhase.h rename to src/libraries/Box2D/Collision/b2BroadPhase.h diff --git a/src/modules/physics/box2d/Box2D/Collision/b2CollideCircle.cpp b/src/libraries/Box2D/Collision/b2CollideCircle.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/b2CollideCircle.cpp rename to src/libraries/Box2D/Collision/b2CollideCircle.cpp diff --git a/src/modules/physics/box2d/Box2D/Collision/b2CollideEdge.cpp b/src/libraries/Box2D/Collision/b2CollideEdge.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/b2CollideEdge.cpp rename to src/libraries/Box2D/Collision/b2CollideEdge.cpp diff --git a/src/modules/physics/box2d/Box2D/Collision/b2CollidePolygon.cpp b/src/libraries/Box2D/Collision/b2CollidePolygon.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/b2CollidePolygon.cpp rename to src/libraries/Box2D/Collision/b2CollidePolygon.cpp diff --git a/src/modules/physics/box2d/Box2D/Collision/b2Collision.cpp b/src/libraries/Box2D/Collision/b2Collision.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/b2Collision.cpp rename to src/libraries/Box2D/Collision/b2Collision.cpp diff --git a/src/modules/physics/box2d/Box2D/Collision/b2Collision.h b/src/libraries/Box2D/Collision/b2Collision.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/b2Collision.h rename to src/libraries/Box2D/Collision/b2Collision.h diff --git a/src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp b/src/libraries/Box2D/Collision/b2Distance.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/b2Distance.cpp rename to src/libraries/Box2D/Collision/b2Distance.cpp diff --git a/src/modules/physics/box2d/Box2D/Collision/b2Distance.h b/src/libraries/Box2D/Collision/b2Distance.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/b2Distance.h rename to src/libraries/Box2D/Collision/b2Distance.h diff --git a/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.cpp b/src/libraries/Box2D/Collision/b2DynamicTree.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.cpp rename to src/libraries/Box2D/Collision/b2DynamicTree.cpp diff --git a/src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.h b/src/libraries/Box2D/Collision/b2DynamicTree.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/b2DynamicTree.h rename to src/libraries/Box2D/Collision/b2DynamicTree.h diff --git a/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.cpp b/src/libraries/Box2D/Collision/b2TimeOfImpact.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.cpp rename to src/libraries/Box2D/Collision/b2TimeOfImpact.cpp diff --git a/src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.h b/src/libraries/Box2D/Collision/b2TimeOfImpact.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Collision/b2TimeOfImpact.h rename to src/libraries/Box2D/Collision/b2TimeOfImpact.h diff --git a/src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.cpp b/src/libraries/Box2D/Common/b2BlockAllocator.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.cpp rename to src/libraries/Box2D/Common/b2BlockAllocator.cpp diff --git a/src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.h b/src/libraries/Box2D/Common/b2BlockAllocator.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Common/b2BlockAllocator.h rename to src/libraries/Box2D/Common/b2BlockAllocator.h diff --git a/src/modules/physics/box2d/Box2D/Common/b2Draw.cpp b/src/libraries/Box2D/Common/b2Draw.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Common/b2Draw.cpp rename to src/libraries/Box2D/Common/b2Draw.cpp diff --git a/src/modules/physics/box2d/Box2D/Common/b2Draw.h b/src/libraries/Box2D/Common/b2Draw.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Common/b2Draw.h rename to src/libraries/Box2D/Common/b2Draw.h diff --git a/src/modules/physics/box2d/Box2D/Common/b2GrowableStack.h b/src/libraries/Box2D/Common/b2GrowableStack.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Common/b2GrowableStack.h rename to src/libraries/Box2D/Common/b2GrowableStack.h diff --git a/src/modules/physics/box2d/Box2D/Common/b2Math.cpp b/src/libraries/Box2D/Common/b2Math.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Common/b2Math.cpp rename to src/libraries/Box2D/Common/b2Math.cpp diff --git a/src/modules/physics/box2d/Box2D/Common/b2Math.h b/src/libraries/Box2D/Common/b2Math.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Common/b2Math.h rename to src/libraries/Box2D/Common/b2Math.h diff --git a/src/modules/physics/box2d/Box2D/Common/b2Settings.cpp b/src/libraries/Box2D/Common/b2Settings.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Common/b2Settings.cpp rename to src/libraries/Box2D/Common/b2Settings.cpp diff --git a/src/modules/physics/box2d/Box2D/Common/b2Settings.h b/src/libraries/Box2D/Common/b2Settings.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Common/b2Settings.h rename to src/libraries/Box2D/Common/b2Settings.h diff --git a/src/modules/physics/box2d/Box2D/Common/b2StackAllocator.cpp b/src/libraries/Box2D/Common/b2StackAllocator.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Common/b2StackAllocator.cpp rename to src/libraries/Box2D/Common/b2StackAllocator.cpp diff --git a/src/modules/physics/box2d/Box2D/Common/b2StackAllocator.h b/src/libraries/Box2D/Common/b2StackAllocator.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Common/b2StackAllocator.h rename to src/libraries/Box2D/Common/b2StackAllocator.h diff --git a/src/modules/physics/box2d/Box2D/Common/b2Timer.cpp b/src/libraries/Box2D/Common/b2Timer.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Common/b2Timer.cpp rename to src/libraries/Box2D/Common/b2Timer.cpp diff --git a/src/modules/physics/box2d/Box2D/Common/b2Timer.h b/src/libraries/Box2D/Common/b2Timer.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Common/b2Timer.h rename to src/libraries/Box2D/Common/b2Timer.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp b/src/libraries/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp rename to src/libraries/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h b/src/libraries/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h rename to src/libraries/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp b/src/libraries/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp rename to src/libraries/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h b/src/libraries/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h rename to src/libraries/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.cpp b/src/libraries/Box2D/Dynamics/Contacts/b2CircleContact.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.cpp rename to src/libraries/Box2D/Dynamics/Contacts/b2CircleContact.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.h b/src/libraries/Box2D/Dynamics/Contacts/b2CircleContact.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2CircleContact.h rename to src/libraries/Box2D/Dynamics/Contacts/b2CircleContact.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp b/src/libraries/Box2D/Dynamics/Contacts/b2Contact.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp rename to src/libraries/Box2D/Dynamics/Contacts/b2Contact.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.h b/src/libraries/Box2D/Dynamics/Contacts/b2Contact.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2Contact.h rename to src/libraries/Box2D/Dynamics/Contacts/b2Contact.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.cpp b/src/libraries/Box2D/Dynamics/Contacts/b2ContactSolver.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.cpp rename to src/libraries/Box2D/Dynamics/Contacts/b2ContactSolver.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.h b/src/libraries/Box2D/Dynamics/Contacts/b2ContactSolver.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.h rename to src/libraries/Box2D/Dynamics/Contacts/b2ContactSolver.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp b/src/libraries/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp rename to src/libraries/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h b/src/libraries/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h rename to src/libraries/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp b/src/libraries/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp rename to src/libraries/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h b/src/libraries/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h rename to src/libraries/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp b/src/libraries/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp rename to src/libraries/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h b/src/libraries/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h rename to src/libraries/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.cpp b/src/libraries/Box2D/Dynamics/Contacts/b2PolygonContact.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.cpp rename to src/libraries/Box2D/Dynamics/Contacts/b2PolygonContact.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.h b/src/libraries/Box2D/Dynamics/Contacts/b2PolygonContact.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.h rename to src/libraries/Box2D/Dynamics/Contacts/b2PolygonContact.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp b/src/libraries/Box2D/Dynamics/Joints/b2DistanceJoint.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp rename to src/libraries/Box2D/Dynamics/Joints/b2DistanceJoint.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h b/src/libraries/Box2D/Dynamics/Joints/b2DistanceJoint.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h rename to src/libraries/Box2D/Dynamics/Joints/b2DistanceJoint.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp b/src/libraries/Box2D/Dynamics/Joints/b2FrictionJoint.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp rename to src/libraries/Box2D/Dynamics/Joints/b2FrictionJoint.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h b/src/libraries/Box2D/Dynamics/Joints/b2FrictionJoint.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.h rename to src/libraries/Box2D/Dynamics/Joints/b2FrictionJoint.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp b/src/libraries/Box2D/Dynamics/Joints/b2GearJoint.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp rename to src/libraries/Box2D/Dynamics/Joints/b2GearJoint.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.h b/src/libraries/Box2D/Dynamics/Joints/b2GearJoint.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2GearJoint.h rename to src/libraries/Box2D/Dynamics/Joints/b2GearJoint.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.cpp b/src/libraries/Box2D/Dynamics/Joints/b2Joint.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.cpp rename to src/libraries/Box2D/Dynamics/Joints/b2Joint.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.h b/src/libraries/Box2D/Dynamics/Joints/b2Joint.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2Joint.h rename to src/libraries/Box2D/Dynamics/Joints/b2Joint.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.cpp b/src/libraries/Box2D/Dynamics/Joints/b2MouseJoint.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.cpp rename to src/libraries/Box2D/Dynamics/Joints/b2MouseJoint.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.h b/src/libraries/Box2D/Dynamics/Joints/b2MouseJoint.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2MouseJoint.h rename to src/libraries/Box2D/Dynamics/Joints/b2MouseJoint.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp b/src/libraries/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp rename to src/libraries/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h b/src/libraries/Box2D/Dynamics/Joints/b2PrismaticJoint.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h rename to src/libraries/Box2D/Dynamics/Joints/b2PrismaticJoint.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp b/src/libraries/Box2D/Dynamics/Joints/b2PulleyJoint.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp rename to src/libraries/Box2D/Dynamics/Joints/b2PulleyJoint.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.h b/src/libraries/Box2D/Dynamics/Joints/b2PulleyJoint.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.h rename to src/libraries/Box2D/Dynamics/Joints/b2PulleyJoint.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp b/src/libraries/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp rename to src/libraries/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h b/src/libraries/Box2D/Dynamics/Joints/b2RevoluteJoint.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h rename to src/libraries/Box2D/Dynamics/Joints/b2RevoluteJoint.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.cpp b/src/libraries/Box2D/Dynamics/Joints/b2RopeJoint.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.cpp rename to src/libraries/Box2D/Dynamics/Joints/b2RopeJoint.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.h b/src/libraries/Box2D/Dynamics/Joints/b2RopeJoint.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2RopeJoint.h rename to src/libraries/Box2D/Dynamics/Joints/b2RopeJoint.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp b/src/libraries/Box2D/Dynamics/Joints/b2WeldJoint.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.cpp rename to src/libraries/Box2D/Dynamics/Joints/b2WeldJoint.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h b/src/libraries/Box2D/Dynamics/Joints/b2WeldJoint.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WeldJoint.h rename to src/libraries/Box2D/Dynamics/Joints/b2WeldJoint.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.cpp b/src/libraries/Box2D/Dynamics/Joints/b2WheelJoint.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.cpp rename to src/libraries/Box2D/Dynamics/Joints/b2WheelJoint.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.h b/src/libraries/Box2D/Dynamics/Joints/b2WheelJoint.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/Joints/b2WheelJoint.h rename to src/libraries/Box2D/Dynamics/Joints/b2WheelJoint.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp b/src/libraries/Box2D/Dynamics/b2Body.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/b2Body.cpp rename to src/libraries/Box2D/Dynamics/b2Body.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Body.h b/src/libraries/Box2D/Dynamics/b2Body.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/b2Body.h rename to src/libraries/Box2D/Dynamics/b2Body.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp b/src/libraries/Box2D/Dynamics/b2ContactManager.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.cpp rename to src/libraries/Box2D/Dynamics/b2ContactManager.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.h b/src/libraries/Box2D/Dynamics/b2ContactManager.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/b2ContactManager.h rename to src/libraries/Box2D/Dynamics/b2ContactManager.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp b/src/libraries/Box2D/Dynamics/b2Fixture.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.cpp rename to src/libraries/Box2D/Dynamics/b2Fixture.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h b/src/libraries/Box2D/Dynamics/b2Fixture.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/b2Fixture.h rename to src/libraries/Box2D/Dynamics/b2Fixture.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Island.cpp b/src/libraries/Box2D/Dynamics/b2Island.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/b2Island.cpp rename to src/libraries/Box2D/Dynamics/b2Island.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2Island.h b/src/libraries/Box2D/Dynamics/b2Island.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/b2Island.h rename to src/libraries/Box2D/Dynamics/b2Island.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2TimeStep.h b/src/libraries/Box2D/Dynamics/b2TimeStep.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/b2TimeStep.h rename to src/libraries/Box2D/Dynamics/b2TimeStep.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp b/src/libraries/Box2D/Dynamics/b2World.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/b2World.cpp rename to src/libraries/Box2D/Dynamics/b2World.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2World.h b/src/libraries/Box2D/Dynamics/b2World.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/b2World.h rename to src/libraries/Box2D/Dynamics/b2World.h diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.cpp b/src/libraries/Box2D/Dynamics/b2WorldCallbacks.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.cpp rename to src/libraries/Box2D/Dynamics/b2WorldCallbacks.cpp diff --git a/src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.h b/src/libraries/Box2D/Dynamics/b2WorldCallbacks.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Dynamics/b2WorldCallbacks.h rename to src/libraries/Box2D/Dynamics/b2WorldCallbacks.h diff --git a/src/modules/physics/box2d/Box2D/Rope/b2Rope.cpp b/src/libraries/Box2D/Rope/b2Rope.cpp similarity index 100% rename from src/modules/physics/box2d/Box2D/Rope/b2Rope.cpp rename to src/libraries/Box2D/Rope/b2Rope.cpp diff --git a/src/modules/physics/box2d/Box2D/Rope/b2Rope.h b/src/libraries/Box2D/Rope/b2Rope.h similarity index 100% rename from src/modules/physics/box2d/Box2D/Rope/b2Rope.h rename to src/libraries/Box2D/Rope/b2Rope.h From e2b832015b3db75310ad20b1fb3edf20b9f402b4 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 16:15:09 -0400 Subject: [PATCH 49/78] Add World:queryBoundingBox --HG-- branch : box2d-update --- src/modules/physics/box2d/World.cpp | 43 +++++++++++++++++++++++- src/modules/physics/box2d/World.h | 15 +++++++++ src/modules/physics/box2d/wrap_World.cpp | 8 +++++ src/modules/physics/box2d/wrap_World.h | 1 + 4 files changed, 66 insertions(+), 1 deletion(-) diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index 110a1b80a..7d6671767 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -142,6 +142,32 @@ namespace box2d } return true; } + + World::QueryCallback::QueryCallback() + : ref(0) + { + } + + World::QueryCallback::~QueryCallback() + { + if(ref != 0) + delete ref; + } + + bool World::QueryCallback::ReportFixture(b2Fixture * fixture) + { + if (ref != 0) + { + lua_State * L = ref->getL(); + ref->push(); + Fixture * f = (Fixture *)Memoizer::find(fixture); + if (!f) throw love::Exception("A fixture has escaped Memoizer!"); + luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)f); + lua_call(L, 1, 1); + return luax_toboolean(L, -1); + } + return true; + } World::World() : world(NULL) @@ -176,7 +202,6 @@ namespace box2d { world->Step(dt, 8, 6); - begin.process(); end.process(); presolve.process(); @@ -298,6 +323,22 @@ namespace box2d { return groundBody; } + + int World::queryBoundingBox(lua_State * L) + { + luax_assert_argc(L, 5); + b2AABB box; + float lx = (float)luaL_checknumber(L, 1); + float ly = (float)luaL_checknumber(L, 2); + float ux = (float)luaL_checknumber(L, 3); + float uy = (float)luaL_checknumber(L, 4); + box.lowerBound = Physics::scaleDown(b2Vec2(lx, ly)); + box.upperBound = Physics::scaleDown(b2Vec2(ux, uy)); + if (query.ref) delete query.ref; + query.ref = luax_refif(L, LUA_TFUNCTION); + world->QueryAABB(&query, box); + return 0; + } } // box2d } // physics diff --git a/src/modules/physics/box2d/World.h b/src/modules/physics/box2d/World.h index 1798372af..f2508a6c5 100644 --- a/src/modules/physics/box2d/World.h +++ b/src/modules/physics/box2d/World.h @@ -86,6 +86,15 @@ namespace box2d ~ContactFilter(); bool process(Fixture * a, Fixture * b); }; + + class QueryCallback : public b2QueryCallback + { + public: + Reference * ref; + QueryCallback(); + ~QueryCallback(); + virtual bool ReportFixture(b2Fixture * fixture); + }; private: @@ -98,6 +107,7 @@ namespace box2d // Contact callbacks. ContactCallback begin, end, presolve, postsolve; ContactFilter filter; + QueryCallback query; public: @@ -200,6 +210,11 @@ namespace box2d * @return The ground body. **/ b2Body * getGroundBody(); + + /** + * Gets all fixtures that overlap a given bounding box. + **/ + int queryBoundingBox(lua_State * L); }; diff --git a/src/modules/physics/box2d/wrap_World.cpp b/src/modules/physics/box2d/wrap_World.cpp index febfcfcb4..39b846e15 100644 --- a/src/modules/physics/box2d/wrap_World.cpp +++ b/src/modules/physics/box2d/wrap_World.cpp @@ -112,6 +112,13 @@ namespace box2d lua_pushinteger(L, t->getJointCount()); return 1; } + + int w_World_queryBoundingBox(lua_State * L) + { + World * t = luax_checkworld(L, 1); + lua_remove(L, 1); + return t->queryBoundingBox(L); + } static const luaL_Reg functions[] = { { "update", w_World_update }, @@ -125,6 +132,7 @@ namespace box2d { "getAllowSleeping", w_World_getAllowSleeping }, { "getBodyCount", w_World_getBodyCount }, { "getJointCount", w_World_getJointCount }, + { "queryBoundingBox", w_World_queryBoundingBox }, { 0, 0 } }; diff --git a/src/modules/physics/box2d/wrap_World.h b/src/modules/physics/box2d/wrap_World.h index 372928c22..4c2192842 100644 --- a/src/modules/physics/box2d/wrap_World.h +++ b/src/modules/physics/box2d/wrap_World.h @@ -43,6 +43,7 @@ namespace box2d int w_World_getAllowSleeping(lua_State * L); int w_World_getBodyCount(lua_State * L); int w_World_getJointCount(lua_State * L); + int w_World_queryBoundingBox(lua_State * L); int luaopen_world(lua_State * L); } // box2d From f852c9bac2181a8c44a102419b3de9293da53faa Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 16:26:41 -0400 Subject: [PATCH 50/78] Add World:rayCast --HG-- branch : box2d-update --- src/modules/physics/box2d/World.cpp | 48 ++++++++++++++++++++++++ src/modules/physics/box2d/World.h | 15 ++++++++ src/modules/physics/box2d/wrap_World.cpp | 8 ++++ src/modules/physics/box2d/wrap_World.h | 1 + 4 files changed, 72 insertions(+) diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index 7d6671767..9f1cf7f76 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -168,6 +168,39 @@ namespace box2d } return true; } + + World::RayCastCallback::RayCastCallback() + : ref(0) + { + } + + World::RayCastCallback::~RayCastCallback() + { + if(ref != 0) + delete ref; + } + + float32 World::RayCastCallback::ReportFixture(b2Fixture * fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction) + { + if (ref != 0) + { + lua_State * L = ref->getL(); + ref->push(); + Fixture * f = (Fixture *)Memoizer::find(fixture); + if (!f) throw love::Exception("A fixture has escaped Memoizer!"); + luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)f); + b2Vec2 scaledPoint = Physics::scaleUp(point); + lua_pushnumber(L, scaledPoint.x); + lua_pushnumber(L, scaledPoint.y); + b2Vec2 scaledNormal = Physics::scaleUp(normal); + lua_pushnumber(L, scaledNormal.x); + lua_pushnumber(L, scaledNormal.y); + lua_pushnumber(L, fraction); + lua_call(L, 6, 1); + return (float32)luaL_checknumber(L, -1); + } + return 0; + } World::World() : world(NULL) @@ -339,6 +372,21 @@ namespace box2d world->QueryAABB(&query, box); return 0; } + + int World::rayCast(lua_State * L) + { + luax_assert_argc(L, 5); + float x1 = (float)luaL_checknumber(L, 1); + float y1 = (float)luaL_checknumber(L, 2); + float x2 = (float)luaL_checknumber(L, 3); + float y2 = (float)luaL_checknumber(L, 4); + b2Vec2 v1 = Physics::scaleDown(b2Vec2(x1, y1)); + b2Vec2 v2 = Physics::scaleDown(b2Vec2(x2, y2)); + if (raycast.ref) delete raycast.ref; + raycast.ref = luax_refif(L, LUA_TFUNCTION); + world->RayCast(&raycast, v1, v2); + return 0; + } } // box2d } // physics diff --git a/src/modules/physics/box2d/World.h b/src/modules/physics/box2d/World.h index f2508a6c5..76d84fd98 100644 --- a/src/modules/physics/box2d/World.h +++ b/src/modules/physics/box2d/World.h @@ -95,6 +95,15 @@ namespace box2d ~QueryCallback(); virtual bool ReportFixture(b2Fixture * fixture); }; + + class RayCastCallback : public b2RayCastCallback + { + public: + Reference * ref; + RayCastCallback(); + ~RayCastCallback(); + virtual float32 ReportFixture(b2Fixture * fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction); + }; private: @@ -108,6 +117,7 @@ namespace box2d ContactCallback begin, end, presolve, postsolve; ContactFilter filter; QueryCallback query; + RayCastCallback raycast; public: @@ -215,6 +225,11 @@ namespace box2d * Gets all fixtures that overlap a given bounding box. **/ int queryBoundingBox(lua_State * L); + + /** + * Raycasts the World for all Fixtures in the path of the ray. + **/ + int rayCast(lua_State * L); }; diff --git a/src/modules/physics/box2d/wrap_World.cpp b/src/modules/physics/box2d/wrap_World.cpp index 39b846e15..9fe819f3f 100644 --- a/src/modules/physics/box2d/wrap_World.cpp +++ b/src/modules/physics/box2d/wrap_World.cpp @@ -119,6 +119,13 @@ namespace box2d lua_remove(L, 1); return t->queryBoundingBox(L); } + + int w_World_rayCast(lua_State * L) + { + World * t = luax_checkworld(L, 1); + lua_remove(L, 1); + return t->rayCast(L); + } static const luaL_Reg functions[] = { { "update", w_World_update }, @@ -133,6 +140,7 @@ namespace box2d { "getBodyCount", w_World_getBodyCount }, { "getJointCount", w_World_getJointCount }, { "queryBoundingBox", w_World_queryBoundingBox }, + { "rayCast", w_World_rayCast }, { 0, 0 } }; diff --git a/src/modules/physics/box2d/wrap_World.h b/src/modules/physics/box2d/wrap_World.h index 4c2192842..3fddb8ec6 100644 --- a/src/modules/physics/box2d/wrap_World.h +++ b/src/modules/physics/box2d/wrap_World.h @@ -44,6 +44,7 @@ namespace box2d int w_World_getBodyCount(lua_State * L); int w_World_getJointCount(lua_State * L); int w_World_queryBoundingBox(lua_State * L); + int w_World_rayCast(lua_State * L); int luaopen_world(lua_State * L); } // box2d From 6a0c5b485b31a1013e728e120d0e087a3eee1aa0 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 16:46:07 -0400 Subject: [PATCH 51/78] Memoize Contacts, and add List-fetching functions to World (they return arrays) --HG-- branch : box2d-update --- src/modules/physics/box2d/Contact.cpp | 4 ++ src/modules/physics/box2d/World.cpp | 50 ++++++++++++++++++++++++ src/modules/physics/box2d/World.h | 24 ++++++++++++ src/modules/physics/box2d/wrap_World.cpp | 32 +++++++++++++++ src/modules/physics/box2d/wrap_World.h | 4 ++ 5 files changed, 114 insertions(+) diff --git a/src/modules/physics/box2d/Contact.cpp b/src/modules/physics/box2d/Contact.cpp index 7a1b9ffa8..166d66d09 100644 --- a/src/modules/physics/box2d/Contact.cpp +++ b/src/modules/physics/box2d/Contact.cpp @@ -22,6 +22,8 @@ #include "World.h" #include "Physics.h" +#include + namespace love { namespace physics @@ -31,10 +33,12 @@ namespace box2d Contact::Contact(b2Contact * contact) : contact(contact) { + Memoizer::add(contact, this); } Contact::~Contact() { + Memoizer::remove(contact); } int Contact::getPositions(lua_State * L) diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index 9f1cf7f76..699d1b3d1 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -352,6 +352,56 @@ namespace box2d return world->GetJointCount(); } + int World::getContactCount() + { + return world->GetContactCount(); + } + + int World::getBodyList(lua_State * L) + { + lua_newtable(L); + b2Body * b = world->GetBodyList(); + for (int i = 1; i <= world->GetBodyCount(); i++) { + if (!b) return 1; + Body * body = (Body *)Memoizer::find(b); + if (!body) throw love::Exception("A body has escaped Memoizer!"); + luax_newtype(L, "Body", PHYSICS_BODY_T, (void*)body); + lua_rawseti(L, -1, i); + b = b->GetNext(); + } + return 1; + } + + int World::getJointList(lua_State * L) + { + lua_newtable(L); + b2Joint * j = world->GetJointList(); + for (int i = 1; i <= world->GetJointCount(); i++) { + if (!j) return 1; + Joint * joint = (Joint *)Memoizer::find(j); + if (!joint) throw love::Exception("A joint has escaped Memoizer!"); + luax_newtype(L, "Joint", PHYSICS_JOINT_T, (void*)joint); + lua_rawseti(L, -1, i); + j = j->GetNext(); + } + return 1; + } + + int World::getContactList(lua_State * L) + { + lua_newtable(L); + b2Contact * c = world->GetContactList(); + for (int i = 1; i <= world->GetContactCount(); i++) { + if (!c) return 1; + Contact * contact = (Contact *)Memoizer::find(c); + if (!contact) throw love::Exception("A contact has escaped Memoizer!"); + luax_newtype(L, "Contact", PHYSICS_CONTACT_T, (void*)contact); + lua_rawseti(L, -1, i); + c = c->GetNext(); + } + return 1; + } + b2Body * World::getGroundBody() { return groundBody; diff --git a/src/modules/physics/box2d/World.h b/src/modules/physics/box2d/World.h index 76d84fd98..74987f84f 100644 --- a/src/modules/physics/box2d/World.h +++ b/src/modules/physics/box2d/World.h @@ -214,6 +214,30 @@ namespace box2d * @return The number of joints. **/ int getJointCount(); + + /** + * Get the current contact count. + * @return The number of contacts. + **/ + int getContactCount(); + + /** + * Get an array of all the Bodies in the World. + * @return An array of Bodies. + **/ + int getBodyList(lua_State * L); + + /** + * Get an array of all the Joints in the World. + * @return An array of Joints. + **/ + int getJointList(lua_State * L); + + /** + * Get an array of all the Contacts in the World. + * @return An array of Contacts. + **/ + int getContactList(lua_State * L); /** * Gets the ground body. diff --git a/src/modules/physics/box2d/wrap_World.cpp b/src/modules/physics/box2d/wrap_World.cpp index 9fe819f3f..2b60404a4 100644 --- a/src/modules/physics/box2d/wrap_World.cpp +++ b/src/modules/physics/box2d/wrap_World.cpp @@ -113,6 +113,34 @@ namespace box2d return 1; } + int w_World_getContactCount(lua_State * L) + { + World * t = luax_checkworld(L, 1); + lua_pushinteger(L, t->getContactCount()); + return 1; + } + + int w_World_getBodyList(lua_State * L) + { + World * t = luax_checkworld(L, 1); + lua_remove(L, 1); + return t->getBodyList(L); + } + + int w_World_getJointList(lua_State * L) + { + World * t = luax_checkworld(L, 1); + lua_remove(L, 1); + return t->getJointList(L); + } + + int w_World_getContactList(lua_State * L) + { + World * t = luax_checkworld(L, 1); + lua_remove(L, 1); + return t->getContactList(L); + } + int w_World_queryBoundingBox(lua_State * L) { World * t = luax_checkworld(L, 1); @@ -139,6 +167,10 @@ namespace box2d { "getAllowSleeping", w_World_getAllowSleeping }, { "getBodyCount", w_World_getBodyCount }, { "getJointCount", w_World_getJointCount }, + { "getContactCount", w_World_getContactCount }, + { "getBodyList", w_World_getBodyList }, + { "getJointList", w_World_getJointList }, + { "getContactList", w_World_getContactList }, { "queryBoundingBox", w_World_queryBoundingBox }, { "rayCast", w_World_rayCast }, { 0, 0 } diff --git a/src/modules/physics/box2d/wrap_World.h b/src/modules/physics/box2d/wrap_World.h index 3fddb8ec6..e2a10a19c 100644 --- a/src/modules/physics/box2d/wrap_World.h +++ b/src/modules/physics/box2d/wrap_World.h @@ -43,6 +43,10 @@ namespace box2d int w_World_getAllowSleeping(lua_State * L); int w_World_getBodyCount(lua_State * L); int w_World_getJointCount(lua_State * L); + int w_World_getContactCount(lua_State * L); + int w_World_getBodyList(lua_State * L); + int w_World_getJointList(lua_State * L); + int w_World_getContactList(lua_State * L); int w_World_queryBoundingBox(lua_State * L); int w_World_rayCast(lua_State * L); int luaopen_world(lua_State * L); From dd3993623bab5b55e99235deebebe95ec80ccdbb Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 16:59:45 -0400 Subject: [PATCH 52/78] Add World:isLocked and const-ify a few worthy methods --HG-- branch : box2d-update --- src/modules/physics/box2d/World.cpp | 19 ++++++++++++------- src/modules/physics/box2d/World.h | 21 ++++++++++++++------- src/modules/physics/box2d/wrap_World.cpp | 8 ++++++++ src/modules/physics/box2d/wrap_World.h | 1 + 4 files changed, 35 insertions(+), 14 deletions(-) diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index 699d1b3d1..303a70b17 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -341,23 +341,28 @@ namespace box2d { return world->GetAllowSleeping(); } + + bool World::isLocked() const + { + return world->IsLocked(); + } - int World::getBodyCount() + int World::getBodyCount() const { return world->GetBodyCount(); } - int World::getJointCount() + int World::getJointCount() const { return world->GetJointCount(); } - int World::getContactCount() + int World::getContactCount() const { return world->GetContactCount(); } - int World::getBodyList(lua_State * L) + int World::getBodyList(lua_State * L) const { lua_newtable(L); b2Body * b = world->GetBodyList(); @@ -372,7 +377,7 @@ namespace box2d return 1; } - int World::getJointList(lua_State * L) + int World::getJointList(lua_State * L) const { lua_newtable(L); b2Joint * j = world->GetJointList(); @@ -387,7 +392,7 @@ namespace box2d return 1; } - int World::getContactList(lua_State * L) + int World::getContactList(lua_State * L) const { lua_newtable(L); b2Contact * c = world->GetContactList(); @@ -402,7 +407,7 @@ namespace box2d return 1; } - b2Body * World::getGroundBody() + b2Body * World::getGroundBody() const { return groundBody; } diff --git a/src/modules/physics/box2d/World.h b/src/modules/physics/box2d/World.h index 74987f84f..7bd605f1a 100644 --- a/src/modules/physics/box2d/World.h +++ b/src/modules/physics/box2d/World.h @@ -202,48 +202,55 @@ namespace box2d * @return True if allowed, false if disallowed. **/ bool getAllowSleeping() const; + + /** + * Returns whether this World is currently locked. + * If it's locked, it's in the middle of a timestep. + * @return Whether the World is locked. + **/ + bool isLocked() const; /** * Get the current body count. * @return The number of bodies. **/ - int getBodyCount(); + int getBodyCount() const; /** * Get the current joint count. * @return The number of joints. **/ - int getJointCount(); + int getJointCount() const; /** * Get the current contact count. * @return The number of contacts. **/ - int getContactCount(); + int getContactCount() const; /** * Get an array of all the Bodies in the World. * @return An array of Bodies. **/ - int getBodyList(lua_State * L); + int getBodyList(lua_State * L) const; /** * Get an array of all the Joints in the World. * @return An array of Joints. **/ - int getJointList(lua_State * L); + int getJointList(lua_State * L) const; /** * Get an array of all the Contacts in the World. * @return An array of Contacts. **/ - int getContactList(lua_State * L); + int getContactList(lua_State * L) const; /** * Gets the ground body. * @return The ground body. **/ - b2Body * getGroundBody(); + b2Body * getGroundBody() const; /** * Gets all fixtures that overlap a given bounding box. diff --git a/src/modules/physics/box2d/wrap_World.cpp b/src/modules/physics/box2d/wrap_World.cpp index 2b60404a4..430f5ae9c 100644 --- a/src/modules/physics/box2d/wrap_World.cpp +++ b/src/modules/physics/box2d/wrap_World.cpp @@ -98,6 +98,13 @@ namespace box2d luax_pushboolean(L, t->getAllowSleeping()); return 1; } + + int w_World_isLocked(lua_State * L) + { + World * t = luax_checkworld(L, 1); + luax_pushboolean(L, t->isLocked()); + return 1; + } int w_World_getBodyCount(lua_State * L) { @@ -165,6 +172,7 @@ namespace box2d { "getGravity", w_World_getGravity }, { "setAllowSleeping", w_World_setAllowSleeping }, { "getAllowSleeping", w_World_getAllowSleeping }, + { "isLocked", w_World_isLocked }, { "getBodyCount", w_World_getBodyCount }, { "getJointCount", w_World_getJointCount }, { "getContactCount", w_World_getContactCount }, diff --git a/src/modules/physics/box2d/wrap_World.h b/src/modules/physics/box2d/wrap_World.h index e2a10a19c..3953bec83 100644 --- a/src/modules/physics/box2d/wrap_World.h +++ b/src/modules/physics/box2d/wrap_World.h @@ -41,6 +41,7 @@ namespace box2d int w_World_getGravity(lua_State * L); int w_World_setAllowSleeping(lua_State * L); int w_World_getAllowSleeping(lua_State * L); + int w_World_isLocked(lua_State * L); int w_World_getBodyCount(lua_State * L); int w_World_getJointCount(lua_State * L); int w_World_getContactCount(lua_State * L); From 15d2b7c63d157d6e0be0d1705fe32fc46694f2df Mon Sep 17 00:00:00 2001 From: Bart van Strien Date: Sat, 24 Sep 2011 23:07:02 +0200 Subject: [PATCH 53/78] Add Box2D include in linux build files --HG-- branch : box2d-update --- platform/unix/gen-makefile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/platform/unix/gen-makefile b/platform/unix/gen-makefile index e75836f01..4824822ca 100644 --- a/platform/unix/gen-makefile +++ b/platform/unix/gen-makefile @@ -3,7 +3,8 @@ echo Generating src/Makefile.am ... cd src inc_current=. inc_modules="$inc_current/modules" -echo "AM_CPPFLAGS = -I$inc_current -I$inc_modules -I/usr/include/AL -I/usr/include/freetype2 \$(INCLUDE_LUA) -I/usr/include/SDL \$(FILE_OFFSET) +inc_box2d="$inc_current/libraries/Box2D" +echo "AM_CPPFLAGS = -I$inc_current -I$inc_modules -I$inc_box2d -I/usr/include/AL -I/usr/include/freetype2 \$(INCLUDE_LUA) -I/usr/include/SDL \$(FILE_OFFSET) AUTOMAKE_OPTIONS = subdir-objects DEFAULT_INCLUDES = SUBDIRS = From 221d9699f67dfe642755135a7e3c153cbccecca8 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 17:12:45 -0400 Subject: [PATCH 54/78] Add Body:getFilterList --HG-- branch : box2d-update --- src/modules/physics/box2d/Body.cpp | 15 +++++++++++++++ src/modules/physics/box2d/Body.h | 7 +++++++ src/modules/physics/box2d/wrap_Body.cpp | 8 ++++++++ src/modules/physics/box2d/wrap_Body.h | 1 + 4 files changed, 31 insertions(+) diff --git a/src/modules/physics/box2d/Body.cpp b/src/modules/physics/box2d/Body.cpp index a5cba16ca..7f4786676 100644 --- a/src/modules/physics/box2d/Body.cpp +++ b/src/modules/physics/box2d/Body.cpp @@ -394,6 +394,21 @@ namespace box2d { return world; } + + int Body::getFixtureList(lua_State * L) const + { + lua_newtable(L); + b2Fixture * f = body->GetFixtureList(); + int i = 1; + do { + if (!f) break; + Fixture * fixture = (Fixture *)Memoizer::find(f); + if (!fixture) throw love::Exception("A fixture has escaped Memoizer!"); + luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)fixture); + lua_rawseti(L, -1, i); + } while ((f = f->GetNext())); + return 1; + } b2Vec2 Body::getVector(lua_State * L) { diff --git a/src/modules/physics/box2d/Body.h b/src/modules/physics/box2d/Body.h index 07c181365..f5b457bab 100644 --- a/src/modules/physics/box2d/Body.h +++ b/src/modules/physics/box2d/Body.h @@ -378,6 +378,13 @@ namespace box2d * Get the World this Body resides in. */ World * getWorld() const; + + /** + * Get an array of all the Fixtures attached to this Body. + * @return An array of Fixtures. + **/ + int getFixtureList(lua_State * L) const; + private: /** diff --git a/src/modules/physics/box2d/wrap_Body.cpp b/src/modules/physics/box2d/wrap_Body.cpp index 909f5e429..2e0413091 100644 --- a/src/modules/physics/box2d/wrap_Body.cpp +++ b/src/modules/physics/box2d/wrap_Body.cpp @@ -499,6 +499,13 @@ namespace box2d luax_pushboolean(L, b); return 1; } + + int w_Body_getFixtureList(lua_State * L) + { + Body * t = luax_checkbody(L, 1); + lua_remove(L, 1); + return t->getFixtureList(L); + } int w_Body_destroy(lua_State * L) { @@ -561,6 +568,7 @@ namespace box2d { "setAwake", w_Body_setAwake }, { "setFixedRotation", w_Body_setFixedRotation }, { "isFixedRotation", w_Body_isFixedRotation }, + { "getFixtureList", w_Body_getFixtureList }, { "destroy", w_Body_destroy }, { 0, 0 } }; diff --git a/src/modules/physics/box2d/wrap_Body.h b/src/modules/physics/box2d/wrap_Body.h index e7a8fe6e2..2d5ac84b6 100644 --- a/src/modules/physics/box2d/wrap_Body.h +++ b/src/modules/physics/box2d/wrap_Body.h @@ -82,6 +82,7 @@ namespace box2d int w_Body_setAwake(lua_State * L); int w_Body_setFixedRotation(lua_State * L); int w_Body_isFixedRotation(lua_State * L); + int w_Body_getFixtureList(lua_State * L); int w_Body_destroy(lua_State * L); int luaopen_body(lua_State * L); From 3bd2316c6c85aa6992fa8a90128fb213c30a6c72 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 17:14:03 -0400 Subject: [PATCH 55/78] Remove Fixture:getNext, it was just for testing --HG-- branch : box2d-update --- src/modules/physics/box2d/Fixture.cpp | 9 --------- src/modules/physics/box2d/Fixture.h | 5 ----- src/modules/physics/box2d/wrap_Fixture.cpp | 11 ----------- src/modules/physics/box2d/wrap_Fixture.h | 1 - 4 files changed, 26 deletions(-) diff --git a/src/modules/physics/box2d/Fixture.cpp b/src/modules/physics/box2d/Fixture.cpp index b07b98092..58cb74072 100644 --- a/src/modules/physics/box2d/Fixture.cpp +++ b/src/modules/physics/box2d/Fixture.cpp @@ -132,15 +132,6 @@ namespace box2d if (!s) s = new Shape(fixture->GetShape()); return s; } - - Fixture * Fixture::getNext() const - { - b2Fixture * f = fixture->GetNext(); - if (!f) return NULL; - Fixture * fix = (Fixture *)Memoizer::find(f); - if (!fix) fix = new Fixture(f); - return fix; - } void Fixture::setFilterData(int * v) { diff --git a/src/modules/physics/box2d/Fixture.h b/src/modules/physics/box2d/Fixture.h index 69734d770..a1060667b 100644 --- a/src/modules/physics/box2d/Fixture.h +++ b/src/modules/physics/box2d/Fixture.h @@ -105,11 +105,6 @@ namespace box2d **/ Body * getBody() const; - /** - * Gets the next Fixture attached to the parent Body. - **/ - Fixture * getNext() const; - /** * Sets the filter data. An integer array is used even though the * first two elements are unsigned shorts. The elements are: diff --git a/src/modules/physics/box2d/wrap_Fixture.cpp b/src/modules/physics/box2d/wrap_Fixture.cpp index c420f38e6..bc758f4db 100644 --- a/src/modules/physics/box2d/wrap_Fixture.cpp +++ b/src/modules/physics/box2d/wrap_Fixture.cpp @@ -122,16 +122,6 @@ namespace box2d luax_newtype(L, "Shape", PHYSICS_SHAPE_T, (void*)shape); return 1; } - - int w_Fixture_getNext(lua_State * L) - { - Fixture * t = luax_checkfixture(L, 1); - Fixture * f = t->getNext(); - if (f == 0) return 0; - f->retain(); - luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)f); - return 1; - } int w_Fixture_testPoint(lua_State * L) { @@ -264,7 +254,6 @@ namespace box2d { "getDensity", w_Fixture_getDensity }, { "getBody", w_Fixture_getBody }, { "getShape", w_Fixture_getShape }, - { "getNext", w_Fixture_getNext }, { "isSensor", w_Fixture_isSensor }, { "testPoint", w_Fixture_testPoint }, { "rayCast", w_Fixture_rayCast }, diff --git a/src/modules/physics/box2d/wrap_Fixture.h b/src/modules/physics/box2d/wrap_Fixture.h index 675ab7342..d41f6b25a 100644 --- a/src/modules/physics/box2d/wrap_Fixture.h +++ b/src/modules/physics/box2d/wrap_Fixture.h @@ -43,7 +43,6 @@ namespace box2d int w_Fixture_isSensor(lua_State * L); int w_Fixture_getBody(lua_State * L); int w_Fixture_getShape(lua_State * L); - int w_Fixture_getNext(lua_State * L); int w_Fixture_testPoint(lua_State * L); int w_Fixture_rayCast(lua_State * L); int w_Fixture_setFilterData(lua_State * L); From 680dd65c196aaa8268917adb0dc2c2b068ae72c9 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 17:29:42 -0400 Subject: [PATCH 56/78] Add love.physics.getDistance(fixtureA, fixtureB) - gets the distance between and the closest points of two fixtures --HG-- branch : box2d-update --- src/modules/physics/box2d/Fixture.h | 2 ++ src/modules/physics/box2d/Physics.cpp | 25 ++++++++++++++++++++++ src/modules/physics/box2d/Physics.h | 9 ++++++++ src/modules/physics/box2d/wrap_Physics.cpp | 5 +++++ src/modules/physics/box2d/wrap_Physics.h | 1 + 5 files changed, 42 insertions(+) diff --git a/src/modules/physics/box2d/Fixture.h b/src/modules/physics/box2d/Fixture.h index a1060667b..c3fdfb581 100644 --- a/src/modules/physics/box2d/Fixture.h +++ b/src/modules/physics/box2d/Fixture.h @@ -57,6 +57,8 @@ namespace box2d **/ class Fixture : public Object { + friend class Physics; + protected: Body * body; diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 9c76a7ff0..466c07fc3 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -208,6 +208,31 @@ namespace box2d return new Fixture(body, shape, density); } + int Physics::getDistance(lua_State * L) + { + Fixture * fixtureA = luax_checktype(L, 1, "Fixture", PHYSICS_FIXTURE_T); + Fixture * fixtureB = luax_checktype(L, 2, "Fixture", PHYSICS_FIXTURE_T); + b2DistanceInput i; + b2DistanceProxy pA; + pA.Set(fixtureA->fixture->GetShape(), 0); + b2DistanceProxy pB; + pB.Set(fixtureB->fixture->GetShape(), 0); + i.proxyA = pA; + i.proxyB = pB; + i.transformA = fixtureA->fixture->GetBody()->GetTransform(); + i.transformB = fixtureB->fixture->GetBody()->GetTransform(); + i.useRadii = true; + b2DistanceOutput o; + b2SimplexCache c; + b2Distance(&o, &c, &i); + lua_pushnumber(L, o.distance); + lua_pushnumber(L, Physics::scaleUp(o.pointA.x)); + lua_pushnumber(L, Physics::scaleUp(o.pointA.y)); + lua_pushnumber(L, Physics::scaleUp(o.pointB.x)); + lua_pushnumber(L, Physics::scaleUp(o.pointB.y)); + return 5; + } + void Physics::setMeter(int meter) { Physics::meter = meter; diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index b26f61e42..89ff428a5 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -258,6 +258,15 @@ namespace box2d Fixture * newFixture(Body * body, Shape * shape, float density); + /** + * Calculates the distance between two Fixtures. + * @param fixtureA The first Fixture. + * @param fixtureB The sceond Fixture. + * @return The distance between them, and the two points closest + * to each other. + **/ + int getDistance(lua_State * L); + /** * Sets the number of pixels in one meter. * @param pixels The number of pixels in one meter. (1m ~= 3.3ft). diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index e84839187..1b11e05ec 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -272,6 +272,11 @@ namespace box2d return 1; } + int w_getDistance(lua_State * L) + { + return instance->getDistance(L); + } + int w_setMeter(lua_State * L) { int arg1 = luaL_checkint(L, 1); diff --git a/src/modules/physics/box2d/wrap_Physics.h b/src/modules/physics/box2d/wrap_Physics.h index 8de805600..5a086b01e 100644 --- a/src/modules/physics/box2d/wrap_Physics.h +++ b/src/modules/physics/box2d/wrap_Physics.h @@ -69,6 +69,7 @@ namespace box2d int w_newWeldJoint(lua_State * L); int w_newWheelJoint(lua_State * L); int w_newRopeJoint(lua_State * L); + int w_getDistance(lua_State * L); int w_setMeter(lua_State * L); int w_getMeter(lua_State * L); extern "C" LOVE_EXPORT int luaopen_love_physics(lua_State * L); From 624e1bf8f5bdd1181d92cf7625963782a90251a8 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 24 Sep 2011 23:52:56 -0400 Subject: [PATCH 57/78] Missed a bunch of retain() calls --HG-- branch : box2d-update --- src/modules/physics/box2d/World.cpp | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index 303a70b17..0e097c781 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -79,8 +79,10 @@ namespace box2d // Push first fixture. { Fixture * a = (Fixture *)Memoizer::find(contacts[i]->contact->GetFixtureA()); - if(a != 0) + if(a != 0) { + a->retain(); luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)a); + } else throw love::Exception("A fixture has escaped Memoizer!"); } @@ -88,8 +90,10 @@ namespace box2d // Push second userdata. { Fixture * b = (Fixture *)Memoizer::find(contacts[i]->contact->GetFixtureB()); - if(b != 0) + if(b != 0) { + b->retain(); luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)b); + } else throw love::Exception("A fixture has escaped Memoizer!"); } @@ -162,6 +166,7 @@ namespace box2d ref->push(); Fixture * f = (Fixture *)Memoizer::find(fixture); if (!f) throw love::Exception("A fixture has escaped Memoizer!"); + f->retain(); luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)f); lua_call(L, 1, 1); return luax_toboolean(L, -1); @@ -188,6 +193,7 @@ namespace box2d ref->push(); Fixture * f = (Fixture *)Memoizer::find(fixture); if (!f) throw love::Exception("A fixture has escaped Memoizer!"); + f->retain(); luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)f); b2Vec2 scaledPoint = Physics::scaleUp(point); lua_pushnumber(L, scaledPoint.x); @@ -267,8 +273,10 @@ namespace box2d // Fixtures should be memoized, if we created them Fixture * a = (Fixture *)Memoizer::find(fixtureA); if (!a) throw love::Exception("A fixture has escaped Memoizer!"); + a->retain(); Fixture * b = (Fixture *)Memoizer::find(fixtureB); if (!b) throw love::Exception("A fixture has escaped Memoizer!"); + b->retain(); return filter.process(a, b); } @@ -370,6 +378,7 @@ namespace box2d if (!b) return 1; Body * body = (Body *)Memoizer::find(b); if (!body) throw love::Exception("A body has escaped Memoizer!"); + body->retain(); luax_newtype(L, "Body", PHYSICS_BODY_T, (void*)body); lua_rawseti(L, -1, i); b = b->GetNext(); @@ -385,6 +394,7 @@ namespace box2d if (!j) return 1; Joint * joint = (Joint *)Memoizer::find(j); if (!joint) throw love::Exception("A joint has escaped Memoizer!"); + joint->retain(); luax_newtype(L, "Joint", PHYSICS_JOINT_T, (void*)joint); lua_rawseti(L, -1, i); j = j->GetNext(); @@ -400,6 +410,7 @@ namespace box2d if (!c) return 1; Contact * contact = (Contact *)Memoizer::find(c); if (!contact) throw love::Exception("A contact has escaped Memoizer!"); + contact->retain(); luax_newtype(L, "Contact", PHYSICS_CONTACT_T, (void*)contact); lua_rawseti(L, -1, i); c = c->GetNext(); From 56ce9a2e170e575595ba4acd9ad2c7379c42b765 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 25 Sep 2011 11:21:05 -0400 Subject: [PATCH 58/78] Expose love.physics.getDistance --HG-- branch : box2d-update --- src/modules/physics/box2d/wrap_Physics.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index 1b11e05ec..7fc77dd57 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -310,6 +310,7 @@ namespace box2d { "newWeldJoint", w_newWeldJoint }, { "newWheelJoint", w_newWheelJoint }, { "newRopeJoint", w_newRopeJoint }, + { "getDistance", w_getDistance }, { "getMeter", w_getMeter }, { "setMeter", w_setMeter }, { 0, 0 }, From 5cd2ce05fd408c856d3fcaac2406c179fc73b2df Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 25 Sep 2011 11:30:58 -0400 Subject: [PATCH 59/78] Fix scaling errors with CircleShape's radius --HG-- branch : box2d-update --- src/modules/physics/box2d/CircleShape.cpp | 5 +++-- src/modules/physics/box2d/Physics.cpp | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/modules/physics/box2d/CircleShape.cpp b/src/modules/physics/box2d/CircleShape.cpp index a9123a3b9..09e03ab69 100644 --- a/src/modules/physics/box2d/CircleShape.cpp +++ b/src/modules/physics/box2d/CircleShape.cpp @@ -23,6 +23,7 @@ // Module #include "Body.h" #include "World.h" +#include "Physics.h" #include @@ -46,12 +47,12 @@ namespace box2d float CircleShape::getRadius() const { - return shape->m_radius; + return Physics::scaleUp(shape->m_radius); } void CircleShape::setRadius(float r) { - shape->m_radius = r; + shape->m_radius = Physics::scaleDown(r); } } // box2d diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 466c07fc3..7bfffec98 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -63,7 +63,7 @@ namespace box2d { b2CircleShape *s = new b2CircleShape(); s->m_p = Physics::scaleDown(b2Vec2(x, y)); - s->m_radius = radius; + s->m_radius = Physics::scaleDown(radius); return new CircleShape(s); } @@ -225,7 +225,7 @@ namespace box2d b2DistanceOutput o; b2SimplexCache c; b2Distance(&o, &c, &i); - lua_pushnumber(L, o.distance); + lua_pushnumber(L, Physics::scaleUp(o.distance)); lua_pushnumber(L, Physics::scaleUp(o.pointA.x)); lua_pushnumber(L, Physics::scaleUp(o.pointA.y)); lua_pushnumber(L, Physics::scaleUp(o.pointB.x)); From b6f3d2114f83495c7d00833f10adfe20caa8712a Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 25 Sep 2011 11:32:46 -0400 Subject: [PATCH 60/78] Remove legacy meter setting from love.physics.newWorld --HG-- branch : box2d-update --- src/modules/physics/box2d/Physics.cpp | 3 +-- src/modules/physics/box2d/Physics.h | 3 +-- src/modules/physics/box2d/wrap_Physics.cpp | 3 +-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 7bfffec98..e2e6be22e 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -38,9 +38,8 @@ namespace box2d return "love.physics.box2d"; } - World * Physics::newWorld(float gx, float gy, bool sleep, int meter) + World * Physics::newWorld(float gx, float gy, bool sleep) { - Physics::setMeter(meter); return new World(b2Vec2(gx, gy), sleep); } diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index 89ff428a5..127e28ec2 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -72,9 +72,8 @@ namespace box2d * @param gx Gravity along x-axis. * @param gy Gravity along y-axis. * @param sleep Whether the World allows sleep. - * @param meter The scale in px/m. **/ - World * newWorld(float gx, float gy, bool sleep, int meter); + World * newWorld(float gx, float gy, bool sleep); /** * Creates a new Body at the specified position. diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index 7fc77dd57..89d82424c 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -34,9 +34,8 @@ namespace box2d float gx = (float)luaL_optnumber(L, 1, 0); float gy = (float)luaL_optnumber(L, 2, 0); bool sleep = luax_optboolean(L, 3, true); - int meter = (int)luaL_optnumber(L, 4, Physics::DEFAULT_METER); - World * w = instance->newWorld(gx, gy, sleep, meter); + World * w = instance->newWorld(gx, gy, sleep); luax_newtype(L, "World", PHYSICS_WORLD_T, (void*)w); return 1; From 28c5982d92ad9c00344ddbad9bbd536786086dfe Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 25 Sep 2011 12:18:13 -0400 Subject: [PATCH 61/78] Fix table creation for getList() functions, and ignore the ground body --HG-- branch : box2d-update --- src/modules/physics/box2d/Body.cpp | 3 ++- src/modules/physics/box2d/World.cpp | 41 +++++++++++++++-------------- 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/src/modules/physics/box2d/Body.cpp b/src/modules/physics/box2d/Body.cpp index 7f4786676..8f64660f1 100644 --- a/src/modules/physics/box2d/Body.cpp +++ b/src/modules/physics/box2d/Body.cpp @@ -405,7 +405,8 @@ namespace box2d Fixture * fixture = (Fixture *)Memoizer::find(f); if (!fixture) throw love::Exception("A fixture has escaped Memoizer!"); luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)fixture); - lua_rawseti(L, -1, i); + lua_rawseti(L, -2, i); + i++; } while ((f = f->GetNext())); return 1; } diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index 0e097c781..c0ef5ebff 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -357,7 +357,7 @@ namespace box2d int World::getBodyCount() const { - return world->GetBodyCount(); + return world->GetBodyCount()-1; // ignore the ground body } int World::getJointCount() const @@ -374,15 +374,16 @@ namespace box2d { lua_newtable(L); b2Body * b = world->GetBodyList(); - for (int i = 1; i <= world->GetBodyCount(); i++) { - if (!b) return 1; + int i = 1; + do { + if (!b) break; + if (b == groundBody) continue; Body * body = (Body *)Memoizer::find(b); if (!body) throw love::Exception("A body has escaped Memoizer!"); - body->retain(); luax_newtype(L, "Body", PHYSICS_BODY_T, (void*)body); - lua_rawseti(L, -1, i); - b = b->GetNext(); - } + lua_rawseti(L, -2, i); + i++; + } while ((b = b->GetNext())); return 1; } @@ -390,15 +391,15 @@ namespace box2d { lua_newtable(L); b2Joint * j = world->GetJointList(); - for (int i = 1; i <= world->GetJointCount(); i++) { - if (!j) return 1; + int i = 1; + do { + if (!j) break; Joint * joint = (Joint *)Memoizer::find(j); if (!joint) throw love::Exception("A joint has escaped Memoizer!"); - joint->retain(); luax_newtype(L, "Joint", PHYSICS_JOINT_T, (void*)joint); - lua_rawseti(L, -1, i); - j = j->GetNext(); - } + lua_rawseti(L, -2, i); + i++; + } while ((j = j->GetNext())); return 1; } @@ -406,15 +407,15 @@ namespace box2d { lua_newtable(L); b2Contact * c = world->GetContactList(); - for (int i = 1; i <= world->GetContactCount(); i++) { - if (!c) return 1; - Contact * contact = (Contact *)Memoizer::find(c); + int i = 1; + do { + if (!c) break; + Contact * contact = (Contact *)Memoizer::find(c); if (!contact) throw love::Exception("A contact has escaped Memoizer!"); - contact->retain(); luax_newtype(L, "Contact", PHYSICS_CONTACT_T, (void*)contact); - lua_rawseti(L, -1, i); - c = c->GetNext(); - } + lua_rawseti(L, -2, i); + i++; + } while ((c = c->GetNext())); return 1; } From de908f335426af9b74ab9a8f5ac237fc5b8e9b62 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 25 Sep 2011 12:35:57 -0400 Subject: [PATCH 62/78] Missing retain() calls in get*List functions --HG-- branch : box2d-update --- src/modules/physics/box2d/Body.cpp | 1 + src/modules/physics/box2d/World.cpp | 3 +++ 2 files changed, 4 insertions(+) diff --git a/src/modules/physics/box2d/Body.cpp b/src/modules/physics/box2d/Body.cpp index 8f64660f1..44fb96eb5 100644 --- a/src/modules/physics/box2d/Body.cpp +++ b/src/modules/physics/box2d/Body.cpp @@ -404,6 +404,7 @@ namespace box2d if (!f) break; Fixture * fixture = (Fixture *)Memoizer::find(f); if (!fixture) throw love::Exception("A fixture has escaped Memoizer!"); + fixture->retain(); luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)fixture); lua_rawseti(L, -2, i); i++; diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index c0ef5ebff..4a81fc516 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -380,6 +380,7 @@ namespace box2d if (b == groundBody) continue; Body * body = (Body *)Memoizer::find(b); if (!body) throw love::Exception("A body has escaped Memoizer!"); + body->retain(); luax_newtype(L, "Body", PHYSICS_BODY_T, (void*)body); lua_rawseti(L, -2, i); i++; @@ -396,6 +397,7 @@ namespace box2d if (!j) break; Joint * joint = (Joint *)Memoizer::find(j); if (!joint) throw love::Exception("A joint has escaped Memoizer!"); + joint->retain(); luax_newtype(L, "Joint", PHYSICS_JOINT_T, (void*)joint); lua_rawseti(L, -2, i); i++; @@ -412,6 +414,7 @@ namespace box2d if (!c) break; Contact * contact = (Contact *)Memoizer::find(c); if (!contact) throw love::Exception("A contact has escaped Memoizer!"); + contact->retain(); luax_newtype(L, "Contact", PHYSICS_CONTACT_T, (void*)contact); lua_rawseti(L, -2, i); i++; From 80fb261b5ace1e2286ac8a374823435f373cfbf1 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 25 Sep 2011 22:29:30 -0400 Subject: [PATCH 63/78] Better ChainShape API consistency --HG-- branch : box2d-update --- src/modules/physics/box2d/ChainShape.cpp | 11 ++++++++--- src/modules/physics/box2d/ChainShape.h | 4 ++-- src/modules/physics/box2d/wrap_ChainShape.cpp | 17 +++++++---------- src/modules/physics/box2d/wrap_ChainShape.h | 4 ++-- 4 files changed, 19 insertions(+), 17 deletions(-) diff --git a/src/modules/physics/box2d/ChainShape.cpp b/src/modules/physics/box2d/ChainShape.cpp index 2f3a3a1ec..2839118c2 100644 --- a/src/modules/physics/box2d/ChainShape.cpp +++ b/src/modules/physics/box2d/ChainShape.cpp @@ -72,7 +72,12 @@ namespace box2d b2ChainShape * c = (b2ChainShape *)shape; b2EdgeShape e; c->GetChildEdge(&e, index); - return new EdgeShape(&e); + EdgeShape * edge = (EdgeShape *)Memoizer::find(&e); + if (!edge) return new EdgeShape(&e); + else { + edge->retain(); + return edge; + } } int ChainShape::getChildCount() const @@ -87,14 +92,14 @@ namespace box2d return c->m_count; } - b2Vec2 ChainShape::getVertex(int index) const + b2Vec2 ChainShape::getPoint(int index) const { b2ChainShape * c = (b2ChainShape *)shape; const b2Vec2 & v = c->m_vertices[index]; return Physics::scaleUp(v); } - const b2Vec2 * ChainShape::getVertices() const + const b2Vec2 * ChainShape::getPoints() const { b2ChainShape * c = (b2ChainShape *)shape; return c->m_vertices; diff --git a/src/modules/physics/box2d/ChainShape.h b/src/modules/physics/box2d/ChainShape.h index ccabc2e08..6668de47b 100644 --- a/src/modules/physics/box2d/ChainShape.h +++ b/src/modules/physics/box2d/ChainShape.h @@ -89,13 +89,13 @@ namespace box2d * @param index The index of the vertex. * @returns The specified vertex. **/ - b2Vec2 getVertex(int index) const; + b2Vec2 getPoint(int index) const; /** * Returns all of the vertices. * @returns The vertices the shape comprises. **/ - const b2Vec2 * getVertices() const; + const b2Vec2 * getPoints() const; }; diff --git a/src/modules/physics/box2d/wrap_ChainShape.cpp b/src/modules/physics/box2d/wrap_ChainShape.cpp index ef5195cfe..22114ee54 100644 --- a/src/modules/physics/box2d/wrap_ChainShape.cpp +++ b/src/modules/physics/box2d/wrap_ChainShape.cpp @@ -74,30 +74,27 @@ namespace box2d return 1; } - int w_ChainShape_getVertex(lua_State * L) + int w_ChainShape_getPoint(lua_State * L) { ChainShape * c = luax_checkchainshape(L, 1); int index = luaL_checkint(L, 2); - b2Vec2 v = c->getVertex(index); + b2Vec2 v = c->getPoint(index); lua_pushnumber(L, v.x); lua_pushnumber(L, v.y); return 2; } - int w_ChainShape_getVertices(lua_State * L) + int w_ChainShape_getPoints(lua_State * L) { ChainShape * c = luax_checkchainshape(L, 1); - const b2Vec2 * verts = c->getVertices(); + const b2Vec2 * verts = c->getPoints(); int count = c->getVertexCount(); - lua_createtable(L, count*2, 0); for (int i = 0; i < count; i++) { b2Vec2 v = Physics::scaleUp(verts[i]); lua_pushnumber(L, v.x); - lua_rawseti(L, -2, i*2+1); lua_pushnumber(L, v.y); - lua_rawseti(L, -2, i*2+2); } - return 1; + return count*2; } static const luaL_Reg functions[] = { @@ -106,8 +103,8 @@ namespace box2d { "getChildCount", w_ChainShape_getChildCount }, { "getChildEdge", w_ChainShape_getChildEdge }, { "getVertexCount", w_ChainShape_getVertexCount }, - { "getVertex", w_ChainShape_getVertex }, - { "getVertices", w_ChainShape_getVertices }, + { "getPoint", w_ChainShape_getPoint }, + { "getPoints", w_ChainShape_getPoints }, // From Shape. { "getType", w_Shape_getType }, { "getRadius", w_Shape_getRadius }, diff --git a/src/modules/physics/box2d/wrap_ChainShape.h b/src/modules/physics/box2d/wrap_ChainShape.h index ae81e4ba8..4e29e0b0b 100644 --- a/src/modules/physics/box2d/wrap_ChainShape.h +++ b/src/modules/physics/box2d/wrap_ChainShape.h @@ -39,8 +39,8 @@ namespace box2d int w_ChainShape_getChildCount(lua_State * L); int w_ChainShape_getChildEdge(lua_State * L); int w_ChainShape_getVertexCount(lua_State * L); - int w_ChainShape_getVertex(lua_State * L); - int w_ChainShape_getVertices(lua_State * L); + int w_ChainShape_getPoint(lua_State * L); + int w_ChainShape_getPoints(lua_State * L); int luaopen_chainshape(lua_State * L); From 5886977baa7d458183d3192c8ec22235225bec17 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Mon, 26 Sep 2011 11:20:26 -0400 Subject: [PATCH 64/78] Fix World:getCallbacks/getContactFilter to not return any arguments passed (though you shouldn't be passing any arguments anyway, that's silly) --HG-- branch : box2d-update --- src/modules/physics/box2d/World.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index 4a81fc516..dfac1a5e1 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -310,7 +310,7 @@ namespace box2d end.ref ? end.ref->push() : lua_pushnil(L); presolve.ref ? presolve.ref->push() : lua_pushnil(L); postsolve.ref ? postsolve.ref->push() : lua_pushnil(L); - return lua_gettop(L); + return 4; } int World::setContactFilter(lua_State * L) @@ -324,7 +324,7 @@ namespace box2d int World::getContactFilter(lua_State * L) { filter.ref ? filter.ref->push() : lua_pushnil(L); - return lua_gettop(L); + return 1; } void World::setGravity(float x, float y) From 413f5026fac1c2f47515854da9ec81d583f937dc Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Mon, 26 Sep 2011 19:13:44 -0300 Subject: [PATCH 65/78] Fix invalid pointer issue in PostSolve callback --HG-- branch : box2d-update --- src/modules/physics/box2d/World.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index dfac1a5e1..f6c2f8368 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -61,7 +61,15 @@ namespace box2d { if(ref != 0) { contacts.push_back(new Contact(contact)); - impulses.push_back(impulse); + // copy the impulse struct + b2ContactImpulse * i = new b2ContactImpulse(); + i->normalImpulses[0] = impulse->normalImpulses[0]; + i->normalImpulses[1] = impulse->normalImpulses[1]; + i->tangentImpulses[0] = impulse->tangentImpulses[0]; + i->tangentImpulses[1] = impulse->tangentImpulses[1]; + i->count = impulse->count; + + impulses.push_back(i); } } @@ -117,6 +125,8 @@ namespace box2d delete contacts[i]; contacts.clear(); // Clear impulses. + for(int i = 0;i<(int)impulses.size();i++) + delete impulses[i]; impulses.clear(); } From 16fb73e92a2b747eb06f22134065d02f02e539e4 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Mon, 26 Sep 2011 20:22:03 -0400 Subject: [PATCH 66/78] Callbacks now actually fire when they're supposed to, instead of post-step (means PreSolve collision filtering works) --HG-- branch : box2d-update --- src/modules/physics/box2d/World.cpp | 121 +++++++++------------------- src/modules/physics/box2d/World.h | 8 +- 2 files changed, 39 insertions(+), 90 deletions(-) diff --git a/src/modules/physics/box2d/World.cpp b/src/modules/physics/box2d/World.cpp index f6c2f8368..e35b4b5d6 100644 --- a/src/modules/physics/box2d/World.cpp +++ b/src/modules/physics/box2d/World.cpp @@ -44,90 +44,50 @@ namespace box2d if(ref != 0) delete ref; } - - void World::ContactCallback::add(b2Contact* contact) - { - /** - * We must copy contacts, since we're not allowed to process - * them inside this function. Removing bodies in this function - * pretty much guarantees segfault. ^^ - **/ - - if(ref != 0) - contacts.push_back(new Contact(contact)); - } - void World::ContactCallback::add(b2Contact* contact, const b2ContactImpulse* impulse) - { - if(ref != 0) { - contacts.push_back(new Contact(contact)); - // copy the impulse struct - b2ContactImpulse * i = new b2ContactImpulse(); - i->normalImpulses[0] = impulse->normalImpulses[0]; - i->normalImpulses[1] = impulse->normalImpulses[1]; - i->tangentImpulses[0] = impulse->tangentImpulses[0]; - i->tangentImpulses[1] = impulse->tangentImpulses[1]; - i->count = impulse->count; - - impulses.push_back(i); - } - } - - void World::ContactCallback::process() + void World::ContactCallback::process(b2Contact* contact, const b2ContactImpulse* impulse) { // Process contacts. if(ref != 0) { lua_State * L = ref->getL(); - for(int i = 0;i<(int)contacts.size();i++) + ref->push(); + + // Push first fixture. { - // Push the function. - ref->push(); - - // Push first fixture. - { - Fixture * a = (Fixture *)Memoizer::find(contacts[i]->contact->GetFixtureA()); - if(a != 0) { - a->retain(); - luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)a); - } - else - throw love::Exception("A fixture has escaped Memoizer!"); + Fixture * a = (Fixture *)Memoizer::find(contact->GetFixtureA()); + if(a != 0) { + a->retain(); + luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)a); } - - // Push second userdata. - { - Fixture * b = (Fixture *)Memoizer::find(contacts[i]->contact->GetFixtureB()); - if(b != 0) { - b->retain(); - luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)b); - } - else - throw love::Exception("A fixture has escaped Memoizer!"); - } - - luax_newtype(L, "Contact", (PHYSICS_CONTACT_T), (void*)contacts[i], false); - - int args = 3; - if ((int)impulses.size() > i) { - const b2ContactImpulse * impulse = impulses[i]; - for (int c = 0; c < impulse->count; c++) { - lua_pushnumber(L, Physics::scaleUp(impulse->normalImpulses[c])); - lua_pushnumber(L, Physics::scaleUp(impulse->tangentImpulses[c])); - args += 2; - } - } - lua_call(L, args, 0); + else + throw love::Exception("A fixture has escaped Memoizer!"); } - // Clear contacts. - for(int i = 0;i<(int)contacts.size();i++) - delete contacts[i]; - contacts.clear(); - // Clear impulses. - for(int i = 0;i<(int)impulses.size();i++) - delete impulses[i]; - impulses.clear(); + // Push second userdata. + { + Fixture * b = (Fixture *)Memoizer::find(contact->GetFixtureB()); + if(b != 0) { + b->retain(); + luax_newtype(L, "Fixture", PHYSICS_FIXTURE_T, (void*)b); + } + else + throw love::Exception("A fixture has escaped Memoizer!"); + } + + Contact * c = new Contact(contact); + + luax_newtype(L, "Contact", (PHYSICS_CONTACT_T), (void*)c, false); + + int args = 3; + if (impulse) { + for (int c = 0; c < impulse->count; c++) { + lua_pushnumber(L, Physics::scaleUp(impulse->normalImpulses[c])); + lua_pushnumber(L, Physics::scaleUp(impulse->tangentImpulses[c])); + args += 2; + } + } + lua_call(L, args, 0); } } @@ -250,32 +210,27 @@ namespace box2d void World::update(float dt) { world->Step(dt, 8, 6); - - begin.process(); - end.process(); - presolve.process(); - postsolve.process(); } void World::BeginContact(b2Contact* contact) { - begin.add(contact); + begin.process(contact); } void World::EndContact(b2Contact* contact) { - end.add(contact); + end.process(contact); } void World::PreSolve(b2Contact* contact, const b2Manifold* oldManifold) { B2_NOT_USED(oldManifold); // not sure what to do with this - presolve.add(contact); + presolve.process(contact); } void World::PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) { - postsolve.add(contact, impulse); + postsolve.process(contact, impulse); } bool World::ShouldCollide(b2Fixture * fixtureA, b2Fixture * fixtureB) diff --git a/src/modules/physics/box2d/World.h b/src/modules/physics/box2d/World.h index 7bd605f1a..fc6d3aca8 100644 --- a/src/modules/physics/box2d/World.h +++ b/src/modules/physics/box2d/World.h @@ -67,15 +67,9 @@ namespace box2d { public: Reference * ref; - std::vector contacts; - std::vector impulses; - b2Manifold* oldManifold; - b2ContactImpulse* impulse; ContactCallback(); ~ContactCallback(); - void add(b2Contact* contact); - void add(b2Contact* contact, const b2ContactImpulse* impulse); - void process(); + void process(b2Contact* contact, const b2ContactImpulse* impulse = NULL); }; class ContactFilter From 356b3c880d9e98e4b01ff74513c23497a48f33c8 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Mon, 26 Sep 2011 21:35:44 -0400 Subject: [PATCH 67/78] Fixture:getShape() returns a Shape of the type it actually is --HG-- branch : box2d-update --- src/modules/physics/box2d/CircleShape.h | 2 +- src/modules/physics/box2d/wrap_Fixture.cpp | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/modules/physics/box2d/CircleShape.h b/src/modules/physics/box2d/CircleShape.h index a48becb06..2b75dff8d 100644 --- a/src/modules/physics/box2d/CircleShape.h +++ b/src/modules/physics/box2d/CircleShape.h @@ -59,7 +59,7 @@ namespace box2d float getRadius() const; /** - * Gets the radius for the circle. + * Sets the radius for the circle. **/ void setRadius(float r); }; diff --git a/src/modules/physics/box2d/wrap_Fixture.cpp b/src/modules/physics/box2d/wrap_Fixture.cpp index bc758f4db..61de81111 100644 --- a/src/modules/physics/box2d/wrap_Fixture.cpp +++ b/src/modules/physics/box2d/wrap_Fixture.cpp @@ -119,7 +119,23 @@ namespace box2d if(shape == 0) return 0; shape->retain(); - luax_newtype(L, "Shape", PHYSICS_SHAPE_T, (void*)shape); + switch (shape->getType()) { + case Shape::SHAPE_EDGE: + luax_newtype(L, "EdgeShape", PHYSICS_EDGE_SHAPE_T, (void*)shape); + break; + case Shape::SHAPE_CHAIN: + luax_newtype(L, "ChainShape", PHYSICS_CHAIN_SHAPE_T, (void*)shape); + break; + case Shape::SHAPE_CIRCLE: + luax_newtype(L, "CircleShape", PHYSICS_CIRCLE_SHAPE_T, (void*)shape); + break; + case Shape::SHAPE_POLYGON: + luax_newtype(L, "PolygonShape", PHYSICS_POLYGON_SHAPE_T, (void*)shape); + break; + default: + luax_newtype(L, "Shape", PHYSICS_SHAPE_T, (void*)shape); + break; + } return 1; } From 5244463109b99d41dd5bf00a75b67ec3ec48ae1b Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Tue, 27 Sep 2011 15:48:29 -0400 Subject: [PATCH 68/78] Add second body anchor point as a parameter to love.physics.newPrismaticJoint, and fix some scaling issues with PrismaticJoint --HG-- branch : box2d-update --- src/modules/physics/box2d/Physics.cpp | 4 ++-- src/modules/physics/box2d/Physics.h | 8 ++++--- src/modules/physics/box2d/PrismaticJoint.cpp | 9 ++++---- src/modules/physics/box2d/PrismaticJoint.h | 2 +- src/modules/physics/box2d/wrap_Physics.cpp | 24 +++++++++++++++----- 5 files changed, 31 insertions(+), 16 deletions(-) diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index e2e6be22e..7720b92ea 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -167,9 +167,9 @@ namespace box2d return new RevoluteJoint(body1, body2, x, y, collideConnected); } - PrismaticJoint * Physics::newPrismaticJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected) + PrismaticJoint * Physics::newPrismaticJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, float ax, float ay, bool collideConnected) { - return new PrismaticJoint(body1, body2, x, y, ax, ay, collideConnected); + return new PrismaticJoint(body1, body2, xA, yA, xB, yB, ax, ay, collideConnected); } PulleyJoint * Physics::newPulleyJoint(Body * body1, Body * body2, b2Vec2 groundAnchor1, b2Vec2 groundAnchor2, b2Vec2 anchor1, b2Vec2 anchor2, float ratio, bool collideConnected) diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index 127e28ec2..96ed7989a 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -183,13 +183,15 @@ namespace box2d /** * Creates a new PrismaticJoint connecting body1 with body2. - * @param x World-anchor along the x-axis. - * @param y World-anchor along the y-axis. + * @param xA World-anchor for body1 along the x-axis. + * @param yA World-anchor for body1 along the y-axis. + * @param xB World-anchor for body2 along the x-axis. + * @param yB World-anchor for body2 along the y-axis. * @param ax The x-component of the world-axis. * @param ay The y-component of the world-axis. * @param collideConnected Whether the connected bodies should collide with each other. Defaults to false. **/ - PrismaticJoint * newPrismaticJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected); + PrismaticJoint * newPrismaticJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, float ax, float ay, bool collideConnected); /** * Creates a new PulleyJoint connecting body1 with body2. diff --git a/src/modules/physics/box2d/PrismaticJoint.cpp b/src/modules/physics/box2d/PrismaticJoint.cpp index 17b6b1c7e..276cb5493 100644 --- a/src/modules/physics/box2d/PrismaticJoint.cpp +++ b/src/modules/physics/box2d/PrismaticJoint.cpp @@ -31,12 +31,13 @@ namespace physics { namespace box2d { - PrismaticJoint::PrismaticJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected) + PrismaticJoint::PrismaticJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, float ax, float ay, bool collideConnected) : Joint(body1, body2), joint(NULL) { b2PrismaticJointDef def; - def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(x,y)), b2Vec2(ax,ay)); + def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(xA,yA)), b2Vec2(ax,ay)); + def.localAnchorB = body2->body->GetLocalPoint(Physics::scaleDown(b2Vec2(xB, yB))); def.lowerTranslation = 0.0f; def.upperTranslation = 100.0f; def.enableLimit = true; @@ -52,12 +53,12 @@ namespace box2d float PrismaticJoint::getJointTranslation() const { - return Physics::scaleDown(joint->GetJointTranslation()); + return Physics::scaleUp(joint->GetJointTranslation()); } float PrismaticJoint::getJointSpeed() const { - return Physics::scaleDown(joint->GetJointSpeed()); + return Physics::scaleUp(joint->GetJointSpeed()); } void PrismaticJoint::enableMotor(bool motor) diff --git a/src/modules/physics/box2d/PrismaticJoint.h b/src/modules/physics/box2d/PrismaticJoint.h index 5e0c39222..b7c5efeec 100644 --- a/src/modules/physics/box2d/PrismaticJoint.h +++ b/src/modules/physics/box2d/PrismaticJoint.h @@ -46,7 +46,7 @@ namespace box2d /** * Creates a new PrismaticJoint connecting body1 and body2. **/ - PrismaticJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected); + PrismaticJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, float ax, float ay, bool collideConnected); virtual ~PrismaticJoint(); diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index 89d82424c..dd422f579 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -176,12 +176,24 @@ namespace box2d { Body * body1 = luax_checktype(L, 1, "Body", PHYSICS_BODY_T); Body * body2 = luax_checktype(L, 2, "Body", PHYSICS_BODY_T); - float x = (float)luaL_checknumber(L, 3); - float y = (float)luaL_checknumber(L, 4); - float ax = (float)luaL_checknumber(L, 5); - float ay = (float)luaL_checknumber(L, 6); - bool collideConnected = luax_optboolean(L, 7, false); - PrismaticJoint * j = instance->newPrismaticJoint(body1, body2, x, y, ax, ay, collideConnected); + float xA = (float)luaL_checknumber(L, 3); + float yA = (float)luaL_checknumber(L, 4); + float xB, yB, ax, ay; + bool collideConnected; + if (lua_gettop(L) >= 8) { + xB = (float)luaL_checknumber(L, 5); + yB = (float)luaL_checknumber(L, 6); + ax = (float)luaL_checknumber(L, 7); + ay = (float)luaL_checknumber(L, 8); + collideConnected = luax_optboolean(L, 9, false); + } else { + xB = xA; + yB = yA; + ax = (float)luaL_checknumber(L, 5); + ay = (float)luaL_checknumber(L, 6); + collideConnected = luax_optboolean(L, 7, false); + } + PrismaticJoint * j = instance->newPrismaticJoint(body1, body2, xA, yA, xB, yB, ax, ay, collideConnected); luax_newtype(L, "PrismaticJoint", PHYSICS_PRISMATIC_JOINT_T, (void*)j); return 1; } From d4703960a44baf08bab489d88e8c3ea776528c04 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Tue, 27 Sep 2011 16:38:46 -0400 Subject: [PATCH 69/78] Do the same for WheelJoint --HG-- branch : box2d-update --- src/modules/physics/box2d/Physics.cpp | 4 ++-- src/modules/physics/box2d/Physics.h | 8 ++++--- src/modules/physics/box2d/WheelJoint.cpp | 9 ++++---- src/modules/physics/box2d/WheelJoint.h | 2 +- src/modules/physics/box2d/wrap_Physics.cpp | 25 ++++++++++++++++------ 5 files changed, 32 insertions(+), 16 deletions(-) diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 7720b92ea..7ba45f241 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -192,9 +192,9 @@ namespace box2d return new WeldJoint(body1, body2, x, y, collideConnected); } - WheelJoint * Physics::newWheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected) + WheelJoint * Physics::newWheelJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, float ax, float ay, bool collideConnected) { - return new WheelJoint(body1, body2, x, y, ax, ay, collideConnected); + return new WheelJoint(body1, body2, xA, yA, xB, yB, ax, ay, collideConnected); } RopeJoint * Physics::newRopeJoint(Body * body1, Body * body2, float x1, float y1, float x2, float y2, float maxLength, bool collideConnected) diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index 96ed7989a..2c4491d3f 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -231,13 +231,15 @@ namespace box2d /** * Creates a new WheelJoint connecting body1 with body2. - * @param x Anchor along the x-axis. (World coordinates) - * @param y Anchor along the y-axis. (World coordinates) + * @param xA Anchor for body 1 along the x-axis. (World coordinates) + * @param yA Anchor for body 1 along the y-axis. (World coordinates) + * @param xB Anchor for body 2 along the x-axis. (World coordinates) + * @param yB Anchor for body 2 along the y-axis. (World coordinates) * @param ax The x-component of the world-axis. * @param ay The y-component of the world-axis. * @param collideConnected Whether the connected bodies should collide with each other. Defaults to false. **/ - WheelJoint * newWheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected); + WheelJoint * newWheelJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, float ax, float ay, bool collideConnected); /** * Creates a new RopeJoint connecting body1 with body2. diff --git a/src/modules/physics/box2d/WheelJoint.cpp b/src/modules/physics/box2d/WheelJoint.cpp index 93e59a910..2a7fb7317 100644 --- a/src/modules/physics/box2d/WheelJoint.cpp +++ b/src/modules/physics/box2d/WheelJoint.cpp @@ -31,12 +31,13 @@ namespace physics { namespace box2d { - WheelJoint::WheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected) + WheelJoint::WheelJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, float ax, float ay, bool collideConnected) : Joint(body1, body2), joint(NULL) { b2WheelJointDef def; - def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(x,y)), b2Vec2(ax,ay)); + def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(xA,yA)), b2Vec2(ax,ay)); + def.localAnchorB = body2->body->GetLocalPoint(Physics::scaleDown(b2Vec2(xB, yB))); def.collideConnected = collideConnected; joint = (b2WheelJoint*)createJoint(&def); } @@ -49,12 +50,12 @@ namespace box2d float WheelJoint::getJointTranslation() const { - return Physics::scaleDown(joint->GetJointTranslation()); + return Physics::scaleUp(joint->GetJointTranslation()); } float WheelJoint::getJointSpeed() const { - return Physics::scaleDown(joint->GetJointSpeed()); + return Physics::scaleUp(joint->GetJointSpeed()); } void WheelJoint::enableMotor(bool motor) diff --git a/src/modules/physics/box2d/WheelJoint.h b/src/modules/physics/box2d/WheelJoint.h index eb4053636..2f50b14fc 100644 --- a/src/modules/physics/box2d/WheelJoint.h +++ b/src/modules/physics/box2d/WheelJoint.h @@ -47,7 +47,7 @@ namespace box2d /** * Creates a new WheelJoint connecting body1 and body2. **/ - WheelJoint(Body * body1, Body * body2, float x, float y, float ax, float ay, bool collideConnected); + WheelJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, float ax, float ay, bool collideConnected); virtual ~WheelJoint(); diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index dd422f579..0d7f409bc 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -258,12 +258,25 @@ namespace box2d { Body * body1 = luax_checktype(L, 1, "Body", PHYSICS_BODY_T); Body * body2 = luax_checktype(L, 2, "Body", PHYSICS_BODY_T); - float x = (float)luaL_checknumber(L, 3); - float y = (float)luaL_checknumber(L, 4); - float ax = (float)luaL_checknumber(L, 5); - float ay = (float)luaL_checknumber(L, 6); - bool collideConnected = luax_optboolean(L, 7, false); - WheelJoint * j = instance->newWheelJoint(body1, body2, x, y, ax, ay, collideConnected); + float xA = (float)luaL_checknumber(L, 3); + float yA = (float)luaL_checknumber(L, 4); + float xB, yB, ax, ay; + bool collideConnected; + if (lua_gettop(L) >= 8) { + xB = (float)luaL_checknumber(L, 5); + yB = (float)luaL_checknumber(L, 6); + ax = (float)luaL_checknumber(L, 7); + ay = (float)luaL_checknumber(L, 8); + collideConnected = luax_optboolean(L, 9, false); + } else { + xB = xA; + yB = yA; + ax = (float)luaL_checknumber(L, 5); + ay = (float)luaL_checknumber(L, 6); + collideConnected = luax_optboolean(L, 7, false); + } + + WheelJoint * j = instance->newWheelJoint(body1, body2, xA, yA, xB, yB, ax, ay, collideConnected); luax_newtype(L, "WheelJoint", PHYSICS_WHEEL_JOINT_T, (void*)j); return 1; } From c5cd6d709bf3432bee0b1cfedd70eaac42011a08 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Thu, 29 Sep 2011 11:09:08 -0400 Subject: [PATCH 70/78] Fix a lot of scaling issues --HG-- branch : box2d-update --- src/modules/physics/box2d/Body.cpp | 10 ++++++---- src/modules/physics/box2d/FrictionJoint.cpp | 8 ++++---- src/modules/physics/box2d/Joint.cpp | 4 ++-- src/modules/physics/box2d/MouseJoint.cpp | 4 ++-- src/modules/physics/box2d/RevoluteJoint.cpp | 4 ++-- src/modules/physics/box2d/RevoluteJoint.h | 4 ++-- src/modules/physics/box2d/WheelJoint.cpp | 18 +++++++++--------- 7 files changed, 27 insertions(+), 25 deletions(-) diff --git a/src/modules/physics/box2d/Body.cpp b/src/modules/physics/box2d/Body.cpp index 44fb96eb5..22d38f4e2 100644 --- a/src/modules/physics/box2d/Body.cpp +++ b/src/modules/physics/box2d/Body.cpp @@ -176,22 +176,24 @@ namespace box2d void Body::applyAngularImpulse(float impulse) { - body->ApplyAngularImpulse(Physics::scaleDown(impulse)); + // Angular impulse is in kg*m^2/s, meaning it needs to be scaled twice + body->ApplyAngularImpulse(Physics::scaleDown(Physics::scaleDown(impulse))); } void Body::applyTorque(float t) { - body->ApplyTorque(t); + // Torque is in N*m, or kg*m^2/s^2, meaning it also needs to be scaled twice + body->ApplyTorque(Physics::scaleDown(Physics::scaleDown(t))); } void Body::applyForce(float fx, float fy, float rx, float ry) { - body->ApplyForce(b2Vec2(fx, fy), Physics::scaleDown(b2Vec2(rx, ry))); + body->ApplyForce(Physics::scaleDown(b2Vec2(fx, fy)), Physics::scaleDown(b2Vec2(rx, ry))); } void Body::applyForce(float fx, float fy) { - body->ApplyForce(b2Vec2(fx, fy), body->GetWorldCenter()); + body->ApplyForce(Physics::scaleDown(b2Vec2(fx, fy)), body->GetWorldCenter()); } void Body::setX(float x) diff --git a/src/modules/physics/box2d/FrictionJoint.cpp b/src/modules/physics/box2d/FrictionJoint.cpp index 699bd478a..7449aab19 100644 --- a/src/modules/physics/box2d/FrictionJoint.cpp +++ b/src/modules/physics/box2d/FrictionJoint.cpp @@ -50,22 +50,22 @@ namespace box2d void FrictionJoint::setMaxForce(float force) { - joint->SetMaxForce(force); + joint->SetMaxForce(Physics::scaleDown(force)); } float FrictionJoint::getMaxForce() const { - return joint->GetMaxForce(); + return Physics::scaleUp(joint->GetMaxForce()); } void FrictionJoint::setMaxTorque(float torque) { - joint->SetMaxTorque(torque); + joint->SetMaxTorque(Physics::scaleDown(Physics::scaleDown(torque))); } float FrictionJoint::getMaxTorque() const { - return joint->GetMaxTorque(); + return Physics::scaleUp(Physics::scaleUp(joint->GetMaxTorque())); } diff --git a/src/modules/physics/box2d/Joint.cpp b/src/modules/physics/box2d/Joint.cpp index 1aa48f00d..13a29f18a 100644 --- a/src/modules/physics/box2d/Joint.cpp +++ b/src/modules/physics/box2d/Joint.cpp @@ -98,7 +98,7 @@ namespace box2d int Joint::getReactionForce(lua_State * L) { float dt = (float)luaL_checknumber(L, 2); - b2Vec2 v = joint->GetReactionForce(dt); + b2Vec2 v = Physics::scaleUp(joint->GetReactionForce(dt)); lua_pushnumber(L, v.x); lua_pushnumber(L, v.y); return 2; @@ -106,7 +106,7 @@ namespace box2d float Joint::getReactionTorque(float dt) { - return joint->GetReactionTorque(dt); + return Physics::scaleUp(Physics::scaleUp(joint->GetReactionTorque(dt))); } b2Joint * Joint::createJoint(b2JointDef * def) diff --git a/src/modules/physics/box2d/MouseJoint.cpp b/src/modules/physics/box2d/MouseJoint.cpp index 9ea217b6f..b800645c8 100644 --- a/src/modules/physics/box2d/MouseJoint.cpp +++ b/src/modules/physics/box2d/MouseJoint.cpp @@ -63,12 +63,12 @@ namespace box2d void MouseJoint::setMaxForce(float force) { - joint->SetMaxForce(force); + joint->SetMaxForce(Physics::scaleDown(force)); } float MouseJoint::getMaxForce() const { - return joint->GetMaxForce(); + return Physics::scaleUp(joint->GetMaxForce()); } void MouseJoint::setFrequency(float hz) diff --git a/src/modules/physics/box2d/RevoluteJoint.cpp b/src/modules/physics/box2d/RevoluteJoint.cpp index a80ffe303..45b66856d 100644 --- a/src/modules/physics/box2d/RevoluteJoint.cpp +++ b/src/modules/physics/box2d/RevoluteJoint.cpp @@ -70,7 +70,7 @@ namespace box2d void RevoluteJoint::setMaxMotorTorque(float torque) { - joint->SetMaxMotorTorque(torque); + joint->SetMaxMotorTorque(Physics::scaleDown(Physics::scaleDown(torque))); } void RevoluteJoint::setMotorSpeed(float speed) @@ -85,7 +85,7 @@ namespace box2d float RevoluteJoint::getMotorTorque(float inv_dt) const { - return joint->GetMotorTorque(inv_dt); + return Physics::scaleUp(Physics::scaleUp(joint->GetMotorTorque(inv_dt))); } void RevoluteJoint::enableLimit(bool limit) diff --git a/src/modules/physics/box2d/RevoluteJoint.h b/src/modules/physics/box2d/RevoluteJoint.h index c5b255e23..3043f19c6 100644 --- a/src/modules/physics/box2d/RevoluteJoint.h +++ b/src/modules/physics/box2d/RevoluteJoint.h @@ -76,12 +76,12 @@ namespace box2d void setMaxMotorTorque(float torque); /** - * Sets the motor speed in degrees per second. + * Sets the motor speed in radians per second. **/ void setMotorSpeed(float speed); /** - * Gets the motor speed in degrees per second. + * Gets the motor speed in radians per second. **/ float getMotorSpeed() const; diff --git a/src/modules/physics/box2d/WheelJoint.cpp b/src/modules/physics/box2d/WheelJoint.cpp index 2a7fb7317..c818d1fb6 100644 --- a/src/modules/physics/box2d/WheelJoint.cpp +++ b/src/modules/physics/box2d/WheelJoint.cpp @@ -70,47 +70,47 @@ namespace box2d void WheelJoint::setMotorSpeed(float speed) { - joint->SetMotorSpeed(Physics::scaleDown(speed)); + joint->SetMotorSpeed(speed); } float WheelJoint::getMotorSpeed() const { - return Physics::scaleUp(joint->GetMotorSpeed()); + return joint->GetMotorSpeed(); } void WheelJoint::setMaxMotorTorque(float torque) { - joint->SetMaxMotorTorque(Physics::scaleDown(torque)); + joint->SetMaxMotorTorque(Physics::scaleDown(Physics::scaleDown(torque))); } float WheelJoint::getMaxMotorTorque() const { - return Physics::scaleUp(joint->GetMaxMotorTorque()); + return Physics::scaleUp(Physics::scaleUp(joint->GetMaxMotorTorque())); } float WheelJoint::getMotorTorque(float inv_dt) const { - return Physics::scaleUp(joint->GetMotorTorque(inv_dt)); + return Physics::scaleUp(Physics::scaleUp(joint->GetMotorTorque(inv_dt))); } void WheelJoint::setSpringFrequencyHz(float hz) { - joint->SetSpringFrequencyHz(Physics::scaleDown(hz)); + joint->SetSpringFrequencyHz(hz); } float WheelJoint::getSpringFrequencyHz() const { - return Physics::scaleUp(joint->GetSpringFrequencyHz()); + return joint->GetSpringFrequencyHz(); } void WheelJoint::setSpringDampingRatio(float ratio) { - joint->SetSpringDampingRatio(Physics::scaleDown(ratio)); + joint->SetSpringDampingRatio(ratio); } float WheelJoint::getSpringDampingRatio() const { - return Physics::scaleUp(joint->GetSpringDampingRatio()); + return joint->GetSpringDampingRatio(); } From 53cdd0ea7d809929ddcb93fe63cdda4be03d8b39 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Thu, 29 Sep 2011 11:12:03 -0400 Subject: [PATCH 71/78] Add RevoluteJoint:getMaxMotorTorque --HG-- branch : box2d-update --- src/modules/physics/box2d/RevoluteJoint.cpp | 5 +++++ src/modules/physics/box2d/RevoluteJoint.h | 5 +++++ src/modules/physics/box2d/wrap_RevoluteJoint.cpp | 8 ++++++++ src/modules/physics/box2d/wrap_RevoluteJoint.h | 1 + 4 files changed, 19 insertions(+) diff --git a/src/modules/physics/box2d/RevoluteJoint.cpp b/src/modules/physics/box2d/RevoluteJoint.cpp index 45b66856d..3beaa136c 100644 --- a/src/modules/physics/box2d/RevoluteJoint.cpp +++ b/src/modules/physics/box2d/RevoluteJoint.cpp @@ -87,6 +87,11 @@ namespace box2d { return Physics::scaleUp(Physics::scaleUp(joint->GetMotorTorque(inv_dt))); } + + float RevoluteJoint::getMaxMotorTorque() + { + return Physics::scaleUp(Physics::scaleUp(joint->GetMaxMotorTorque())); + } void RevoluteJoint::enableLimit(bool limit) { diff --git a/src/modules/physics/box2d/RevoluteJoint.h b/src/modules/physics/box2d/RevoluteJoint.h index 3043f19c6..5c6c95096 100644 --- a/src/modules/physics/box2d/RevoluteJoint.h +++ b/src/modules/physics/box2d/RevoluteJoint.h @@ -91,6 +91,11 @@ namespace box2d **/ float getMotorTorque(float inv_dt) const; + /** + * Get the maximum motor torque, usually in N-m. + **/ + float getMaxMotorTorque(); + /** * Enable/disable the joint limit. **/ diff --git a/src/modules/physics/box2d/wrap_RevoluteJoint.cpp b/src/modules/physics/box2d/wrap_RevoluteJoint.cpp index d6517e687..51b092eed 100644 --- a/src/modules/physics/box2d/wrap_RevoluteJoint.cpp +++ b/src/modules/physics/box2d/wrap_RevoluteJoint.cpp @@ -90,6 +90,13 @@ namespace box2d lua_pushnumber(L, t->getMotorTorque(inv_dt)); return 1; } + + int w_RevoluteJoint_getMaxMotorTorque(lua_State * L) + { + RevoluteJoint * t = luax_checkrevolutejoint(L, 1); + lua_pushnumber(L, t->getMaxMotorTorque()); + return 1; + } int w_RevoluteJoint_enableLimit(lua_State * L) { @@ -161,6 +168,7 @@ namespace box2d { "setMotorSpeed", w_RevoluteJoint_setMotorSpeed }, { "getMotorSpeed", w_RevoluteJoint_getMotorSpeed }, { "getMotorTorque", w_RevoluteJoint_getMotorTorque }, + { "getMaxMotorTorque", w_RevoluteJoint_getMaxMotorTorque }, { "enableLimit", w_RevoluteJoint_enableLimit }, { "isLimitEnabled", w_RevoluteJoint_isLimitEnabled }, { "setUpperLimit", w_RevoluteJoint_setUpperLimit }, diff --git a/src/modules/physics/box2d/wrap_RevoluteJoint.h b/src/modules/physics/box2d/wrap_RevoluteJoint.h index 1e13aec3a..a06767b6c 100644 --- a/src/modules/physics/box2d/wrap_RevoluteJoint.h +++ b/src/modules/physics/box2d/wrap_RevoluteJoint.h @@ -41,6 +41,7 @@ namespace box2d int w_RevoluteJoint_setMotorSpeed(lua_State * L); int w_RevoluteJoint_getMotorSpeed(lua_State * L); int w_RevoluteJoint_getMotorTorque(lua_State * L); + int w_RevoluteJoint_getMaxMotorTorque(lua_State * L); int w_RevoluteJoint_enableLimit(lua_State * L); int w_RevoluteJoint_isLimitEnabled(lua_State * L); int w_RevoluteJoint_setUpperLimit(lua_State * L); From fa58c87605e4bf6f42e44e12f3e1a849e9a7af68 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Thu, 29 Sep 2011 11:14:42 -0400 Subject: [PATCH 72/78] Add PrismaticJoint:getMaxMotorForce --HG-- branch : box2d-update --- src/modules/physics/box2d/PrismaticJoint.cpp | 5 +++++ src/modules/physics/box2d/PrismaticJoint.h | 5 +++++ src/modules/physics/box2d/RevoluteJoint.cpp | 2 +- src/modules/physics/box2d/RevoluteJoint.h | 2 +- src/modules/physics/box2d/wrap_PrismaticJoint.cpp | 8 ++++++++ src/modules/physics/box2d/wrap_PrismaticJoint.h | 1 + 6 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/modules/physics/box2d/PrismaticJoint.cpp b/src/modules/physics/box2d/PrismaticJoint.cpp index 276cb5493..d9b407a7d 100644 --- a/src/modules/physics/box2d/PrismaticJoint.cpp +++ b/src/modules/physics/box2d/PrismaticJoint.cpp @@ -90,6 +90,11 @@ namespace box2d { return Physics::scaleUp(joint->GetMotorForce(inv_dt)); } + + float PrismaticJoint::getMaxMotorForce() const + { + return Physics::scaleUp(joint->GetMaxMotorForce()); + } void PrismaticJoint::enableLimit(bool limit) { diff --git a/src/modules/physics/box2d/PrismaticJoint.h b/src/modules/physics/box2d/PrismaticJoint.h index b7c5efeec..c267f4ec7 100644 --- a/src/modules/physics/box2d/PrismaticJoint.h +++ b/src/modules/physics/box2d/PrismaticJoint.h @@ -91,6 +91,11 @@ namespace box2d **/ float getMotorForce(float inv_dt) const; + /** + * Get the maximum motor force, usually in N. + **/ + float getMaxMotorForce() const; + /** * Enable/disable the joint limit. **/ diff --git a/src/modules/physics/box2d/RevoluteJoint.cpp b/src/modules/physics/box2d/RevoluteJoint.cpp index 3beaa136c..30ef8ce14 100644 --- a/src/modules/physics/box2d/RevoluteJoint.cpp +++ b/src/modules/physics/box2d/RevoluteJoint.cpp @@ -88,7 +88,7 @@ namespace box2d return Physics::scaleUp(Physics::scaleUp(joint->GetMotorTorque(inv_dt))); } - float RevoluteJoint::getMaxMotorTorque() + float RevoluteJoint::getMaxMotorTorque() const { return Physics::scaleUp(Physics::scaleUp(joint->GetMaxMotorTorque())); } diff --git a/src/modules/physics/box2d/RevoluteJoint.h b/src/modules/physics/box2d/RevoluteJoint.h index 5c6c95096..2147b59e1 100644 --- a/src/modules/physics/box2d/RevoluteJoint.h +++ b/src/modules/physics/box2d/RevoluteJoint.h @@ -94,7 +94,7 @@ namespace box2d /** * Get the maximum motor torque, usually in N-m. **/ - float getMaxMotorTorque(); + float getMaxMotorTorque() const; /** * Enable/disable the joint limit. diff --git a/src/modules/physics/box2d/wrap_PrismaticJoint.cpp b/src/modules/physics/box2d/wrap_PrismaticJoint.cpp index a09344a06..5d9d04953 100644 --- a/src/modules/physics/box2d/wrap_PrismaticJoint.cpp +++ b/src/modules/physics/box2d/wrap_PrismaticJoint.cpp @@ -90,6 +90,13 @@ namespace box2d lua_pushnumber(L, t->getMotorForce(inv_dt)); return 1; } + + int w_PrismaticJoint_getMaxMotorForce(lua_State * L) + { + PrismaticJoint * t = luax_checkprismaticjoint(L, 1); + lua_pushnumber(L, t->getMaxMotorForce()); + return 1; + } int w_PrismaticJoint_enableLimit(lua_State * L) { @@ -161,6 +168,7 @@ namespace box2d { "setMotorSpeed", w_PrismaticJoint_setMotorSpeed }, { "getMotorSpeed", w_PrismaticJoint_getMotorSpeed }, { "getMotorForce", w_PrismaticJoint_getMotorForce }, + { "getMaxMotorForce", w_PrismaticJoint_getMaxMotorForce }, { "enableLimit", w_PrismaticJoint_enableLimit }, { "isLimitEnabled", w_PrismaticJoint_isLimitEnabled }, { "setUpperLimit", w_PrismaticJoint_setUpperLimit }, diff --git a/src/modules/physics/box2d/wrap_PrismaticJoint.h b/src/modules/physics/box2d/wrap_PrismaticJoint.h index 203edaea7..3f7152338 100644 --- a/src/modules/physics/box2d/wrap_PrismaticJoint.h +++ b/src/modules/physics/box2d/wrap_PrismaticJoint.h @@ -41,6 +41,7 @@ namespace box2d int w_PrismaticJoint_setMotorSpeed(lua_State * L); int w_PrismaticJoint_getMotorSpeed(lua_State * L); int w_PrismaticJoint_getMotorForce(lua_State * L); + int w_PrismaticJoint_getMaxMotorForce(lua_State * L); int w_PrismaticJoint_enableLimit(lua_State * L); int w_PrismaticJoint_isLimitEnabled(lua_State * L); int w_PrismaticJoint_setUpperLimit(lua_State * L); From 5d26c564e052ad3298a05e0bfaee10d45d60ce96 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Thu, 29 Sep 2011 11:19:30 -0400 Subject: [PATCH 73/78] Add EdgeShape:getPoints() --HG-- branch : box2d-update --- src/modules/physics/box2d/EdgeShape.cpp | 14 ++++++++++++++ src/modules/physics/box2d/EdgeShape.h | 8 ++++++++ src/modules/physics/box2d/wrap_EdgeShape.cpp | 8 ++++++++ src/modules/physics/box2d/wrap_EdgeShape.h | 1 + 4 files changed, 31 insertions(+) diff --git a/src/modules/physics/box2d/EdgeShape.cpp b/src/modules/physics/box2d/EdgeShape.cpp index 1416419b1..2795d2d11 100644 --- a/src/modules/physics/box2d/EdgeShape.cpp +++ b/src/modules/physics/box2d/EdgeShape.cpp @@ -23,6 +23,7 @@ // Module #include "Body.h" #include "World.h" +#include "Physics.h" #include @@ -43,6 +44,19 @@ namespace box2d delete shape; shape = NULL; } + + int EdgeShape::getPoints(lua_State * L) + { + b2EdgeShape * e = (b2EdgeShape *)shape; + b2Vec2 v1 = Physics::scaleUp(e->m_vertex1); + b2Vec2 v2 = Physics::scaleUp(e->m_vertex2); + lua_pushnumber(L, v1.x); + lua_pushnumber(L, v1.y); + lua_pushnumber(L, v2.x); + lua_pushnumber(L, v2.y); + return 4; + + } } // box2d } // physics diff --git a/src/modules/physics/box2d/EdgeShape.h b/src/modules/physics/box2d/EdgeShape.h index 67569b51b..6f51c2008 100644 --- a/src/modules/physics/box2d/EdgeShape.h +++ b/src/modules/physics/box2d/EdgeShape.h @@ -45,6 +45,14 @@ namespace box2d EdgeShape(b2EdgeShape * e); virtual ~EdgeShape(); + + /** + * Returns the transformed points of the edge shape. + * This function is useful for debug drawing and such. + * + * The result can be directly passed into love.graphics.line(). + **/ + int getPoints(lua_State * L); }; } // box2d diff --git a/src/modules/physics/box2d/wrap_EdgeShape.cpp b/src/modules/physics/box2d/wrap_EdgeShape.cpp index 3a8f23276..5d4d113d1 100644 --- a/src/modules/physics/box2d/wrap_EdgeShape.cpp +++ b/src/modules/physics/box2d/wrap_EdgeShape.cpp @@ -30,8 +30,16 @@ namespace box2d { return luax_checktype(L, idx, "EdgeShape", PHYSICS_EDGE_SHAPE_T); } + + int w_EdgeShape_getPoints(lua_State * L) + { + EdgeShape * t = luax_checkedgeshape(L, 1); + lua_remove(L, 1); + return t->getPoints(L); + } static const luaL_Reg functions[] = { + { "getPoints", w_EdgeShape_getPoints }, // From Shape. { "getType", w_Shape_getType }, { "getRadius", w_Shape_getRadius }, diff --git a/src/modules/physics/box2d/wrap_EdgeShape.h b/src/modules/physics/box2d/wrap_EdgeShape.h index 4b9cba3b4..9a5a39be0 100644 --- a/src/modules/physics/box2d/wrap_EdgeShape.h +++ b/src/modules/physics/box2d/wrap_EdgeShape.h @@ -33,6 +33,7 @@ namespace physics namespace box2d { EdgeShape * luax_checkedgeshape(lua_State * L, int idx); + int w_EdgeShape_getPoints(lua_State * L); int luaopen_edgeshape(lua_State * L); } // box2d From ffef6f58a94201ebaf72449abcab61838fd03471 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 2 Oct 2011 09:28:39 -0400 Subject: [PATCH 74/78] Make Joint::getReactionForce use the right stack position --HG-- branch : box2d-update --- src/modules/physics/box2d/Joint.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/modules/physics/box2d/Joint.cpp b/src/modules/physics/box2d/Joint.cpp index 13a29f18a..97aa16785 100644 --- a/src/modules/physics/box2d/Joint.cpp +++ b/src/modules/physics/box2d/Joint.cpp @@ -97,7 +97,7 @@ namespace box2d int Joint::getReactionForce(lua_State * L) { - float dt = (float)luaL_checknumber(L, 2); + float dt = (float)luaL_checknumber(L, 1); b2Vec2 v = Physics::scaleUp(joint->GetReactionForce(dt)); lua_pushnumber(L, v.x); lua_pushnumber(L, v.y); From 735c52b228a52413c4be00245aa38dc3b5942c18 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 2 Oct 2011 09:33:42 -0400 Subject: [PATCH 75/78] make love.physics.setMeter error on invalid meters (anything less than 1) --HG-- branch : box2d-update --- src/modules/physics/box2d/Physics.cpp | 1 + src/modules/physics/box2d/wrap_Physics.cpp | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 7ba45f241..37aa766a0 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -234,6 +234,7 @@ namespace box2d void Physics::setMeter(int meter) { + if (meter < 1) throw love::Exception("Physics error: invalid meter"); Physics::meter = meter; } diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index 0d7f409bc..b1af0a61d 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -304,7 +304,11 @@ namespace box2d int w_setMeter(lua_State * L) { int arg1 = luaL_checkint(L, 1); - Physics::setMeter(arg1); + try { + Physics::setMeter(arg1); + } catch (love::Exception e) { + return luaL_error(L, e.what()); + } return 0; } From f38655a934167a8279ded7ff2edb6f4eb10fa0ce Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 2 Oct 2011 10:06:31 -0400 Subject: [PATCH 76/78] Add second body anchor point to FrictionJoint/WeldJoint constructors --HG-- branch : box2d-update --- src/modules/physics/box2d/FrictionJoint.cpp | 5 +-- src/modules/physics/box2d/FrictionJoint.h | 2 +- src/modules/physics/box2d/Physics.cpp | 8 ++--- src/modules/physics/box2d/Physics.h | 16 +++++---- src/modules/physics/box2d/WeldJoint.cpp | 5 +-- src/modules/physics/box2d/WeldJoint.h | 2 +- src/modules/physics/box2d/wrap_Physics.cpp | 36 ++++++++++++++++----- 7 files changed, 50 insertions(+), 24 deletions(-) diff --git a/src/modules/physics/box2d/FrictionJoint.cpp b/src/modules/physics/box2d/FrictionJoint.cpp index 7449aab19..524c746f7 100644 --- a/src/modules/physics/box2d/FrictionJoint.cpp +++ b/src/modules/physics/box2d/FrictionJoint.cpp @@ -33,11 +33,12 @@ namespace physics { namespace box2d { - FrictionJoint::FrictionJoint(Body * body1, Body * body2, float x, float y, bool collideConnected) + FrictionJoint::FrictionJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, bool collideConnected) : Joint(body1, body2), joint(NULL) { b2FrictionJointDef def; - def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(x,y))); + def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(xA,yA))); + def.localAnchorB = Physics::scaleDown(b2Vec2(xB, yB)); def.collideConnected = collideConnected; joint = (b2FrictionJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/FrictionJoint.h b/src/modules/physics/box2d/FrictionJoint.h index d334c4799..e0dbb2f60 100644 --- a/src/modules/physics/box2d/FrictionJoint.h +++ b/src/modules/physics/box2d/FrictionJoint.h @@ -45,7 +45,7 @@ namespace box2d /** * Creates a new FrictionJoint connecting body1 and body2. **/ - FrictionJoint(Body * body1, Body * body2, float x, float y, bool collideConnected); + FrictionJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, bool collideConnected); virtual ~FrictionJoint(); diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 37aa766a0..55cb889f2 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -182,14 +182,14 @@ namespace box2d return new GearJoint(joint1, joint2, ratio, collideConnected); } - FrictionJoint * Physics::newFrictionJoint(Body * body1, Body * body2, float x, float y, bool collideConnected) + FrictionJoint * Physics::newFrictionJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, bool collideConnected) { - return new FrictionJoint(body1, body2, x, y, collideConnected); + return new FrictionJoint(body1, body2, xA, yA, xB, yB, collideConnected); } - WeldJoint * Physics::newWeldJoint(Body * body1, Body * body2, float x, float y, bool collideConnected) + WeldJoint * Physics::newWeldJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, bool collideConnected) { - return new WeldJoint(body1, body2, x, y, collideConnected); + return new WeldJoint(body1, body2, xA, yA, xB, yB, collideConnected); } WheelJoint * Physics::newWheelJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, float ax, float ay, bool collideConnected) diff --git a/src/modules/physics/box2d/Physics.h b/src/modules/physics/box2d/Physics.h index 2c4491d3f..d04dc2755 100644 --- a/src/modules/physics/box2d/Physics.h +++ b/src/modules/physics/box2d/Physics.h @@ -215,19 +215,23 @@ namespace box2d /** * Creates a new FrictionJoint connecting body1 with body2. - * @param x Anchor along the x-axis. (World coordinates) - * @param y Anchor along the y-axis. (World coordinates) + * @param xA Anchor for body 1 along the x-axis. (World coordinates) + * @param yA Anchor for body 1 along the y-axis. (World coordinates) + * @param xB Anchor for body 2 along the x-axis. (World coordinates) + * @param yB Anchor for body 2 along the y-axis. (World coordinates) * @param collideConnected Whether the connected bodies should collide with each other. Defaults to false. **/ - FrictionJoint * newFrictionJoint(Body * body1, Body * body2, float x, float y, bool collideConnected); + FrictionJoint * newFrictionJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, bool collideConnected); /** * Creates a new WeldJoint connecting body1 with body2. - * @param x Anchor along the x-axis. (World coordinates) - * @param y Anchor along the y-axis. (World coordinates) + * @param xA Anchor for body 1 along the x-axis. (World coordinates) + * @param yA Anchor for body 1 along the y-axis. (World coordinates) + * @param xB Anchor for body 2 along the x-axis. (World coordinates) + * @param yB Anchor for body 2 along the y-axis. (World coordinates) * @param collideConnected Whether the connected bodies should collide with each other. Defaults to false. **/ - WeldJoint * newWeldJoint(Body * body1, Body * body2, float x, float y, bool collideConnected); + WeldJoint * newWeldJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, bool collideConnected); /** * Creates a new WheelJoint connecting body1 with body2. diff --git a/src/modules/physics/box2d/WeldJoint.cpp b/src/modules/physics/box2d/WeldJoint.cpp index b2882d0be..7e437437a 100644 --- a/src/modules/physics/box2d/WeldJoint.cpp +++ b/src/modules/physics/box2d/WeldJoint.cpp @@ -33,11 +33,12 @@ namespace physics { namespace box2d { - WeldJoint::WeldJoint(Body * body1, Body * body2, float x, float y, bool collideConnected) + WeldJoint::WeldJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, bool collideConnected) : Joint(body1, body2), joint(NULL) { b2WeldJointDef def; - def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(x,y))); + def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(xA,yA))); + def.localAnchorB = Physics::scaleDown(b2Vec2(xB, yB)); def.collideConnected = collideConnected; joint = (b2WeldJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/WeldJoint.h b/src/modules/physics/box2d/WeldJoint.h index e8469dac2..c62b1912c 100644 --- a/src/modules/physics/box2d/WeldJoint.h +++ b/src/modules/physics/box2d/WeldJoint.h @@ -45,7 +45,7 @@ namespace box2d /** * Creates a new WeldJoint connecting body1 and body2. **/ - WeldJoint(Body * body1, Body * body2, float x, float y, bool collideConnected); + WeldJoint(Body * body1, Body * body2, float xA, float yA, float xB, float yB, bool collideConnected); virtual ~WeldJoint(); diff --git a/src/modules/physics/box2d/wrap_Physics.cpp b/src/modules/physics/box2d/wrap_Physics.cpp index b1af0a61d..d9cb427c8 100644 --- a/src/modules/physics/box2d/wrap_Physics.cpp +++ b/src/modules/physics/box2d/wrap_Physics.cpp @@ -234,10 +234,20 @@ namespace box2d { Body * body1 = luax_checktype(L, 1, "Body", PHYSICS_BODY_T); Body * body2 = luax_checktype(L, 2, "Body", PHYSICS_BODY_T); - float x = (float)luaL_checknumber(L, 3); - float y = (float)luaL_checknumber(L, 4); - bool collideConnected = luax_optboolean(L, 5, false); - FrictionJoint * j = instance->newFrictionJoint(body1, body2, x, y, collideConnected); + float xA = (float)luaL_checknumber(L, 3); + float yA = (float)luaL_checknumber(L, 4); + float xB, yB; + bool collideConnected; + if (lua_gettop(L) >= 6) { + xB = (float)luaL_checknumber(L, 5); + yB = (float)luaL_checknumber(L, 6); + collideConnected = luax_optboolean(L, 7, false); + } else { + xB = xA; + yB = yA; + collideConnected = luax_optboolean(L, 5, false); + } + FrictionJoint * j = instance->newFrictionJoint(body1, body2, xA, yA, xB, yB, collideConnected); luax_newtype(L, "FrictionJoint", PHYSICS_FRICTION_JOINT_T, (void*)j); return 1; } @@ -246,10 +256,20 @@ namespace box2d { Body * body1 = luax_checktype(L, 1, "Body", PHYSICS_BODY_T); Body * body2 = luax_checktype(L, 2, "Body", PHYSICS_BODY_T); - float x = (float)luaL_checknumber(L, 3); - float y = (float)luaL_checknumber(L, 4); - bool collideConnected = luax_optboolean(L, 5, false); - WeldJoint * j = instance->newWeldJoint(body1, body2, x, y, collideConnected); + float xA = (float)luaL_checknumber(L, 3); + float yA = (float)luaL_checknumber(L, 4); + float xB, yB; + bool collideConnected; + if (lua_gettop(L) >= 6) { + xB = (float)luaL_checknumber(L, 5); + yB = (float)luaL_checknumber(L, 6); + collideConnected = luax_optboolean(L, 7, false); + } else { + xB = xA; + yB = yA; + collideConnected = luax_optboolean(L, 5, false); + } + WeldJoint * j = instance->newWeldJoint(body1, body2, xA, yA, xB, yB, collideConnected); luax_newtype(L, "WeldJoint", PHYSICS_WELD_JOINT_T, (void*)j); return 1; } From 705fa14736e5e5cf9342498095eed0a6a703077d Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sun, 2 Oct 2011 10:28:37 -0400 Subject: [PATCH 77/78] Forgot to put the second anchor points in local coordinates --HG-- branch : box2d-update --- src/modules/physics/box2d/FrictionJoint.cpp | 2 +- src/modules/physics/box2d/WeldJoint.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/modules/physics/box2d/FrictionJoint.cpp b/src/modules/physics/box2d/FrictionJoint.cpp index 524c746f7..416f58a5c 100644 --- a/src/modules/physics/box2d/FrictionJoint.cpp +++ b/src/modules/physics/box2d/FrictionJoint.cpp @@ -38,7 +38,7 @@ namespace box2d { b2FrictionJointDef def; def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(xA,yA))); - def.localAnchorB = Physics::scaleDown(b2Vec2(xB, yB)); + def.localAnchorB = body2->body->GetLocalPoint(Physics::scaleDown(b2Vec2(xB, yB))); def.collideConnected = collideConnected; joint = (b2FrictionJoint*)createJoint(&def); } diff --git a/src/modules/physics/box2d/WeldJoint.cpp b/src/modules/physics/box2d/WeldJoint.cpp index 7e437437a..2360a517e 100644 --- a/src/modules/physics/box2d/WeldJoint.cpp +++ b/src/modules/physics/box2d/WeldJoint.cpp @@ -38,7 +38,7 @@ namespace box2d { b2WeldJointDef def; def.Initialize(body1->body, body2->body, Physics::scaleDown(b2Vec2(xA,yA))); - def.localAnchorB = Physics::scaleDown(b2Vec2(xB, yB)); + def.localAnchorB = body2->body->GetLocalPoint(Physics::scaleDown(b2Vec2(xB, yB))); def.collideConnected = collideConnected; joint = (b2WeldJoint*)createJoint(&def); } From 7584efe46d1311f713d9d50325360fc812f9dbce Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Fri, 7 Oct 2011 15:14:43 -0400 Subject: [PATCH 78/78] Fix include paths on Linux (from bartbes) --HG-- branch : box2d-update --- platform/unix/gen-makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/platform/unix/gen-makefile b/platform/unix/gen-makefile index 4824822ca..8dc6e4c57 100644 --- a/platform/unix/gen-makefile +++ b/platform/unix/gen-makefile @@ -3,8 +3,8 @@ echo Generating src/Makefile.am ... cd src inc_current=. inc_modules="$inc_current/modules" -inc_box2d="$inc_current/libraries/Box2D" -echo "AM_CPPFLAGS = -I$inc_current -I$inc_modules -I$inc_box2d -I/usr/include/AL -I/usr/include/freetype2 \$(INCLUDE_LUA) -I/usr/include/SDL \$(FILE_OFFSET) +inc_libraries="$inc_current/libraries" +echo "AM_CPPFLAGS = -I$inc_current -I$inc_modules -I$inc_libraries -I/usr/include/AL -I/usr/include/freetype2 \$(INCLUDE_LUA) -I/usr/include/SDL \$(FILE_OFFSET) AUTOMAKE_OPTIONS = subdir-objects DEFAULT_INCLUDES = SUBDIRS =