Browse Source

Initial import.

Refactored from BaH.Box2D, to use Structs where appropriate.
Brucey 4 years ago
parent
commit
6c17afa5ef
100 changed files with 28906 additions and 0 deletions
  1. 12 0
      .gitignore
  2. 151 0
      box2d.mod/Source/Collision/Shapes/b2CircleShape.cpp
  3. 98 0
      box2d.mod/Source/Collision/Shapes/b2CircleShape.h
  4. 202 0
      box2d.mod/Source/Collision/Shapes/b2EdgeShape.cpp
  5. 222 0
      box2d.mod/Source/Collision/Shapes/b2EdgeShape.h
  6. 569 0
      box2d.mod/Source/Collision/Shapes/b2PolygonShape.cpp
  7. 169 0
      box2d.mod/Source/Collision/Shapes/b2PolygonShape.h
  8. 177 0
      box2d.mod/Source/Collision/Shapes/b2Shape.cpp
  9. 337 0
      box2d.mod/Source/Collision/Shapes/b2Shape.h
  10. 938 0
      box2d.mod/Source/Collision/b2BroadPhase.cpp
  11. 158 0
      box2d.mod/Source/Collision/b2BroadPhase.h
  12. 168 0
      box2d.mod/Source/Collision/b2CollideCircle.cpp
  13. 353 0
      box2d.mod/Source/Collision/b2CollidePoly.cpp
  14. 72 0
      box2d.mod/Source/Collision/b2Collision.cpp
  15. 155 0
      box2d.mod/Source/Collision/b2Collision.h
  16. 437 0
      box2d.mod/Source/Collision/b2Distance.cpp
  17. 396 0
      box2d.mod/Source/Collision/b2PairManager.cpp
  18. 121 0
      box2d.mod/Source/Collision/b2PairManager.h
  19. 112 0
      box2d.mod/Source/Collision/b2TimeOfImpact.cpp
  20. 477 0
      box2d.mod/Source/Common/Fixed.h
  21. 207 0
      box2d.mod/Source/Common/b2BlockAllocator.cpp
  22. 59 0
      box2d.mod/Source/Common/b2BlockAllocator.h
  23. 82 0
      box2d.mod/Source/Common/b2Math.cpp
  24. 716 0
      box2d.mod/Source/Common/b2Math.h
  25. 51 0
      box2d.mod/Source/Common/b2Settings.cpp
  26. 178 0
      box2d.mod/Source/Common/b2Settings.h
  27. 83 0
      box2d.mod/Source/Common/b2StackAllocator.cpp
  28. 60 0
      box2d.mod/Source/Common/b2StackAllocator.h
  29. 139 0
      box2d.mod/Source/Common/jtypes.h
  30. 122 0
      box2d.mod/Source/Dynamics/Contacts/b2CircleContact.cpp
  31. 46 0
      box2d.mod/Source/Dynamics/Contacts/b2CircleContact.h
  32. 175 0
      box2d.mod/Source/Dynamics/Contacts/b2Contact.cpp
  33. 179 0
      box2d.mod/Source/Dynamics/Contacts/b2Contact.h
  34. 731 0
      box2d.mod/Source/Dynamics/Contacts/b2ContactSolver.cpp
  35. 78 0
      box2d.mod/Source/Dynamics/Contacts/b2ContactSolver.h
  36. 193 0
      box2d.mod/Source/Dynamics/Contacts/b2EdgeAndCircleContact.cpp
  37. 51 0
      box2d.mod/Source/Dynamics/Contacts/b2EdgeAndCircleContact.h
  38. 33 0
      box2d.mod/Source/Dynamics/Contacts/b2NullContact.h
  39. 156 0
      box2d.mod/Source/Dynamics/Contacts/b2PolyAndCircleContact.cpp
  40. 44 0
      box2d.mod/Source/Dynamics/Contacts/b2PolyAndCircleContact.h
  41. 369 0
      box2d.mod/Source/Dynamics/Contacts/b2PolyAndEdgeContact.cpp
  42. 47 0
      box2d.mod/Source/Dynamics/Contacts/b2PolyAndEdgeContact.h
  43. 157 0
      box2d.mod/Source/Dynamics/Contacts/b2PolyContact.cpp
  44. 44 0
      box2d.mod/Source/Dynamics/Contacts/b2PolyContact.h
  45. 111 0
      box2d.mod/Source/Dynamics/Controllers/b2BuoyancyController.cpp
  46. 102 0
      box2d.mod/Source/Dynamics/Controllers/b2BuoyancyController.h
  47. 46 0
      box2d.mod/Source/Dynamics/Controllers/b2ConstantAccelController.cpp
  48. 54 0
      box2d.mod/Source/Dynamics/Controllers/b2ConstantAccelController.h
  49. 47 0
      box2d.mod/Source/Dynamics/Controllers/b2ConstantForceController.cpp
  50. 54 0
      box2d.mod/Source/Dynamics/Controllers/b2ConstantForceController.h
  51. 110 0
      box2d.mod/Source/Dynamics/Controllers/b2Controller.cpp
  52. 159 0
      box2d.mod/Source/Dynamics/Controllers/b2Controller.h
  53. 70 0
      box2d.mod/Source/Dynamics/Controllers/b2GravityController.cpp
  54. 59 0
      box2d.mod/Source/Dynamics/Controllers/b2GravityController.h
  55. 72 0
      box2d.mod/Source/Dynamics/Controllers/b2TensorDampingController.cpp
  56. 69 0
      box2d.mod/Source/Dynamics/Controllers/b2TensorDampingController.h
  57. 209 0
      box2d.mod/Source/Dynamics/Joints/b2DistanceJoint.cpp
  58. 96 0
      box2d.mod/Source/Dynamics/Joints/b2DistanceJoint.h
  59. 257 0
      box2d.mod/Source/Dynamics/Joints/b2GearJoint.cpp
  60. 109 0
      box2d.mod/Source/Dynamics/Joints/b2GearJoint.h
  61. 146 0
      box2d.mod/Source/Dynamics/Joints/b2Joint.cpp
  62. 230 0
      box2d.mod/Source/Dynamics/Joints/b2Joint.h
  63. 559 0
      box2d.mod/Source/Dynamics/Joints/b2LineJoint.cpp
  64. 168 0
      box2d.mod/Source/Dynamics/Joints/b2LineJoint.h
  65. 153 0
      box2d.mod/Source/Dynamics/Joints/b2MouseJoint.cpp
  66. 97 0
      box2d.mod/Source/Dynamics/Joints/b2MouseJoint.h
  67. 587 0
      box2d.mod/Source/Dynamics/Joints/b2PrismaticJoint.cpp
  68. 173 0
      box2d.mod/Source/Dynamics/Joints/b2PrismaticJoint.h
  69. 428 0
      box2d.mod/Source/Dynamics/Joints/b2PulleyJoint.cpp
  70. 148 0
      box2d.mod/Source/Dynamics/Joints/b2PulleyJoint.h
  71. 474 0
      box2d.mod/Source/Dynamics/Joints/b2RevoluteJoint.cpp
  72. 170 0
      box2d.mod/Source/Dynamics/Joints/b2RevoluteJoint.h
  73. 457 0
      box2d.mod/Source/Dynamics/b2Body.cpp
  74. 604 0
      box2d.mod/Source/Dynamics/b2Body.h
  75. 237 0
      box2d.mod/Source/Dynamics/b2ContactManager.cpp
  76. 54 0
      box2d.mod/Source/Dynamics/b2ContactManager.h
  77. 471 0
      box2d.mod/Source/Dynamics/b2Island.cpp
  78. 104 0
      box2d.mod/Source/Dynamics/b2Island.h
  79. 1262 0
      box2d.mod/Source/Dynamics/b2World.cpp
  80. 320 0
      box2d.mod/Source/Dynamics/b2World.h
  81. 71 0
      box2d.mod/Source/Dynamics/b2WorldCallbacks.cpp
  82. 176 0
      box2d.mod/Source/Dynamics/b2WorldCallbacks.h
  83. 5238 0
      box2d.mod/box2d.bmx
  84. 464 0
      box2d.mod/common.bmx
  85. BIN
      box2d.mod/doc/box2d_logo.gif
  86. BIN
      box2d.mod/doc/images/bodyOrigin.gif
  87. BIN
      box2d.mod/doc/images/convex_concave.gif
  88. BIN
      box2d.mod/doc/images/distanceJoint.gif
  89. BIN
      box2d.mod/doc/images/gearJoint.gif
  90. BIN
      box2d.mod/doc/images/prismaticJoint.gif
  91. BIN
      box2d.mod/doc/images/pulleyJoint.gif
  92. BIN
      box2d.mod/doc/images/revoluteJoint.gif
  93. 4486 0
      box2d.mod/doc/intro.bbdoc
  94. 75 0
      box2d.mod/doc/manual.css
  95. BIN
      box2d.mod/examples/04B_03__.ttf
  96. 111 0
      box2d.mod/examples/applyforce.bmx
  97. 94 0
      box2d.mod/examples/bridge.bmx
  98. 114 0
      box2d.mod/examples/buoyancy.bmx
  99. 214 0
      box2d.mod/examples/car.bmx
  100. 73 0
      box2d.mod/examples/ccdtest.bmx

+ 12 - 0
.gitignore

@@ -0,0 +1,12 @@
+
+.bmx
+
+*.bak
+
+*.a
+
+*.i
+
+*.i2
+
+box2d.mod/doc/commands.html

+ 151 - 0
box2d.mod/Source/Collision/Shapes/b2CircleShape.cpp

@@ -0,0 +1,151 @@
+/*
+* 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
+b2SegmentCollide 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)
+	{
+		*lambda = 0;
+		return e_startsInsideCollide;
+	}
+
+	// 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 e_missCollide;
+	}
+
+	// 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 e_hitCollide;
+	}
+
+	return e_missCollide;
+}
+
+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));
+}
+
+float32 b2CircleShape::ComputeSubmergedArea(	const b2Vec2& normal,
+												float32 offset,
+												const b2XForm& xf, 
+												b2Vec2* c) const
+{
+	b2Vec2 p = b2Mul(xf,m_localPosition);
+	float32 l = -(b2Dot(normal,p) - offset);
+	if(l<-m_radius+B2_FLT_EPSILON){
+		//Completely dry
+		return 0;
+	}
+	if(l>m_radius){
+		//Completely wet
+		*c = p;
+		return b2_pi*m_radius*m_radius;
+	}
+	
+	//Magic
+	float32 r2 = m_radius*m_radius;
+	float32 l2 = l*l;
+    //TODO: write b2Sqrt to handle fixed point case.
+	float32 area = r2 * (asin(l/m_radius) + b2_pi/2.0f)+ l * b2Sqrt(r2 - l2);
+	float32 com = -2.0f/3.0f*pow(r2-l2,1.5f)/area;
+	
+	c->x = p.x + normal.x * com;
+	c->y = p.y + normal.y * com;
+	
+	return area;
+}

+ 98 - 0
box2d.mod/Source/Collision/Shapes/b2CircleShape.h

@@ -0,0 +1,98 @@
+/*
+* 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
+	b2SegmentCollide 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;
+
+	/// @see b2Shape::ComputeSubmergedArea
+	float32 ComputeSubmergedArea(	const b2Vec2& normal,
+									float32 offset,
+									const b2XForm& xf, 
+									b2Vec2* c) 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

+ 202 - 0
box2d.mod/Source/Collision/Shapes/b2EdgeShape.cpp

@@ -0,0 +1,202 @@
+/*
+* 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 "b2EdgeShape.h"
+
+b2EdgeShape::b2EdgeShape(const b2Vec2& v1, const b2Vec2& v2, const b2ShapeDef* def)
+: b2Shape(def)
+{
+	b2Assert(def->type == e_edgeShape);
+
+	m_type = e_edgeShape;
+	
+	m_prevEdge = NULL;
+	m_nextEdge = NULL;
+	
+	m_v1 = v1;
+	m_v2 = v2;
+	
+	m_direction = m_v2 - m_v1;
+	m_length = m_direction.Normalize();
+	m_normal.Set(m_direction.y, -m_direction.x);
+	
+	m_coreV1 = -b2_toiSlop * (m_normal - m_direction) + m_v1;
+	m_coreV2 = -b2_toiSlop * (m_normal + m_direction) + m_v2;
+	
+	m_cornerDir1 = m_normal;
+	m_cornerDir2 = -1.0f * m_normal;
+}
+
+void b2EdgeShape::UpdateSweepRadius(const b2Vec2& center)
+{
+	// Update the sweep radius (maximum radius) as measured from
+	// a local center point.
+	b2Vec2 d = m_coreV1 - center;
+	float32 d1 = b2Dot(d,d);
+	d = m_coreV2 - center;
+	float32 d2 = b2Dot(d,d);
+	m_sweepRadius = b2Sqrt(d1 > d2 ? d1 : d2);
+}
+
+bool b2EdgeShape::TestPoint(const b2XForm& transform, const b2Vec2& p) const
+{
+	B2_NOT_USED(transform);
+	B2_NOT_USED(p);
+	return false;
+}
+
+b2SegmentCollide b2EdgeShape::TestSegment(const b2XForm& transform,
+								float32* lambda,
+								b2Vec2* normal,
+								const b2Segment& segment,
+								float32 maxLambda) const
+{
+	b2Vec2 r = segment.p2 - segment.p1;
+	b2Vec2 v1 = b2Mul(transform, m_v1);
+	b2Vec2 d = b2Mul(transform, m_v2) - v1;
+	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 = segment.p1 - v1;
+		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 e_hitCollide;
+			}
+		}
+	}
+
+	return e_missCollide;
+}
+
+void b2EdgeShape::ComputeAABB(b2AABB* aabb, const b2XForm& transform) const
+{
+	b2Vec2 v1 = b2Mul(transform, m_v1);
+	b2Vec2 v2 = b2Mul(transform, m_v2);
+	aabb->lowerBound = b2Min(v1, v2);
+	aabb->upperBound = b2Max(v1, v2);
+}
+
+void b2EdgeShape::ComputeSweptAABB(b2AABB* aabb, const b2XForm& transform1, const b2XForm& transform2) const
+{
+	b2Vec2 v1 = b2Mul(transform1, m_v1);
+	b2Vec2 v2 = b2Mul(transform1, m_v2);
+	b2Vec2 v3 = b2Mul(transform2, m_v1);
+	b2Vec2 v4 = b2Mul(transform2, m_v2);
+	aabb->lowerBound = b2Min(b2Min(b2Min(v1, v2), v3), v4);
+	aabb->upperBound = b2Max(b2Max(b2Max(v1, v2), v3), v4);
+}
+
+void b2EdgeShape::ComputeMass(b2MassData* massData) const
+{
+	massData->mass = 0;
+	massData->center = m_v1;
+
+	// inertia about the local origin
+	massData->I = 0;
+}
+
+b2Vec2 b2EdgeShape::Support(const b2XForm& xf, const b2Vec2& d) const
+{
+	b2Vec2 v1 = b2Mul(xf, m_coreV1);
+	b2Vec2 v2 = b2Mul(xf, m_coreV2);
+	return b2Dot(v1, d) > b2Dot(v2, d) ? v1 : v2;
+}
+
+void b2EdgeShape::SetPrevEdge(b2EdgeShape* edge, const b2Vec2& core, const b2Vec2& cornerDir, bool convex)
+{
+	m_prevEdge = edge;
+	m_coreV1 = core;
+	m_cornerDir1 = cornerDir;
+	m_cornerConvex1 = convex;
+}
+
+void b2EdgeShape::SetNextEdge(b2EdgeShape* edge, const b2Vec2& core, const b2Vec2& cornerDir, bool convex)
+{
+	m_nextEdge = edge;
+	m_coreV2 = core;
+	m_cornerDir2 = cornerDir;
+	m_cornerConvex2 = convex;
+}
+
+float32 b2EdgeShape::ComputeSubmergedArea(	const b2Vec2& normal,
+												float32 offset,
+												const b2XForm& xf, 
+												b2Vec2* c) const
+{
+	//Note that v0 is independant of any details of the specific edge
+	//We are relying on v0 being consistent between multiple edges of the same body
+	b2Vec2 v0 = offset * normal;
+	//b2Vec2 v0 = xf.position + (offset - b2Dot(normal, xf.position)) * normal;
+
+	b2Vec2 v1 = b2Mul(xf, m_v1);
+	b2Vec2 v2 = b2Mul(xf, m_v2);
+
+	float32 d1 = b2Dot(normal, v1) - offset;
+	float32 d2 = b2Dot(normal, v2) - offset;
+
+	if(d1>0)
+	{
+		if(d2>0)
+		{
+			return 0;
+		}
+		else
+		{
+			v1 = -d2 / (d1 - d2) * v1 + d1 / (d1 - d2) * v2;
+		}
+	}
+	else
+	{
+		if(d2>0)
+		{
+			v2 = -d2 / (d1 - d2) * v1 + d1 / (d1 - d2) * v2;
+		}
+		else
+		{
+			//Nothing
+		}
+	}
+
+	// v0,v1,v2 represents a fully submerged triangle
+	float32 k_inv3 = 1.0f / 3.0f;
+
+	// Area weighted centroid
+	*c = k_inv3 * (v0 + v1 + v2);
+
+	b2Vec2 e1 = v1 - v0;
+	b2Vec2 e2 = v2 - v0;
+
+	return 0.5f * b2Cross(e1, e2);
+}

+ 222 - 0
box2d.mod/Source/Collision/Shapes/b2EdgeShape.h

@@ -0,0 +1,222 @@
+/*
+* 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_EDGE_SHAPE_H
+#define B2_EDGE_SHAPE_H
+
+#include "b2Shape.h"
+
+/// This structure is used to build circle shapes.
+struct b2EdgeChainDef : public b2ShapeDef
+{
+	b2EdgeChainDef()
+	{
+		type = e_edgeShape;
+		vertexCount = 0;
+		isALoop = true;
+		vertices = NULL;
+	}
+	/// The vertices in local coordinates. You must manage the memory
+	/// of this array on your own, outside of Box2D. 
+	b2Vec2* vertices;
+	
+	/// The number of vertices in the chain. 
+	int32 vertexCount;
+	
+	/// Whether to create an extra edge between the first and last vertices:
+	bool isALoop;
+};
+
+/// A circle shape.
+class b2EdgeShape : public b2Shape
+{
+public:
+	/// @see b2Shape::TestPoint
+	bool TestPoint(const b2XForm& transform, const b2Vec2& p) const;
+
+	/// @see b2Shape::TestSegment
+	b2SegmentCollide 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;
+
+	/// @warning This only gives a consistent and sensible answer when when summed over a body only contains loops of edges
+	/// @see b2Shape::ComputeSubmergedArea
+	float32 ComputeSubmergedArea(	const b2Vec2& normal,
+									float32 offset,
+									const b2XForm& xf, 
+									b2Vec2* c) const;
+	
+	/// Linear distance from vertex1 to vertex2:
+	float32 GetLength() const;
+
+	/// Local position of vertex in parent body
+	const b2Vec2& GetVertex1() const;
+
+	/// Local position of vertex in parent body
+	const b2Vec2& GetVertex2() const;
+
+	/// "Core" vertex with TOI slop for b2Distance functions:
+	const b2Vec2& GetCoreVertex1() const;
+
+	/// "Core" vertex with TOI slop for b2Distance functions:
+	const b2Vec2& GetCoreVertex2() const;
+	
+	/// Perpendicular unit vector point, pointing from the solid side to the empty side: 
+	const b2Vec2& GetNormalVector() const;
+	
+	/// Parallel unit vector, pointing from vertex1 to vertex2:
+	const b2Vec2& GetDirectionVector() const;
+	
+	const b2Vec2& GetCorner1Vector() const;
+	
+	const b2Vec2& GetCorner2Vector() const;
+	
+	bool Corner1IsConvex() const;
+	
+	bool Corner2IsConvex() const;
+
+	b2Vec2 GetFirstVertex(const b2XForm& xf) const;
+
+	b2Vec2 Support(const b2XForm& xf, const b2Vec2& d) const;
+	
+	/// Get the next edge in the chain.
+	b2EdgeShape* GetNextEdge() const;
+	
+	/// Get the previous edge in the chain.
+	b2EdgeShape* GetPrevEdge() const;
+
+	void SetPrevEdge(b2EdgeShape* edge, const b2Vec2& core, const b2Vec2& cornerDir, bool convex);
+	void SetNextEdge(b2EdgeShape* edge, const b2Vec2& core, const b2Vec2& cornerDir, bool convex);
+	
+private:
+
+	friend class b2Shape;
+	friend class b2Body;
+
+	b2EdgeShape(const b2Vec2& v1, const b2Vec2& v2, const b2ShapeDef* def);
+
+	void UpdateSweepRadius(const b2Vec2& center);
+
+	b2Vec2 m_v1;
+	b2Vec2 m_v2;
+	
+	b2Vec2 m_coreV1;
+	b2Vec2 m_coreV2;
+	
+	float32 m_length;
+	
+	b2Vec2 m_normal;
+	
+	b2Vec2 m_direction;
+	
+	// Unit vector halfway between m_direction and m_prevEdge.m_direction:
+	b2Vec2 m_cornerDir1;
+	
+	// Unit vector halfway between m_direction and m_nextEdge.m_direction:
+	b2Vec2 m_cornerDir2;
+	
+	bool m_cornerConvex1;
+	bool m_cornerConvex2;
+	
+	b2EdgeShape* m_nextEdge;
+	b2EdgeShape* m_prevEdge;
+};
+
+inline float32 b2EdgeShape::GetLength() const
+{
+	return m_length;
+}
+
+inline const b2Vec2& b2EdgeShape::GetVertex1() const
+{
+	return m_v1;
+}
+
+inline const b2Vec2& b2EdgeShape::GetVertex2() const
+{
+	return m_v2;
+}
+
+inline const b2Vec2& b2EdgeShape::GetCoreVertex1() const
+{
+	return m_coreV1;
+}
+
+inline const b2Vec2& b2EdgeShape::GetCoreVertex2() const
+{
+	return m_coreV2;
+}
+
+inline const b2Vec2& b2EdgeShape::GetNormalVector() const
+{
+	return m_normal;
+}
+
+inline const b2Vec2& b2EdgeShape::GetDirectionVector() const
+{
+	return m_direction;
+}
+
+inline const b2Vec2& b2EdgeShape::GetCorner1Vector() const
+{
+	return m_cornerDir1;
+}
+
+inline const b2Vec2& b2EdgeShape::GetCorner2Vector() const
+{
+	return m_cornerDir2;
+}
+
+inline b2EdgeShape* b2EdgeShape::GetNextEdge() const
+{
+	return m_nextEdge;
+}
+
+inline b2EdgeShape* b2EdgeShape::GetPrevEdge() const
+{
+	return m_prevEdge;
+}
+
+inline b2Vec2 b2EdgeShape::GetFirstVertex(const b2XForm& xf) const
+{
+	return b2Mul(xf, m_coreV1);
+}
+
+inline bool b2EdgeShape::Corner1IsConvex() const
+{
+	return m_cornerConvex1;
+}
+
+inline bool b2EdgeShape::Corner2IsConvex() const
+{
+	return m_cornerConvex2;
+}
+#endif

+ 569 - 0
box2d.mod/Source/Collision/Shapes/b2PolygonShape.cpp

@@ -0,0 +1,569 @@
+
+/*
+* 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;
+}
+
+b2SegmentCollide 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);
+
+		if (denominator == 0.0f)
+		{	
+			if (numerator < 0.0f)
+			{
+				return e_missCollide;
+			}
+		}
+		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;
+			}
+		}
+
+		if (upper < lower)
+		{
+			return e_missCollide;
+		}
+	}
+
+	b2Assert(0.0f <= lower && lower <= maxLambda);
+
+	if (index >= 0)
+	{
+		*lambda = lower;
+		*normal = b2Mul(xf.R, m_normals[index]);
+		return e_hitCollide;
+	}
+
+	*lambda = 0;
+	return e_startsInsideCollide;
+}
+
+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;
+}
+
+
+float32 b2PolygonShape::ComputeSubmergedArea(	const b2Vec2& normal,
+												float32 offset,
+												const b2XForm& xf, 
+												b2Vec2* c) const
+{
+	//Transform plane into shape co-ordinates
+	b2Vec2 normalL = b2MulT(xf.R,normal);
+	float32 offsetL = offset - b2Dot(normal,xf.position);
+	
+	float32 depths[b2_maxPolygonVertices];
+	int32 diveCount = 0;
+	int32 intoIndex = -1;
+	int32 outoIndex = -1;
+	
+	bool lastSubmerged = false;
+	int32 i;
+	for(i=0;i<m_vertexCount;i++){
+		depths[i] = b2Dot(normalL,m_vertices[i]) - offsetL;
+		bool isSubmerged = depths[i]<-B2_FLT_EPSILON;
+		if(i>0){
+			if(isSubmerged){
+				if(!lastSubmerged){
+					intoIndex = i-1;
+					diveCount++;
+				}
+			}else{
+				if(lastSubmerged){
+					outoIndex = i-1;
+					diveCount++;
+				}
+			}
+		}
+		lastSubmerged = isSubmerged;
+	}
+	switch(diveCount){
+		case 0:
+			if(lastSubmerged){
+				//Completely submerged
+				b2MassData md;
+				ComputeMass(&md);
+				*c = b2Mul(xf,md.center);
+				return md.mass/m_density;
+			}else{
+				//Completely dry
+				return 0;
+			}
+			break;
+		case 1:
+			if(intoIndex==-1){
+				intoIndex = m_vertexCount-1;
+			}else{
+				outoIndex = m_vertexCount-1;
+			}
+			break;
+	}
+	int32 intoIndex2 = (intoIndex+1)%m_vertexCount;
+	int32 outoIndex2 = (outoIndex+1)%m_vertexCount;
+	
+	float32 intoLambda = (0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex]);
+	float32 outoLambda = (0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex]);
+	
+	b2Vec2 intoVec(	m_vertices[intoIndex].x*(1-intoLambda)+m_vertices[intoIndex2].x*intoLambda,
+					m_vertices[intoIndex].y*(1-intoLambda)+m_vertices[intoIndex2].y*intoLambda);
+	b2Vec2 outoVec(	m_vertices[outoIndex].x*(1-outoLambda)+m_vertices[outoIndex2].x*outoLambda,
+					m_vertices[outoIndex].y*(1-outoLambda)+m_vertices[outoIndex2].y*outoLambda);
+	
+	//Initialize accumulator
+	float32 area = 0;
+	b2Vec2 center(0,0);
+	b2Vec2 p2 = m_vertices[intoIndex2];
+	b2Vec2 p3;
+	
+	float32 k_inv3 = 1.0f / 3.0f;
+	
+	//An awkward loop from intoIndex2+1 to outIndex2
+	i = intoIndex2;
+	while(i!=outoIndex2){
+		i=(i+1)%m_vertexCount;
+		if(i==outoIndex2)
+			p3 = outoVec;
+		else
+			p3 = m_vertices[i];
+		//Add the triangle formed by intoVec,p2,p3
+		{
+			b2Vec2 e1 = p2 - intoVec;
+			b2Vec2 e2 = p3 - intoVec;
+			
+			float32 D = b2Cross(e1, e2);
+			
+			float32 triangleArea = 0.5f * D;
+
+			area += triangleArea;
+			
+			// Area weighted centroid
+			center += triangleArea * k_inv3 * (intoVec + p2 + p3);
+
+		}
+		//
+		p2=p3;
+	}
+	
+	//Normalize and transform centroid
+	center *= 1.0f/area;
+	
+	*c = b2Mul(xf,center);
+	
+	return area;
+}
+
+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]);
+}

+ 169 - 0
box2d.mod/Source/Collision/Shapes/b2PolygonShape.h

@@ -0,0 +1,169 @@
+/*
+* 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
+	b2SegmentCollide 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;
+
+	/// @see b2Shape::ComputeSubmergedArea
+	float32 ComputeSubmergedArea(	const b2Vec2& normal,
+									float32 offset,
+									const b2XForm& xf, 
+									b2Vec2* c) 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

+ 177 - 0
box2d.mod/Source/Collision/Shapes/b2Shape.cpp

@@ -0,0 +1,177 @@
+/*
+* 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 "b2EdgeShape.h"
+#include "../b2Collision.h"
+#include "../b2BroadPhase.h"
+#include "../../Common/b2BlockAllocator.h"
+
+#include <new>
+
+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)
+{
+	b2EdgeShape* edge;
+	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;
+
+	case e_edgeShape:
+		edge = (b2EdgeShape*) s;
+		if (edge->m_nextEdge != NULL) edge->m_nextEdge->m_prevEdge = NULL;
+		if (edge->m_prevEdge != NULL) edge->m_prevEdge->m_nextEdge = NULL;
+		s->~b2Shape();
+		allocator->Free(s, sizeof(b2EdgeShape));
+		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;
+	}
+}

+ 337 - 0
box2d.mod/Source/Collision/Shapes/b2Shape.h

@@ -0,0 +1,337 @@
+/*
+* 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_edgeShape,
+	e_shapeTypeCount,
+};
+
+/// Return codes from TestSegment
+enum b2SegmentCollide
+{
+	e_startsInsideCollide = -1,
+	e_missCollide = 0,
+	e_hitCollide = 1
+};
+
+/// 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].
+	virtual b2SegmentCollide 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;
+
+	/// Compute the volume and centroid of this shape intersected with a half plane
+	/// @param normal the surface normal
+	/// @param offset the surface offset along normal
+	/// @param xf the shape transform
+	/// @param c returns the centroid
+	/// @return the total volume less than offset along normal
+	virtual float32 ComputeSubmergedArea(	const b2Vec2& normal,
+											float32 offset,
+											const b2XForm& xf, 
+											b2Vec2* c) 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;
+
+	/// 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 density of the shape.
+	float32 GetDensity() const;
+
+	/// Set the density of the shape.
+	void SetDensity(float32 density);
+
+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;
+
+	float32 m_density;
+	float32 m_friction;
+	float32 m_restitution;
+
+	uint16 m_proxyId;
+	b2FilterData m_filter;
+
+	bool m_isSensor;
+
+	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 void b2Shape::SetFriction(float32 friction)
+{
+	m_friction = friction;
+}
+
+inline float32 b2Shape::GetRestitution() const
+{
+	return m_restitution;
+}
+
+inline void b2Shape::SetRestitution(float32 restitution)
+{
+	m_restitution = restitution;
+}
+
+
+inline float32 b2Shape::GetDensity() const
+{
+	return m_density;
+}
+
+inline void b2Shape::SetDensity(float32 density)
+{
+	m_density = density;
+}
+
+#endif

+ 938 - 0
box2d.mod/Source/Collision/b2BroadPhase.cpp

@@ -0,0 +1,938 @@
+/*
+* 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 <algorithm>
+
+#include <cstring>
+
+// 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);
+		}
+	}
+}
+
+
+int32 b2BroadPhase::QuerySegment(const b2Segment& segment, void** userData, int32 maxCount, SortKeyFunc sortKey)
+{
+	float32 maxLambda = 1;
+
+	float32 dx = (segment.p2.x-segment.p1.x)*m_quantizationFactor.x;
+	float32 dy = (segment.p2.y-segment.p1.y)*m_quantizationFactor.y;
+
+	int32 sx = dx<-B2_FLT_EPSILON ? -1 : (dx>B2_FLT_EPSILON ? 1 : 0);
+	int32 sy = dy<-B2_FLT_EPSILON ? -1 : (dy>B2_FLT_EPSILON ? 1 : 0);
+
+	b2Assert(sx!=0||sy!=0);
+
+	float32 p1x = (segment.p1.x-m_worldAABB.lowerBound.x)*m_quantizationFactor.x;
+	float32 p1y = (segment.p1.y-m_worldAABB.lowerBound.y)*m_quantizationFactor.y;
+
+	uint16 startValues[2];
+	uint16 startValues2[2];
+
+	int32 xIndex;
+	int32 yIndex;
+
+	uint16 proxyId;
+	b2Proxy* proxy;
+	
+	// TODO_ERIN implement fast float to uint16 conversion.
+	startValues[0] = (uint16)(p1x) & (B2BROADPHASE_MAX - 1);
+	startValues2[0] = (uint16)(p1x) | 1;
+
+	startValues[1] = (uint16)(p1y) & (B2BROADPHASE_MAX - 1);
+	startValues2[1] = (uint16)(p1y) | 1;
+
+	//First deal with all the proxies that contain segment.p1
+	int32 lowerIndex;
+	int32 upperIndex;
+	Query(&lowerIndex,&upperIndex,startValues[0],startValues2[0],m_bounds[0],2*m_proxyCount,0);
+	if(sx>=0)	xIndex = upperIndex-1;
+	else		xIndex = lowerIndex;
+	Query(&lowerIndex,&upperIndex,startValues[1],startValues2[1],m_bounds[1],2*m_proxyCount,1);
+	if(sy>=0)	yIndex = upperIndex-1;
+	else		yIndex = lowerIndex;
+
+	//If we are using sortKey, then sort what we have so far, filtering negative keys
+	if(sortKey)
+	{
+		//Fill keys
+		for(int32 i=0;i<m_queryResultCount;i++)
+		{
+			m_querySortKeys[i] = sortKey(m_proxyPool[m_queryResults[i]].userData);
+		}
+		//Bubble sort keys
+		//Sorting negative values to the top, so we can easily remove them
+		int32 i = 0;
+		while(i<m_queryResultCount-1)
+		{
+			float32 a = m_querySortKeys[i];
+			float32 b = m_querySortKeys[i+1];
+			if((a<0)?(b>=0):(a>b&&b>=0))
+			{
+				m_querySortKeys[i+1] = a;
+				m_querySortKeys[i]   = b;
+				uint16 tempValue = m_queryResults[i+1];
+				m_queryResults[i+1] = m_queryResults[i];
+				m_queryResults[i] = tempValue;
+				i--;
+				if(i==-1) i=1;
+			}
+			else
+			{
+				i++;
+			}
+		}
+		//Skim off negative values
+		while(m_queryResultCount>0 && m_querySortKeys[m_queryResultCount-1]<0)
+			m_queryResultCount--;
+	}
+
+	//Now work through the rest of the segment
+	for (;;)
+	{
+		float32 xProgress = 0;
+		float32 yProgress = 0;
+		//Move on to the next bound
+		xIndex += sx>=0?1:-1;
+		if(xIndex<0||xIndex>=m_proxyCount*2)
+			break;
+		if(sx!=0)
+			xProgress = ((float32)m_bounds[0][xIndex].value-p1x)/dx;
+		//Move on to the next bound
+		yIndex += sy>=0?1:-1;
+		if(yIndex<0||yIndex>=m_proxyCount*2)
+			break;
+		if(sy!=0)
+			yProgress = ((float32)m_bounds[1][yIndex].value-p1y)/dy;
+		for(;;)
+		{
+			if(sy==0||(sx!=0&&xProgress<yProgress))
+			{
+				if(xProgress>maxLambda)
+					break;
+
+				//Check that we are entering a proxy, not leaving
+				if(sx>0?m_bounds[0][xIndex].IsLower():m_bounds[0][xIndex].IsUpper()){
+					//Check the other axis of the proxy
+					proxyId = m_bounds[0][xIndex].proxyId;
+					proxy = m_proxyPool+proxyId;
+					if(sy>=0)
+					{
+						if(proxy->lowerBounds[1]<=yIndex-1&&proxy->upperBounds[1]>=yIndex)
+						{
+							//Add the proxy
+							if(sortKey)
+							{
+								AddProxyResult(proxyId,proxy,maxCount,sortKey);
+							}
+							else
+							{
+								m_queryResults[m_queryResultCount] = proxyId;
+								++m_queryResultCount;
+							}
+						}
+					}
+					else
+					{
+						if(proxy->lowerBounds[1]<=yIndex&&proxy->upperBounds[1]>=yIndex+1)
+						{
+							//Add the proxy
+							if(sortKey)
+							{
+								AddProxyResult(proxyId,proxy,maxCount,sortKey);
+							}
+							else
+							{
+								m_queryResults[m_queryResultCount] = proxyId;
+								++m_queryResultCount;
+							}
+						}
+					}
+				}
+
+				//Early out
+				if(sortKey && m_queryResultCount==maxCount && m_queryResultCount>0 && xProgress>m_querySortKeys[m_queryResultCount-1])
+					break;
+
+				//Move on to the next bound
+				if(sx>0)
+				{
+					xIndex++;
+					if(xIndex==m_proxyCount*2)
+						break;
+				}
+				else
+				{
+					xIndex--;
+					if(xIndex<0)
+						break;
+				}
+				xProgress = ((float32)m_bounds[0][xIndex].value - p1x) / dx;
+			}
+			else
+			{
+				if(yProgress>maxLambda)
+					break;
+
+				//Check that we are entering a proxy, not leaving
+				if(sy>0?m_bounds[1][yIndex].IsLower():m_bounds[1][yIndex].IsUpper()){
+					//Check the other axis of the proxy
+					proxyId = m_bounds[1][yIndex].proxyId;
+					proxy = m_proxyPool+proxyId;
+					if(sx>=0)
+					{
+						if(proxy->lowerBounds[0]<=xIndex-1&&proxy->upperBounds[0]>=xIndex)
+						{
+							//Add the proxy
+							if(sortKey)
+							{
+								AddProxyResult(proxyId,proxy,maxCount,sortKey);
+							}
+							else
+							{
+								m_queryResults[m_queryResultCount] = proxyId;
+								++m_queryResultCount;
+							}
+						}
+					}
+					else
+					{
+						if(proxy->lowerBounds[0]<=xIndex&&proxy->upperBounds[0]>=xIndex+1)
+						{
+							//Add the proxy
+							if(sortKey)
+							{
+								AddProxyResult(proxyId,proxy,maxCount,sortKey);
+							}
+							else
+							{
+								m_queryResults[m_queryResultCount] = proxyId;
+								++m_queryResultCount;
+							}
+						}
+					}
+				}
+
+				//Early out
+				if(sortKey && m_queryResultCount==maxCount && m_queryResultCount>0 && yProgress>m_querySortKeys[m_queryResultCount-1])
+					break;
+
+				//Move on to the next bound
+				if(sy>0)
+				{
+					yIndex++;
+					if(yIndex==m_proxyCount*2)
+						break;
+				}
+				else
+				{
+					yIndex--;
+					if(yIndex<0)
+						break;
+				}
+				yProgress = ((float32)m_bounds[1][yIndex].value - p1y) / dy;
+			}
+		}
+
+		break;
+	}
+
+	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::AddProxyResult(uint16 proxyId, b2Proxy* proxy, int32 maxCount, SortKeyFunc sortKey)
+{
+	float32 key = sortKey(proxy->userData);
+	//Filter proxies on positive keys
+	if(key<0)
+		return;
+	//Merge the new key into the sorted list.
+	//float32* p = std::lower_bound(m_querySortKeys,m_querySortKeys+m_queryResultCount,key);
+	float32* p = m_querySortKeys;
+	while(*p<key&&p<m_querySortKeys+m_queryResultCount)
+		p++;
+	int32 i = (int32)(p-m_querySortKeys);
+	if(maxCount==m_queryResultCount&&i==m_queryResultCount)
+		return;
+	if(maxCount==m_queryResultCount)
+		m_queryResultCount--;
+	//std::copy_backward
+	for(int32 j=m_queryResultCount+1;j>i;--j){
+		m_querySortKeys[j] = m_querySortKeys[j-1];
+		m_queryResults[j]  = m_queryResults[j-1];
+	}
+	m_querySortKeys[i] = key;
+	m_queryResults[i] = proxyId;
+	m_queryResultCount++;
+}

+ 158 - 0
box2d.mod/Source/Collision/b2BroadPhase.h

@@ -0,0 +1,158 @@
+/*
+* 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 <climits>
+
+#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;
+};
+
+typedef float32 (*SortKeyFunc)(void* shape);
+
+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);
+
+	// Query a segment for overlapping proxies, returns the user data and
+	// the count, up to the supplied maximum count.
+	// If sortKey is provided, then it is a function mapping from proxy userDatas to distances along the segment (between 0 & 1)
+	// Then the returned proxies are sorted on that, before being truncated to maxCount
+	// The sortKey of a proxy is assumed to be larger than the closest point inside the proxy along the segment, this allows for early exits
+	// Proxies with a negative sortKey are discarded
+	int32 QuerySegment(const b2Segment& segment, void** userData, int32 maxCount, SortKeyFunc sortKey);
+
+	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();
+	void AddProxyResult(uint16 proxyId, b2Proxy* proxy, int32 maxCount, SortKeyFunc sortKey);
+
+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];
+	float32 m_querySortKeys[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

+ 168 - 0
box2d.mod/Source/Collision/b2CollideCircle.cpp

@@ -0,0 +1,168 @@
+/*
+* 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 = b2_nullFeature;
+	}
+
+	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;
+}

+ 353 - 0
box2d.mod/Source/Collision/b2CollidePoly.cpp

@@ -0,0 +1,353 @@
+/*
+* 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 "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;
+}
+
+// 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)
+{
+	int32 count1 = poly1->GetVertexCount();
+	const b2Vec2* vertices1 = poly1->GetVertices();
+	const b2Vec2* normals1 = poly1->GetNormals();
+
+	int32 count2 = poly2->GetVertexCount();
+	const b2Vec2* vertices2 = poly2->GetVertices();
+
+	b2Assert(0 <= edge1 && edge1 < count1);
+
+	// Convert normal from poly1's frame into poly2's frame.
+	b2Vec2 normal1World = b2Mul(xf1.R, normals1[edge1]);
+	b2Vec2 normal1 = b2MulT(xf2.R, normal1World);
+
+	// Find support vertex on poly2 for -normal.
+	int32 index = 0;
+	float32 minDot = B2_FLT_MAX;
+
+	for (int32 i = 0; i < count2; ++i)
+	{
+		float32 dot = b2Dot(vertices2[i], normal1);
+		if (dot < minDot)
+		{
+			minDot = dot;
+			index = i;
+		}
+	}
+
+	b2Vec2 v1 = b2Mul(xf1, vertices1[edge1]);
+	b2Vec2 v2 = b2Mul(xf2, vertices2[index]);
+	float32 separation = b2Dot(v2 - v1, normal1World);
+	return separation;
+}
+
+// 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)
+{
+	int32 count1 = poly1->GetVertexCount();
+	const b2Vec2* normals1 = poly1->GetNormals();
+
+	// Vector pointing from the centroid of poly1 to the centroid of poly2.
+	b2Vec2 d = b2Mul(xf2, poly2->GetCentroid()) - b2Mul(xf1, poly1->GetCentroid());
+	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;
+	for (int32 i = 0; i < count1; ++i)
+	{
+		float32 dot = b2Dot(normals1[i], dLocal1);
+		if (dot > maxDot)
+		{
+			maxDot = dot;
+			edge = i;
+		}
+	}
+
+	// Get the separation for the edge normal.
+	float32 s = EdgeSeparation(poly1, xf1, edge, poly2, xf2);
+	if (s > 0.0f)
+	{
+		return s;
+	}
+
+	// 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;
+	}
+
+	// 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;
+	}
+
+	// Find the best edge and the search direction.
+	int32 bestEdge;
+	float32 bestSeparation;
+	int32 increment;
+	if (sPrev > s && sPrev > sNext)
+	{
+		increment = -1;
+		bestEdge = prevEdge;
+		bestSeparation = sPrev;
+	}
+	else if (sNext > s)
+	{
+		increment = 1;
+		bestEdge = nextEdge;
+		bestSeparation = sNext;
+	}
+	else
+	{
+		*edgeIndex = edge;
+		return s;
+	}
+
+	// Perform a local search for the best edge normal.
+	for ( ; ; )
+	{
+		if (increment == -1)
+			edge = bestEdge - 1 >= 0 ? bestEdge - 1 : count1 - 1;
+		else
+			edge = bestEdge + 1 < count1 ? bestEdge + 1 : 0;
+
+		s = EdgeSeparation(poly1, xf1, edge, poly2, xf2);
+		if (s > 0.0f)
+		{
+			return s;
+		}
+
+		if (s > bestSeparation)
+		{
+			bestEdge = edge;
+			bestSeparation = s;
+		}
+		else
+		{
+			break;
+		}
+	}
+
+	*edgeIndex = bestEdge;
+	return bestSeparation;
+}
+
+static void FindIncidentEdge(ClipVertex c[2],
+							 const b2PolygonShape* poly1, const b2XForm& xf1, int32 edge1,
+							 const b2PolygonShape* poly2, const b2XForm& xf2)
+{
+	int32 count1 = poly1->GetVertexCount();
+	const b2Vec2* normals1 = poly1->GetNormals();
+
+	int32 count2 = poly2->GetVertexCount();
+	const b2Vec2* vertices2 = poly2->GetVertices();
+	const b2Vec2* normals2 = poly2->GetNormals();
+
+	b2Assert(0 <= edge1 && edge1 < count1);
+
+	// Get the normal of the reference edge in poly2's frame.
+	b2Vec2 normal1 = b2MulT(xf2.R, b2Mul(xf1.R, normals1[edge1]));
+
+	// Find the incident edge on poly2.
+	int32 index = 0;
+	float32 minDot = B2_FLT_MAX;
+	for (int32 i = 0; i < count2; ++i)
+	{
+		float32 dot = b2Dot(normal1, normals2[i]);
+		if (dot < minDot)
+		{
+			minDot = dot;
+			index = i;
+		}
+	}
+
+	// Build the clip vertices for the incident edge.
+	int32 i1 = index;
+	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[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;
+}
+
+// Find edge normal of max separation on A - return if separating axis is found
+// Find edge normal of max separation on B - return if separation axis is found
+// Choose reference edge as min(minA, minB)
+// Find incident edge
+// Clip
+
+// The normal points from 1 to 2
+void b2CollidePolygons(b2Manifold* manifold,
+					  const b2PolygonShape* polyA, const b2XForm& xfA,
+					  const b2PolygonShape* polyB, const b2XForm& xfB)
+{
+	manifold->pointCount = 0;
+
+	int32 edgeA = 0;
+	float32 separationA = FindMaxSeparation(&edgeA, polyA, xfA, polyB, xfB);
+	if (separationA > 0.0f)
+		return;
+
+	int32 edgeB = 0;
+	float32 separationB = FindMaxSeparation(&edgeB, polyB, xfB, polyA, xfA);
+	if (separationB > 0.0f)
+		return;
+
+	const b2PolygonShape* poly1;	// reference poly
+	const b2PolygonShape* poly2;	// incident poly
+	b2XForm 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;
+		poly2 = polyA;
+		xf1 = xfB;
+		xf2 = xfA;
+		edge1 = edgeB;
+		flip = 1;
+	}
+	else
+	{
+		poly1 = polyA;
+		poly2 = polyB;
+		xf1 = xfA;
+		xf2 = xfB;
+		edge1 = edgeA;
+		flip = 0;
+	}
+
+	ClipVertex incidentEdge[2];
+	FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2);
+
+	int32 count1 = poly1->GetVertexCount();
+	const b2Vec2* vertices1 = poly1->GetVertices();
+
+	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);
+	
+	v11 = b2Mul(xf1, v11);
+	v12 = b2Mul(xf1, v12);
+
+	float32 frontOffset = b2Dot(frontNormal, v11);
+	float32 sideOffset1 = -b2Dot(sideNormal, v11);
+	float32 sideOffset2 = b2Dot(sideNormal, v12);
+
+	// Clip incident edge against extruded edge1 side edges.
+	ClipVertex clipPoints1[2];
+	ClipVertex clipPoints2[2];
+	int np;
+
+	// Clip to box side 1
+	np = ClipSegmentToLine(clipPoints1, incidentEdge, -sideNormal, sideOffset1);
+
+	if (np < 2)
+		return;
+
+	// Clip to negative box side 1
+	np = ClipSegmentToLine(clipPoints2, clipPoints1,  sideNormal, sideOffset2);
+
+	if (np < 2)
+	{
+		return;
+	}
+
+	// Now clipPoints2 contains the clipped points.
+	manifold->normal = flip ? -frontNormal : frontNormal;
+
+	int32 pointCount = 0;
+	for (int32 i = 0; i < b2_maxManifoldPoints; ++i)
+	{
+		float32 separation = b2Dot(frontNormal, clipPoints2[i].v) - frontOffset;
+
+		if (separation <= 0.0f)
+		{
+			b2ManifoldPoint* cp = manifold->points + pointCount;
+			cp->separation = separation;
+			cp->localPoint1 = b2MulT(xfA, clipPoints2[i].v);
+			cp->localPoint2 = b2MulT(xfB, clipPoints2[i].v);
+			cp->id = clipPoints2[i].id;
+			cp->id.features.flip = flip;
+			++pointCount;
+		}
+	}
+
+	manifold->pointCount = pointCount;}

+ 72 - 0
box2d.mod/Source/Collision/b2Collision.cpp

@@ -0,0 +1,72 @@
+/*
+* 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;
+}
+
+

+ 155 - 0
box2d.mod/Source/Collision/b2Collision.h

@@ -0,0 +1,155 @@
+/*
+* 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 <climits>
+
+/// @file
+/// Structures and functions used for computing contact points, distance
+/// queries, and TOI queries.
+
+class b2Shape;
+class b2CircleShape;
+class b2PolygonShape;
+class b2EdgeShape;
+
+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

+ 437 - 0
box2d.mod/Source/Collision/b2Distance.cpp

@@ -0,0 +1,437 @@
+/*
+* 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"
+#include "Shapes/b2EdgeShape.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 <typename T1, typename T2>
+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 (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;
+}
+
+static float32 DistanceEdgeCircle(
+	b2Vec2* x1, b2Vec2* x2,
+	const b2EdgeShape* edge, const b2XForm& xf1,
+	const b2CircleShape* circle, const b2XForm& xf2)
+{
+	b2Vec2 vWorld;
+	b2Vec2 d;
+	float32 dSqr;
+	float32 dLen;
+	float32 r = circle->GetRadius() - b2_toiSlop;
+	b2Vec2 cWorld = b2Mul(xf2, circle->GetLocalPosition());
+	b2Vec2 cLocal = b2MulT(xf1, cWorld);
+	float32 dirDist = b2Dot(cLocal - edge->GetCoreVertex1(), edge->GetDirectionVector());
+	if (dirDist <= 0.0f) {
+		vWorld = b2Mul(xf1, edge->GetCoreVertex1());
+	} else if (dirDist >= edge->GetLength()) {
+		vWorld = b2Mul(xf1, edge->GetCoreVertex2());
+	} else {
+		*x1 = b2Mul(xf1, edge->GetCoreVertex1() + dirDist * edge->GetDirectionVector());
+		dLen = b2Dot(cLocal - edge->GetCoreVertex1(), edge->GetNormalVector());
+		if (dLen < 0.0f) {
+			if (dLen < -r) {
+				*x2 = b2Mul(xf1, cLocal + r * edge->GetNormalVector());
+				return -dLen - r;
+			} else {
+				*x2 = *x1;
+				return 0.0f;
+			}
+		} else {
+			if (dLen > r) {
+				*x2 = b2Mul(xf1, cLocal  - r * edge->GetNormalVector());
+				return dLen - r;
+			} else {
+				*x2 = *x1;
+				return 0.0f;
+			}
+		}
+	}
+	
+	*x1 = vWorld;
+	d = cWorld - vWorld;
+	dSqr = b2Dot(d, d);
+	if (dSqr > r * r) {
+		dLen = d.Normalize();
+		*x2 = cWorld - r * d;
+		return dLen - r;
+	} else {
+		*x2 = vWorld;
+		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);
+	}
+
+	if (type1 == e_edgeShape && type2 == e_circleShape)
+	{
+		return DistanceEdgeCircle(x1, x2, (b2EdgeShape*)shape1, xf1, (b2CircleShape*)shape2, xf2);
+	}
+	
+	if (type1 == e_circleShape && type2 == e_edgeShape)
+	{
+		return DistanceEdgeCircle(x2, x1, (b2EdgeShape*)shape2, xf2, (b2CircleShape*)shape1, xf1);
+	}
+
+	if (type1 == e_polygonShape && type2 == e_edgeShape)
+	{
+		return DistanceGeneric(x2, x1, (b2EdgeShape*)shape2, xf2, (b2PolygonShape*)shape1, xf1);
+	}
+
+	if (type1 == e_edgeShape && type2 == e_polygonShape)
+	{
+		return DistanceGeneric(x1, x2, (b2EdgeShape*)shape1, xf1, (b2PolygonShape*)shape2, xf2);
+	}
+
+	return 0.0f;
+}

+ 396 - 0
box2d.mod/Source/Collision/b2PairManager.cpp

@@ -0,0 +1,396 @@
+/*
+* 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 <algorithm>
+
+// 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
+}

+ 121 - 0
box2d.mod/Source/Collision/b2PairManager.h

@@ -0,0 +1,121 @@
+/*
+* 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 <climits>
+
+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

+ 112 - 0
box2d.mod/Source/Collision/b2TimeOfImpact.cpp

@@ -0,0 +1,112 @@
+/*
+* 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;
+}

+ 477 - 0
box2d.mod/Source/Common/Fixed.h

@@ -0,0 +1,477 @@
+/*
+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 <stdio.h>
+
+#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); }  // smallest step we can represent
+
+// for private construction via guts
+inline Fixed::Fixed(FixedRaw, int guts) : g(guts) {}
+
+inline Fixed::Fixed() : g(0) {}
+inline Fixed::Fixed(const Fixed &a) : g( a.g ) {}
+inline Fixed::Fixed(float a) : g( int(a * (float)(1<<BP)) ) {}
+inline Fixed::Fixed(double a) : g( int(a * (double)(1<<BP) ) ) {}
+inline Fixed::Fixed(int a) : g( a << BP ) {}
+inline Fixed::Fixed(long a) : g( a << BP ) {}
+
+inline Fixed& Fixed::operator =(const Fixed a) { g= a.g; return *this; }
+inline Fixed& Fixed::operator =(float a) { g= Fixed(a).g; return *this; }
+inline Fixed& Fixed::operator =(double a) { g= Fixed(a).g; return *this; }
+inline Fixed& Fixed::operator =(int a) { g= Fixed(a).g; return *this; }
+inline Fixed& Fixed::operator =(long a) { g= Fixed(a).g; return *this; }
+
+inline Fixed::operator float() { return g * (float)STEP(); }
+inline Fixed::operator double() { return g * (double)STEP(); }
+inline Fixed::operator int() { return g>>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); }
+
+inline Fixed Fixed::operator +() const { return Fixed(RAW,g); }
+inline Fixed Fixed::operator -() const { return Fixed(RAW,-g); }
+
+inline Fixed Fixed::operator +(const Fixed a) const { return Fixed(RAW, g + a.g); }
+inline Fixed Fixed::operator -(const Fixed a) const { return Fixed(RAW, g - a.g); }
+
+#if 1
+// more acurate, using long long
+inline Fixed Fixed::operator *(const Fixed a) const { return Fixed(RAW,  (int)( ((long long)g * (long long)a.g ) >> BP)); }
+
+#elif 0
+
+// check for overflow and figure out where.  Must specify -rdynamic in linker
+#include <execinfo.h>
+#include <signal.h>
+#include <exception>
+
+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<nSize; i++) {
+			printf(" %s", symbols[i]);
+		}
+		printf("\n");
+	}
+	return Fixed(RAW, (int)(x>>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))<<BP));
+}
+#else
+inline Fixed Fixed::sqrt()
+{
+	long long m, root = 0, left = (long long)g<<FIXED_BP;
+	for ( m = (long long)1<<( (sizeof(long long)<<3) - 2); m; m >>= 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

+ 207 - 0
box2d.mod/Source/Common/b2BlockAllocator.cpp

@@ -0,0 +1,207 @@
+/*
+* 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 "b2BlockAllocator.h"
+#include <cstdlib>
+#include <memory>
+#include <climits>
+
+#include <cstring>
+
+int32 b2BlockAllocator::s_blockSizes[b2_blockSizes] = 
+{
+	16,		// 0
+	32,		// 1
+	64,		// 2
+	96,		// 3
+	128,	// 4
+	160,	// 5
+	192,	// 6
+	224,	// 7
+	256,	// 8
+	320,	// 9
+	384,	// 10
+	448,	// 11
+	512,	// 12
+	640,	// 13
+};
+uint8 b2BlockAllocator::s_blockSizeLookup[b2_maxBlockSize + 1];
+bool b2BlockAllocator::s_blockSizeLookupInitialized;
+
+struct b2Chunk
+{
+	int32 blockSize;
+	b2Block* blocks;
+};
+
+struct b2Block
+{
+	b2Block* next;
+};
+
+b2BlockAllocator::b2BlockAllocator()
+{
+	b2Assert(b2_blockSizes < UCHAR_MAX);
+
+	m_chunkSpace = b2_chunkArrayIncrement;
+	m_chunkCount = 0;
+	m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk));
+	
+	memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk));
+	memset(m_freeLists, 0, sizeof(m_freeLists));
+
+	if (s_blockSizeLookupInitialized == false)
+	{
+		int32 j = 0;
+		for (int32 i = 1; i <= b2_maxBlockSize; ++i)
+		{
+			b2Assert(j < b2_blockSizes);
+			if (i <= s_blockSizes[j])
+			{
+				s_blockSizeLookup[i] = (uint8)j;
+			}
+			else
+			{
+				++j;
+				s_blockSizeLookup[i] = (uint8)j;
+			}
+		}
+
+		s_blockSizeLookupInitialized = true;
+	}
+}
+
+b2BlockAllocator::~b2BlockAllocator()
+{
+	for (int32 i = 0; i < m_chunkCount; ++i)
+	{
+		b2Free(m_chunks[i].blocks);
+	}
+
+	b2Free(m_chunks);
+}
+
+void* b2BlockAllocator::Allocate(int32 size)
+{
+	if (size == 0)
+		return NULL;
+
+	b2Assert(0 < size && size <= b2_maxBlockSize);
+
+	int32 index = s_blockSizeLookup[size];
+	b2Assert(0 <= index && index < b2_blockSizes);
+
+	if (m_freeLists[index])
+	{
+		b2Block* block = m_freeLists[index];
+		m_freeLists[index] = block->next;
+		return block;
+	}
+	else
+	{
+		if (m_chunkCount == m_chunkSpace)
+		{
+			b2Chunk* oldChunks = m_chunks;
+			m_chunkSpace += b2_chunkArrayIncrement;
+			m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk));
+			memcpy(m_chunks, oldChunks, m_chunkCount * sizeof(b2Chunk));
+			memset(m_chunks + m_chunkCount, 0, b2_chunkArrayIncrement * sizeof(b2Chunk));
+			b2Free(oldChunks);
+		}
+
+		b2Chunk* chunk = m_chunks + m_chunkCount;
+		chunk->blocks = (b2Block*)b2Alloc(b2_chunkSize);
+#if defined(_DEBUG)
+		memset(chunk->blocks, 0xcd, b2_chunkSize);
+#endif
+		int32 blockSize = s_blockSizes[index];
+		chunk->blockSize = blockSize;
+		int32 blockCount = b2_chunkSize / blockSize;
+		b2Assert(blockCount * blockSize <= b2_chunkSize);
+		for (int32 i = 0; i < blockCount - 1; ++i)
+		{
+			b2Block* block = (b2Block*)((int8*)chunk->blocks + blockSize * i);
+			b2Block* next = (b2Block*)((int8*)chunk->blocks + blockSize * (i + 1));
+			block->next = next;
+		}
+		b2Block* last = (b2Block*)((int8*)chunk->blocks + blockSize * (blockCount - 1));
+		last->next = NULL;
+
+		m_freeLists[index] = chunk->blocks->next;
+		++m_chunkCount;
+
+		return chunk->blocks;
+	}
+}
+
+void b2BlockAllocator::Free(void* p, int32 size)
+{
+	if (size == 0)
+	{
+		return;
+	}
+
+	b2Assert(0 < size && size <= b2_maxBlockSize);
+
+	int32 index = s_blockSizeLookup[size];
+	b2Assert(0 <= index && index < b2_blockSizes);
+
+#ifdef _DEBUG
+	// 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);
+		}
+		else
+		{
+			if ((int8*)chunk->blocks <= (int8*)p && (int8*)p + blockSize <= (int8*)chunk->blocks + b2_chunkSize)
+			{
+				found = true;
+			}
+		}
+	}
+
+	b2Assert(found);
+
+	memset(p, 0xfd, blockSize);
+#endif
+
+	b2Block* block = (b2Block*)p;
+	block->next = m_freeLists[index];
+	m_freeLists[index] = block;
+}
+
+void b2BlockAllocator::Clear()
+{
+	for (int32 i = 0; i < m_chunkCount; ++i)
+	{
+		b2Free(m_chunks[i].blocks);
+	}
+
+	m_chunkCount = 0;
+	memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk));
+
+	memset(m_freeLists, 0, sizeof(m_freeLists));
+}

+ 59 - 0
box2d.mod/Source/Common/b2BlockAllocator.h

@@ -0,0 +1,59 @@
+/*
+* 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_BLOCK_ALLOCATOR_H
+#define B2_BLOCK_ALLOCATOR_H
+
+#include "b2Settings.h"
+
+const int32 b2_chunkSize = 4096;
+const int32 b2_maxBlockSize = 640;
+const int32 b2_blockSizes = 14;
+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
+class b2BlockAllocator
+{
+public:
+	b2BlockAllocator();
+	~b2BlockAllocator();
+
+	void* Allocate(int32 size);
+	void Free(void* p, int32 size);
+
+	void Clear();
+
+private:
+
+	b2Chunk* m_chunks;
+	int32 m_chunkCount;
+	int32 m_chunkSpace;
+
+	b2Block* m_freeLists[b2_blockSizes];
+
+	static int32 s_blockSizes[b2_blockSizes];
+	static uint8 s_blockSizeLookup[b2_maxBlockSize + 1];
+	static bool s_blockSizeLookupInitialized;
+};
+
+#endif

+ 82 - 0
box2d.mod/Source/Common/b2Math.cpp

@@ -0,0 +1,82 @@
+/*
+* 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);
+
+/// 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));
+	b2Assert(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;
+	b2Assert(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;
+}
+
+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;
+	}
+}

+ 716 - 0
box2d.mod/Source/Common/b2Math.h

@@ -0,0 +1,716 @@
+/*
+* 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_MATH_H
+#define B2_MATH_H
+
+#include "b2Settings.h"
+
+#ifdef TARGET_OS_IPHONE
+#include "math.h"
+#else
+#include <cmath>
+#endif
+
+
+
+#include <cfloat>
+#include <cstdlib>
+
+#include <stdio.h>
+
+#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)
+{
+	B2_NOT_USED(x);
+	return true;
+}
+
+#define	b2Sqrt(x)	sqrt(x)
+#define	b2Atan2(y, x)	atan2(y, x)
+
+#else
+
+/// 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
+	
+#ifdef TARGET_OS_IPHONE
+	return isfinite(x);
+#else
+	return finite(x) != 0;
+#endif
+	
+	
+#endif
+}
+
+/// This is a approximate yet fast inverse square-root.
+inline float32 b2InvSqrt(float32 x)
+{
+	union
+	{
+		float32 x;
+		int32 i;
+	} convert;
+
+	convert.x = x;
+	float32 xhalf = 0.5f * x;
+	convert.i = 0x5f3759df - (convert.i >> 1);
+	x = convert.x;
+	x = x * (1.5f - xhalf * x * x);
+	return 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).
+	b2Vec2() {}
+
+	/// Construct using coordinates.
+	b2Vec2(float32 x, float32 y) : x(x), y(y) {}
+
+	/// Set this vector to all zeros.
+	void SetZero() { x = 0.0f; y = 0.0f; }
+
+	/// Set this vector to some specified coordinates.
+	void Set(float32 x_, float32 y_) { x = x_; y = y_; }
+
+	/// Negate this vector.
+	b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; }
+	
+	/// Add a vector to this vector.
+	void operator += (const b2Vec2& v)
+	{
+		x += v.x; y += v.y;
+	}
+	
+	/// Subtract a vector from this vector.
+	void operator -= (const b2Vec2& v)
+	{
+		x -= v.x; y -= v.y;
+	}
+
+	/// Multiply this vector by a scalar.
+	void operator *= (float32 a)
+	{
+		x *= a; y *= a;
+	}
+
+	/// 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
+	/// b2Vec2::Length (if possible).
+	float32 LengthSquared() const
+	{
+		return x * x + y * y;
+	}
+
+	/// 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)
+		{
+			return 0.0f;
+		}
+		float32 invLength = 1.0f / length;
+		x *= invLength;
+		y *= invLength;
+
+		return length;
+	}
+#endif
+
+	/// Does this vector contain finite coordinates?
+	bool IsValid() const
+	{
+		return b2IsValid(x) && b2IsValid(y);
+	}
+
+	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
+{
+	/// The default constructor does nothing (for performance).
+	b2Mat22() {}
+
+	/// Construct this matrix using columns.
+	b2Mat22(const b2Vec2& c1, const b2Vec2& c2)
+	{
+		col1 = c1;
+		col2 = 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;
+	}
+
+	/// 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;
+	}
+
+	/// Set this to the identity matrix.
+	void SetIdentity()
+	{
+		col1.x = 1.0f; col2.x = 0.0f;
+		col1.y = 0.0f; col2.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);
+	}
+
+#ifdef TARGET_FLOAT32_IS_FIXED
+
+	/// Compute the inverse of this matrix, such that inv(A) * A = identity.
+	b2Mat22 GetInverse() 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<<n; b = b<<n; 
+			c = c<<n; d = d<<n;
+			det = a * d - b * c;
+			b2Assert(det != 0.0f);
+			det = float32(1) / det;
+			B.col1.x = ( det * d) << n;	B.col2.x = (-det * b) << n;
+			B.col1.y = (-det * c) << n;	B.col2.y = ( det * a) << n;
+		} 
+		else
+		{
+			n = (b2Abs(det) >= 16.0)? 4 : 0;
+			b2Assert(det != 0.0f);
+			det = float32(1<<n) / det;
+			B.col1.x = ( det * d) >> 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<<n; a12 = col2.x<<n;
+			a21 = col1.y<<n; a22 = col2.y<<n;
+			det = a11 * a22 - a12 * a21;
+			b2Assert(det != 0.0f);
+			det = float32(1) / det;
+			x.x = (det * (a22 * b.x - a12 * b.y)) << n;
+			x.y = (det * (a11 * b.y - a21 * b.x)) << n;
+		} 
+		else 
+		{
+			n = (b2Abs(det) >= 16.0) ? 4 : 0;
+			b2Assert(det != 0.0f);
+			det = float32(1<<n) / det;
+			x.x = (det * (a22 * b.x - a12 * b.y)) >> n;
+			x.y = (det * (a11 * b.y - a21 * b.x)) >> n;
+		}
+
+		return x;
+	}
+
+#else
+	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;
+		B.col1.x =  det * d;	B.col2.x = -det * b;
+		B.col1.y = -det * c;	B.col2.y =  det * a;
+		return B;
+	}
+
+	/// Solve A * x = b, where b is a column vector. This is more efficient
+	/// 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 det = a11 * a22 - a12 * a21;
+		b2Assert(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 3-by-3 matrix. Stored in column-major order.
+struct b2Mat33
+{
+	/// The default constructor does nothing (for performance).
+	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 b2XForm
+{
+	/// The default constructor does nothing (for performance).
+	b2XForm() {}
+
+	/// Initialize using a position vector and a rotation matrix.
+	b2XForm(const b2Vec2& position, const b2Mat22& R) : position(position), R(R) {}
+
+	/// Set this to the identity transform.
+	void SetIdentity()
+	{
+		position.SetZero();
+		R.SetIdentity();
+	}
+
+	b2Vec2 position;
+	b2Mat22 R;
+};
+
+/// This describes the motion of a body/shape for TOI computation.
+/// Shapes are defined with respect to the body origin, which may
+/// no coincide with the center of mass. However, to support dynamics
+/// we must interpolate the center of mass position.
+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;
+
+	/// Advance the sweep forward, yielding a new initial state.
+	/// @param t the new initial time.
+	void Advance(float32 t);
+
+	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;
+
+/// Peform the dot product on two vectors.
+inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b)
+{
+	return a.x * b.x + a.y * b.y;
+}
+
+/// Perform the cross product on two vectors. In 2D this produces a scalar.
+inline float32 b2Cross(const b2Vec2& a, const b2Vec2& b)
+{
+	return a.x * b.y - a.y * b.x;
+}
+
+/// Perform the cross product on a vector and a scalar. In 2D this produces
+/// a vector.
+inline b2Vec2 b2Cross(const b2Vec2& a, float32 s)
+{
+	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)
+{
+	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)
+{
+	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)
+{
+	return b2Vec2(b2Dot(v, A.col1), b2Dot(v, A.col2));
+}
+
+/// Add two vectors component-wise.
+inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b)
+{
+	return b2Vec2(a.x + b.x, a.y + b.y);
+}
+
+/// Subtract two vectors component-wise.
+inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b)
+{
+	return b2Vec2(a.x - b.x, a.y - b.y);
+}
+
+inline b2Vec2 operator * (float32 s, const b2Vec2& a)
+{
+	return b2Vec2(s * a.x, s * a.y);
+}
+
+inline bool operator == (const b2Vec2& a, const b2Vec2& b)
+{
+	return a.x == b.x && a.y == b.y;
+}
+
+inline float32 b2Distance(const b2Vec2& a, const b2Vec2& b)
+{
+	b2Vec2 c = a - b;
+	return c.Length();
+}
+
+inline float32 b2DistanceSquared(const b2Vec2& a, const b2Vec2& b)
+{
+	b2Vec2 c = a - 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)
+{
+	return b2Mat22(A.col1 + B.col1, A.col2 + B.col2);
+}
+
+// A * B
+inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B)
+{
+	return b2Mat22(b2Mul(A, B.col1), b2Mul(A, B.col2));
+}
+
+// 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));
+	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;
+}
+
+inline b2Vec2 b2Mul(const b2XForm& T, const b2Vec2& v)
+{
+	return T.position + b2Mul(T.R, v);
+}
+
+inline b2Vec2 b2MulT(const b2XForm& T, const b2Vec2& v)
+{
+	return b2MulT(T.R, v - T.position);
+}
+
+inline b2Vec2 b2Abs(const b2Vec2& a)
+{
+	return b2Vec2(b2Abs(a.x), b2Abs(a.y));
+}
+
+inline b2Mat22 b2Abs(const b2Mat22& A)
+{
+	return b2Mat22(b2Abs(A.col1), b2Abs(A.col2));
+}
+
+template <typename T>
+inline T b2Min(T a, T b)
+{
+	return a < b ? a : b;
+}
+
+inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b)
+{
+	return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y));
+}
+
+template <typename T>
+inline T b2Max(T a, T b)
+{
+	return a > b ? a : b;
+}
+
+inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b)
+{
+	return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y));
+}
+
+template <typename T>
+inline T b2Clamp(T a, T low, T high)
+{
+	return b2Max(low, b2Min(a, high));
+}
+
+inline b2Vec2 b2Clamp(const b2Vec2& a, const b2Vec2& low, const b2Vec2& high)
+{
+	return b2Max(low, b2Min(a, high));
+}
+
+template<typename T> inline void b2Swap(T& a, T& b)
+{
+	T tmp = a;
+	a = b;
+	b = tmp;
+}
+
+/// "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
+/// the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next
+/// largest power of 2. For a 32-bit value:"
+inline uint32 b2NextPowerOfTwo(uint32 x)
+{
+	x |= (x >> 1);
+	x |= (x >> 2);
+	x |= (x >> 4);
+	x |= (x >> 8);
+	x |= (x >> 16);
+	return x + 1;
+}
+
+inline bool b2IsPowerOfTwo(uint32 x)
+{
+	bool result = x > 0 && (x & (x - 1)) == 0;
+	return result;
+}
+
+#endif

+ 51 - 0
box2d.mod/Source/Common/b2Settings.cpp

@@ -0,0 +1,51 @@
+/*
+* 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 "b2Settings.h"
+#include <cstdlib>
+
+b2Version b2_version = {2, 0, 2};
+
+int32 b2_byteCount = 0;
+
+
+
+// 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);
+}

+ 178 - 0
box2d.mod/Source/Common/b2Settings.h

@@ -0,0 +1,178 @@
+/*
+* 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_SETTINGS_H
+#define B2_SETTINGS_H
+
+#include <assert.h>
+#include <math.h>
+
+#define B2_NOT_USED(x) x
+#define b2Assert(A) assert(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;
+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;
+
+/// @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 = 512;				// this must be a power of two
+const int32 b2_maxPairs = 8 * b2_maxProxies;	// this must be a power of two
+
+// Dynamics
+
+/// 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
+
+/// 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
+
+/// 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;
+
+/// Maximum number of contacts to be handled to solve a TOI island.
+const int32 b2_maxTOIContactsPerIsland = 32;
+
+/// Maximum number of joints to be handled to solve a TOI island.
+const int32 b2_maxTOIJointsPerIsland = 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
+
+/// The maximum linear position correction used when solving constraints. This helps to
+/// prevent overshoot.
+const float32 b2_maxLinearCorrection = 0.2f;	// 20 cm
+
+/// 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
+
+/// 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
+
+/// 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
+
+/// 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;
+
+// Sleep
+
+/// The time that a body must be still before it will go to sleep.
+const float32 b2_timeToSleep = 0.5f;									// half a second
+
+/// A body cannot sleep if its linear velocity is above this tolerance.
+const float32 b2_linearSleepTolerance = 0.01f;		// 1 cm/s
+
+/// A body cannot sleep if its angular velocity is above this tolerance.
+const float32 b2_angularSleepTolerance = 2.0f / 180.0f;		// 2 degrees/s
+
+// 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);
+
+/// If you implement b2Alloc, you should also implement this function.
+void b2Free(void* mem);
+
+/// Version numbering scheme.
+/// See http://en.wikipedia.org/wiki/Software_versioning
+struct b2Version
+{
+	int32 major;		///< significant changes
+	int32 minor;		///< incremental changes
+	int32 revision;		///< bug fixes
+};
+
+/// 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

+ 83 - 0
box2d.mod/Source/Common/b2StackAllocator.cpp

@@ -0,0 +1,83 @@
+/*
+* 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 "b2StackAllocator.h"
+#include "b2Math.h"
+
+b2StackAllocator::b2StackAllocator()
+{
+	m_index = 0;
+	m_allocation = 0;
+	m_maxAllocation = 0;
+	m_entryCount = 0;
+}
+
+b2StackAllocator::~b2StackAllocator()
+{
+	b2Assert(m_index == 0);
+	b2Assert(m_entryCount == 0);
+}
+
+void* b2StackAllocator::Allocate(int32 size)
+{
+	b2Assert(m_entryCount < b2_maxStackEntries);
+
+	b2StackEntry* entry = m_entries + m_entryCount;
+	entry->size = size;
+	if (m_index + size > b2_stackSize)
+	{
+		entry->data = (char*)b2Alloc(size);
+		entry->usedMalloc = true;
+	}
+	else
+	{
+		entry->data = m_data + m_index;
+		entry->usedMalloc = false;
+		m_index += size;
+	}
+
+	m_allocation += size;
+	m_maxAllocation = b2Max(m_maxAllocation, m_allocation);
+	++m_entryCount;
+
+	return entry->data;
+}
+
+void b2StackAllocator::Free(void* p)
+{
+	b2Assert(m_entryCount > 0);
+	b2StackEntry* entry = m_entries + m_entryCount - 1;
+	b2Assert(p == entry->data);
+	if (entry->usedMalloc)
+	{
+		b2Free(p);
+	}
+	else
+	{
+		m_index -= entry->size;
+	}
+	m_allocation -= entry->size;
+	--m_entryCount;
+
+	p = NULL;
+}
+
+int32 b2StackAllocator::GetMaxAllocation() const
+{
+	return m_maxAllocation;
+}

+ 60 - 0
box2d.mod/Source/Common/b2StackAllocator.h

@@ -0,0 +1,60 @@
+/*
+* 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_STACK_ALLOCATOR_H
+#define B2_STACK_ALLOCATOR_H
+
+#include "b2Settings.h"
+
+const int32 b2_stackSize = 100 * 1024;	// 100k
+const int32 b2_maxStackEntries = 32;
+
+struct b2StackEntry
+{
+	char* data;
+	int32 size;
+	bool usedMalloc;
+};
+
+// This is a stack allocator used for fast per step allocations.
+// You must nest allocate/free pairs. The code will assert
+// if you try to interleave multiple allocate/free pairs.
+class b2StackAllocator
+{
+public:
+	b2StackAllocator();
+	~b2StackAllocator();
+
+	void* Allocate(int32 size);
+	void Free(void* p);
+
+	int32 GetMaxAllocation() const;
+
+private:
+
+	char m_data[b2_stackSize];
+	int32 m_index;
+
+	int32 m_allocation;
+	int32 m_maxAllocation;
+
+	b2StackEntry m_entries[b2_maxStackEntries];
+	int32 m_entryCount;
+};
+
+#endif

+ 139 - 0
box2d.mod/Source/Common/jtypes.h

@@ -0,0 +1,139 @@
+/*---------------------------------------------------------------------------------
+	$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 <stdint.h>
+
+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
+//---------------------------------------------------------------------------------

+ 122 - 0
box2d.mod/Source/Dynamics/Contacts/b2CircleContact.cpp

@@ -0,0 +1,122 @@
+/*
+* 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 <new>
+#include <cstring>
+
+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 = b2MixFriction(m_shape1->GetFriction(), m_shape2->GetFriction());
+	cp.restitution = b2MixRestitution(m_shape1->GetRestitution(), m_shape2->GetRestitution());
+
+	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);
+		}
+	}
+}

+ 46 - 0
box2d.mod/Source/Dynamics/Contacts/b2CircleContact.h

@@ -0,0 +1,46 @@
+/*
+* 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 CIRCLE_CONTACT_H
+#define CIRCLE_CONTACT_H
+
+#include "../../Common/b2Math.h"
+#include "../../Collision/b2Collision.h"
+#include "b2Contact.h"
+
+class b2BlockAllocator;
+
+class b2CircleContact : public b2Contact
+{
+public:
+	static b2Contact* Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+	b2CircleContact(b2Shape* shape1, b2Shape* shape2);
+	~b2CircleContact() {}
+
+	void Evaluate(b2ContactListener* listener);
+	b2Manifold* GetManifolds()
+	{
+		return &m_manifold;
+	}
+
+	b2Manifold m_manifold;
+};
+
+#endif

+ 175 - 0
box2d.mod/Source/Dynamics/Contacts/b2Contact.cpp

@@ -0,0 +1,175 @@
+/*
+* 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 "b2EdgeAndCircleContact.h"
+#include "b2PolyAndEdgeContact.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);
+	
+	AddType(b2EdgeAndCircleContact::Create, b2EdgeAndCircleContact::Destroy, e_edgeShape, e_circleShape);
+	AddType(b2PolyAndEdgeContact::Create, b2PolyAndEdgeContact::Destroy, e_polygonShape, e_edgeShape);
+}
+
+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_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;
+	}
+}

+ 179 - 0
box2d.mod/Source/Dynamics/Contacts/b2Contact.h

@@ -0,0 +1,179 @@
+/*
+* 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;
+
+	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

+ 731 - 0
box2d.mod/Source/Dynamics/Contacts/b2ContactSolver.cpp

@@ -0,0 +1,731 @@
+/*
+* 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"
+
+#define B2_DEBUG_SOLVER 0
+
+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];
+
+		b2Shape* shape1 = contact->m_shape1;
+		b2Shape* shape2 = contact->m_shape2;
+		b2Body* b1 = shape1->GetBody();
+		b2Body* b2 = shape2->GetBody();
+		int32 manifoldCount = contact->GetManifoldCount();
+		b2Manifold* manifolds = contact->GetManifolds();
+
+		float32 friction = b2MixFriction(shape1->GetFriction(), shape2->GetFriction());
+		float32 restitution = b2MixRestitution(shape1->GetRestitution(), shape2->GetRestitution());
+
+		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* cc = m_constraints + count;
+			cc->body1 = b1;
+			cc->body2 = b2;
+			cc->manifold = manifold;
+			cc->normal = normal;
+			cc->pointCount = manifold->pointCount;
+			cc->friction = friction;
+			cc->restitution = restitution;
+
+			for (int32 k = 0; k < cc->pointCount; ++k)
+			{
+				b2ManifoldPoint* cp = manifold->points + k;
+				b2ContactConstraintPoint* ccp = cc->points + k;
+
+				ccp->normalImpulse = cp->normalImpulse;
+				ccp->tangentImpulse = cp->tangentImpulse;
+				ccp->separation = cp->separation;
+
+				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 rn1 = b2Cross(ccp->r1, normal);
+				float32 rn2 = b2Cross(ccp->r2, normal);
+				rn1 *= rn1;
+				rn2 *= rn2;
+
+				float32 kNormal = b1->m_invMass + b2->m_invMass + b1->m_invI * rn1 + b2->m_invI * 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 * rn1 + b2->m_mass * b2->m_invI * rn2;
+
+				b2Assert(kEqualized > B2_FLT_EPSILON);
+				ccp->equalizedMass = 1.0f / kEqualized;
+
+				b2Vec2 tangent = b2Cross(normal, 1.0f);
+
+				float32 rt1 = b2Cross(ccp->r1, tangent);
+				float32 rt2 = b2Cross(ccp->r2, tangent);
+				rt1 *= rt1;
+				rt2 *= rt2;
+
+				float32 kTangent = b1->m_invMass + b2->m_invMass + b1->m_invI * rt1 + b2->m_invI * 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 = -step.inv_dt * ccp->separation; // TODO_ERIN b2TimeStep
+				}
+				else
+				{
+					float32 vRel = b2Dot(cc->normal, v2 + b2Cross(w2, ccp->r2) - v1 - b2Cross(w1, ccp->r1));
+					if (vRel < -b2_velocityThreshold)
+					{
+						ccp->velocityBias = -cc->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 invMass1 = b1->m_invMass;
+				float32 invI1 = b1->m_invI;
+				float32 invMass2 = b2->m_invMass;
+				float32 invI2 = b2->m_invI;
+
+				float32 rn11 = b2Cross(ccp1->r1, normal);
+				float32 rn12 = b2Cross(ccp1->r2, normal);
+				float32 rn21 = b2Cross(ccp2->r1, normal);
+				float32 rn22 = b2Cross(ccp2->r2, normal);
+
+				float32 k11 = invMass1 + invMass2 + invI1 * rn11 * rn11 + invI2 * rn12 * rn12;
+				float32 k22 = invMass1 + invMass2 + invI1 * rn21 * rn21 + invI2 * rn22 * rn22;
+				float32 k12 = invMass1 + invMass2 + invI1 * rn11 * rn21 + invI2 * rn12 * rn22;
+
+				// 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;
+				}
+			}
+
+			++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;
+
+		b2Assert(c->pointCount == 1 || c->pointCount == 2);
+
+		// Solve normal constraints
+		if (c->pointCount == 1)
+		{
+			b2ContactConstraintPoint* ccp = c->points + 0;
+
+			// 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;
+			v1 -= invMass1 * P;
+			w1 -= invI1 * b2Cross(ccp->r1, P);
+
+			v2 += invMass2 * P;
+			w2 += invI2 * b2Cross(ccp->r2, 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 = v2 + b2Cross(w2, cp1->r2) - v1 - b2Cross(w1, cp1->r1);
+			b2Vec2 dv2 = v2 + b2Cross(w2, cp2->r2) - v1 - b2Cross(w1, cp2->r1);
+
+			// 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;
+					v1 -= invMass1 * (P1 + P2);
+					w1 -= invI1 * (b2Cross(cp1->r1, P1) + b2Cross(cp2->r1, P2));
+
+					v2 += invMass2 * (P1 + P2);
+					w2 += invI2 * (b2Cross(cp1->r2, P1) + b2Cross(cp2->r2, P2));
+
+					// Accumulate
+					cp1->normalImpulse = x.x;
+					cp2->normalImpulse = x.y;
+
+#if B2_DEBUG_SOLVER == 1
+					// Postconditions
+					dv1 = v2 + b2Cross(w2, cp1->r2) - v1 - b2Cross(w1, cp1->r1);
+					dv2 = v2 + b2Cross(w2, cp2->r2) - v1 - b2Cross(w1, cp2->r1);
+
+					// 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;
+					v1 -= invMass1 * (P1 + P2);
+					w1 -= invI1 * (b2Cross(cp1->r1, P1) + b2Cross(cp2->r1, P2));
+
+					v2 += invMass2 * (P1 + P2);
+					w2 += invI2 * (b2Cross(cp1->r2, P1) + b2Cross(cp2->r2, P2));
+
+					// Accumulate
+					cp1->normalImpulse = x.x;
+					cp2->normalImpulse = x.y;
+
+#if B2_DEBUG_SOLVER == 1
+					// Postconditions
+					dv1 = v2 + b2Cross(w2, cp1->r2) - v1 - b2Cross(w1, cp1->r1);
+
+					// Compute normal velocity
+					vn1 = b2Dot(dv1, normal);
+
+					b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol);
+#endif
+					break;
+				}
+
+
+				//
+				// Case 3: w2 = 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;
+					v1 -= invMass1 * (P1 + P2);
+					w1 -= invI1 * (b2Cross(cp1->r1, P1) + b2Cross(cp2->r1, P2));
+
+					v2 += invMass2 * (P1 + P2);
+					w2 += invI2 * (b2Cross(cp1->r2, P1) + b2Cross(cp2->r2, P2));
+
+					// Accumulate
+					cp1->normalImpulse = x.x;
+					cp2->normalImpulse = x.y;
+
+#if B2_DEBUG_SOLVER == 1
+					// Postconditions
+					dv2 = v2 + b2Cross(w2, cp2->r2) - v1 - b2Cross(w1, cp2->r1);
+
+					// 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;
+					v1 -= invMass1 * (P1 + P2);
+					w1 -= invI1 * (b2Cross(cp1->r1, P1) + b2Cross(cp2->r1, P2));
+
+					v2 += invMass2 * (P1 + P2);
+					w2 += invI2 * (b2Cross(cp1->r2, P1) + b2Cross(cp2->r2, 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;
+			}
+		}
+
+		// 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;
+		}
+	}
+}
+
+#if 1
+// 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* 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 impulse = -ccp->equalizedMass * C;
+
+			b2Vec2 P = impulse * normal;
+
+			b1->m_sweep.c -= invMass1 * P;
+			b1->m_sweep.a -= invI1 * b2Cross(r1, P);
+			b1->SynchronizeTransform();
+
+			b2->m_sweep.c += invMass2 * P;
+			b2->m_sweep.a += invI2 * b2Cross(r2, P);
+			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;
+}
+
+#else
+
+// Block solver. Doesn't seem that great.
+void b2ContactSolver::SolvePositionConstraints(float32 baumgarte)
+{
+	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;
+		bool singlePoint = c->pointCount == 1;
+
+		if (c->pointCount == 2)
+		{
+			b2ContactConstraintPoint* ccp1 = c->points + 0;
+			b2ContactConstraintPoint* ccp2 = c->points + 1;
+
+			b2Vec2 r11 = b2Mul(b1->GetXForm().R, ccp1->localAnchor1 - b1->GetLocalCenter());
+			b2Vec2 r12 = b2Mul(b2->GetXForm().R, ccp1->localAnchor2 - b2->GetLocalCenter());
+
+			b2Vec2 r21 = b2Mul(b1->GetXForm().R, ccp2->localAnchor1 - b1->GetLocalCenter());
+			b2Vec2 r22 = b2Mul(b2->GetXForm().R, ccp2->localAnchor2 - b2->GetLocalCenter());
+
+			b2Vec2 p11 = b1->m_sweep.c + r11;
+			b2Vec2 p12 = b2->m_sweep.c + r12;
+			b2Vec2 dp1 = p12 - p11;
+
+			b2Vec2 p21 = b1->m_sweep.c + r21;
+			b2Vec2 p22 = b2->m_sweep.c + r22;
+			b2Vec2 dp2 = p22 - p21;
+
+			float32 rn11 = b2Cross(r11, normal);
+			float32 rn12 = b2Cross(r12, normal);
+			float32 rn21 = b2Cross(r21, normal);
+			float32 rn22 = b2Cross(r22, normal);
+
+			float32 k11 = invMass1 + invMass2 + invI1 * rn11 * rn11 + invI2 * rn12 * rn12;
+			float32 k22 = invMass1 + invMass2 + invI1 * rn21 * rn21 + invI2 * rn22 * rn22;
+			float32 k12 = invMass1 + invMass2 + invI1 * rn11 * rn21 + invI2 * rn12 * rn22;
+
+			// Ensure a reasonable condition number.
+			const float32 k_maxConditionNumber = 100.0f;
+			if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12))
+			{
+				b2Mat22 K;
+				K.col1.Set(k11, k12);
+				K.col2.Set(k12, k22);
+
+				float32 separation1 = b2Dot(dp1, normal) + ccp1->separation;
+				float32 separation2 = b2Dot(dp2, normal) + ccp2->separation;
+
+				b2Vec2 C;
+				C.x = baumgarte * (separation1 + b2_linearSlop);
+				C.y = baumgarte * (separation2 + b2_linearSlop);
+
+				b2Vec2 f = K.Solve(-C);
+
+				if (f.x < 0.0f && f.y < 0.0f)
+				{
+					f.SetZero();
+				}
+				else if (f.x < 0.0f)
+				{
+					f.x = 0.0f;
+					f.y = -C.y / k22;
+				}
+				else if (f.y < 0.0f)
+				{
+					f.x = -C.x / k11;
+					f.y = 0.0f;
+				}
+
+				b2Vec2 P1 = f.x * normal;
+				b2Vec2 P2 = f.y * normal;
+
+				b1->m_sweep.c -= invMass1 * (P1 + P2);
+				b1->m_sweep.a -= invI1 * (b2Cross(r11, P1) + b2Cross(r21, P2));
+				b1->SynchronizeTransform();
+
+				b2->m_sweep.c += invMass2 * (P1 + P2);
+				b2->m_sweep.a += invI2 * (b2Cross(r12, P1) + b2Cross(r22, P2));
+				b2->SynchronizeTransform();
+			}
+			else
+			{
+				// The constraints are linearly dependent, so just use the first one.
+				// This my cause a problem if the deepest one is ignored.
+				singlePoint = true;
+			}
+		}
+
+		if (singlePoint)
+		{
+			b2ContactConstraintPoint* ccp = c->points + 0;
+
+			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;
+
+			// Prevent large corrections and allow slop.
+			float32 C = baumgarte * b2Clamp(separation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f);
+
+			// Compute normal impulse
+			float32 impulse = -ccp->equalizedMass * C;
+
+			b2Vec2 P = impulse * normal;
+
+			b1->m_sweep.c -= invMass1 * P;
+			b1->m_sweep.a -= invI1 * b2Cross(r1, P);
+			b1->SynchronizeTransform();
+
+			b2->m_sweep.c += invMass2 * P;
+			b2->m_sweep.a += invI2 * b2Cross(r2, P);
+			b2->SynchronizeTransform();
+		}
+	}
+}
+
+#endif

+ 78 - 0
box2d.mod/Source/Dynamics/Contacts/b2ContactSolver.h

@@ -0,0 +1,78 @@
+/*
+* 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_SOLVER_H
+#define CONTACT_SOLVER_H
+
+#include "../../Common/b2Math.h"
+#include "../../Collision/b2Collision.h"
+#include "../b2World.h"
+
+class b2Contact;
+class b2Body;
+class b2Island;
+class b2StackAllocator;
+
+struct b2ContactConstraintPoint
+{
+	b2Vec2 localAnchor1;
+	b2Vec2 localAnchor2;
+	b2Vec2 r1;
+	b2Vec2 r2;
+	float32 normalImpulse;
+	float32 tangentImpulse;
+	float32 normalMass;
+	float32 tangentMass;
+	float32 equalizedMass;
+	float32 separation;
+	float32 velocityBias;
+};
+
+struct b2ContactConstraint
+{
+	b2ContactConstraintPoint points[b2_maxManifoldPoints];
+	b2Vec2 normal;
+	b2Mat22 normalMass;
+	b2Mat22 K;
+	b2Manifold* manifold;
+	b2Body* body1;
+	b2Body* body2;
+	float32 friction;
+	float32 restitution;
+	int32 pointCount;
+};
+
+class b2ContactSolver
+{
+public:
+	b2ContactSolver(const b2TimeStep& step, b2Contact** contacts, int32 contactCount, b2StackAllocator* allocator);
+	~b2ContactSolver();
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints();
+	void FinalizeVelocityConstraints();
+
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2TimeStep m_step;
+	b2StackAllocator* m_allocator;
+	b2ContactConstraint* m_constraints;
+	int m_constraintCount;
+};
+
+#endif

+ 193 - 0
box2d.mod/Source/Dynamics/Contacts/b2EdgeAndCircleContact.cpp

@@ -0,0 +1,193 @@
+/*
+* 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 "b2EdgeAndCircleContact.h"
+#include "../b2Body.h"
+#include "../b2WorldCallbacks.h"
+#include "../../Common/b2BlockAllocator.h"
+#include "../../Collision/Shapes/b2EdgeShape.h"
+
+#include <new>
+#include <cstring>
+
+b2Contact* b2EdgeAndCircleContact::Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator)
+{
+	void* mem = allocator->Allocate(sizeof(b2EdgeAndCircleContact));
+	return new (mem) b2EdgeAndCircleContact(shape1, shape2);
+}
+
+void b2EdgeAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
+{
+	((b2EdgeAndCircleContact*)contact)->~b2EdgeAndCircleContact();
+	allocator->Free(contact, sizeof(b2EdgeAndCircleContact));
+}
+
+b2EdgeAndCircleContact::b2EdgeAndCircleContact(b2Shape* s1, b2Shape* s2)
+: b2Contact(s1, s2)
+{
+	b2Assert(m_shape1->GetType() == e_edgeShape);
+	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 b2EdgeAndCircleContact::Evaluate(b2ContactListener* listener)
+{
+	b2Body* b1 = m_shape1->GetBody();
+	b2Body* b2 = m_shape2->GetBody();
+
+	b2Manifold m0;
+	memcpy(&m0, &m_manifold, sizeof(b2Manifold));
+
+	b2CollideEdgeAndCircle(&m_manifold, (b2EdgeShape*)m_shape1, b1->GetXForm(), (b2CircleShape*)m_shape2, b2->GetXForm());
+
+	b2ContactPoint cp;
+	cp.shape1 = m_shape1;
+	cp.shape2 = m_shape2;
+	cp.friction = b2MixFriction(m_shape1->GetFriction(), m_shape2->GetFriction());
+	cp.restitution = b2MixRestitution(m_shape1->GetRestitution(), m_shape2->GetRestitution());
+
+	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);
+		}
+	}
+}
+
+void b2EdgeAndCircleContact::b2CollideEdgeAndCircle(b2Manifold* manifold,
+																const b2EdgeShape* edge, 
+																const b2XForm& xf1,
+																const b2CircleShape* circle, 
+																const b2XForm& xf2)
+{
+	manifold->pointCount = 0;
+	b2Vec2 d;
+	b2Vec2 c = b2Mul(xf2, circle->GetLocalPosition());
+	b2Vec2 cLocal = b2MulT(xf1, c);
+	b2Vec2 n = edge->GetNormalVector();
+	b2Vec2 v1 = edge->GetVertex1();
+	b2Vec2 v2 = edge->GetVertex2();
+	float32 radius = circle->GetRadius();
+	float32 separation;
+	
+	float32 dirDist = b2Dot((cLocal - v1), edge->GetDirectionVector());
+	if (dirDist <= 0) {
+		d = cLocal - v1;
+		if (b2Dot(d, edge->GetCorner1Vector()) < 0) {
+			return;
+		}
+		d = c - b2Mul(xf1, v1);
+	} else if (dirDist >= edge->GetLength()) {
+		d = cLocal - v2;
+		if (b2Dot(d, edge->GetCorner2Vector()) > 0) {
+			return;
+		}
+		d = c - b2Mul(xf1, v2);
+	} else {
+		separation = b2Dot(cLocal - v1, n);
+		if (separation > radius || separation < -radius) {
+			return;
+		}
+		separation -= radius;
+		manifold->normal = b2Mul(xf1.R, n);
+		manifold->pointCount = 1;
+		manifold->points[0].id.key = 0;
+		manifold->points[0].separation = separation;
+		c = c - radius * manifold->normal;
+		manifold->points[0].localPoint1 = b2MulT(xf1, c);
+		manifold->points[0].localPoint2 = b2MulT(xf2, c);
+		return;
+	}
+	
+	float32 distSqr = b2Dot(d,d);
+	if (distSqr > radius * radius)
+	{
+		return;
+	}
+	
+	if (distSqr < B2_FLT_EPSILON)
+	{
+		separation = -radius;
+		manifold->normal = b2Mul(xf1.R, n);
+	}
+	else
+	{
+		separation = d.Normalize() - radius;
+		manifold->normal = d;
+	}
+	
+	manifold->pointCount = 1;
+	manifold->points[0].id.key = 0;
+	manifold->points[0].separation = separation;
+	c = c - radius * manifold->normal;
+	manifold->points[0].localPoint1 = b2MulT(xf1, c);
+	manifold->points[0].localPoint2 = b2MulT(xf2, c);
+}

+ 51 - 0
box2d.mod/Source/Dynamics/Contacts/b2EdgeAndCircleContact.h

@@ -0,0 +1,51 @@
+/*
+* 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 EDGE_AND_CIRCLE_CONTACT_H
+#define EDGE_AND_CIRCLE_CONTACT_H
+
+#include "../../Common/b2Math.h"
+#include "../../Collision/b2Collision.h"
+#include "../../Collision/Shapes/b2EdgeShape.h"
+#include "../../Collision/Shapes/b2CircleShape.h"
+#include "b2Contact.h"
+
+class b2BlockAllocator;
+
+class b2EdgeAndCircleContact : public b2Contact
+{
+public:
+	static b2Contact* Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+	b2EdgeAndCircleContact(b2Shape* shape1, b2Shape* shape2);
+	~b2EdgeAndCircleContact() {}
+
+	void Evaluate(b2ContactListener* listener);
+	void b2CollideEdgeAndCircle(b2Manifold* manifold,
+									  const b2EdgeShape* edge, const b2XForm& xf1,
+									  const b2CircleShape* circle, const b2XForm& xf2);
+	b2Manifold* GetManifolds()
+	{
+		return &m_manifold;
+	}
+
+	b2Manifold m_manifold;
+};
+
+#endif

+ 33 - 0
box2d.mod/Source/Dynamics/Contacts/b2NullContact.h

@@ -0,0 +1,33 @@
+/*
+* 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_NULL_CONTACT_H
+#define B2_NULL_CONTACT_H
+
+#include "../../Common/b2Math.h"
+#include "b2Contact.h"
+
+class b2NullContact : public b2Contact
+{
+public:
+	b2NullContact() {}
+	void Evaluate(b2ContactListener*) {}
+	b2Manifold* GetManifolds() { return NULL; }
+};
+
+#endif

+ 156 - 0
box2d.mod/Source/Dynamics/Contacts/b2PolyAndCircleContact.cpp

@@ -0,0 +1,156 @@
+/*
+* 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 <new>
+#include <cstring>
+
+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;
+}
+
+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 = b2MixFriction(m_shape1->GetFriction(), m_shape2->GetFriction());
+	cp.restitution = b2MixRestitution(m_shape1->GetRestitution(), m_shape2->GetRestitution());
+
+	// 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);
+	}
+}

+ 44 - 0
box2d.mod/Source/Dynamics/Contacts/b2PolyAndCircleContact.h

@@ -0,0 +1,44 @@
+/*
+* 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 POLY_AND_CIRCLE_CONTACT_H
+#define POLY_AND_CIRCLE_CONTACT_H
+
+#include "b2Contact.h"
+
+class b2BlockAllocator;
+
+class b2PolyAndCircleContact : public b2Contact
+{
+public:
+	static b2Contact* Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+	b2PolyAndCircleContact(b2Shape* shape1, b2Shape* shape2);
+	~b2PolyAndCircleContact() {}
+
+	void Evaluate(b2ContactListener* listener);
+	b2Manifold* GetManifolds()
+	{
+		return &m_manifold;
+	}
+
+	b2Manifold m_manifold;
+};
+
+#endif

+ 369 - 0
box2d.mod/Source/Dynamics/Contacts/b2PolyAndEdgeContact.cpp

@@ -0,0 +1,369 @@
+/*
+* 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 "b2PolyAndEdgeContact.h"
+#include "../b2Body.h"
+#include "../b2WorldCallbacks.h"
+#include "../../Common/b2BlockAllocator.h"
+#include "../../Collision/Shapes/b2EdgeShape.h"
+#include "../../Collision/Shapes/b2PolygonShape.h"
+
+#include <new>
+#include <cstring>
+
+b2Contact* b2PolyAndEdgeContact::Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator)
+{
+	void* mem = allocator->Allocate(sizeof(b2PolyAndEdgeContact));
+	return new (mem) b2PolyAndEdgeContact(shape1, shape2);
+}
+
+void b2PolyAndEdgeContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
+{
+	((b2PolyAndEdgeContact*)contact)->~b2PolyAndEdgeContact();
+	allocator->Free(contact, sizeof(b2PolyAndEdgeContact));
+}
+
+b2PolyAndEdgeContact::b2PolyAndEdgeContact(b2Shape* s1, b2Shape* s2)
+: b2Contact(s1, s2)
+{
+	b2Assert(m_shape1->GetType() == e_polygonShape);
+	b2Assert(m_shape2->GetType() == e_edgeShape);
+	m_manifold.pointCount = 0;
+}
+
+void b2PolyAndEdgeContact::Evaluate(b2ContactListener* listener)
+{
+	b2Body* b1 = m_shape1->GetBody();
+	b2Body* b2 = m_shape2->GetBody();
+
+	b2Manifold m0;
+	memcpy(&m0, &m_manifold, sizeof(b2Manifold));
+
+	b2CollidePolyAndEdge(&m_manifold, (b2PolygonShape*)m_shape1, b1->GetXForm(), (b2EdgeShape*)m_shape2, b2->GetXForm());
+
+	bool persisted[b2_maxManifoldPoints] = {false, false};
+
+	b2ContactPoint cp;
+	cp.shape1 = m_shape1;
+	cp.shape2 = m_shape2;
+	cp.friction = b2MixFriction(m_shape1->GetFriction(), m_shape2->GetFriction());
+	cp.restitution = b2MixRestitution(m_shape1->GetRestitution(), m_shape2->GetRestitution());
+
+	// 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);
+	}
+}
+
+void b2PolyAndEdgeContact::b2CollidePolyAndEdge(b2Manifold* manifold,
+														  const b2PolygonShape* polygon, 
+														  const b2XForm& xf1,
+														  const b2EdgeShape* edge, 
+														  const b2XForm& xf2)
+{
+	manifold->pointCount = 0;
+	b2Vec2 v1 = b2Mul(xf2, edge->GetVertex1());
+	b2Vec2 v2 = b2Mul(xf2, edge->GetVertex2());
+	b2Vec2 n = b2Mul(xf2.R, edge->GetNormalVector());
+	b2Vec2 v1Local = b2MulT(xf1, v1);
+	b2Vec2 v2Local = b2MulT(xf1, v2);
+	b2Vec2 nLocal = b2MulT(xf1.R, n);
+		
+	float32 separation1;
+	int32 separationIndex1 = -1; // which normal on the poly found the shallowest depth?
+	float32 separationMax1 = -B2_FLT_MAX; // the shallowest depth of edge in poly
+	float32 separation2;
+	int32 separationIndex2 = -1; // which normal on the poly found the shallowest depth?
+	float32 separationMax2 = -B2_FLT_MAX; // the shallowest depth of edge in poly
+	float32 separationMax = -B2_FLT_MAX; // the shallowest depth of edge in poly
+	bool separationV1 = false; // is the shallowest depth from edge's v1 or v2 vertex?
+	int32 separationIndex = -1; // which normal on the poly found the shallowest depth?
+		
+	int32 vertexCount = polygon->GetVertexCount();
+	const b2Vec2* vertices = polygon->GetVertices();
+	const b2Vec2* normals = polygon->GetNormals();
+		
+	int32 enterStartIndex = -1; // the last poly vertex above the edge
+	int32 enterEndIndex = -1; // the first poly vertex below the edge
+	int32 exitStartIndex = -1; // the last poly vertex below the edge
+	int32 exitEndIndex = -1; // the first poly vertex above the edge
+	//int32 deepestIndex;
+	
+	// the "N" in the following variables refers to the edge's normal. 
+	// these are projections of poly vertices along the edge's normal, 
+	// a.k.a. they are the separation of the poly from the edge. 
+	float32 prevSepN = 0.0f;
+	float32 nextSepN = 0.0f;
+	float32 enterSepN = 0.0f; // the depth of enterEndIndex under the edge (stored as a separation, so it's negative)
+	float32 exitSepN = 0.0f; // the depth of exitStartIndex under the edge (stored as a separation, so it's negative)
+	float32 deepestSepN = B2_FLT_MAX; // the depth of the deepest poly vertex under the end (stored as a separation, so it's negative)
+	
+	
+	// for each poly normal, get the edge's depth into the poly. 
+	// for each poly vertex, get the vertex's depth into the edge. 
+	// use these calculations to define the remaining variables declared above.
+	prevSepN = b2Dot(vertices[vertexCount-1] - v1Local, nLocal);
+	for (int32 i = 0; i < vertexCount; i++)
+	{
+		separation1 = b2Dot(v1Local - vertices[i], normals[i]);
+		separation2 = b2Dot(v2Local - vertices[i], normals[i]);
+		if (separation2 < separation1) {
+			if (separation2 > separationMax) {
+				separationMax = separation2;
+				separationV1 = false;
+				separationIndex = i;
+			}
+		} else {
+			if (separation1 > separationMax) {
+				separationMax = separation1;
+				separationV1 = true;
+				separationIndex = i;
+			}
+		}
+		if (separation1 > separationMax1) {
+			separationMax1 = separation1;
+			separationIndex1 = i;
+		}
+		if (separation2 > separationMax2) {
+			separationMax2 = separation2;
+			separationIndex2 = i;
+		}
+		
+		nextSepN = b2Dot(vertices[i] - v1Local, nLocal);
+		if (nextSepN >= 0.0f && prevSepN < 0.0f) {
+			exitStartIndex = (i == 0) ? vertexCount-1 : i-1;
+			exitEndIndex = i;
+			exitSepN = prevSepN;
+		} else if (nextSepN < 0.0f && prevSepN >= 0.0f) {
+			enterStartIndex = (i == 0) ? vertexCount-1 : i-1;
+			enterEndIndex = i;
+			enterSepN = nextSepN;
+		}
+		if (nextSepN < deepestSepN) {
+			deepestSepN = nextSepN;
+			//deepestIndex = i;
+		}
+		prevSepN = nextSepN;
+	}
+	
+	if (enterStartIndex == -1) {
+		// poly is entirely below or entirely above edge, return with no contact:
+		return;
+	}
+	if (separationMax > 0.0f) {
+		// poly is laterally disjoint with edge, return with no contact:
+		return;
+	}
+	
+	// if the poly is near a convex corner on the edge
+	if ((separationV1 && edge->Corner1IsConvex()) || (!separationV1 && edge->Corner2IsConvex())) {
+		// if shallowest depth was from edge into poly, 
+		// use the edge's vertex as the contact point:
+		if (separationMax > deepestSepN + b2_linearSlop) {
+			// if -normal angle is closer to adjacent edge than this edge, 
+			// let the adjacent edge handle it and return with no contact:
+			if (separationV1) {
+				if (b2Dot(normals[separationIndex1], b2MulT(xf1.R, b2Mul(xf2.R, edge->GetCorner1Vector()))) >= 0.0f) {
+					return;
+				}
+			} else {
+				if (b2Dot(normals[separationIndex2], b2MulT(xf1.R, b2Mul(xf2.R, edge->GetCorner2Vector()))) <= 0.0f) {
+					return;
+				}
+			}
+			
+			manifold->pointCount = 1;
+			manifold->normal = b2Mul(xf1.R, normals[separationIndex]);
+			manifold->points[0].separation = separationMax;
+			manifold->points[0].id.features.incidentEdge = (uint8)separationIndex;
+			manifold->points[0].id.features.incidentVertex = b2_nullFeature;
+			manifold->points[0].id.features.referenceEdge = 0;
+			manifold->points[0].id.features.flip = 0;
+			if (separationV1) {
+				manifold->points[0].localPoint1 = v1Local;
+				manifold->points[0].localPoint2 = edge->GetVertex1();
+			} else {
+				manifold->points[0].localPoint1 = v2Local;
+				manifold->points[0].localPoint2 = edge->GetVertex2();
+			}
+			return;
+		}
+	}
+	
+	// We're going to use the edge's normal now.
+	manifold->normal = (-1.0f) * n;
+	
+	// Check whether we only need one contact point.
+	if (enterEndIndex == exitStartIndex) {
+		manifold->pointCount = 1;
+		manifold->points[0].id.features.incidentEdge = (uint8)enterEndIndex;
+		manifold->points[0].id.features.incidentVertex = b2_nullFeature;
+		manifold->points[0].id.features.referenceEdge = 0;
+		manifold->points[0].id.features.flip = 0;
+		manifold->points[0].localPoint1 = vertices[enterEndIndex];
+		manifold->points[0].localPoint2 = b2MulT(xf2, b2Mul(xf1, vertices[enterEndIndex]));
+		manifold->points[0].separation = enterSepN;
+		return;
+	}
+		
+	manifold->pointCount = 2;
+	
+	// dirLocal should be the edge's direction vector, but in the frame of the polygon.
+	b2Vec2 dirLocal = b2Cross(nLocal, -1.0f); // TODO: figure out why this optimization didn't work
+	//b2Vec2 dirLocal = b2MulT(xf1.R, b2Mul(xf2.R, edge->GetDirectionVector()));
+	
+	float32 dirProj1 = b2Dot(dirLocal, vertices[enterEndIndex] - v1Local);
+	float32 dirProj2;
+	
+	// The contact resolution is more robust if the two manifold points are 
+	// adjacent to each other on the polygon. So pick the first two poly
+	// vertices that are under the edge:
+	exitEndIndex = (enterEndIndex == vertexCount - 1) ? 0 : enterEndIndex + 1;
+	if (exitEndIndex != exitStartIndex) {
+		exitStartIndex = exitEndIndex;
+		exitSepN = b2Dot(nLocal, vertices[exitStartIndex] - v1Local);
+	}
+	dirProj2 = b2Dot(dirLocal, vertices[exitStartIndex] - v1Local);
+	
+	manifold->points[0].id.features.incidentEdge = (uint8)enterEndIndex;
+	manifold->points[0].id.features.incidentVertex = b2_nullFeature;
+	manifold->points[0].id.features.referenceEdge = 0;
+	manifold->points[0].id.features.flip = 0;
+	
+	if (dirProj1 > edge->GetLength()) {
+		manifold->points[0].localPoint1 = v2Local;
+		manifold->points[0].localPoint2 = edge->GetVertex2();
+		float32 ratio = (edge->GetLength() - dirProj2) / (dirProj1 - dirProj2);
+		if (ratio > 100.0f * B2_FLT_EPSILON && ratio < 1.0f) {
+			manifold->points[0].separation = exitSepN * (1.0f - ratio) + enterSepN * ratio;
+		} else {
+			manifold->points[0].separation = enterSepN;
+		}
+	} else {
+		manifold->points[0].localPoint1 = vertices[enterEndIndex];
+		manifold->points[0].localPoint2 = b2MulT(xf2, b2Mul(xf1, vertices[enterEndIndex]));
+		manifold->points[0].separation = enterSepN;
+	}
+		
+	manifold->points[1].id.features.incidentEdge = (uint8)exitStartIndex;
+	manifold->points[1].id.features.incidentVertex = b2_nullFeature;
+	manifold->points[1].id.features.referenceEdge = 0;
+	manifold->points[1].id.features.flip = 0;
+		
+	if (dirProj2 < 0.0f) {
+		manifold->points[1].localPoint1 = v1Local;
+		manifold->points[1].localPoint2 = edge->GetVertex1();
+		float32 ratio = (-dirProj1) / (dirProj2 - dirProj1);
+		if (ratio > 100.0f * B2_FLT_EPSILON && ratio < 1.0f) {
+			manifold->points[1].separation = enterSepN * (1.0f - ratio) + exitSepN * ratio;
+		} else {
+			manifold->points[1].separation = exitSepN;
+		}
+	} else {
+		manifold->points[1].localPoint1 = vertices[exitStartIndex];
+		manifold->points[1].localPoint2 = b2MulT(xf2, b2Mul(xf1, vertices[exitStartIndex]));
+		manifold->points[1].separation = exitSepN;
+	}
+}

+ 47 - 0
box2d.mod/Source/Dynamics/Contacts/b2PolyAndEdgeContact.h

@@ -0,0 +1,47 @@
+/*
+* 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 POLY_AND_EDGE_CONTACT_H
+#define POLY_AND_EDGE_CONTACT_H
+
+#include "b2Contact.h"
+
+class b2BlockAllocator;
+
+class b2PolyAndEdgeContact : public b2Contact
+{
+public:
+	static b2Contact* Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+	b2PolyAndEdgeContact(b2Shape* shape1, b2Shape* shape2);
+	~b2PolyAndEdgeContact() {}
+
+	void Evaluate(b2ContactListener* listener);
+	void b2CollidePolyAndEdge(b2Manifold* manifold,
+									const b2PolygonShape* poly, const b2XForm& xf1,
+									const b2EdgeShape* edge, const b2XForm& xf2);
+	b2Manifold* GetManifolds()
+	{
+		return &m_manifold;
+	}
+
+	b2Manifold m_manifold;
+};
+
+#endif

+ 157 - 0
box2d.mod/Source/Dynamics/Contacts/b2PolyContact.cpp

@@ -0,0 +1,157 @@
+/*
+* 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 <memory>
+#include <new>
+#include <cstring>
+
+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 = b2MixFriction(m_shape1->GetFriction(), m_shape2->GetFriction());
+	cp.restitution = b2MixRestitution(m_shape1->GetRestitution(), m_shape2->GetRestitution());
+
+	// 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);
+	}
+}

+ 44 - 0
box2d.mod/Source/Dynamics/Contacts/b2PolyContact.h

@@ -0,0 +1,44 @@
+/*
+* 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 POLYCONTACT_H
+#define POLYCONTACT_H
+
+#include "b2Contact.h"
+
+class b2BlockAllocator;
+
+class b2PolygonContact : public b2Contact
+{
+public:
+	static b2Contact* Create(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+	b2PolygonContact(b2Shape* shape1, b2Shape* shape2);
+	~b2PolygonContact() {}
+
+	void Evaluate(b2ContactListener* listener);
+	b2Manifold* GetManifolds()
+	{
+		return &m_manifold;
+	}
+
+	b2Manifold m_manifold;
+};
+
+#endif

+ 111 - 0
box2d.mod/Source/Dynamics/Controllers/b2BuoyancyController.cpp

@@ -0,0 +1,111 @@
+/*
+* 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 "b2BuoyancyController.h"
+
+b2BuoyancyController::b2BuoyancyController(const b2BuoyancyControllerDef* def) : b2Controller(def)
+{
+	normal = def->normal;
+	offset = def->offset;
+	density = def->density;
+	velocity = def->velocity;
+	linearDrag = def->linearDrag;
+	angularDrag = def->angularDrag;
+	useDensity = def->useDensity;
+	useWorldGravity = def->useWorldGravity;
+	gravity = def->gravity;
+}
+
+void b2BuoyancyController::Step(const b2TimeStep& step)
+{
+	B2_NOT_USED(step);
+	if(!m_bodyList)
+		return;
+	if(useWorldGravity){
+		gravity = m_world->GetGravity();
+	}
+	for(b2ControllerEdge *i=m_bodyList;i;i=i->nextBody){
+		b2Body* body = i->body;
+		if(body->IsSleeping()){
+			//Buoyancy force is just a function of position,
+			//so unlike most forces, it is safe to ignore sleeping bodes
+			continue;
+		}
+		b2Vec2 areac(0,0);
+		b2Vec2 massc(0,0);
+		float32 area = 0;
+		float32 mass = 0;
+		for(b2Shape* shape=body->GetShapeList();shape;shape=shape->GetNext()){
+			b2Vec2 sc(0,0);
+			float32 sarea = shape->ComputeSubmergedArea(normal,offset,body->GetXForm(),&sc);
+			area += sarea;
+			areac.x += sarea * sc.x;
+			areac.y += sarea * sc.y;
+			float shapeDensity = 0;
+			if(useDensity){
+				//TODO: Expose density publicly
+				shapeDensity=shape->GetDensity();
+			}else{
+				shapeDensity = 1;
+			}
+			mass += sarea*shapeDensity;
+			massc.x += sarea * sc.x * shapeDensity;
+			massc.y += sarea * sc.y * shapeDensity;
+		}
+		areac.x/=area;
+		areac.y/=area;
+		b2Vec2 localCentroid = b2MulT(body->GetXForm(),areac);
+		massc.x/=mass;
+		massc.y/=mass;
+		if(area<B2_FLT_EPSILON)
+			continue;
+		//Buoyancy
+		b2Vec2 buoyancyForce = -density*area*gravity;
+		body->ApplyForce(buoyancyForce,massc);
+		//Linear drag
+		b2Vec2 dragForce = body->GetLinearVelocityFromWorldPoint(areac) - velocity;
+		dragForce *= -linearDrag*area;
+		body->ApplyForce(dragForce,areac);
+		//Angular drag
+		//TODO: Something that makes more physical sense?
+		body->ApplyTorque(-body->GetInertia()/body->GetMass()*area*body->GetAngularVelocity()*angularDrag);
+		
+	}
+}
+
+void b2BuoyancyController::Draw(b2DebugDraw *debugDraw)
+{
+	float32 r = 1000;
+	b2Vec2 p1 = offset * normal + b2Cross(normal, r);
+	b2Vec2 p2 = offset * normal - b2Cross(normal, r);
+
+	b2Color color(0,0,0.8f);
+
+	debugDraw->DrawSegment(p1, p2, color);
+}
+
+void b2BuoyancyController::Destroy(b2BlockAllocator* allocator)
+{
+	allocator->Free(this, sizeof(b2BuoyancyController));
+}
+
+b2BuoyancyController* b2BuoyancyControllerDef::Create(b2BlockAllocator* allocator)
+{
+	void* mem = allocator->Allocate(sizeof(b2BuoyancyController));
+	return new (mem) b2BuoyancyController(this);
+}

+ 102 - 0
box2d.mod/Source/Dynamics/Controllers/b2BuoyancyController.h

@@ -0,0 +1,102 @@
+/*
+* 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_BUOYANCYCONTROLLER_H
+#define B2_BUOYANCYCONTROLLER_H
+
+#include "b2Controller.h"
+
+class b2BuoyancyControllerDef;
+
+/// Calculates buoyancy forces for fluids in the form of a half plane.
+class b2BuoyancyController : public b2Controller{
+public:
+	/// The outer surface normal
+	b2Vec2 normal;
+	/// The height of the fluid surface along the normal
+	float32 offset;
+	/// The fluid density
+	float32 density;
+	/// Fluid velocity, for drag calculations
+	b2Vec2 velocity;
+	/// Linear drag co-efficient
+	float32 linearDrag;
+	/// Linear drag co-efficient
+	float32 angularDrag;
+	/// If false, bodies are assumed to be uniformly dense, otherwise use the shapes densities
+	bool useDensity; //False by default to prevent a gotcha
+	/// If true, gravity is taken from the world instead of the gravity parameter.
+	bool useWorldGravity;
+	/// Gravity vector, if the world's gravity is not used
+	b2Vec2 gravity;
+
+	/// @see b2Controller::Step
+	void Step(const b2TimeStep& step);
+
+	/// @see b2Controller::Draw
+	void Draw(b2DebugDraw *debugDraw);
+
+protected:
+	void Destroy(b2BlockAllocator* allocator);
+
+private:
+	friend class b2BuoyancyControllerDef;
+	b2BuoyancyController(const b2BuoyancyControllerDef* def);
+};
+
+/// This class is used to build buoyancy controllers
+class b2BuoyancyControllerDef : public b2ControllerDef
+{
+public:
+	/// The outer surface normal
+	b2Vec2 normal;
+	/// The height of the fluid surface along the normal
+	float32 offset;
+	/// The fluid density
+	float32 density;
+	/// Fluid velocity, for drag calculations
+	b2Vec2 velocity;
+	/// Linear drag co-efficient
+	float32 linearDrag;
+	/// Linear drag co-efficient
+	float32 angularDrag;
+	/// If false, bodies are assumed to be uniformly dense, otherwise use the shapes densities
+	bool useDensity; //False by default to prevent a gotcha
+	/// If true, gravity is taken from the world instead of the gravity parameter.
+	bool useWorldGravity;
+	/// Gravity vector, if the world's gravity is not used
+	b2Vec2 gravity;
+
+	b2BuoyancyControllerDef():
+		normal(0,1),
+		offset(0),
+		density(0),
+		velocity(0,0),
+		linearDrag(0),
+		angularDrag(0),
+		useDensity(false),
+		useWorldGravity(true),
+		gravity(0,0)
+	{
+	}
+
+private:
+	b2BuoyancyController* Create(b2BlockAllocator* allocator);
+};
+
+#endif

+ 46 - 0
box2d.mod/Source/Dynamics/Controllers/b2ConstantAccelController.cpp

@@ -0,0 +1,46 @@
+/*
+* 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 "b2ConstantAccelController.h"
+
+b2ConstantAccelController::b2ConstantAccelController(const b2ConstantAccelControllerDef* def) : b2Controller(def)
+{
+	A = def->A;
+}
+
+void b2ConstantAccelController::Step(const b2TimeStep& step)
+{
+	for(b2ControllerEdge *i=m_bodyList;i;i=i->nextBody){
+		b2Body* body = i->body;
+		if(body->IsSleeping())
+			continue; 
+		body->SetLinearVelocity(body->GetLinearVelocity()+step.dt*A);
+	}
+}
+
+void b2ConstantAccelController::Destroy(b2BlockAllocator* allocator)
+{
+	allocator->Free(this, sizeof(b2ConstantAccelController));
+}
+
+
+b2ConstantAccelController* b2ConstantAccelControllerDef::Create(b2BlockAllocator* allocator)
+{
+	void* mem = allocator->Allocate(sizeof(b2ConstantAccelController));
+	return new (mem) b2ConstantAccelController(this);
+}

+ 54 - 0
box2d.mod/Source/Dynamics/Controllers/b2ConstantAccelController.h

@@ -0,0 +1,54 @@
+/*
+* 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_CONSTANTACCELCONTROLLER_H
+#define B2_CONSTANTACCELCONTROLLER_H
+
+#include "b2Controller.h"
+
+class b2ConstantAccelControllerDef;
+
+/// Applies a force every frame
+class b2ConstantAccelController : public b2Controller{
+public:
+	/// The force to apply
+	b2Vec2 A;
+
+	/// @see b2Controller::Step
+	void Step(const b2TimeStep& step);
+
+protected:
+	void Destroy(b2BlockAllocator* allocator);
+
+private:
+	friend class b2ConstantAccelControllerDef;
+	b2ConstantAccelController(const b2ConstantAccelControllerDef* def);
+
+};
+
+/// This class is used to build constant acceleration controllers
+class b2ConstantAccelControllerDef : public b2ControllerDef
+{
+public:
+	/// The force to apply
+	b2Vec2 A;
+private:
+	b2ConstantAccelController* Create(b2BlockAllocator* allocator);
+};
+
+#endif

+ 47 - 0
box2d.mod/Source/Dynamics/Controllers/b2ConstantForceController.cpp

@@ -0,0 +1,47 @@
+/*
+* 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 "b2ConstantForceController.h"
+
+b2ConstantForceController::b2ConstantForceController(const b2ConstantForceControllerDef* def) : b2Controller(def)
+{
+	F = def->F;
+}
+
+void b2ConstantForceController::Step(const b2TimeStep& step)
+{
+	B2_NOT_USED(step);
+	for(b2ControllerEdge *i=m_bodyList;i;i=i->nextBody){
+		b2Body* body = i->body;
+		if(body->IsSleeping())
+			continue;
+		body->ApplyForce(F,body->GetWorldCenter());
+	}
+}
+
+void b2ConstantForceController::Destroy(b2BlockAllocator* allocator)
+{
+	allocator->Free(this, sizeof(b2ConstantForceController));
+}
+
+
+b2ConstantForceController* b2ConstantForceControllerDef::Create(b2BlockAllocator* allocator)
+{
+	void* mem = allocator->Allocate(sizeof(b2ConstantForceController));
+	return new (mem) b2ConstantForceController(this);
+}

+ 54 - 0
box2d.mod/Source/Dynamics/Controllers/b2ConstantForceController.h

@@ -0,0 +1,54 @@
+/*
+* 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_CONSTANTFORCECONTROLLER_H
+#define B2_CONSTANTFORCECONTROLLER_H
+
+#include "b2Controller.h"
+
+class b2ConstantForceControllerDef;
+
+/// Applies a force every frame
+class b2ConstantForceController : public b2Controller
+{
+public:
+	/// The force to apply
+	b2Vec2 F;
+
+	/// @see b2Controller::Step
+	void Step(const b2TimeStep& step);
+
+protected:
+	void Destroy(b2BlockAllocator* allocator);
+
+private:
+	friend class b2ConstantForceControllerDef;
+	b2ConstantForceController(const b2ConstantForceControllerDef* def);
+};
+
+/// This class is used to build constant force controllers
+class b2ConstantForceControllerDef : public b2ControllerDef
+{
+public:
+	/// The force to apply
+	b2Vec2 F;
+private:
+	b2ConstantForceController* Create(b2BlockAllocator* allocator);
+};
+
+#endif

+ 110 - 0
box2d.mod/Source/Dynamics/Controllers/b2Controller.cpp

@@ -0,0 +1,110 @@
+/*
+* 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 "b2Controller.h"
+#include "../../Common/b2BlockAllocator.h"
+
+
+b2Controller::~b2Controller()
+{
+	//Remove attached bodies
+	Clear();
+}
+
+void b2Controller::AddBody(b2Body* body)
+{
+	void* mem = m_world->m_blockAllocator.Allocate(sizeof(b2ControllerEdge));
+	b2ControllerEdge* edge = new (mem) b2ControllerEdge;
+	
+	edge->body = body;
+	edge->controller = this;
+	
+	//Add edge to controller list
+	edge->nextBody = m_bodyList;
+	edge->prevBody = NULL;
+	if(m_bodyList)
+		m_bodyList->prevBody = edge;
+	m_bodyList = edge;
+	++m_bodyCount;
+
+	//Add edge to body list
+	edge->nextController = body->m_controllerList;
+	edge->prevController = NULL;
+	if(body->m_controllerList)
+		body->m_controllerList->prevController = edge;
+	body->m_controllerList = edge;
+}
+
+void b2Controller::RemoveBody(b2Body* body)
+{
+	//Assert that the controller is not empty
+	b2Assert(m_bodyCount>0);
+
+	//Find the corresponding edge
+	b2ControllerEdge* edge = m_bodyList;
+	while(edge && edge->body!=body)
+		edge = edge->nextBody;
+
+	//Assert that we are removing a body that is currently attached to the controller
+	b2Assert(edge!=NULL);
+
+	//Remove edge from controller list
+	if(edge->prevBody)
+		edge->prevBody->nextBody = edge->nextBody;
+	if(edge->nextBody)
+		edge->nextBody->prevBody = edge->prevBody;
+	if(edge == m_bodyList)
+		m_bodyList = edge->nextBody;
+	--m_bodyCount;
+
+	//Remove edge from body list
+	if(edge->prevController)
+		edge->prevController->nextController = edge->nextController;
+	if(edge->nextController)
+		edge->nextController->prevController = edge->prevController;
+	if(edge == body->m_controllerList)
+		body->m_controllerList = edge->nextController;
+
+	//Free the edge
+	m_world->m_blockAllocator.Free(edge, sizeof(b2ControllerEdge));
+}
+
+void b2Controller::Clear(){
+
+	while(m_bodyList)
+	{
+		b2ControllerEdge* edge = m_bodyList;
+
+		//Remove edge from controller list
+		m_bodyList = edge->nextBody;
+
+		//Remove edge from body list
+		if(edge->prevController)
+			edge->prevController->nextController = edge->nextController;
+		if(edge->nextController)
+			edge->nextController->prevController = edge->prevController;
+		if(edge == edge->body->m_controllerList)
+			edge->body->m_controllerList = edge->nextController;
+
+		//Free the edge
+		m_world->m_blockAllocator.Free(edge, sizeof(b2ControllerEdge));
+	}
+
+	m_bodyCount = 0;
+}
+

+ 159 - 0
box2d.mod/Source/Dynamics/Controllers/b2Controller.h

@@ -0,0 +1,159 @@
+/*
+* 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_CONTROLLER_H
+#define B2_CONTROLLER_H
+
+#include "../../Dynamics/b2World.h"
+#include "../../Dynamics/b2Body.h"
+
+class b2Body;
+class b2World;
+
+class b2Controller;
+
+/// A controller edge is used to connect bodies and controllers together
+/// in a bipartite graph.
+struct b2ControllerEdge
+{
+	b2Controller* controller;		///< provides quick access to other end of this edge.
+	b2Body* body;					///< the body
+	b2ControllerEdge* prevBody;		///< the previous controller edge in the controllers's joint list
+	b2ControllerEdge* nextBody;		///< the next controller edge in the controllers's joint list
+	b2ControllerEdge* prevController;		///< the previous controller edge in the body's joint list
+	b2ControllerEdge* nextController;		///< the next controller edge in the body's joint list
+};
+
+class b2ControllerDef;
+
+/// Base class for controllers. Controllers are a convience for encapsulating common
+/// per-step functionality.
+class b2Controller
+{
+public:
+	virtual ~b2Controller();
+
+	/// Controllers override this to implement per-step functionality.
+	virtual void Step(const b2TimeStep& step) = 0;
+
+	/// Controllers override this to provide debug drawing.
+	virtual void Draw(b2DebugDraw *debugDraw) {B2_NOT_USED(debugDraw);};
+
+	/// Adds a body to the controller list.
+	void AddBody(b2Body* body);
+
+	/// Removes a body from the controller list.
+	void RemoveBody(b2Body* body);
+
+	/// Removes all bodies from the controller list.
+	void Clear();
+
+	/// Get the next controller in the world's body list.
+	b2Controller* GetNext();
+
+	/// Get the parent world of this body.
+	b2World* GetWorld();
+
+	/// Get the attached body list
+	b2ControllerEdge* GetBodyList();
+
+	/// Get the user data pointer that was provided in the controller definition.
+	void* GetUserData();
+
+	/// Set the user data. Use this to store your application specific data.
+	void SetUserData(void* data);
+
+protected:
+	friend class b2World;
+
+	b2World* m_world;
+
+	b2ControllerEdge* m_bodyList;
+	int32 m_bodyCount;
+
+	b2Controller(const b2ControllerDef* def):
+		m_world(NULL),
+		m_bodyList(NULL),
+		m_bodyCount(0),
+		m_prev(NULL),
+		m_next(NULL),
+		m_userData(NULL)
+		{
+			B2_NOT_USED(def);
+		}
+	virtual void Destroy(b2BlockAllocator* allocator) = 0;
+
+private:
+	b2Controller* m_prev;
+	b2Controller* m_next;
+
+	static void Destroy(b2Controller* controller, b2BlockAllocator* allocator);
+
+	void* m_userData;
+};
+
+class b2ControllerDef
+{
+protected:
+	b2ControllerDef()
+	{
+		userData = NULL;
+	}
+
+public:
+	virtual ~b2ControllerDef() {};
+	
+	/// Use this to store application specific controller data.
+	void* userData;
+
+private:
+	friend class b2World;
+	virtual b2Controller* Create(b2BlockAllocator* allocator) = 0;
+};
+
+inline b2Controller* b2Controller::GetNext()
+{
+	return m_next;
+}
+
+inline b2World* b2Controller::GetWorld()
+{
+	return m_world;
+}
+
+inline b2ControllerEdge* b2Controller::GetBodyList()
+{
+	return m_bodyList;
+}
+
+inline void b2Controller::Destroy(b2Controller* controller, b2BlockAllocator* allocator)
+{
+	controller->Destroy(allocator);
+}
+
+inline void* b2Controller::GetUserData()
+{
+	return m_userData;
+}
+
+inline void b2Controller::SetUserData(void* data)
+{
+	m_userData = data;
+}
+
+#endif

+ 70 - 0
box2d.mod/Source/Dynamics/Controllers/b2GravityController.cpp

@@ -0,0 +1,70 @@
+/*
+* 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 "b2GravityController.h"
+
+b2GravityController::b2GravityController(const b2GravityControllerDef* def) : b2Controller(def)
+{
+	G = def->G;
+	invSqr = def->invSqr;
+}
+
+void b2GravityController::Step(const b2TimeStep& step)
+{
+	B2_NOT_USED(step);
+	if(invSqr){
+		for(b2ControllerEdge *i=m_bodyList;i;i=i->nextBody){
+			b2Body* body1 = i->body;
+			for(b2ControllerEdge *j=m_bodyList;j!=i;j=j->nextBody){
+				b2Body* body2 = j->body;
+				b2Vec2 d = body2->GetWorldCenter() - body1->GetWorldCenter();
+				float32 r2 = d.LengthSquared();
+				if(r2 < B2_FLT_EPSILON)
+					continue;
+				b2Vec2 f = G / r2 / sqrt(r2) * body1->GetMass() * body2->GetMass() * d;
+				body1->ApplyForce(f      , body1->GetWorldCenter());
+				body2->ApplyForce(-1.0f*f, body2->GetWorldCenter());
+			}
+		}
+	}else{
+		for(b2ControllerEdge *i=m_bodyList;i;i=i->nextBody){
+			b2Body* body1 = i->body;
+			for(b2ControllerEdge *j=m_bodyList;j!=i;j=j->nextBody){
+				b2Body* body2 = j->body;
+				b2Vec2 d = body2->GetWorldCenter() - body1->GetWorldCenter();
+				float32 r2 = d.LengthSquared();
+				if(r2 < B2_FLT_EPSILON)
+					continue;
+				b2Vec2 f = G / r2 * body1->GetMass() * body2->GetMass() * d;
+				body1->ApplyForce(f      , body1->GetWorldCenter());
+				body2->ApplyForce(-1.0f*f, body2->GetWorldCenter());
+			}
+		}
+	}
+}
+
+void b2GravityController::Destroy(b2BlockAllocator* allocator)
+{
+	allocator->Free(this, sizeof(b2GravityController));
+}
+
+b2GravityController* b2GravityControllerDef::Create(b2BlockAllocator* allocator)
+{
+	void* mem = allocator->Allocate(sizeof(b2GravityController));
+	return new (mem) b2GravityController(this);
+}

+ 59 - 0
box2d.mod/Source/Dynamics/Controllers/b2GravityController.h

@@ -0,0 +1,59 @@
+/*
+* 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_GRAVITYCONTROLLER_H
+#define B2_GRAVITYCONTROLLER_H
+
+#include "b2Controller.h"
+
+class b2GravityControllerDef;
+
+/// Applies simplified gravity between every pair of bodies
+class b2GravityController : public b2Controller{
+public:
+	/// Specifies the strength of the gravitiation force
+	float32 G;
+	/// If true, gravity is proportional to r^-2, otherwise r^-1
+	bool invSqr;
+
+	/// @see b2Controller::Step
+	void Step(const b2TimeStep& step);
+
+protected:
+	void Destroy(b2BlockAllocator* allocator);
+
+private:
+	friend class b2GravityControllerDef;
+	b2GravityController(const b2GravityControllerDef* def);
+
+
+};
+
+/// This class is used to build gravity controllers
+class b2GravityControllerDef : public b2ControllerDef
+{
+public:
+	/// Specifies the strength of the gravitiation force
+	float32 G;
+	/// If true, gravity is proportional to r^-2, otherwise r^-1
+	bool invSqr;
+private:
+	b2GravityController* Create(b2BlockAllocator* allocator);
+};
+
+#endif

+ 72 - 0
box2d.mod/Source/Dynamics/Controllers/b2TensorDampingController.cpp

@@ -0,0 +1,72 @@
+/*
+* 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 "b2TensorDampingController.h"
+
+b2TensorDampingController::b2TensorDampingController(const b2TensorDampingControllerDef* def) : b2Controller(def)
+{
+	T = def->T;
+	maxTimestep = def->maxTimestep;
+}
+
+void b2TensorDampingController::Step(const b2TimeStep& step)
+{
+	float32 timestep = step.dt;
+	if(timestep<=B2_FLT_EPSILON)
+		return;
+	if(timestep>maxTimestep && maxTimestep>0)
+		timestep = maxTimestep;
+	for(b2ControllerEdge *i=m_bodyList;i;i=i->nextBody){
+		b2Body* body = i->body;
+		if(body->IsSleeping())
+			continue;
+		b2Vec2 damping = body->GetWorldVector(
+							b2Mul(T,
+								body->GetLocalVector(
+									body->GetLinearVelocity()
+								)
+							)
+						);
+		body->SetLinearVelocity(body->GetLinearVelocity() + timestep * damping);
+	}
+}
+
+void b2TensorDampingControllerDef::SetAxisAligned(float32 xDamping, float32 yDamping)
+{
+	T.col1.x = -xDamping;
+	T.col1.y = 0;
+	T.col2.x = 0;
+	T.col2.y = -yDamping;
+	if(xDamping>0 || yDamping>0){
+		maxTimestep = 1/b2Max(xDamping,yDamping);
+	}else{
+		maxTimestep = 0;
+	}
+}
+
+void b2TensorDampingController::Destroy(b2BlockAllocator* allocator)
+{
+	allocator->Free(this, sizeof(b2TensorDampingController));
+}
+
+
+b2TensorDampingController* b2TensorDampingControllerDef::Create(b2BlockAllocator* allocator)
+{
+	void* mem = allocator->Allocate(sizeof(b2TensorDampingController));
+	return new (mem) b2TensorDampingController(this);
+}

+ 69 - 0
box2d.mod/Source/Dynamics/Controllers/b2TensorDampingController.h

@@ -0,0 +1,69 @@
+/*
+* 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_TENSORDAMPINGCONTROLLER_H
+#define B2_TENSORDAMPINGCONTROLLER_H
+
+#include "b2Controller.h"
+
+class b2TensorDampingControllerDef;
+
+/// Applies top down linear damping to the controlled bodies
+/// The damping is calculated by multiplying velocity by a matrix in local co-ordinates.
+class b2TensorDampingController : public b2Controller{
+public:
+	/// Tensor to use in damping model
+	b2Mat22 T;
+	/*Some examples (matrixes in format (row1; row2) )
+	(-a 0;0 -a)		Standard isotropic damping with strength a
+	(0 a;-a 0)		Electron in fixed field - a force at right angles to velocity with proportional magnitude
+	(-a 0;0 -b)		Differing x and y damping. Useful e.g. for top-down wheels.
+	*/
+	//By the way, tensor in this case just means matrix, don't let the terminology get you down.
+
+	/// Set this to a positive number to clamp the maximum amount of damping done.
+	float32 maxTimestep;
+	// Typically one wants maxTimestep to be 1/(max eigenvalue of T), so that damping will never cause something to reverse direction
+
+	/// @see b2Controller::Step
+	void Step(const b2TimeStep& step);
+
+protected:
+	void Destroy(b2BlockAllocator* allocator);
+
+private:
+	friend class b2TensorDampingControllerDef;
+	b2TensorDampingController(const b2TensorDampingControllerDef* def);
+
+};
+
+/// This class is used to build tensor damping controllers
+class b2TensorDampingControllerDef : public b2ControllerDef
+{
+public:
+	/// Tensor to use in damping model
+	b2Mat22 T;
+	/// Set this to a positive number to clamp the maximum amount of damping done.
+	float32 maxTimestep;
+	/// Sets damping independantly along the x and y axes
+	void SetAxisAligned(float32 xDamping,float32 yDamping);
+private:
+	b2TensorDampingController* Create(b2BlockAllocator* allocator);
+};
+
+#endif

+ 209 - 0
box2d.mod/Source/Dynamics/Joints/b2DistanceJoint.cpp

@@ -0,0 +1,209 @@
+/*
+* 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 "b2DistanceJoint.h"
+#include "../b2Body.h"
+#include "../b2World.h"
+
+// 1-D constrained system
+// m (v2 - v1) = lambda
+// v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass.
+// x2 = x1 + h * v2
+
+// 1-D mass-damper-spring system
+// m (v2 - v1) + h * d * v2 + h * k * 
+
+// C = norm(p2 - p1) - L
+// u = (p2 - p1) / norm(p2 - p1)
+// Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1))
+// J = [-u -cross(r1, u) u cross(r2, u)]
+// K = J * invM * JT
+//   = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2
+
+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);
+	b2Vec2 d = anchor2 - anchor1;
+	length = d.Length();
+}
+
+
+b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def)
+: b2Joint(def)
+{
+	m_localAnchor1 = def->localAnchor1;
+	m_localAnchor2 = def->localAnchor2;
+	m_length = def->length;
+	m_frequencyHz = def->frequencyHz;
+	m_dampingRatio = def->dampingRatio;
+	m_impulse = 0.0f;
+	m_gamma = 0.0f;
+	m_bias = 0.0f;
+}
+
+void b2DistanceJoint::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());
+	m_u = b2->m_sweep.c + r2 - b1->m_sweep.c - r1;
+
+	// Handle singularity.
+	float32 length = m_u.Length();
+	if (length > b2_linearSlop)
+	{
+		m_u *= 1.0f / length;
+	}
+	else
+	{
+		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;
+	b2Assert(invMass > B2_FLT_EPSILON);
+	m_mass = 1.0f / invMass;
+
+	if (m_frequencyHz > 0.0f)
+	{
+		float32 C = length - m_length;
+
+		// Frequency
+		float32 omega = 2.0f * b2_pi * m_frequencyHz;
+
+		// Damping coefficient
+		float32 d = 2.0f * m_mass * m_dampingRatio * omega;
+
+		// Spring stiffness
+		float32 k = m_mass * omega * omega;
+
+		// magic formulas
+		m_gamma = 1.0f / (step.dt * (d + step.dt * k));
+		m_bias = C * step.dt * k * m_gamma;
+
+		m_mass = 1.0f / (invMass + m_gamma);
+	}
+
+	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);
+		b2->m_linearVelocity += b2->m_invMass * P;
+		b2->m_angularVelocity += b2->m_invI * b2Cross(r2, P);
+	}
+	else
+	{
+		m_impulse = 0.0f;
+	}
+}
+
+void b2DistanceJoint::SolveVelocityConstraints(const b2TimeStep& step)
+{
+	B2_NOT_USED(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());
+
+	// 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);
+
+	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);
+}
+
+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;
+
+	b2Vec2 r1 = b2Mul(b1->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter());
+	b2Vec2 r2 = b2Mul(b2->GetXForm().R, m_localAnchor2 - b2->GetLocalCenter());
+
+	b2Vec2 d = b2->m_sweep.c + r2 - b1->m_sweep.c - r1;
+
+	float32 length = d.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;
+
+	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);
+
+	b1->SynchronizeTransform();
+	b2->SynchronizeTransform();
+
+	return b2Abs(C) < b2_linearSlop;
+}
+
+b2Vec2 b2DistanceJoint::GetAnchor1() const
+{
+	return m_body1->GetWorldPoint(m_localAnchor1);
+}
+
+b2Vec2 b2DistanceJoint::GetAnchor2() const
+{
+	return m_body2->GetWorldPoint(m_localAnchor2);
+}
+
+b2Vec2 b2DistanceJoint::GetReactionForce(float32 inv_dt) const
+{
+	b2Vec2 F = (inv_dt * m_impulse) * m_u;
+	return F;
+}
+
+float32 b2DistanceJoint::GetReactionTorque(float32 inv_dt) const
+{
+	B2_NOT_USED(inv_dt);
+	return 0.0f;
+}

+ 96 - 0
box2d.mod/Source/Dynamics/Joints/b2DistanceJoint.h

@@ -0,0 +1,96 @@
+/*
+* 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_DISTANCE_JOINT_H
+#define B2_DISTANCE_JOINT_H
+
+#include "b2Joint.h"
+
+/// Distance joint definition. This requires defining an
+/// anchor point on both bodies and the non-zero length of the
+/// distance joint. The definition uses local anchor points
+/// so that the initial configuration can violate the constraint
+/// slightly. This helps when saving and loading a game.
+/// @warning Do not use a zero or short length.
+struct b2DistanceJointDef : public b2JointDef
+{
+	b2DistanceJointDef()
+	{
+		type = e_distanceJoint;
+		localAnchor1.Set(0.0f, 0.0f);
+		localAnchor2.Set(0.0f, 0.0f);
+		length = 1.0f;
+		frequencyHz = 0.0f;
+		dampingRatio = 0.0f;
+	}
+
+	/// Initialize the bodies, anchors, and length using the world
+	/// anchors.
+	void Initialize(b2Body* body1, b2Body* body2,
+					const b2Vec2& anchor1, const b2Vec2& anchor2);
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchor1;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchor2;
+
+	/// The equilibrium length between the anchor points.
+	float32 length;
+
+	/// The response speed.
+	float32 frequencyHz;
+
+	/// The damping ratio. 0 = no damping, 1 = critical damping.
+	float32 dampingRatio;
+};
+
+/// A distance joint constrains two points on two bodies
+/// to remain at a fixed distance from each other. You can view
+/// this as a massless, rigid rod.
+class b2DistanceJoint : public b2Joint
+{
+public:
+
+	b2Vec2 GetAnchor1() const;
+	b2Vec2 GetAnchor2() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	//--------------- Internals Below -------------------
+
+	b2DistanceJoint(const b2DistanceJointDef* data);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_localAnchor1;
+	b2Vec2 m_localAnchor2;
+	b2Vec2 m_u;
+	float32 m_frequencyHz;
+	float32 m_dampingRatio;
+	float32 m_gamma;
+	float32 m_bias;
+	float32 m_impulse;
+	float32 m_mass;		// effective mass for the constraint.
+	float32 m_length;
+};
+
+#endif

+ 257 - 0
box2d.mod/Source/Dynamics/Joints/b2GearJoint.cpp

@@ -0,0 +1,257 @@
+/*
+* 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 "b2GearJoint.h"
+#include "b2RevoluteJoint.h"
+#include "b2PrismaticJoint.h"
+#include "../b2Body.h"
+#include "../b2World.h"
+
+// Gear Joint:
+// C0 = (coordinate1 + ratio * coordinate2)_initial
+// C = C0 - (cordinate1 + ratio * coordinate2) = 0
+// Cdot = -(Cdot1 + ratio * Cdot2)
+// J = -[J1 ratio * J2]
+// K = J * invM * JT
+//   = J1 * invM1 * J1T + ratio * ratio * J2 * invM2 * J2T
+//
+// Revolute:
+// coordinate = rotation
+// Cdot = angularVelocity
+// J = [0 0 1]
+// K = J * invM * JT = invI
+//
+// Prismatic:
+// coordinate = dot(p - pg, ug)
+// Cdot = dot(v + cross(w, r), ug)
+// J = [ug cross(r, ug)]
+// K = J * invM * JT = invMass + invI * cross(r, ug)^2
+
+b2GearJoint::b2GearJoint(const b2GearJointDef* def)
+: b2Joint(def)
+{
+	b2JointType type1 = def->joint1->GetType();
+	b2JointType type2 = def->joint2->GetType();
+
+	b2Assert(type1 == e_revoluteJoint || type1 == e_prismaticJoint);
+	b2Assert(type2 == e_revoluteJoint || type2 == e_prismaticJoint);
+	b2Assert(def->joint1->GetBody1()->IsStatic());
+	b2Assert(def->joint2->GetBody1()->IsStatic());
+
+	m_revolute1 = NULL;
+	m_prismatic1 = NULL;
+	m_revolute2 = NULL;
+	m_prismatic2 = NULL;
+
+	float32 coordinate1, coordinate2;
+
+	m_ground1 = def->joint1->GetBody1();
+	m_body1 = def->joint1->GetBody2();
+	if (type1 == e_revoluteJoint)
+	{
+		m_revolute1 = (b2RevoluteJoint*)def->joint1;
+		m_groundAnchor1 = m_revolute1->m_localAnchor1;
+		m_localAnchor1 = m_revolute1->m_localAnchor2;
+		coordinate1 = m_revolute1->GetJointAngle();
+	}
+	else
+	{
+		m_prismatic1 = (b2PrismaticJoint*)def->joint1;
+		m_groundAnchor1 = m_prismatic1->m_localAnchor1;
+		m_localAnchor1 = m_prismatic1->m_localAnchor2;
+		coordinate1 = m_prismatic1->GetJointTranslation();
+	}
+
+	m_ground2 = def->joint2->GetBody1();
+	m_body2 = def->joint2->GetBody2();
+	if (type2 == e_revoluteJoint)
+	{
+		m_revolute2 = (b2RevoluteJoint*)def->joint2;
+		m_groundAnchor2 = m_revolute2->m_localAnchor1;
+		m_localAnchor2 = m_revolute2->m_localAnchor2;
+		coordinate2 = m_revolute2->GetJointAngle();
+	}
+	else
+	{
+		m_prismatic2 = (b2PrismaticJoint*)def->joint2;
+		m_groundAnchor2 = m_prismatic2->m_localAnchor1;
+		m_localAnchor2 = m_prismatic2->m_localAnchor2;
+		coordinate2 = m_prismatic2->GetJointTranslation();
+	}
+
+	m_ratio = def->ratio;
+
+	m_constant = coordinate1 + m_ratio * coordinate2;
+
+	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;
+
+	float32 K = 0.0f;
+	m_J.SetZero();
+
+	if (m_revolute1)
+	{
+		m_J.angular1 = -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());
+		float32 crug = b2Cross(r, ug);
+		m_J.linear1 = -ug;
+		m_J.angular1 = -crug;
+		K += b1->m_invMass + b1->m_invI * crug * crug;
+	}
+
+	if (m_revolute2)
+	{
+		m_J.angular2 = -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());
+		float32 crug = b2Cross(r, ug);
+		m_J.linear2 = -m_ratio * ug;
+		m_J.angular2 = -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;
+
+	if (step.warmStarting)
+	{
+		// Warm starting.
+		b1->m_linearVelocity += b1->m_invMass * m_impulse * m_J.linear1;
+		b1->m_angularVelocity += b1->m_invI * m_impulse * m_J.angular1;
+		b2->m_linearVelocity += b2->m_invMass * m_impulse * m_J.linear2;
+		b2->m_angularVelocity += b2->m_invI * m_impulse * m_J.angular2;
+	}
+	else
+	{
+		m_impulse = 0.0f;
+	}
+}
+
+void b2GearJoint::SolveVelocityConstraints(const b2TimeStep& step)
+{
+	B2_NOT_USED(step);
+
+	b2Body* b1 = m_body1;
+	b2Body* b2 = m_body2;
+
+	float32 Cdot = m_J.Compute(	b1->m_linearVelocity, b1->m_angularVelocity,
+								b2->m_linearVelocity, b2->m_angularVelocity);
+
+	float32 impulse = m_mass * (-Cdot);
+	m_impulse += impulse;
+
+	b1->m_linearVelocity += b1->m_invMass * impulse * m_J.linear1;
+	b1->m_angularVelocity += b1->m_invI * impulse * m_J.angular1;
+	b2->m_linearVelocity += b2->m_invMass * impulse * m_J.linear2;
+	b2->m_angularVelocity += b2->m_invI * impulse * m_J.angular2;
+}
+
+bool b2GearJoint::SolvePositionConstraints(float32 baumgarte)
+{
+	B2_NOT_USED(baumgarte);
+	
+	float32 linearError = 0.0f;
+
+	b2Body* b1 = m_body1;
+	b2Body* b2 = m_body2;
+
+	float32 coordinate1, coordinate2;
+	if (m_revolute1)
+	{
+		coordinate1 = m_revolute1->GetJointAngle();
+	}
+	else
+	{
+		coordinate1 = m_prismatic1->GetJointTranslation();
+	}
+
+	if (m_revolute2)
+	{
+		coordinate2 = m_revolute2->GetJointAngle();
+	}
+	else
+	{
+		coordinate2 = m_prismatic2->GetJointTranslation();
+	}
+
+	float32 C = m_constant - (coordinate1 + m_ratio * coordinate2);
+
+	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->SynchronizeTransform();
+	b2->SynchronizeTransform();
+
+	// TODO_ERIN not implemented
+	return linearError < b2_linearSlop;
+}
+
+b2Vec2 b2GearJoint::GetAnchor1() const
+{
+	return m_body1->GetWorldPoint(m_localAnchor1);
+}
+
+b2Vec2 b2GearJoint::GetAnchor2() const
+{
+	return m_body2->GetWorldPoint(m_localAnchor2);
+}
+
+b2Vec2 b2GearJoint::GetReactionForce(float32 inv_dt) const
+{
+	// TODO_ERIN not tested
+	b2Vec2 P = m_impulse * m_J.linear2;
+	return inv_dt * P;
+}
+
+float32 b2GearJoint::GetReactionTorque(float32 inv_dt) const
+{
+	// TODO_ERIN not tested
+	b2Vec2 r = b2Mul(m_body2->GetXForm().R, m_localAnchor2 - m_body2->GetLocalCenter());
+	b2Vec2 P = m_impulse * m_J.linear2;
+	float32 L = m_impulse * m_J.angular2 - b2Cross(r, P);
+	return inv_dt * L;
+}
+
+float32 b2GearJoint::GetRatio() const
+{
+	return m_ratio;
+}
+
+
+

+ 109 - 0
box2d.mod/Source/Dynamics/Joints/b2GearJoint.h

@@ -0,0 +1,109 @@
+/*
+* 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_GEAR_JOINT_H
+#define B2_GEAR_JOINT_H
+
+#include "b2Joint.h"
+
+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()
+	{
+		type = e_gearJoint;
+		joint1 = NULL;
+		joint2 = NULL;
+		ratio = 1.0f;
+	}
+
+	/// The first revolute/prismatic joint attached to the gear joint.
+	b2Joint* joint1;
+
+	/// The second revolute/prismatic joint attached to the gear joint.
+	b2Joint* joint2;
+
+	/// The gear ratio.
+	/// @see b2GearJoint for explanation.
+	float32 ratio;
+};
+
+/// A gear joint is used to connect two joints together. Either joint
+/// can be a revolute or prismatic joint. You specify a gear ratio
+/// to bind the motions together:
+/// coordinate1 + ratio * coordinate2 = constant
+/// 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).
+class b2GearJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchor1() const;
+	b2Vec2 GetAnchor2() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Get the gear ratio.
+	float32 GetRatio() const;
+
+	//--------------- Internals Below -------------------
+
+	b2GearJoint(const b2GearJointDef* data);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Body* m_ground1;
+	b2Body* m_ground2;
+
+	// One of these is NULL.
+	b2RevoluteJoint* m_revolute1;
+	b2PrismaticJoint* m_prismatic1;
+
+	// One of these is NULL.
+	b2RevoluteJoint* m_revolute2;
+	b2PrismaticJoint* m_prismatic2;
+
+	b2Vec2 m_groundAnchor1;
+	b2Vec2 m_groundAnchor2;
+
+	b2Vec2 m_localAnchor1;
+	b2Vec2 m_localAnchor2;
+
+	b2Jacobian m_J;
+
+	float32 m_constant;
+	float32 m_ratio;
+
+	// Effective mass
+	float32 m_mass;
+
+	// Impulse for accumulation/warm starting.
+	float32 m_impulse;
+};
+
+#endif

+ 146 - 0
box2d.mod/Source/Dynamics/Joints/b2Joint.cpp

@@ -0,0 +1,146 @@
+/*
+* 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 "b2Joint.h"
+#include "b2DistanceJoint.h"
+#include "b2LineJoint.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 <new>
+
+b2Joint* b2Joint::Create(const b2JointDef* def, b2BlockAllocator* allocator)
+{
+	b2Joint* joint = NULL;
+
+	switch (def->type)
+	{
+	case e_distanceJoint:
+		{
+			void* mem = allocator->Allocate(sizeof(b2DistanceJoint));
+			joint = new (mem) b2DistanceJoint((b2DistanceJointDef*)def);
+		}
+		break;
+
+	case e_mouseJoint:
+		{
+			void* mem = allocator->Allocate(sizeof(b2MouseJoint));
+			joint = new (mem) b2MouseJoint((b2MouseJointDef*)def);
+		}
+		break;
+
+	case e_prismaticJoint:
+		{
+			void* mem = allocator->Allocate(sizeof(b2PrismaticJoint));
+			joint = new (mem) b2PrismaticJoint((b2PrismaticJointDef*)def);
+		}
+		break;
+
+	case e_revoluteJoint:
+		{
+			void* mem = allocator->Allocate(sizeof(b2RevoluteJoint));
+			joint = new (mem) b2RevoluteJoint((b2RevoluteJointDef*)def);
+		}
+		break;
+
+	case e_pulleyJoint:
+		{
+			void* mem = allocator->Allocate(sizeof(b2PulleyJoint));
+			joint = new (mem) b2PulleyJoint((b2PulleyJointDef*)def);
+		}
+		break;
+
+	case e_gearJoint:
+		{
+			void* mem = allocator->Allocate(sizeof(b2GearJoint));
+			joint = new (mem) b2GearJoint((b2GearJointDef*)def);
+		}
+		break;
+
+	case e_lineJoint:
+		{
+			void* mem = allocator->Allocate(sizeof(b2LineJoint));
+			joint = new (mem) b2LineJoint((b2LineJointDef*)def);
+		}
+		break;
+
+	default:
+		b2Assert(false);
+		break;
+	}
+
+	return joint;
+}
+
+void b2Joint::Destroy(b2Joint* joint, b2BlockAllocator* allocator)
+{
+	joint->~b2Joint();
+	switch (joint->m_type)
+	{
+	case e_distanceJoint:
+		allocator->Free(joint, sizeof(b2DistanceJoint));
+		break;
+
+	case e_mouseJoint:
+		allocator->Free(joint, sizeof(b2MouseJoint));
+		break;
+
+	case e_prismaticJoint:
+		allocator->Free(joint, sizeof(b2PrismaticJoint));
+		break;
+
+	case e_revoluteJoint:
+		allocator->Free(joint, sizeof(b2RevoluteJoint));
+		break;
+
+	case e_pulleyJoint:
+		allocator->Free(joint, sizeof(b2PulleyJoint));
+		break;
+
+	case e_gearJoint:
+		allocator->Free(joint, sizeof(b2GearJoint));
+		break;
+
+	case e_lineJoint:
+		allocator->Free(joint, sizeof(b2LineJoint));
+		break;
+
+	default:
+		b2Assert(false);
+		break;
+	}
+}
+
+b2Joint::b2Joint(const b2JointDef* def)
+{
+	m_type = def->type;
+	m_prev = NULL;
+	m_next = NULL;
+	m_body1 = def->body1;
+	m_body2 = def->body2;
+	m_collideConnected = def->collideConnected;
+	m_islandFlag = false;
+	m_userData = def->userData;
+}

+ 230 - 0
box2d.mod/Source/Dynamics/Joints/b2Joint.h

@@ -0,0 +1,230 @@
+/*
+* 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 JOINT_H
+#define JOINT_H
+
+#include "../../Common/b2Math.h"
+
+class b2Body;
+class b2Joint;
+struct b2TimeStep;
+class b2BlockAllocator;
+
+enum b2JointType
+{
+	e_unknownJoint,
+	e_revoluteJoint,
+	e_prismaticJoint,
+	e_distanceJoint,
+	e_pulleyJoint,
+	e_mouseJoint,
+	e_gearJoint,
+	e_lineJoint
+};
+
+enum b2LimitState
+{
+	e_inactiveLimit,
+	e_atLowerLimit,
+	e_atUpperLimit,
+	e_equalLimits
+};
+
+struct b2Jacobian
+{
+	b2Vec2 linear1;
+	float32 angular1;
+	b2Vec2 linear2;
+	float32 angular2;
+
+	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
+/// in a joint graph where each body is a node and each joint
+/// is an edge. A joint edge belongs to a doubly linked list
+/// maintained in each attached body. Each joint has two joint
+/// nodes, one for each attached body.
+struct b2JointEdge
+{
+	b2Body* other;			///< provides quick access to the other body attached.
+	b2Joint* joint;			///< the joint
+	b2JointEdge* prev;		///< the previous joint edge in the body's joint list
+	b2JointEdge* next;		///< the next joint edge in the body's joint list
+};
+
+/// Joint definitions are used to construct joints.
+struct b2JointDef
+{
+	b2JointDef()
+	{
+		type = e_unknownJoint;
+		userData = NULL;
+		body1 = NULL;
+		body2 = NULL;
+		collideConnected = false;
+	}
+
+	/// The joint type is set automatically for concrete joint types.
+	b2JointType type;
+
+	/// Use this to attach application specific data to your joints.
+	void* userData;
+
+	/// The first attached body.
+	b2Body* body1;
+
+	/// The second attached body.
+	b2Body* body2;
+
+	/// Set this flag to true if the attached bodies should collide.
+	bool collideConnected;
+};
+
+/// The base joint class. Joints are used to constraint two bodies together in
+/// various fashions. Some joints also feature limits and motors.
+class b2Joint
+{
+public:
+
+	/// Get the type of the concrete joint.
+	b2JointType GetType() const;
+
+	/// Get the first body attached to this joint.
+	b2Body* GetBody1();
+
+	/// Get the second body attached to this joint.
+	b2Body* GetBody2();
+
+	/// Get the anchor point on body1 in world coordinates.
+	virtual b2Vec2 GetAnchor1() const = 0;
+
+	/// Get the anchor point on body2 in world coordinates.
+	virtual b2Vec2 GetAnchor2() const = 0;
+
+	/// Get the reaction force on body2 at the joint anchor.
+	virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0;
+
+	/// Get the reaction torque on body2.
+	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();
+
+	/// Set the user data pointer.
+	void SetUserData(void* data);
+
+	//--------------- Internals Below -------------------
+protected:
+	friend class b2World;
+	friend class b2Body;
+	friend class b2Island;
+
+	static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allocator);
+	static void Destroy(b2Joint* joint, b2BlockAllocator* allocator);
+
+	b2Joint(const b2JointDef* def);
+	virtual ~b2Joint() {}
+
+	virtual void InitVelocityConstraints(const b2TimeStep& step) = 0;
+	virtual void SolveVelocityConstraints(const b2TimeStep& step) = 0;
+
+	// This returns true if the position errors are within tolerance.
+	virtual bool SolvePositionConstraints(float32 baumgarte) = 0;
+
+	void ComputeXForm(b2XForm* xf, const b2Vec2& center, const b2Vec2& localCenter, float32 angle) const;
+
+	b2JointType m_type;
+	b2Joint* m_prev;
+	b2Joint* m_next;
+	b2JointEdge m_node1;
+	b2JointEdge m_node2;
+	b2Body* m_body1;
+	b2Body* m_body2;
+
+	bool m_islandFlag;
+	bool m_collideConnected;
+
+	void* m_userData;
+
+	// Cache here per time step to reduce cache misses.
+	b2Vec2 m_localCenter1, m_localCenter2;
+	float32 m_invMass1, m_invI1;
+	float32 m_invMass2, m_invI2;
+};
+
+inline void b2Jacobian::SetZero()
+{
+	linear1.SetZero(); angular1 = 0.0f;
+	linear2.SetZero(); angular2 = 0.0f;
+}
+
+inline void b2Jacobian::Set(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2)
+{
+	linear1 = x1; angular1 = a1;
+	linear2 = x2; angular2 = 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;
+}
+
+inline b2JointType b2Joint::GetType() const
+{
+	return m_type;
+}
+
+inline b2Body* b2Joint::GetBody1()
+{
+	return m_body1;
+}
+
+inline b2Body* b2Joint::GetBody2()
+{
+	return m_body2;
+}
+
+inline b2Joint* b2Joint::GetNext()
+{
+	return m_next;
+}
+
+inline void* b2Joint::GetUserData()
+{
+	return m_userData;
+}
+
+inline void b2Joint::SetUserData(void* data)
+{
+	m_userData = data;
+}
+
+inline void b2Joint::ComputeXForm(b2XForm* xf, const b2Vec2& center, const b2Vec2& localCenter, float32 angle) const
+{
+	xf->R.Set(angle);
+	xf->position = center - b2Mul(xf->R, localCenter);
+}
+
+#endif

+ 559 - 0
box2d.mod/Source/Dynamics/Joints/b2LineJoint.cpp

@@ -0,0 +1,559 @@
+/*
+* 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 "b2LineJoint.h"
+#include "../b2Body.h"
+#include "../b2World.h"
+
+// 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)
+{
+	body1 = b1;
+	body2 = b2;
+	localAnchor1 = body1->GetLocalPoint(anchor);
+	localAnchor2 = body2->GetLocalPoint(anchor);
+	localAxis1 = body1->GetLocalVector(axis);
+}
+
+b2LineJoint::b2LineJoint(const b2LineJointDef* def)
+: b2Joint(def)
+{
+	m_localAnchor1 = def->localAnchor1;
+	m_localAnchor2 = def->localAnchor2;
+	m_localXAxis1 = def->localAxis1;
+	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 = B2FORCE_INV_SCALE(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_body1;
+	b2Body* b2 = m_body2;
+
+	m_localCenter1 = b1->GetLocalCenter();
+	m_localCenter2 = b2->GetLocalCenter();
+
+	b2XForm xf1 = b1->GetXForm();
+	b2XForm xf2 = b2->GetXForm();
+
+	// Compute the effective masses.
+	b2Vec2 r1 = b2Mul(xf1.R, m_localAnchor1 - m_localCenter1);
+	b2Vec2 r2 = b2Mul(xf2.R, m_localAnchor2 - m_localCenter2);
+	b2Vec2 d = b2->m_sweep.c + r2 - b1->m_sweep.c - r1;
+
+	m_invMass1 = b1->m_invMass;
+	m_invI1 = b1->m_invI;
+	m_invMass2 = b2->m_invMass;
+	m_invI2 = 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_invMass1 + m_invMass2 + m_invI1 * m_a1 * m_a1 + m_invI2 * m_a2 * m_a2;
+		b2Assert(m_motorMass > B2_FLT_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_invMass1, m2 = m_invMass2;
+		float32 i1 = m_invI1, i2 = m_invI2;
+
+		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_invMass1 * P;
+		b1->m_angularVelocity -= m_invI1 * L1;
+
+		b2->m_linearVelocity += m_invMass2 * P;
+		b2->m_angularVelocity += m_invI2 * L2;
+	}
+	else
+	{
+		m_impulse.SetZero();
+		m_motorImpulse = 0.0f;
+	}
+}
+
+void b2LineJoint::SolveVelocityConstraints(const b2TimeStep& step)
+{
+	b2Body* b1 = m_body1;
+	b2Body* b2 = m_body2;
+
+	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_invMass1 * P;
+		w1 -= m_invI1 * L1;
+
+		v2 += m_invMass2 * P;
+		w2 += m_invI2 * 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 = b / m_K.col1.x + 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_invMass1 * P;
+		w1 -= m_invI1 * L1;
+
+		v2 += m_invMass2 * P;
+		w2 += m_invI2 * L2;
+	}
+	else
+	{
+		// Limit is inactive, just solve the prismatic constraint in block form.
+		float32 df = (-Cdot1) / m_K.col1.x;
+		m_impulse.x += df;
+
+		b2Vec2 P = df * m_perp;
+		float32 L1 = df * m_s1;
+		float32 L2 = df * m_s2;
+
+		v1 -= m_invMass1 * P;
+		w1 -= m_invI1 * L1;
+
+		v2 += m_invMass2 * P;
+		w2 += m_invI2 * 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_body1;
+	b2Body* b2 = m_body2;
+
+	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_localCenter1);
+	b2Vec2 r2 = b2Mul(R2, m_localAnchor2 - m_localCenter2);
+	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_invMass1, m2 = m_invMass2;
+		float32 i1 = m_invI1, i2 = m_invI2;
+
+		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_invMass1, m2 = m_invMass2;
+		float32 i1 = m_invI1, i2 = m_invI2;
+
+		float32 k11 = m1 + m2 + i1 * m_s1 * m_s1 + i2 * m_s2 * m_s2;
+
+		float32 impulse1 = (-C1) / k11;
+		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_invMass1 * P;
+	a1 -= m_invI1 * L1;
+	c2 += m_invMass2 * P;
+	a2 += m_invI2 * 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::GetAnchor1() const
+{
+	return m_body1->GetWorldPoint(m_localAnchor1);
+}
+
+b2Vec2 b2LineJoint::GetAnchor2() const
+{
+	return m_body2->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_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 b2LineJoint::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 b2LineJoint::IsLimitEnabled() const
+{
+	return m_enableLimit;
+}
+
+void b2LineJoint::EnableLimit(bool flag)
+{
+	m_body1->WakeUp();
+	m_body2->WakeUp();
+	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_body1->WakeUp();
+	m_body2->WakeUp();
+	m_lowerTranslation = lower;
+	m_upperTranslation = upper;
+}
+
+bool b2LineJoint::IsMotorEnabled() const
+{
+	return m_enableMotor;
+}
+
+void b2LineJoint::EnableMotor(bool flag)
+{
+	m_body1->WakeUp();
+	m_body2->WakeUp();
+	m_enableMotor = flag;
+}
+
+void b2LineJoint::SetMotorSpeed(float32 speed)
+{
+	m_body1->WakeUp();
+	m_body2->WakeUp();
+	m_motorSpeed = speed;
+}
+
+void b2LineJoint::SetMaxMotorForce(float32 force)
+{
+	m_body1->WakeUp();
+	m_body2->WakeUp();
+	m_maxMotorForce = B2FORCE_SCALE(float32(1.0))*force;
+}
+
+float32 b2LineJoint::GetMotorForce() const
+{
+	return m_motorImpulse;
+}
+
+
+
+
+

+ 168 - 0
box2d.mod/Source/Dynamics/Joints/b2LineJoint.h

@@ -0,0 +1,168 @@
+/*
+* 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 "b2Joint.h"
+
+/// 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;
+		localAnchor1.SetZero();
+		localAnchor2.SetZero();
+		localAxis1.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* body1, b2Body* body2, const b2Vec2& anchor, const b2Vec2& axis);
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchor1;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchor2;
+
+	/// The local translation axis in body1.
+	b2Vec2 localAxis1;
+
+	/// 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 one degree of freedom: translation
+/// along an axis fixed in body1. 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 GetAnchor1() const;
+	b2Vec2 GetAnchor2() 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 the maximum motor force, usually in N.
+	void SetMaxMotorForce(float32 force);
+
+	/// Get the current motor force, usually in N.
+	float32 GetMotorForce() const;
+
+	//--------------- Internals Below -------------------
+
+	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

+ 153 - 0
box2d.mod/Source/Dynamics/Joints/b2MouseJoint.cpp

@@ -0,0 +1,153 @@
+/*
+* 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 = 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_body2->IsSleeping())
+	{
+		m_body2->WakeUp();
+	}
+	m_target = target;
+}
+
+void b2MouseJoint::InitVelocityConstraints(const b2TimeStep& step)
+{
+	b2Body* b = m_body2;
+
+	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_FLT_EPSILON);
+	m_gamma = 1.0f / (step.dt * (d + step.dt * k));
+	m_beta = step.dt * k * m_gamma;
+
+	// 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.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_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 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::GetAnchor1() const
+{
+	return m_target;
+}
+
+b2Vec2 b2MouseJoint::GetAnchor2() const
+{
+	return m_body2->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;
+}

+ 97 - 0
box2d.mod/Source/Dynamics/Joints/b2MouseJoint.h

@@ -0,0 +1,97 @@
+/*
+* 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_MOUSE_JOINT_H
+#define B2_MOUSE_JOINT_H
+
+#include "b2Joint.h"
+
+/// Mouse joint definition. This requires a world target point,
+/// tuning parameters, and the time step.
+struct b2MouseJointDef : public b2JointDef
+{
+	b2MouseJointDef()
+	{
+		type = e_mouseJoint;
+		target.Set(0.0f, 0.0f);
+		maxForce = 0.0f;
+		frequencyHz = 5.0f;
+		dampingRatio = 0.7f;
+	}
+
+	/// The initial world target point. This is assumed
+	/// to coincide with the body anchor initially.
+	b2Vec2 target;
+
+	/// The maximum constraint force that can be exerted
+	/// to move the candidate body. Usually you will express
+	/// as some multiple of the weight (multiplier * mass * gravity).
+	float32 maxForce;
+
+	/// The response speed.
+	float32 frequencyHz;
+
+	/// The damping ratio. 0 = no damping, 1 = critical damping.
+	float32 dampingRatio;
+};
+
+/// 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.
+class b2MouseJoint : public b2Joint
+{
+public:
+
+	/// Implements b2Joint.
+	b2Vec2 GetAnchor1() const;
+
+	/// Implements b2Joint.
+	b2Vec2 GetAnchor2() const;
+
+	/// Implements b2Joint.
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+
+	/// Implements b2Joint.
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Use this to update the target point.
+	void SetTarget(const b2Vec2& target);
+
+	//--------------- Internals Below -------------------
+
+	b2MouseJoint(const b2MouseJointDef* def);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte) { B2_NOT_USED(baumgarte); return true; }
+
+	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;
+	float32 m_frequencyHz;
+	float32 m_dampingRatio;
+	float32 m_beta;
+	float32 m_gamma;
+};
+
+#endif

+ 587 - 0
box2d.mod/Source/Dynamics/Joints/b2PrismaticJoint.cpp

@@ -0,0 +1,587 @@
+/*
+* 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(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)
+{
+	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_impulse.SetZero();
+	m_motorMass = 0.0;
+	m_motorImpulse = 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;
+	m_limitState = e_inactiveLimit;
+
+	m_axis.SetZero();
+	m_perp.SetZero();
+}
+
+void b2PrismaticJoint::InitVelocityConstraints(const b2TimeStep& step)
+{
+	b2Body* b1 = m_body1;
+	b2Body* b2 = m_body2;
+
+	// You cannot create a prismatic joint between bodies that
+	// both have fixed rotation.
+	b2Assert(b1->m_invI > 0.0f || b2->m_invI > 0.0f);
+
+	m_localCenter1 = b1->GetLocalCenter();
+	m_localCenter2 = b2->GetLocalCenter();
+
+	b2XForm xf1 = b1->GetXForm();
+	b2XForm xf2 = b2->GetXForm();
+
+	// Compute the effective masses.
+	b2Vec2 r1 = b2Mul(xf1.R, m_localAnchor1 - m_localCenter1);
+	b2Vec2 r2 = b2Mul(xf2.R, m_localAnchor2 - m_localCenter2);
+	b2Vec2 d = b2->m_sweep.c + r2 - b1->m_sweep.c - r1;
+
+	m_invMass1 = b1->m_invMass;
+	m_invI1 = b1->m_invI;
+	m_invMass2 = b2->m_invMass;
+	m_invI2 = 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_invMass1 + m_invMass2 + m_invI1 * m_a1 * m_a1 + m_invI2 * m_a2 * m_a2;
+		b2Assert(m_motorMass > B2_FLT_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_invMass1, m2 = m_invMass2;
+		float32 i1 = m_invI1, i2 = m_invI2;
+
+		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;
+	}
+
+	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_invMass1 * P;
+		b1->m_angularVelocity -= m_invI1 * L1;
+
+		b2->m_linearVelocity += m_invMass2 * P;
+		b2->m_angularVelocity += m_invI2 * L2;
+	}
+	else
+	{
+		m_impulse.SetZero();
+		m_motorImpulse = 0.0f;
+	}
+}
+
+void b2PrismaticJoint::SolveVelocityConstraints(const b2TimeStep& step)
+{
+	b2Body* b1 = m_body1;
+	b2Body* b2 = m_body2;
+
+	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_invMass1 * P;
+		w1 -= m_invI1 * L1;
+
+		v2 += m_invMass2 * P;
+		w2 += m_invI2 * 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_invMass1 * P;
+		w1 -= m_invI1 * L1;
+
+		v2 += m_invMass2 * P;
+		w2 += m_invI2 * 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_invMass1 * P;
+		w1 -= m_invI1 * L1;
+
+		v2 += m_invMass2 * P;
+		w2 += m_invI2 * 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_body1;
+	b2Body* b2 = m_body2;
+
+	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_localCenter1);
+	b2Vec2 r2 = b2Mul(R2, m_localAnchor2 - m_localCenter2);
+	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_invMass1, m2 = m_invMass2;
+		float32 i1 = m_invI1, i2 = m_invI2;
+
+		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_invMass1, m2 = m_invMass2;
+		float32 i1 = m_invI1, i2 = m_invI2;
+
+		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_invMass1 * P;
+	a1 -= m_invI1 * L1;
+	c2 += m_invMass2 * P;
+	a2 += m_invI2 * 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::GetAnchor1() const
+{
+	return m_body1->GetWorldPoint(m_localAnchor1);
+}
+
+b2Vec2 b2PrismaticJoint::GetAnchor2() const
+{
+	return m_body2->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_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_body1->WakeUp();
+	m_body2->WakeUp();
+	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_body1->WakeUp();
+	m_body2->WakeUp();
+	m_lowerTranslation = lower;
+	m_upperTranslation = upper;
+}
+
+bool b2PrismaticJoint::IsMotorEnabled() const
+{
+	return m_enableMotor;
+}
+
+void b2PrismaticJoint::EnableMotor(bool flag)
+{
+	m_body1->WakeUp();
+	m_body2->WakeUp();
+	m_enableMotor = flag;
+}
+
+void b2PrismaticJoint::SetMotorSpeed(float32 speed)
+{
+	m_body1->WakeUp();
+	m_body2->WakeUp();
+	m_motorSpeed = speed;
+}
+
+void b2PrismaticJoint::SetMaxMotorForce(float32 force)
+{
+	m_body1->WakeUp();
+	m_body2->WakeUp();
+	m_maxMotorForce = B2FORCE_SCALE(float32(1.0))*force;
+}
+
+float32 b2PrismaticJoint::GetMotorForce() const
+{
+	return m_motorImpulse;
+}

+ 173 - 0
box2d.mod/Source/Dynamics/Joints/b2PrismaticJoint.h

@@ -0,0 +1,173 @@
+/*
+* 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_PRISMATIC_JOINT_H
+#define B2_PRISMATIC_JOINT_H
+
+#include "b2Joint.h"
+
+/// Prismatic 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 b2PrismaticJointDef : public b2JointDef
+{
+	b2PrismaticJointDef()
+	{
+		type = e_prismaticJoint;
+		localAnchor1.SetZero();
+		localAnchor2.SetZero();
+		localAxis1.Set(1.0f, 0.0f);
+		referenceAngle = 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* body1, b2Body* body2, const b2Vec2& anchor, const b2Vec2& axis);
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchor1;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchor2;
+
+	/// The local translation axis in body1.
+	b2Vec2 localAxis1;
+
+	/// The constrained angle between the bodies: body2_angle - body1_angle.
+	float32 referenceAngle;
+
+	/// 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 prismatic joint. This joint provides one degree of freedom: translation
+/// along an axis fixed in body1. 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
+{
+public:
+	b2Vec2 GetAnchor1() const;
+	b2Vec2 GetAnchor2() 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 the maximum motor force, usually in N.
+	void SetMaxMotorForce(float32 force);
+
+	/// Get the current motor force, usually in N.
+	float32 GetMotorForce() const;
+
+	//--------------- Internals Below -------------------
+
+	b2PrismaticJoint(const b2PrismaticJointDef* 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;
+	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;
+};
+
+inline float32 b2PrismaticJoint::GetMotorSpeed() const
+{
+	return m_motorSpeed;
+}
+
+#endif

+ 428 - 0
box2d.mod/Source/Dynamics/Joints/b2PulleyJoint.cpp

@@ -0,0 +1,428 @@
+/*
+* 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 "b2PulleyJoint.h"
+#include "../b2Body.h"
+#include "../b2World.h"
+
+// Pulley:
+// length1 = norm(p1 - s1)
+// length2 = norm(p2 - s2)
+// C0 = (length1 + ratio * length2)_initial
+// C = C0 - (length1 + ratio * length2) >= 0
+// 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,
+				float32 r)
+{
+	body1 = b1;
+	body2 = b2;
+	groundAnchor1 = ga1;
+	groundAnchor2 = ga2;
+	localAnchor1 = body1->GetLocalPoint(anchor1);
+	localAnchor2 = body2->GetLocalPoint(anchor2);
+	b2Vec2 d1 = anchor1 - ga1;
+	length1 = d1.Length();
+	b2Vec2 d2 = anchor2 - ga2;
+	length2 = d2.Length();
+	ratio = r;
+	b2Assert(ratio > B2_FLT_EPSILON);
+	float32 C = length1 + ratio * length2;
+	maxLength1 = C - ratio * b2_minPulleyLength;
+	maxLength2 = (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;
+
+	b2Assert(def->ratio != 0.0f);
+	m_ratio = def->ratio;
+
+	m_constant = def->length1 + m_ratio * def->length2;
+
+	m_maxLength1 = b2Min(def->maxLength1, m_constant - m_ratio * b2_minPulleyLength);
+	m_maxLength2 = b2Min(def->maxLength2, (m_constant - b2_minPulleyLength) / m_ratio);
+
+	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;
+
+	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 s1 = m_ground->GetXForm().position + m_groundAnchor1;
+	b2Vec2 s2 = m_ground->GetXForm().position + m_groundAnchor2;
+
+	// 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;
+	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;
+	}
+
+	// Compute effective mass.
+	float32 cr1u1 = b2Cross(r1, m_u1);
+	float32 cr2u2 = b2Cross(r2, m_u2);
+
+	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);
+	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 = -(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);
+	}
+	else
+	{
+		m_impulse = 0.0f;
+		m_limitImpulse1 = 0.0f;
+		m_limitImpulse2 = 0.0f;
+	}
+}
+
+void b2PulleyJoint::SolveVelocityConstraints(const b2TimeStep& step)
+{
+	B2_NOT_USED(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());
+
+	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);
+
+		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);
+	}
+}
+
+bool b2PulleyJoint::SolvePositionConstraints(float32 baumgarte)
+{
+	B2_NOT_USED(baumgarte);
+
+	b2Body* b1 = m_body1;
+	b2Body* b2 = m_body2;
+
+	b2Vec2 s1 = m_ground->GetXForm().position + m_groundAnchor1;
+	b2Vec2 s2 = m_ground->GetXForm().position + 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 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();
+	}
+
+	if (m_limitState1 == e_atUpperLimit)
+	{
+		b2Vec2 r1 = b2Mul(b1->GetXForm().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();
+	}
+
+	if (m_limitState2 == e_atUpperLimit)
+	{
+		b2Vec2 r2 = b2Mul(b2->GetXForm().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();
+	}
+
+	return linearError < b2_linearSlop;
+}
+
+b2Vec2 b2PulleyJoint::GetAnchor1() const
+{
+	return m_body1->GetWorldPoint(m_localAnchor1);
+}
+
+b2Vec2 b2PulleyJoint::GetAnchor2() const
+{
+	return m_body2->GetWorldPoint(m_localAnchor2);
+}
+
+b2Vec2 b2PulleyJoint::GetReactionForce(float32 inv_dt) const
+{
+	b2Vec2 P = m_impulse * m_u2;
+	return inv_dt * P;
+}
+
+float32 b2PulleyJoint::GetReactionTorque(float32 inv_dt) const
+{
+	B2_NOT_USED(inv_dt);
+	return 0.0f;
+}
+
+b2Vec2 b2PulleyJoint::GetGroundAnchor1() const
+{
+	return m_ground->GetXForm().position + m_groundAnchor1;
+}
+
+b2Vec2 b2PulleyJoint::GetGroundAnchor2() const
+{
+	return m_ground->GetXForm().position + m_groundAnchor2;
+}
+
+float32 b2PulleyJoint::GetLength1() const
+{
+	b2Vec2 p = m_body1->GetWorldPoint(m_localAnchor1);
+	b2Vec2 s = m_ground->GetXForm().position + 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 d = p - s;
+	return d.Length();
+}
+
+float32 b2PulleyJoint::GetRatio() const
+{
+	return m_ratio;
+}

+ 148 - 0
box2d.mod/Source/Dynamics/Joints/b2PulleyJoint.h

@@ -0,0 +1,148 @@
+/*
+* 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_PULLEY_JOINT_H
+#define B2_PULLEY_JOINT_H
+
+#include "b2Joint.h"
+
+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.
+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;
+		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,
+					float32 ratio);
+
+	/// The first ground anchor in world coordinates. This point never moves.
+	b2Vec2 groundAnchor1;
+
+	/// The second ground anchor in world coordinates. This point never moves.
+	b2Vec2 groundAnchor2;
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchor1;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchor2;
+
+	/// The a reference length for the segment attached to body1.
+	float32 length1;
+
+	/// The maximum length of the segment attached to body1.
+	float32 maxLength1;
+
+	/// The a reference length for the segment attached to body2.
+	float32 length2;
+
+	/// The maximum length of the segment attached to body2.
+	float32 maxLength2;
+
+	/// The pulley ratio, used to simulate a block-and-tackle.
+	float32 ratio;
+};
+
+/// The pulley joint is connected to two bodies and two fixed ground points.
+/// 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.
+class b2PulleyJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchor1() const;
+	b2Vec2 GetAnchor2() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Get the first ground anchor.
+	b2Vec2 GetGroundAnchor1() const;
+
+	/// Get the second ground anchor.
+	b2Vec2 GetGroundAnchor2() const;
+
+	/// Get the current length of the segment attached to body1.
+	float32 GetLength1() const;
+
+	/// Get the current length of the segment attached to body2.
+	float32 GetLength2() const;
+
+	/// Get the pulley ratio.
+	float32 GetRatio() const;
+
+	//--------------- Internals Below -------------------
+
+	b2PulleyJoint(const b2PulleyJointDef* data);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Body* m_ground;
+	b2Vec2 m_groundAnchor1;
+	b2Vec2 m_groundAnchor2;
+	b2Vec2 m_localAnchor1;
+	b2Vec2 m_localAnchor2;
+
+	b2Vec2 m_u1;
+	b2Vec2 m_u2;
+	
+	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;
+};
+
+#endif

+ 474 - 0
box2d.mod/Source/Dynamics/Joints/b2RevoluteJoint.cpp

@@ -0,0 +1,474 @@
+/*
+* 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_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_body1;
+	b2Body* b2 = m_body2;
+
+	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->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter());
+	b2Vec2 r2 = b2Mul(b2->GetXForm().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 = 1.0f / (i1 + i2);
+
+	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_body1;
+	b2Body* b2 = m_body2;
+
+	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->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter());
+		b2Vec2 r2 = b2Mul(b2->GetXForm().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->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter());
+		b2Vec2 r2 = b2Mul(b2->GetXForm().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_body1;
+	b2Body* b2 = m_body2;
+
+	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->GetXForm().R, m_localAnchor1 - b1->GetLocalCenter());
+		b2Vec2 r2 = b2Mul(b2->GetXForm().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 k = invMass1 + invMass2;
+			b2Assert(k > B2_FLT_EPSILON);
+			float32 m = 1.0f / k;
+			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::GetAnchor1() const
+{
+	return m_body1->GetWorldPoint(m_localAnchor1);
+}
+
+b2Vec2 b2RevoluteJoint::GetAnchor2() const
+{
+	return m_body2->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_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_body1->WakeUp();
+	m_body2->WakeUp();
+	m_enableMotor = flag;
+}
+
+float32 b2RevoluteJoint::GetMotorTorque() const
+{
+	return m_motorImpulse;
+}
+
+void b2RevoluteJoint::SetMotorSpeed(float32 speed)
+{
+	m_body1->WakeUp();
+	m_body2->WakeUp();
+	m_motorSpeed = speed;
+}
+
+void b2RevoluteJoint::SetMaxMotorTorque(float32 torque)
+{
+	m_body1->WakeUp();
+	m_body2->WakeUp();
+	m_maxMotorTorque = torque;
+}
+
+bool b2RevoluteJoint::IsLimitEnabled() const
+{
+	return m_enableLimit;
+}
+
+void b2RevoluteJoint::EnableLimit(bool flag)
+{
+	m_body1->WakeUp();
+	m_body2->WakeUp();
+	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_body1->WakeUp();
+	m_body2->WakeUp();
+	m_lowerAngle = lower;
+	m_upperAngle = upper;
+}

+ 170 - 0
box2d.mod/Source/Dynamics/Joints/b2RevoluteJoint.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_REVOLUTE_JOINT_H
+#define B2_REVOLUTE_JOINT_H
+
+#include "b2Joint.h"
+
+/// Revolute joint definition. This requires defining an
+/// anchor point where the bodies are joined. The definition
+/// uses local anchor points so that the initial configuration
+/// can violate the constraint slightly. You also need to
+/// specify the initial relative angle for joint limits. This
+/// helps when saving and loading a game.
+/// The local anchor points are measured from the body's origin
+/// rather than the center of mass because:
+/// 1. you might not know where the center of mass will be.
+/// 2. if you add/remove shapes from a body and recompute the mass,
+///    the joints will be broken.
+struct b2RevoluteJointDef : public b2JointDef
+{
+	b2RevoluteJointDef()
+	{
+		type = e_revoluteJoint;
+		localAnchor1.Set(0.0f, 0.0f);
+		localAnchor2.Set(0.0f, 0.0f);
+		referenceAngle = 0.0f;
+		lowerAngle = 0.0f;
+		upperAngle = 0.0f;
+		maxMotorTorque = 0.0f;
+		motorSpeed = 0.0f;
+		enableLimit = false;
+		enableMotor = false;
+	}
+
+	/// Initialize the bodies, anchors, and reference angle using the world
+	/// anchor.
+	void Initialize(b2Body* body1, b2Body* body2, const b2Vec2& anchor);
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchor1;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchor2;
+
+	/// The body2 angle minus body1 angle in the reference state (radians).
+	float32 referenceAngle;
+
+	/// A flag to enable joint limits.
+	bool enableLimit;
+
+	/// The lower angle for the joint limit (radians).
+	float32 lowerAngle;
+
+	/// The upper angle for the joint limit (radians).
+	float32 upperAngle;
+
+	/// A flag to enable the joint motor.
+	bool enableMotor;
+
+	/// The desired motor speed. Usually in radians per second.
+	float32 motorSpeed;
+
+	/// The maximum motor torque used to achieve the desired motor speed.
+	/// Usually in N-m.
+	float32 maxMotorTorque;
+};
+
+/// A revolute joint constrains to 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
+/// to drive the relative rotation about the shared point. A maximum motor torque
+/// is provided so that infinite forces are not generated.
+class b2RevoluteJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchor1() const;
+	b2Vec2 GetAnchor2() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Get the current joint angle in radians.
+	float32 GetJointAngle() const;
+
+	/// Get the current joint angle speed in radians 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 in radians.
+	float32 GetLowerLimit() const;
+
+	/// Get the upper joint limit in radians.
+	float32 GetUpperLimit() const;
+
+	/// Set the joint limits in radians.
+	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 in radians per second.
+	void SetMotorSpeed(float32 speed);
+
+	/// Get the motor speed in radians per second.
+	float32 GetMotorSpeed() const;
+
+	/// 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;
+
+	//--------------- Internals Below -------------------
+	b2RevoluteJoint(const b2RevoluteJointDef* def);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_localAnchor1;	// relative
+	b2Vec2 m_localAnchor2;
+	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;
+
+	bool m_enableLimit;
+	float32 m_referenceAngle;
+	float32 m_lowerAngle;
+	float32 m_upperAngle;
+	b2LimitState m_limitState;
+};
+
+inline float32 b2RevoluteJoint::GetMotorSpeed() const
+{
+	return m_motorSpeed;
+}
+
+#endif

+ 457 - 0
box2d.mod/Source/Dynamics/b2Body.cpp

@@ -0,0 +1,457 @@
+/*
+* 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"
+#include "../Collision/Shapes/b2EdgeShape.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_controllerList = 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
+}
+
+
+float32 connectEdges(b2EdgeShape * const & s1, b2EdgeShape * const & s2, float32 angle1)
+{
+	float32 angle2 = b2Atan2(s2->GetDirectionVector().y, s2->GetDirectionVector().x);
+	b2Vec2 core = tanf((angle2 - angle1) * 0.5f) * s2->GetDirectionVector();
+	core = b2_toiSlop * (core - s2->GetNormalVector()) + s2->GetVertex1();
+	b2Vec2 cornerDir = s1->GetDirectionVector() + s2->GetDirectionVector();
+	cornerDir.Normalize();
+	bool convex = b2Dot(s1->GetDirectionVector(), s2->GetNormalVector()) > 0.0f;
+	s1->SetNextEdge(s2, core, cornerDir, convex);
+	s2->SetPrevEdge(s1, core, cornerDir, convex);
+	return angle2;
+}
+
+b2Shape* b2Body::CreateShape(b2ShapeDef* def)
+{
+	b2Assert(m_world->m_lock == false);
+	if (m_world->m_lock == true)
+	{
+		return NULL;
+	}
+	
+	
+	// TODO: Decide on a better place to initialize edgeShapes. (b2Shape::Create() can't
+	//       return more than one shape to add to parent body... maybe it should add
+	//       shapes directly to the body instead of returning them?)
+	if (def->type == e_edgeShape) {
+		b2EdgeChainDef* edgeDef = (b2EdgeChainDef*)def;
+		b2Vec2 v1;
+		b2Vec2 v2;
+		int i;
+		
+		if (edgeDef->isALoop) {
+			v1 = edgeDef->vertices[edgeDef->vertexCount-1];
+			i = 0;
+		} else {
+			v1 = edgeDef->vertices[0];
+			i = 1;
+		}
+		
+		b2EdgeShape* s0 = NULL;
+		b2EdgeShape* s1 = NULL;
+		b2EdgeShape* s2 = NULL;
+		float32 angle = 0.0f;
+		for (; i < edgeDef->vertexCount; i++) {
+			v2 = edgeDef->vertices[i];
+			
+			void* mem = m_world->m_blockAllocator.Allocate(sizeof(b2EdgeShape));
+			s2 = new (mem) b2EdgeShape(v1, v2, def);
+			s2->m_next = m_shapeList;
+			m_shapeList = s2;
+			++m_shapeCount;
+			s2->m_body = this;
+			s2->CreateProxy(m_world->m_broadPhase, m_xf);
+			s2->UpdateSweepRadius(m_sweep.localCenter);
+			
+			if (s1 == NULL) {
+				s0 = s2;
+				angle = b2Atan2(s2->GetDirectionVector().y, s2->GetDirectionVector().x);
+			} else {
+				angle = connectEdges(s1, s2, angle);
+			}
+			s1 = s2;
+			v1 = v2;
+		}
+		if (edgeDef->isALoop) connectEdges(s1, s0, angle);
+		return s0;
+	}
+	
+	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;
+}

+ 604 - 0
box2d.mod/Source/Dynamics/b2Body.h

@@ -0,0 +1,604 @@
+/*
+* 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 "Controllers/b2Controller.h"
+
+#include <memory>
+
+class b2Joint;
+class b2Contact;
+class b2Controller;
+class b2World;
+struct b2JointEdge;
+struct b2ContactEdge;
+struct b2ControllerEdge;
+
+/// 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 list of all controllers attached to this body.
+	b2ControllerEdge* GetControllerList();
+
+	/// 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();
+
+private:
+
+	friend class b2World;
+	friend class b2Island;
+	friend class b2ContactManager;
+	friend class b2ContactSolver;
+	
+	friend class b2DistanceJoint;
+	friend class b2GearJoint;
+	friend class b2LineJoint;
+	friend class b2MouseJoint;
+	friend class b2PrismaticJoint;
+	friend class b2PulleyJoint;
+	friend class b2RevoluteJoint;
+
+	friend class b2Controller;
+
+	// 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;
+
+	int32 m_islandIndex;
+
+	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;
+
+	b2ControllerEdge* m_controllerList;
+
+	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 b2ControllerEdge* b2Body::GetControllerList()
+{
+	return m_controllerList;
+}
+
+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

+ 237 - 0
box2d.mod/Source/Dynamics/b2ContactManager.cpp

@@ -0,0 +1,237 @@
+/*
+* 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();
+	b2Body* body1 = shape1->GetBody();
+	b2Body* body2 = shape2->GetBody();
+
+	b2ContactPoint cp;
+	cp.shape1 = shape1;
+	cp.shape2 = shape2;
+	cp.friction = b2MixFriction(shape1->GetFriction(), shape2->GetFriction());
+	cp.restitution = b2MixRestitution(shape1->GetRestitution(), shape2->GetRestitution());
+
+	// Inform the user that this contact is ending.
+	int32 manifoldCount = c->GetManifoldCount();
+	if (manifoldCount > 0 && m_world->m_contactListener)
+	{
+		b2Manifold* manifolds = c->GetManifolds();
+
+		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 = body1->GetWorldPoint(mp->localPoint1);
+				b2Vec2 v1 = body1->GetLinearVelocityFromLocalPoint(mp->localPoint1);
+				b2Vec2 v2 = body2->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;
+	}
+
+	// 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);
+	}
+}

+ 54 - 0
box2d.mod/Source/Dynamics/b2ContactManager.h

@@ -0,0 +1,54 @@
+/*
+* 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_CONTACT_MANAGER_H
+#define B2_CONTACT_MANAGER_H
+
+#include "../Collision/b2BroadPhase.h"
+#include "../Dynamics/Contacts/b2NullContact.h"
+
+class b2World;
+class b2Contact;
+struct b2TimeStep;
+
+// Delegate of b2World.
+class b2ContactManager : public b2PairCallback
+{
+public:
+	b2ContactManager() : m_world(NULL), m_destroyImmediate(false) {}
+
+	// Implements PairCallback
+	void* PairAdded(void* proxyUserData1, void* proxyUserData2);
+
+	// Implements PairCallback
+	void PairRemoved(void* proxyUserData1, void* proxyUserData2, void* pairUserData);
+
+	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;
+};
+
+#endif

+ 471 - 0
box2d.mod/Source/Dynamics/b2Island.cpp

@@ -0,0 +1,471 @@
+/*
+* 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 "b2Island.h"
+#include "b2Body.h"
+#include "b2World.h"
+#include "Contacts/b2Contact.h"
+#include "Contacts/b2ContactSolver.h"
+#include "Joints/b2Joint.h"
+#include "../Common/b2StackAllocator.h"
+
+/*
+Position Correction Notes
+=========================
+I tried the several algorithms for position correction of the 2D revolute joint.
+I looked at these systems:
+- simple pendulum (1m diameter sphere on massless 5m stick) with initial angular velocity of 100 rad/s.
+- suspension bridge with 30 1m long planks of length 1m.
+- multi-link chain with 30 1m long links.
+
+Here are the algorithms:
+
+Baumgarte - A fraction of the position error is added to the velocity error. There is no
+separate position solver.
+
+Pseudo Velocities - After the velocity solver and position integration,
+the position error, Jacobian, and effective mass are recomputed. Then
+the velocity constraints are solved with pseudo velocities and a fraction
+of the position error is added to the pseudo velocity error. The pseudo
+velocities are initialized to zero and there is no warm-starting. After
+the position solver, the pseudo velocities are added to the positions.
+This is also called the First Order World method or the Position LCP method.
+
+Modified Nonlinear Gauss-Seidel (NGS) - Like Pseudo Velocities except the
+position error is re-computed for each constraint and the positions are updated
+after the constraint is solved. The radius vectors (aka Jacobians) are
+re-computed too (otherwise the algorithm has horrible instability). The pseudo
+velocity states are not needed because they are effectively zero at the beginning
+of each iteration. Since we have the current position error, we allow the
+iterations to terminate early if the error becomes smaller than b2_linearSlop.
+
+Full NGS or just NGS - Like Modified NGS except the effective mass are re-computed
+each time a constraint is solved.
+
+Here are the results:
+Baumgarte - this is the cheapest algorithm but it has some stability problems,
+especially with the bridge. The chain links separate easily close to the root
+and they jitter as they struggle to pull together. This is one of the most common
+methods in the field. The big drawback is that the position correction artificially
+affects the momentum, thus leading to instabilities and false bounce. I used a
+bias factor of 0.2. A larger bias factor makes the bridge less stable, a smaller
+factor makes joints and contacts more spongy.
+
+Pseudo Velocities - the is more stable than the Baumgarte method. The bridge is
+stable. However, joints still separate with large angular velocities. Drag the
+simple pendulum in a circle quickly and the joint will separate. The chain separates
+easily and does not recover. I used a bias factor of 0.2. A larger value lead to
+the bridge collapsing when a heavy cube drops on it.
+
+Modified NGS - this algorithm is better in some ways than Baumgarte and Pseudo
+Velocities, but in other ways it is worse. The bridge and chain are much more
+stable, but the simple pendulum goes unstable at high angular velocities.
+
+Full NGS - stable in all tests. The joints display good stiffness. The bridge
+still sags, but this is better than infinite forces.
+
+Recommendations
+Pseudo Velocities are not really worthwhile because the bridge and chain cannot
+recover from joint separation. In other cases the benefit over Baumgarte is small.
+
+Modified NGS is not a robust method for the revolute joint due to the violent
+instability seen in the simple pendulum. Perhaps it is viable with other constraint
+types, especially scalar constraints where the effective mass is a scalar.
+
+This leaves Baumgarte and Full NGS. Baumgarte has small, but manageable instabilities
+and is very fast. I don't think we can escape Baumgarte, especially in highly
+demanding cases where high constraint fidelity is not needed.
+
+Full NGS is robust and easy on the eyes. I recommend this as an option for
+higher fidelity simulation and certainly for suspension bridges and long chains.
+Full NGS might be a good choice for ragdolls, especially motorized ragdolls where
+joint separation can be problematic. The number of NGS iterations can be reduced
+for better performance without harming robustness much.
+
+Each joint in a can be handled differently in the position solver. So I recommend
+a system where the user can select the algorithm on a per joint basis. I would
+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,
+	int32 jointCapacity,
+	b2StackAllocator* allocator,
+	b2ContactListener* listener)
+{
+	m_bodyCapacity = bodyCapacity;
+	m_contactCapacity = contactCapacity;
+	m_jointCapacity	 = jointCapacity;
+	m_bodyCount = 0;
+	m_contactCount = 0;
+	m_jointCount = 0;
+
+	m_allocator = allocator;
+	m_listener = listener;
+
+	m_bodies = (b2Body**)m_allocator->Allocate(bodyCapacity * sizeof(b2Body*));
+	m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity	 * sizeof(b2Contact*));
+	m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*));
+
+	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 allowSleep)
+{
+	// Integrate velocities and apply damping.
+	for (int32 i = 0; i < m_bodyCount; ++i)
+	{
+		b2Body* b = m_bodies[i];
+
+		if (b->IsStatic())
+			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)
+		// 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);
+
+		// 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);
+
+	// Initialize velocity constraints.
+	contactSolver.InitVelocityConstraints(step);
+
+	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.FinalizeVelocityConstraints();
+
+	// 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 += step.dt * b->m_linearVelocity;
+		b->m_sweep.a += step.dt * b->m_angularVelocity;
+
+		// Compute new transform
+		b->SynchronizeTransform();
+
+		// Note: shapes are synchronized later.
+	}
+
+	// Iterate over constraints.
+	for (int32 i = 0; i < step.positionIterations; ++i)
+	{
+		bool contactsOkay = contactSolver.SolvePositionConstraints(b2_contactBaumgarte);
+
+		bool jointsOkay = true;
+		for (int32 i = 0; i < m_jointCount; ++i)
+		{
+			bool jointOkay = m_joints[i]->SolvePositionConstraints(b2_contactBaumgarte);
+			jointsOkay = jointsOkay && jointOkay;
+		}
+
+		if (contactsOkay && jointsOkay)
+		{
+			// Exit early if the position errors are small.
+			break;
+		}
+	}
+
+	Report(contactSolver.m_constraints);
+
+	if (allowSleep)
+	{
+		float32 minSleepTime = B2_FLT_MAX;
+
+#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)
+			{
+				continue;
+			}
+
+			if ((b->m_flags & b2Body::e_allowSleepFlag) == 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
+				b->m_angularVelocity * b->m_angularVelocity > angTolSqr ||
+				b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr)
+#endif
+			{
+				b->m_sleepTime = 0.0f;
+				minSleepTime = 0.0f;
+			}
+			else
+			{
+				b->m_sleepTime += step.dt;
+				minSleepTime = b2Min(minSleepTime, b->m_sleepTime);
+			}
+		}
+
+		if (minSleepTime >= b2_timeToSleep)
+		{
+			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;
+			}
+		}
+	}
+}
+
+void b2Island::SolveTOI(b2TimeStep& subStep)
+{
+	b2ContactSolver contactSolver(subStep, m_contacts, m_contactCount, m_allocator);
+
+	// No warm starting needed for TOI contact events.
+
+	// Warm starting for joints is off for now, but we need to
+	// call this function to compute Jacobians.
+	for (int32 i = 0; i < m_jointCount; ++i)
+	{
+		m_joints[i]->InitVelocityConstraints(subStep);
+	}
+
+	// Solve velocity constraints.
+	for (int32 i = 0; i < subStep.velocityIterations; ++i)
+	{
+		contactSolver.SolveVelocityConstraints();
+		for (int32 j = 0; j < m_jointCount; ++j)
+		{
+			m_joints[j]->SolveVelocityConstraints(subStep);
+		}
+	}
+
+	// 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.positionIterations; ++i)
+	{
+		bool contactsOkay = contactSolver.SolvePositionConstraints(k_toiBaumgarte);
+		bool jointsOkay = true;
+		for (int32 j = 0; j < m_jointCount; ++j)
+		{
+			bool jointOkay = m_joints[j]->SolvePositionConstraints(k_toiBaumgarte);
+			jointsOkay = jointsOkay && jointOkay;
+		}
+		
+		if (contactsOkay && jointsOkay)
+		{
+			break;
+		}
+	}
+
+	Report(contactSolver.m_constraints);
+}
+
+void b2Island::Report(b2ContactConstraint* constraints)
+{
+	if (m_listener == NULL)
+	{
+		return;
+	}
+
+	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)
+		{
+			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);
+			}
+		}
+	}
+}

+ 104 - 0
box2d.mod/Source/Dynamics/b2Island.h

@@ -0,0 +1,104 @@
+/*
+* 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_ISLAND_H
+#define B2_ISLAND_H
+
+#include "../Common/b2Math.h"
+#include "b2Body.h"
+
+class b2Contact;
+class b2Joint;
+class b2StackAllocator;
+class b2ContactListener;
+struct b2ContactConstraint;
+struct b2TimeStep;
+
+struct b2Position
+{
+	b2Vec2 x;
+	float32 a;
+};
+
+struct b2Velocity
+{
+	b2Vec2 v;
+	float32 w;
+};
+
+class b2Island
+{
+public:
+	b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity,
+			b2StackAllocator* allocator, b2ContactListener* listener);
+	~b2Island();
+
+	void Clear()
+	{
+		m_bodyCount = 0;
+		m_contactCount = 0;
+		m_jointCount = 0;
+	}
+
+	void Solve(const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep);
+
+	void SolveTOI(b2TimeStep& subStep);
+
+	void Add(b2Body* body)
+	{
+		b2Assert(m_bodyCount < m_bodyCapacity);
+		body->m_islandIndex = m_bodyCount;
+		m_bodies[m_bodyCount++] = body;
+	}
+
+	void Add(b2Contact* contact)
+	{
+		b2Assert(m_contactCount < m_contactCapacity);
+		m_contacts[m_contactCount++] = contact;
+	}
+
+	void Add(b2Joint* joint)
+	{
+		b2Assert(m_jointCount < m_jointCapacity);
+		m_joints[m_jointCount++] = joint;
+	}
+
+	void Report(b2ContactConstraint* constraints);
+
+	b2StackAllocator* m_allocator;
+	b2ContactListener* m_listener;
+
+	b2Body** m_bodies;
+	b2Contact** m_contacts;
+	b2Joint** m_joints;
+
+	b2Position* m_positions;
+	b2Velocity* m_velocities;
+
+	int32 m_bodyCount;
+	int32 m_jointCount;
+	int32 m_contactCount;
+
+	int32 m_bodyCapacity;
+	int32 m_contactCapacity;
+	int32 m_jointCapacity;
+
+	int32 m_positionIterationCount;
+};
+
+#endif

+ 1262 - 0
box2d.mod/Source/Dynamics/b2World.cpp

@@ -0,0 +1,1262 @@
+/*
+* 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 "../Collision/Shapes/b2EdgeShape.h"
+#include <new>
+
+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_controllerList = NULL;
+
+	m_bodyCount = 0;
+	m_contactCount = 0;
+	m_jointCount = 0;
+	m_controllerCount = 0;
+
+	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);
+	}
+
+	//Detach controllers attached to this body
+	b2ControllerEdge* ce = b->m_controllerList;
+	while(ce)
+	{
+		b2ControllerEdge* ce0 = ce;
+		ce = ce->nextController;
+
+		ce0->controller->RemoveBody(b);
+	}
+
+	// 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());
+		}
+	}
+}
+
+b2Controller* b2World::CreateController(b2ControllerDef* def)
+{
+	b2Controller* controller = def->Create(&m_blockAllocator);
+
+	controller->m_next = m_controllerList;
+	controller->m_prev = NULL;
+	if(m_controllerList)
+		m_controllerList->m_prev = controller;
+	m_controllerList = controller;
+	++m_controllerCount;
+
+	controller->m_world = this;
+
+	return controller;
+}
+
+void b2World::DestroyController(b2Controller* controller)
+{
+	b2Assert(m_controllerCount>0);
+	if(controller->m_next)
+		controller->m_next->m_prev = controller->m_prev;
+	if(controller->m_prev)
+		controller->m_prev->m_next = controller->m_next;
+	if(controller == m_controllerList)
+		m_controllerList = controller->m_next;
+	--m_controllerCount;
+
+	b2Controller::Destroy(controller, &m_blockAllocator);
+}
+
+void b2World::Refilter(b2Shape* shape)
+{
+	b2Assert(m_lock == false);
+
+	shape->RefilterProxy(m_broadPhase, shape->GetBody()->GetXForm());
+}
+
+// Find islands, integrate and solve constraints, solve position constraints
+void b2World::Solve(const b2TimeStep& step)
+{
+	// Step all controlls
+	for(b2Controller* controller = m_controllerList;controller;controller=controller->m_next)
+	{
+		controller->Step(step);
+	}
+
+	// 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_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->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 queue for TOI island solution.
+	b2Island island(m_bodyCount, b2_maxTOIContactsPerIsland, b2_maxTOIJointsPerIsland, &m_stackAllocator, m_contactListener);
+	
+	//Simple one pass queue
+	//Relies on the fact that we're only making one pass
+	//through and each body can only be pushed/popped once.
+	//To push: 
+	//  queue[queueStart+queueSize++] = newElement;
+	//To pop: 
+	//	poppedElement = queue[queueStart++];
+	//  --queueSize;
+	int32 queueCapacity = m_bodyCount;
+	b2Body** queue = (b2Body**)m_stackAllocator.Allocate(queueCapacity* 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);
+	}
+
+	for (b2Joint* j = m_jointList; j; j = j->m_next)
+	{
+            j->m_islandFlag = false;
+	}
+
+	// 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 the TOI is in range ...
+				if (0.0f < toi && toi < 1.0f)
+				{
+					// Interpolate on the actual range.
+					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 queue.
+		island.Clear();
+		
+		int32 queueStart = 0; // starting index for queue
+		int32 queueSize = 0;  // elements in queue
+		queue[queueStart + queueSize++] = seed;
+		seed->m_flags |= b2Body::e_islandFlag;
+
+		// Perform a breadth first search (BFS) on the contact/joint graph.
+		while (queueSize > 0)
+		{
+			// Grab the next body off the stack and add it to the island.
+			b2Body* b = queue[queueStart++];
+			--queueSize;
+			
+			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* cEdge = b->m_contactList; cEdge; cEdge = cEdge->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 (cEdge->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 (cEdge->contact->GetManifoldCount() == 0)
+				{
+					continue;
+				}
+
+				island.Add(cEdge->contact);
+				cEdge->contact->m_flags |= b2Contact::e_islandFlag;
+
+				// Update other body.
+				b2Body* other = cEdge->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(queueStart + queueSize < queueCapacity);
+				queue[queueStart + queueSize] = other;
+				++queueSize;
+				other->m_flags |= b2Body::e_islandFlag;
+			}
+			
+			for (b2JointEdge* jEdge = b->m_jointList; jEdge; jEdge = jEdge->next)
+			{
+				if (island.m_jointCount == island.m_jointCapacity)
+				{
+					continue;
+				}
+				
+				if (jEdge->joint->m_islandFlag == true)
+				{
+					continue;
+				}
+				
+				island.Add(jEdge->joint);
+				
+				jEdge->joint->m_islandFlag = true;
+				
+				b2Body* other = jEdge->other;
+				
+				if (other->m_flags & b2Body::e_islandFlag)
+				{
+					continue;
+				}
+				
+				if (!other->IsStatic())
+				{
+					other->Advance(minTOI);
+					other->WakeUp();
+				}
+				
+				b2Assert(queueStart + queueSize < queueCapacity);
+				queue[queueStart + queueSize] = other;
+				++queueSize;
+				other->m_flags |= b2Body::e_islandFlag;
+			}
+		}
+
+		b2TimeStep subStep;
+		subStep.warmStarting = false;
+		subStep.dt = (1.0f - minTOI) * step.dt;
+		subStep.inv_dt = 1.0f / subStep.dt;
+		subStep.dtRatio = 0.0f;
+		subStep.velocityIterations = step.velocityIterations;
+		subStep.positionIterations = step.positionIterations;
+
+		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);
+		}
+
+		for (int32 i = 0; i < island.m_jointCount; ++i)
+		{
+			// Allow joints to participate in future TOI islands.
+			b2Joint* j = island.m_joints[i];
+			j->m_islandFlag = false;
+		}
+		
+		// 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(queue);
+}
+
+void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations)
+{
+	m_lock = true;
+
+	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.
+	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;
+}
+
+int32 b2World::Raycast(const b2Segment& segment, b2Shape** shapes, int32 maxCount, bool solidShapes, void* userData)
+{
+	m_raycastSegment = &segment;
+	m_raycastUserData = userData;
+	m_raycastSolidShape = solidShapes;
+
+	void** results = (void**)m_stackAllocator.Allocate(maxCount * sizeof(void*));
+
+	int32 count = m_broadPhase->QuerySegment(segment,results,maxCount, &RaycastSortKey);
+
+	for (int32 i = 0; i < count; ++i)
+	{
+		shapes[i] = (b2Shape*)results[i];
+	}
+
+	m_stackAllocator.Free(results);
+	return count;
+}
+
+b2Shape* b2World::RaycastOne(const b2Segment& segment, float32* lambda, b2Vec2* normal, bool solidShapes, void* userData)
+{
+	int32 maxCount = 1;
+	b2Shape* shape;
+
+	int32 count = Raycast(segment, &shape, maxCount, solidShapes, userData);
+
+	if(count==0)
+		return NULL;
+
+	b2Assert(count==1);
+
+	//Redundantly do TestSegment a second time, as the previous one's results are inaccessible
+
+	const b2XForm xf = shape->GetBody()->GetXForm();
+	shape->TestSegment(xf, lambda, normal,segment,1);
+	//We already know it returns true
+	return shape;
+}
+
+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;
+		
+	case e_edgeShape:
+		{
+			b2EdgeShape* edge = (b2EdgeShape*)shape;
+			
+			m_debugDraw->DrawSegment(b2Mul(xf, edge->GetVertex1()), b2Mul(xf, edge->GetVertex2()), color);
+			
+			if (core)
+			{
+				m_debugDraw->DrawSegment(b2Mul(xf, edge->GetCoreVertex1()), b2Mul(xf, edge->GetCoreVertex2()), 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_controllerBit)
+	{
+		for (b2Controller* c = m_controllerList; c; c= c->GetNext())
+		{
+			c->Draw(m_debugDraw);
+		}
+	}
+
+	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;
+}
+
+bool b2World::InRange(const b2AABB& aabb) const
+{
+	return m_broadPhase->InRange(aabb);
+}
+
+float32 b2World::RaycastSortKey(void* data)
+{
+	b2Shape* shape = (b2Shape*)data;
+	b2Body* body = shape->GetBody();
+	b2World* world = body->GetWorld();
+	const b2XForm xf = body->GetXForm();
+
+	if(world->m_contactFilter && !world->m_contactFilter->RayCollide(world->m_raycastUserData,shape))
+		return -1;
+
+	float32 lambda;
+	b2SegmentCollide collide = shape->TestSegment(xf, &lambda, &world->m_raycastNormal, *world->m_raycastSegment,1);
+
+	if(world->m_raycastSolidShape && collide==e_missCollide)
+		return -1;
+	if(!world->m_raycastSolidShape && collide!=e_hitCollide)
+		return -1;
+
+	return lambda;
+}

+ 320 - 0
box2d.mod/Source/Dynamics/b2World.h

@@ -0,0 +1,320 @@
+/*
+* 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;
+class b2Controller;
+class b2ControllerDef;
+
+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;
+};
+
+/// 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);
+
+	/// Add a controller to the world.
+	b2Controller* CreateController(b2ControllerDef* def);
+
+	/// Removes a controller from the world.
+	void DestroyController(b2Controller* controller);
+
+	/// 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 velocityIterations for the velocity constraint solver.
+	/// @param positionIterations for the position constraint solver.
+	void Step(float32 timeStep, int32 velocityIterations, int32 positionIterations);
+
+	/// 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);
+
+	/// Query the world for all shapes that intersect a given segment. You provide a shap
+	/// pointer buffer of specified size. The number of shapes found is returned, and the buffer
+	/// is filled in order of intersection
+	/// @param segment defines the begin and end point of the ray cast, from p1 to p2.
+	/// Use b2Segment.Extend to create (semi-)infinite rays
+	/// @param shapes a user allocated shape pointer array of size maxCount (or greater).
+	/// @param maxCount the capacity of the shapes array
+	/// @param solidShapes determines if shapes that the ray starts in are counted as hits.
+	/// @param userData passed through the worlds contact filter, with method RayCollide. This can be used to filter valid shapes
+	/// @returns the number of shapes found
+	int32 Raycast(const b2Segment& segment, b2Shape** shapes, int32 maxCount, bool solidShapes, void* userData);
+
+	/// Performs a raycast as with Raycast, finding the first intersecting shape.
+	/// @param segment defines the begin and end point of the ray cast, from p1 to p2.
+	/// Use b2Segment.Extend to create (semi-)infinite rays	
+	/// @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 solidShapes determines if shapes that the ray starts in are counted as hits.
+	/// @returns the colliding shape shape, or null if not found
+	b2Shape* RaycastOne(const b2Segment& segment, float32* lambda, b2Vec2* normal, bool solidShapes, void* userData);
+
+	/// Check if the AABB is within the broadphase limits.
+	bool InRange(const b2AABB& aabb) 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 controller list. With the returned controller, use b2Controller::GetNext to get
+	/// the next controller in the world list. A NULL controller indicates the end of the list.
+	/// @return the head of the world controller list.
+	b2Controller* GetControllerList();
+
+	/// 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 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 of joints.
+	int32 GetJointCount() const;
+
+	/// Get the number of contacts (each may have 0 or more contact points).
+	int32 GetContactCount() const;
+
+	/// Get the number of controllers.
+	int32 GetControllerCount() const;
+
+	/// Change the global gravity vector.
+	void SetGravity(const b2Vec2& gravity);
+	
+	/// Get the global gravity vector.
+	b2Vec2 GetGravity() const;
+
+private:
+
+	friend class b2Body;
+	friend class b2ContactManager;
+	friend class b2Controller;
+
+	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();
+
+	//Is it safe to pass private static function pointers?
+	static float32 RaycastSortKey(void* shape);
+
+	b2BlockAllocator m_blockAllocator;
+	b2StackAllocator m_stackAllocator;
+
+	bool m_lock;
+
+	b2BroadPhase* m_broadPhase;
+	b2ContactManager m_contactManager;
+
+	b2Body* m_bodyList;
+	b2Joint* m_jointList;
+	b2Controller* m_controllerList;
+
+	b2Vec2 m_raycastNormal;
+	void* m_raycastUserData;
+	const b2Segment* m_raycastSegment;
+	bool m_raycastSolidShape;
+
+
+	// Do not access
+	b2Contact* m_contactList;
+
+	int32 m_bodyCount;
+	int32 m_contactCount;
+	int32 m_jointCount;
+	int32 m_controllerCount;
+
+	b2Vec2 m_gravity;
+	bool m_allowSleep;
+
+	b2Body* m_groundBody;
+
+	b2DestructionListener* m_destructionListener;
+	b2BoundaryListener* m_boundaryListener;
+	b2ContactFilter* m_contactFilter;
+	b2ContactListener* m_contactListener;
+	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::GetGroundBody()
+{
+	return m_groundBody;
+}
+
+inline b2Body* b2World::GetBodyList()
+{
+	return m_bodyList;
+}
+
+inline b2Joint* b2World::GetJointList()
+{
+	return m_jointList;
+}
+
+inline b2Controller* b2World::GetControllerList()
+{
+	return m_controllerList;
+}
+
+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 int32 b2World::GetControllerCount() const
+{
+	return m_controllerCount;
+}
+
+inline void b2World::SetGravity(const b2Vec2& gravity)
+{
+	m_gravity = gravity;
+}
+
+inline b2Vec2 b2World::GetGravity() const
+{
+	return m_gravity;
+}
+
+#endif

+ 71 - 0
box2d.mod/Source/Dynamics/b2WorldCallbacks.cpp

@@ -0,0 +1,71 @@
+/*
+* 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 "b2WorldCallbacks.h"
+#include "../Collision/Shapes/b2Shape.h"
+
+b2ContactFilter b2_defaultFilter;
+
+// 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)
+{
+	const b2FilterData& filter1 = shape1->GetFilterData();
+	const b2FilterData& filter2 = shape2->GetFilterData();
+
+	if (filter1.groupIndex == filter2.groupIndex && filter1.groupIndex != 0)
+	{
+		return filter1.groupIndex > 0;
+	}
+
+	bool collide = (filter1.maskBits & filter2.categoryBits) != 0 && (filter1.categoryBits & filter2.maskBits) != 0;
+	return collide;
+}
+
+bool b2ContactFilter::RayCollide(void* userData, b2Shape* shape)
+{
+	//By default, cast userData as a shape, and then collide if the shapes would collide
+	if(!userData)
+		return true;
+	return ShouldCollide((b2Shape*)userData,shape);
+}
+
+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;
+}

+ 176 - 0
box2d.mod/Source/Dynamics/b2WorldCallbacks.h

@@ -0,0 +1,176 @@
+/*
+* 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_CALLBACKS_H
+#define B2_WORLD_CALLBACKS_H
+
+#include "../Common/b2Settings.h"
+
+struct b2Vec2;
+struct b2XForm;
+class b2Shape;
+class b2Body;
+class b2Joint;
+class b2Contact;
+struct b2ContactPoint;
+struct b2ContactResult;
+
+/// Joints and shapes are destroyed when their associated
+/// body is destroyed. Implement this listener so that you
+/// may nullify references to these joints and shapes.
+class b2DestructionListener
+{
+public:
+	virtual ~b2DestructionListener() {}
+
+	/// Called when any joint is about to be destroyed due
+	/// 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
+	/// to the destruction of its parent body.
+	virtual void SayGoodbye(b2Shape* shape) = 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
+{
+public:
+	virtual ~b2ContactFilter() {}
+
+	/// 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);
+
+	/// Return true if the given shape should be considered for ray intersection
+	virtual bool RayCollide(void* userData, b2Shape* b2Shape);
+};
+
+/// The default contact filter.
+extern b2ContactFilter b2_defaultFilter;
+
+/// Implement this class to get collision results. 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.
+/// Additionally you may receive multiple callbacks for the same contact in a
+/// 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) { B2_NOT_USED(point); }
+
+	/// Called when a contact point persists. This includes the geometry
+	/// and the forces.
+	virtual void Persist(const b2ContactPoint* point) { B2_NOT_USED(point); }
+
+	/// Called when a contact point is removed. This includes the last
+	/// computed geometry and forces.
+	virtual void Remove(const b2ContactPoint* point) { B2_NOT_USED(point); }
+
+	/// Called after a contact point is solved.
+	virtual void Result(const b2ContactResult* point) { B2_NOT_USED(point); }
+};
+
+/// 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) {}
+	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_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_controllerBit			= 0x0080, ///< draw controllers
+	};
+
+	/// 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 DrawXForm(const b2XForm& xf) = 0;
+
+protected:
+	uint32 m_drawFlags;
+};
+
+#endif

+ 5238 - 0
box2d.mod/box2d.bmx

@@ -0,0 +1,5238 @@
+' Copyright (c) 2008-2021 Bruce A Henderson
+' 
+' 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.
+' 
+SuperStrict
+
+Rem
+bbdoc: Box2D
+End Rem
+Module Physics.Box2D
+
+ModuleInfo "Version: 1.06"
+ModuleInfo "License: MIT"
+ModuleInfo "Copyright: Box2D (c) 2006-2016 Erin Catto http://www.gphysics.com"
+ModuleInfo "Copyright: BlitzMax port - 2008-2021 Bruce A Henderson"
+
+ModuleInfo "History: 1.06"
+ModuleInfo "History: Refactored to use structs where appropriate."
+ModuleInfo "History: 1.05"
+ModuleInfo "History: Updated for NG"
+ModuleInfo "History: 1.04"
+ModuleInfo "History: Updated to box2d svn (rev 207)"
+ModuleInfo "History: Added b2LineJoint type."
+ModuleInfo "History: Added b2ShapeDef.SetUserData() method."
+ModuleInfo "History: Added b2Mat22.GetAngle() method."
+ModuleInfo "History: Added b2Mat22 Create... methods, and others."
+ModuleInfo "History: Added shape SetFriction() and SetRestitution() methods."
+ModuleInfo "History: Fixed contact filter example and docs."
+ModuleInfo "History: Added b2EdgeShape type."
+ModuleInfo "History: Added staticedges, dynamicedges, pyramidstaticedges and buoyancy examples."
+ModuleInfo "History: Added buoyancy types + methods."
+ModuleInfo "History: Added b2Body SetMass() method."
+ModuleInfo "History: Added b2BodyDef GetMassData() method."
+ModuleInfo "History: Converted bool handling in glue to use ints instead."
+ModuleInfo "History: Added b2Vec2 SetX() and SetY() methods."
+ModuleInfo "History: 1.03"
+ModuleInfo "History: Updated to box2d svn (rev 172)"
+ModuleInfo "History: Added b2CircleShape and b2PolygonShape types."
+ModuleInfo "History: Added b2OBB type."
+ModuleInfo "History: Added b2Segment type."
+ModuleInfo "History: Added b2World Raycast(), RaycastOne() and InRange() methods."
+ModuleInfo "History: Added b2Body.GetWorld() method."
+ModuleInfo "History: Added raycast example."
+ModuleInfo "History: 1.02"
+ModuleInfo "History: Updated to box2d svn (rev 169)"
+ModuleInfo "History: API CHANGES : DoStep() - changed iteration parameters"
+ModuleInfo "History: API CHANGES : joints - GetReactionForce() And GetReactionTorque() added 'dt' parameter."
+ModuleInfo "History: Added car example."
+ModuleInfo "History: Added revolute example."
+ModuleInfo "History: Added b2ShapeDef - SetIsSensor and IsSensor methods."
+ModuleInfo "History: Fixed typo in b2ContactListener - Remove()."
+ModuleInfo "History: Added b2World.Refilter() and several missing b2Shape methods."
+ModuleInfo "History: Updated Documentation."
+ModuleInfo "History: 1.01"
+ModuleInfo "History: Fixed filterdata problem. Fixed collisionfiltering example."
+ModuleInfo "History: Added Theo Jansen example."
+ModuleInfo "History: 1.00 Initial Release"
+
+Import "common.bmx"
+
+' NOTES :
+'  b2Controller.h - Added userData fields/methods.
+'
+
+Rem
+bbdoc: The world type manages all physics entities, dynamic simulation, and asynchronous queries. 
+about: The world also contains efficient memory management facilities. 
+End Rem
+Type b2World
+
+	Field b2ObjectPtr:Byte Ptr
+	
+	Field filter:b2ContactFilter
+	Field contactListener:b2ContactListener
+	Field boundaryListener:b2BoundaryListener
+	Field destructionListener:b2DestructionListener
+	
+	Function _create:b2World(b2ObjectPtr:Byte Ptr)
+		If b2ObjectPtr Then
+			Local this:b2World = New b2World
+			this.b2ObjectPtr = b2ObjectPtr
+			Return this
+		End If
+	End Function
+
+	Rem
+	bbdoc: Construct a world object. 
+	End Rem
+	Function CreateWorld:b2World(worldAABB:b2AABB, gravity:b2Vec2, doSleep:Int)
+		Return New b2World.Create(worldAABB, gravity, doSleep)
+	End Function
+	
+	Rem
+	bbdoc: Construct a world object. 
+	End Rem
+	Method Create:b2World(worldAABB:b2AABB, gravity:b2Vec2, doSleep:Int)
+		b2ObjectPtr = bmx_b2world_create(worldAABB, gravity, doSleep)
+		
+		' setup default destruction listener
+		SetDestructionListener(New b2DestructionListener)
+		
+		Return Self
+	End Method
+
+	Method Free()
+		If b2ObjectPtr Then
+			bmx_b2world_free(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+	
+	Method Delete()
+		Free()
+	End Method
+	
+	Rem
+	bbdoc: Register a destruction listener.
+	End Rem
+	Method SetDestructionListener(listener:b2DestructionListener)
+		destructionListener = listener
+		bmx_b2world_setdestructionlistener(b2ObjectPtr, listener.b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Register a broad-phase boundary listener.
+	End Rem
+	Method SetBoundaryListener(listener:b2BoundaryListener)
+		boundaryListener = listener
+		bmx_b2world_setboundarylistener(b2ObjectPtr, listener.b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Register a contact filter to provide specific control over collision.
+	about: Otherwise the default filter is used.
+	End Rem
+	Method SetFilter(_filter:b2ContactFilter)
+		filter = _filter
+		bmx_b2world_setfilter(b2ObjectPtr, filter.b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Register a contact event listener
+	End Rem
+	Method SetContactListener(listener:b2ContactListener)
+		contactListener = listener
+		bmx_b2world_setcontactlistener(b2ObjectPtr, listener.b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Register a routine for debug drawing.
+	about: The debug draw functions are called inside the b2World::DoStep method, so make sure your renderer is ready to
+	consume draw commands when you call DoStep().
+	End Rem
+	Method SetDebugDraw(debugDraw:b2DebugDraw)
+		bmx_b2world_setdebugDraw(b2ObjectPtr, debugDraw.b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Create a rigid body given a definition
+	about: No reference to the definition is retained.
+	<p>
+	Warning: This method is locked during callbacks.
+	</p>
+	End Rem
+	Method CreateBody:b2Body(def:b2BodyDef)
+		Local body:b2Body = New b2Body
+		body.userData = def.userData ' copy the userData
+		body.b2ObjectPtr = bmx_b2world_createbody(b2ObjectPtr, def.b2ObjectPtr, body)
+		Return body
+	End Method
+
+	Rem
+	bbdoc: Destroy a rigid body given a definition.
+	about: No reference to the definition is retained.
+	<p>
+	Warning: This automatically deletes all associated shapes and joints.
+	</p>
+	<p>
+	Warning: This method is locked during callbacks.
+	</p>
+	End Rem
+	Method DestroyBody(body:b2Body)
+		bmx_b2world_destroybody(b2ObjectPtr, body.b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Create a joint to constrain bodies together.
+	about: No reference to the definition is retained. This may cause the connected bodies to cease
+	colliding.
+	<p>
+	Warning: This method is locked during callbacks.
+	</p>
+	End Rem
+	Method CreateJoint:b2Joint(def:b2JointDef)
+		Local joint:b2Joint = b2Joint._create(bmx_b2world_createjoint(b2ObjectPtr, def.b2ObjectPtr))
+		joint.userData = def.userData ' copy the userData
+		Return joint
+	End Method
+	
+	' 
+	Function _createJoint:b2Joint(jointType:Int) { nomangle }
+		Local joint:b2Joint
+		Select jointType
+			Case e_unknownJoint
+				joint = New b2Joint
+			Case e_revoluteJoint
+				joint = New b2RevoluteJoint
+			Case e_prismaticJoint
+				joint = New b2PrismaticJoint
+			Case e_distanceJoint
+				joint = New b2DistanceJoint
+			Case e_pulleyJoint
+				joint = New b2PulleyJoint
+			Case e_mouseJoint
+				joint = New b2MouseJoint
+			Case e_gearJoint
+				joint = New b2GearJoint
+			Case e_lineJoint
+				joint = New b2LineJoint
+			Default
+				DebugLog "Warning, joint type '" + jointType + "' is not defined in module."
+				joint = New b2Joint
+		End Select
+		Return joint
+	End Function
+
+	Rem
+	bbdoc: Destroy a joint.
+	about: This may cause the connected bodies to begin colliding.
+	<p>
+	Warning: This method is locked during callbacks.
+	</p>
+	End Rem
+	Method DestroyJoint(joint:b2Joint)
+		bmx_b2world_destroyjoint(b2ObjectPtr, joint.b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Add a controller to the world.
+	End Rem
+	Method CreateController:b2Controller(def:b2ControllerDef)
+		Local controller:b2Controller = b2Controller._create(bmx_b2world_createcontroller(b2ObjectPtr, def.b2ObjectPtr, def._type))
+		controller.userData = def.userData ' copy the userData
+		Return controller
+	End Method
+	' 
+	Function __createController:b2Controller(controllerType:Int) { nomangle }
+		Local controller:b2Controller
+		Select controllerType
+			Case e_buoyancyController
+				controller = New b2BuoyancyController
+			Case e_constantAccelController
+				controller = New b2ConstantAccelController
+			Case e_tensorDampingController
+				controller = New b2TensorDampingController
+			Case e_gravityController
+				controller = New b2GravityController
+			Case e_constantForceController
+				controller = New b2ConstantForceController
+			Default
+				DebugLog "Warning, controller type '" + controllerType + "' is not defined in module."
+				controller = New b2Controller
+		End Select
+		Return controller
+	End Function
+
+	Rem
+	bbdoc: Removes a controller from the world.
+	End Rem
+	Method DestroyController(controller:b2Controller)
+		bmx_b2world_destroycontroller(b2ObjectPtr, controller.b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: The world provides a single static ground body with no collision shapes.
+	about: You can use this to simplify the creation of joints and static shapes.
+	End Rem
+	Method GetGroundBody:b2Body()
+		Return b2Body._create(bmx_b2world_getgroundbody(b2ObjectPtr))
+	End Method
+
+	Rem
+	bbdoc: Take a time Step.
+	about: This performs collision detection, integration, and constraint solution.
+	<p>Parameters: 
+	<ul>
+	<li><b> timeStep </b> : the amount of time To simulate, this should Not vary. </li>
+	<li><b> velocityIterations </b> : for the velocity constraint solver.</li>
+	<li><b> positionIterations </b> : for the position constraint solver.</li>
+	</ul>
+	</p>
+	End Rem
+	Method DoStep(timeStep:Float, velocityIterations:Int, positionIterations:Int)
+		bmx_b2world_dostep(b2ObjectPtr, timeStep, velocityIterations, positionIterations)
+	End Method
+
+	Rem
+	bbdoc: Get the world body list. 
+	returns: The head of the world body list. 
+	about: 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. 
+	End Rem
+	Method GetBodyList:b2Body()
+		Return b2Body._create(bmx_b2world_getbodylist(b2ObjectPtr))
+	End Method
+
+	Rem
+	bbdoc: Get the world joint list.
+	returns: The head of the world joint list. 
+	about: 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.
+	End Rem
+	Method GetJointList:b2Joint()
+		Return b2Joint._create(bmx_b2world_getjointlist(b2ObjectPtr))
+	End Method
+
+	Rem
+	bbdoc: Enable/disable warm starting. For testing. 
+	End Rem
+	Method SetWarmStarting(flag:Int)
+		bmx_b2world_setwarmstarting(b2ObjectPtr, flag)
+	End Method
+
+	Rem
+	bbdoc: Enable/disable continuous physics. For testing. 
+	End Rem
+	Method SetContinuousPhysics(flag:Int)
+		bmx_b2world_setcontinuousphysics(b2ObjectPtr, flag)
+	End Method
+
+	Rem
+	bbdoc: Perform validation of internal data structures.
+	End Rem
+	Method Validate()
+		bmx_b2world_validate(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc:  Change the global gravity vector.
+	End Rem
+	Method SetGravity(gravity:b2Vec2)
+		bmx_b2world_setgravity(b2ObjectPtr, gravity)
+	End Method
+	
+	Rem
+	bbdoc: Get the number of broad-phase proxies.
+	End Rem
+	Method GetProxyCount:Int()
+		Return bmx_b2world_getproxycount(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the number of broad-phase pairs. 
+	End Rem
+	Method GetPairCount:Int()
+		Return bmx_b2world_getpaircount(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the number of bodies. 
+	End Rem
+	Method GetBodyCount:Int()
+		Return bmx_b2world_getbodycount(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the number joints. 
+	End Rem
+	Method GetJointCount:Int()
+		Return bmx_b2world_getjointcount(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Query the world for all shapes that potentially overlap the provided AABB.
+	returns: The number of shapes found in aabb. 
+	about: You provide a shape array for populating. The number of shapes found is returned. 
+	End Rem
+	Method Query:Int(aabb:b2AABB, shapes:b2Shape[])
+		Return bmx_b2world_query(b2ObjectPtr, aabb, shapes)
+	End Method
+	
+	Rem
+	bbdoc: Re-filter a shape.
+	about: This re-runs contact filtering on a shape.
+	End Rem
+	Method Refilter(shape:b2Shape)
+		bmx_b2world_refilter(b2ObjectPtr, shape.b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc:  Query the world for all shapes that intersect a given segment.
+	about: You provide a shape array of an appropriate size. The number of shapes found is returned, and the array
+	is filled in order of intersection.
+	End Rem
+	Method Raycast:Int(segment:b2Segment Var, shapes:b2Shape[], solidShapes:Int)
+		Return bmx_b2world_raycast(b2ObjectPtr, segment, shapes, solidShapes)
+	End Method
+
+	Rem
+	bbdoc: Performs a raycast as with Raycast, finding the first intersecting shape.
+	End Rem
+	Method RaycastOne:b2Shape(segment:b2Segment Var, lambda:Float Var, normal:b2Vec2 Var, solidShapes:Int)
+		Return b2Shape._create(bmx_b2world_raycastone(b2ObjectPtr, segment, Varptr lambda, normal, solidShapes))
+	End Method
+	
+	Rem
+	bbdoc: Check if the AABB is within the broadphase limits.
+	End Rem
+	Method InRange:Int(aabb:b2AABB)
+		Return bmx_b2world_inrange(b2ObjectPtr, aabb)
+	End Method
+	
+	Function _setShape(shapes:b2Shape[], index:Int, shape:Byte Ptr) { nomangle }
+		shapes[index] = b2Shape._create(shape)
+	End Function
+	
+End Type
+
+
+Rem
+bbdoc: An axis aligned bounding box.
+End Rem
+Struct b2AABB
+
+	Field lowerBound:b2Vec2
+	Field upperBound:b2Vec2
+
+	Method Create:b2AABB()
+		Return Self
+	End Method
+
+	Rem
+	bbdoc: Creates a new AABB
+	End Rem
+	Function CreateAABB:b2AABB(lowerBound:b2Vec2, upperBound:b2Vec2)
+		Return New b2AABB.Create(lowerBound, upperBound)
+	End Function
+	
+	Rem
+	bbdoc: Creates a new AABB
+	End Rem
+	Method Create:b2AABB(lowerBound:b2Vec2, upperBound:b2Vec2)
+		Self.lowerBound = lowerBound
+		Self.upperBound = upperBound
+		Return Self
+	End Method
+	
+	Rem
+	bbdoc: Sets the lower vertex.
+	End Rem
+	Method SetLowerBound(lowerBound:b2Vec2)
+		Self.lowerBound = lowerBound
+	End Method
+
+	Rem
+	bbdoc: Sets the upper vertex.
+	End Rem
+	Method SetUpperBound(upperBound:b2Vec2)
+		Self.upperBound = upperBound
+	End Method
+	
+	Rem
+	bbdoc: Verify that the bounds are sorted. 
+	End Rem
+	Method IsValid:Int()
+		Return bmx_b2abb_isvalid(Self)
+	End Method
+
+End Struct
+
+Rem
+bbdoc: A 2D column vector. 
+End Rem
+Struct b2Vec2
+
+	Field x:Float
+	Field y:Float
+	
+	Method New()
+	End Method
+	
+	Method New(x:Float, y:Float)
+		Self.x = x
+		Self.y = y
+	End Method
+	
+	Rem
+	bbdoc: Creates a new vector with the given coordinates.
+	End Rem
+	Function CreateVec2:b2Vec2(x:Float = 0, y:Float = 0)
+		Return New b2Vec2.Create(x, y)
+	End Function
+	
+	Rem
+	bbdoc: Creates a new vector with the given coordinates.
+	End Rem
+	Method Create:b2Vec2(x:Float = 0, y:Float = 0)
+		Self.x = x
+		Self.y = y
+		Return Self
+	End Method
+	
+	Rem
+	bbdoc: Returns the X coordinate.
+	about: Synonym for X().
+	End Rem
+	Method GetX:Float()
+		Return x
+	End Method
+
+	Rem
+	bbdoc: Returns the Y coordinate.
+	about: Synonym for Y().
+	End Rem
+	Method GetY:Float()
+		Return y
+	End Method
+
+	Rem
+	bbdoc: Adds @vec to this vector.
+	End Rem	
+	Method Add(vec:b2Vec2)
+		x :+ vec.x
+		y :+ vec.y
+	End Method
+
+	Rem
+	bbdoc: Adds @vec to this vector, returning the a new b2Vec2.
+	about: This object is not modified.
+	End Rem	
+	Method Plus:b2Vec2(vec:b2Vec2)
+		Return New b2Vec2(x + vec.x, y + vec.y)
+	End Method
+
+	Rem
+	bbdoc: Multiplies the vector by @value.
+	End Rem	
+	Method Multiply:b2Vec2(value:Float)
+		x :* value
+		y :* value
+		Return Self
+	End Method
+
+	Rem
+	bbdoc: Divides the vector by @value.
+	End Rem	
+	Method Divide:b2Vec2(value:Float)
+		Local v:Float = 1.0 / value
+		x :* v
+		y :* v
+		Return Self
+	End Method
+
+	Rem
+	bbdoc: Copies @vec into this object.
+	End Rem	
+	Method Copy(vec:b2Vec2)
+		x = vec.x
+		y = vec.y
+	End Method
+	
+	Rem
+	bbdoc: Subtracts @vec from this object, returning a new b2Vec2.
+	about: This object is not modified.
+	End Rem	
+	Method Subtract:b2Vec2(vec:b2Vec2)
+		Return New b2Vec2(x - vec.x, y - vec.y)
+	End Method
+	
+	Rem
+	bbdoc: Sets the x and y parts.
+	End Rem	
+	Method Set(x:Float, y:Float)
+		Self.x = x
+		Self.y = y
+	End Method
+	
+	Rem
+	bbdoc: Sets the x part.
+	End Rem
+	Method SetX(x:Float)
+		Self.x = x
+	End Method
+
+	Rem
+	bbdoc: Sets the y part.
+	End Rem
+	Method SetY(y:Float)
+		Self.y = y
+	End Method
+	
+	Rem
+	bbdoc: Returns the length of this vector.
+	End Rem	
+	Method Length:Float()
+		Return bmx_b2vec2_length(Self)
+	End Method
+	
+	Rem
+	bbdoc: Convert this vector into a unit vector.
+	returns: The length. 
+	End Rem
+	Method Normalize:Float()
+		Return bmx_b2vec2_normalize(Self)
+	End Method
+	
+	Rem
+	bbdoc: Get the length squared.
+	about: For performance, use this instead of b2Vec2::Length (if possible).
+	End Rem
+	Method LengthSquared:Float()
+		Return bmx_b2vec2_lengthsquared(Self)
+	End Method
+
+	Function _newVecArray:b2Vec2[](count:Int) { nomangle }
+		Return New b2Vec2[count]
+	End Function
+	
+	Rem
+	bbdoc: A zero vector (0,0)
+	End Rem
+	Global ZERO:b2Vec2 = New b2Vec2
+	
+End Struct
+
+Rem
+bbdoc: Convenience function for creating a b2Vec2 object.
+End Rem
+Function Vec2:b2Vec2(x:Float, y:Float)
+	Return New b2Vec2(x, y)
+End Function
+
+Rem
+bbdoc: Joints and shapes are destroyed when their associated body is destroyed. 
+about: Implement this listener so that you may nullify references to these joints and shapes. 
+End Rem
+Type b2DestructionListener
+
+	Field b2ObjectPtr:Byte Ptr
+
+	Method New()
+		b2ObjectPtr = bmx_b2destructionlistener_new(Self)
+	End Method
+
+	Rem
+	bbdoc: Called when any joint is about to be destroyed due to the destruction of one of its attached bodies. 
+	End Rem
+	Method SayGoodbyeJoint(joint:b2Joint)
+	End Method
+
+	Function _SayGoodbyeJoint(listener:b2DestructionListener, joint:Byte Ptr) { nomangle }
+		listener.SayGoodbyeJoint(b2Joint._create(joint))
+	End Function
+	
+	Rem
+	bbdoc: Called when any shape is about to be destroyed due to the destruction of its parent body. 
+	End Rem
+	Method SayGoodbyeShape(shape:b2Shape)
+	End Method
+	
+	Function _SayGoodbyeShape(listener:b2DestructionListener, shape:Byte Ptr) { nomangle }
+		listener.SayGoodbyeShape(b2Shape._create(shape))
+	End Function
+
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2destructionlistener_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: Use this type for when a body's shape passes outside of the world boundary.
+about: Override Violation().
+End Rem
+Type b2BoundaryListener
+
+	Field b2ObjectPtr:Byte Ptr
+
+	Method New()
+		b2ObjectPtr = bmx_b2boundarylistener_new(Self)
+	End Method
+	
+	Rem
+	bbdoc: This is called for each body that leaves the world boundary.
+	about: Warning: you can't modify the world inside this callback.
+	End Rem
+	Method Violation(body:b2Body)
+	End Method
+
+	Function _Violation(listener:b2BoundaryListener, body:Byte Ptr) { nomangle }
+		listener.Violation(b2Body._create(body))
+	End Function
+
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2boundarylistener_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: Implement this type to get collision results. 
+about: 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. Additionally you may receive multiple callbacks for the same contact in a single time step.
+You should strive to make your callbacks efficient because there may be many callbacks per time step. 
+End Rem
+Type b2ContactListener
+
+	Field b2ObjectPtr:Byte Ptr
+
+	Method New()
+		b2ObjectPtr = bmx_b2contactlistener_new(Self)
+	End Method
+
+	Rem
+	bbdoc: Called when a contact point is added.
+	about: This includes the geometry and the forces.
+	End Rem
+	Method Add(point:b2ContactPoint)
+	End Method
+	
+	Function _Add(listener:b2ContactListener, point:Byte Ptr) { nomangle }
+		listener.Add(b2ContactPoint._create(point))
+	End Function
+
+	Rem
+	bbdoc: Called when a contact point persists.
+	about: This includes the geometry and the forces.
+	End Rem
+	Method Persist(point:b2ContactPoint)
+	End Method
+	
+	Function _Persist(listener:b2ContactListener, point:Byte Ptr) { nomangle }
+		listener.Persist(b2ContactPoint._create(point))
+	End Function
+
+	Rem
+	bbdoc: Called when a contact point is removed.
+	about: This includes the last computed geometry and forces.
+	End Rem
+	Method Remove(point:b2ContactPoint)
+	End Method
+
+	Function _Remove(listener:b2ContactListener, point:Byte Ptr) { nomangle }
+		listener.Remove(b2ContactPoint._create(point))
+	End Function
+
+	Rem
+	bbdoc: Called after a contact point is solved.
+	End Rem
+	Method Result(result:b2ContactResult)
+	End Method
+	
+	Function _Result(listener:b2ContactListener, result:Byte Ptr) { nomangle }
+		listener.Result(b2ContactResult._create(result))
+	End Function
+
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2contactlistener_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: Implement this type and override ShouldCollide() to provide collision filtering.
+about: In other words, you can implement this type if you want finer control over contact creation.
+End Rem
+Type b2ContactFilter
+
+	Field b2ObjectPtr:Byte Ptr
+
+	Method New()
+		b2ObjectPtr = bmx_b2contactfilter_new(Self)
+	End Method
+
+	Rem
+	bbdoc: Return True if contact calculations should be performed between these two shapes.
+	about: Warning:  for performance reasons this is only called when the AABBs begin to overlap.
+	End Rem
+	Method ShouldCollide:Int(shape1:b2Shape, shape2:b2Shape)
+		Return True
+	End Method
+
+	Function _ShouldCollide:Int(filter:b2ContactFilter, shape1:Byte Ptr, shape2:Byte Ptr) { nomangle }
+		Return filter.ShouldCollide(b2Shape._create(shape1), b2Shape._create(shape2))
+	End Function
+	
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2contactfilter_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+	
+End Type
+
+Rem
+bbdoc: This type manages contact between two shapes.
+about: 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.
+End Rem
+Type b2Contact
+
+	Field b2ObjectPtr:Byte Ptr
+
+	Function _create:b2Contact(b2ObjectPtr:Byte Ptr)
+		If b2ObjectPtr Then
+			Local contact:b2Contact = New b2Contact
+			contact.b2ObjectPtr = b2ObjectPtr
+			Return contact
+		End If
+	End Function
+
+	Rem
+	bbdoc: Get the first shape in this contact.
+	End Rem
+	Method GetShape1:b2Shape()
+		Return b2Shape._create(bmx_b2contact_getshape1(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Get the second shape in this contact.
+	End Rem
+	Method GetShape2:b2Shape()
+		Return b2Shape._create(bmx_b2contact_getshape2(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Get the next contact in the world's contact list.
+	End Rem
+	Method GetNext:b2Contact()
+		Return b2Contact._create(bmx_b2contact_getnext(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Is this contact solid?
+	returns: True if this contact should generate a response.
+	End Rem
+	Method IsSolid:Int()
+		Return bmx_b2contact_issolid(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the number of manifolds.
+	about: 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.
+	End Rem
+	Method GetManifoldCount:Int()
+		Return bmx_b2contact_getmanifoldcount(b2ObjectPtr)
+	End Method
+	
+End Type
+
+Rem
+bbdoc: This type is used to report contact points. 
+End Rem
+Type b2ContactPoint
+
+	Field b2ObjectPtr:Byte Ptr
+
+	Function _create:b2ContactPoint(b2ObjectPtr:Byte Ptr)
+		If b2ObjectPtr Then
+			Local contactPoint:b2ContactPoint = New b2ContactPoint
+			contactPoint.b2ObjectPtr = b2ObjectPtr
+			Return contactPoint
+		End If
+	End Function
+
+	Rem
+	bbdoc: Returns the first shape.
+	End Rem
+	Method GetShape1:b2Shape()
+		Return b2Shape._create(bmx_b2contactpoint_getshape1(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Returns the second shape.
+	End Rem
+	Method GetShape2:b2Shape()
+		Return b2Shape._create(bmx_b2contactpoint_getshape2(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Returns position in world coordinates.
+	End Rem
+	Method GetPosition:b2Vec2()
+		Return bmx_b2contactpoint_getposition(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Returns the velocity of point on body2 relative to point on body1 (pre-solver).
+	End Rem
+	Method GetVelocity:b2Vec2()
+		Return bmx_b2contactpoint_getvelocity(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Points from shape1 to shape2.
+	End Rem
+	Method GetNormal:b2Vec2()
+		Return bmx_b2contactpoint_getnormal(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: The separation is negative when shapes are touching 
+	End Rem
+	Method GetSeparation:Float()
+		Return bmx_b2contactpoint_getseparation(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Returns the combined friction coefficient.
+	End Rem
+	Method GetFriction:Float()
+		Return bmx_b2contactpoint_getfriction(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Returns the combined restitution coefficient.
+	End Rem
+	Method GetRestitution:Float()
+		Return bmx_b2contactpoint_getrestitution(b2ObjectPtr)
+	End Method
+
+End Type
+
+Rem
+bbdoc: This type is used to report contact point results.
+End Rem
+Type b2ContactResult
+
+	Field b2ObjectPtr:Byte Ptr
+
+	Function _create:b2ContactResult(b2ObjectPtr:Byte Ptr)
+		If b2ObjectPtr Then
+			Local result:b2ContactResult = New b2ContactResult
+			result.b2ObjectPtr = b2ObjectPtr
+			Return result
+		End If
+	End Function
+
+	Rem
+	bbdoc: Returns the first shape.
+	End Rem
+	Method GetShape1:b2Shape()
+		Return b2Shape._create(bmx_b2contactresult_getshape1(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Returns the second shape.
+	End Rem
+	Method GetShape2:b2Shape()
+		Return b2Shape._create(bmx_b2contactresult_getshape2(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Returns position in world coordinates.
+	End Rem
+	Method GetPosition:b2Vec2()
+		Return bmx_b2contactresult_getposition(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Points from shape1 to shape2.
+	End Rem
+	Method GetNormal:b2Vec2()
+		Return bmx_b2contactresult_getnormal(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Returns the normal impulse applied to body2.
+	End Rem
+	Method GetNormalImpulse:Float()
+		Return bmx_b2contactresult_getnormalimpulse(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Returns the tangent impulse applied to body2.
+	End Rem
+	Method GetTangentImpulse:Float()
+		Return bmx_b2contactresult_gettangentimpulse(b2ObjectPtr)
+	End Method
+	
+End Type
+
+Rem
+bbdoc: The base joint type.
+about: Joints are used to constraint two bodies together in various fashions.
+Some joints also feature limits and motors. 
+End Rem
+Type b2Joint
+
+	Field b2ObjectPtr:Byte Ptr
+	Field userData:Object
+
+	Function _create:b2Joint(b2ObjectPtr:Byte Ptr)
+		If b2ObjectPtr Then
+			Local joint:b2Joint = b2Joint(bmx_b2joint_getmaxjoint(b2ObjectPtr))
+			If Not joint Then
+				joint = New b2Joint
+				joint.b2ObjectPtr = b2ObjectPtr
+			Else
+				If Not joint.b2ObjectPtr Then
+					joint.b2ObjectPtr = b2ObjectPtr
+				EndIf
+			End If
+			Return joint
+		End If
+	End Function
+	
+	Rem
+	bbdoc: Get the first body attached to this joint.
+	end rem
+	Method GetBody1:b2Body()
+		Return b2Body._create(bmx_b2joint_getbody1(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Get the second body attached to this joint.
+	end rem
+	Method GetBody2:b2Body()
+		Return b2Body._create(bmx_b2joint_getbody2(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Get the next joint the world joint list.
+	end rem
+	Method GetNext:b2Joint()
+		Return b2Joint._create(bmx_b2joint_getnext(b2ObjectPtr))
+	End Method
+
+	Rem
+	bbdoc: Get the user data pointer that was provided in the joint definition.
+	End Rem
+	Method GetUserData:Object()
+		Return userData
+	End Method
+
+
+End Type
+
+Rem
+bbdoc: Bodies are the backbone for shapes.
+about: Bodies carry shapes and move them around in the world. Bodies are always rigid bodies in Box2D. That
+means that two shapes attached to the same rigid body never move relative to each other.
+<p>
+Bodies have position and velocity. You can apply forces, torques, and impulses to bodies. Bodies can be
+static or dynamic. Static bodies never move and don't collide with other static bodies.
+</p>
+End Rem
+Type b2Body
+	Field b2ObjectPtr:Byte Ptr
+	Field userData:Object
+
+	Function _create:b2Body(b2ObjectPtr:Byte Ptr)
+		If b2ObjectPtr Then
+			Local body:b2Body = b2Body(bmx_b2body_getmaxbody(b2ObjectPtr))
+			If Not body Then
+				body = New b2Body
+				body.b2ObjectPtr = b2ObjectPtr
+			End If
+			Return body
+		End If
+	End Function
+	
+	Rem
+	bbdoc: Creates a shape and attach it to this body. 
+	about: Warning: This method is locked during callbacks.
+	<p>Parameters:
+	<ul>
+	<li><b>def </b> : the shape definition.</li>
+	</ul>
+	</p>
+	End Rem
+	Method CreateShape:b2Shape(def:b2ShapeDef)
+		Local shape:b2Shape
+		shape = b2Shape._create(bmx_b2body_createshape(b2ObjectPtr, def.b2ObjectPtr))
+		shape.userData = def.userData ' copy the userData
+		Return shape
+	End Method
+
+	Function _createShape:b2Shape(shapeType:Int) { nomangle }
+		Local shape:b2Shape
+		Select shapeType
+			Case e_unknownShape
+				shape = New b2Shape
+			Case e_circleShape
+				shape = New b2CircleShape
+			Case e_polygonShape
+				shape = New b2PolygonShape
+			Case e_edgeShape
+				shape = New b2EdgeShape
+			Default
+				DebugLog "Warning, shape type '" + shapeType + "' is not defined in module."
+				shape = New b2Shape
+		End Select
+		Return shape
+	End Function
+
+	Rem
+	bbdoc: Destroy a shape. 
+	about: 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.
+	<p>
+	Warning: This method is locked during callbacks.
+	</p>
+	End Rem
+	Method DestroyShape(shape:b2Shape)
+		bmx_b2body_destroyshape(b2ObjectPtr, shape.b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Compute the mass properties from the attached shapes. 
+	about: 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. 
+	End Rem
+	Method SetMassFromShapes()
+		bmx_b2body_setmassfromshapes(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the world body origin position. 
+	End Rem
+	Method GetPosition:b2Vec2()
+		Return bmx_b2body_getposition(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the angle in degrees.
+	returns: The current world rotation angle in degrees.
+	End Rem
+	Method GetAngle:Float()
+		Return bmx_b2body_getangle(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the world position of the center of mass.
+	End Rem
+	Method GetWorldCenter:b2Vec2()
+		Return bmx_b2body_getworldcenter(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc:Get the Local position of the center of mass.
+	End Rem
+	Method GetLocalCenter:b2Vec2()
+		Return bmx_b2body_getlocalcenter(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Set the linear velocity of the center of mass.
+	about: Parameters:
+	<ul>
+	<li><b>v </b> : the New linear velocity of the center of mass.</li>
+	</ul>
+	End Rem
+	Method SetLinearVelocity(v:b2Vec2)
+		bmx_b2body_setlinearvelocity(b2ObjectPtr, v)
+	End Method
+
+	Rem
+	bbdoc: Get the linear velocity of the center of mass.
+	returns: The linear velocity of the center of mass.
+	End Rem
+	Method GetLinearVelocity:b2Vec2()
+		Return bmx_b2body_getlinearvelocity(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Set the angular velocity.
+	about: Parameters:
+	<ul>
+	<li><b>omega </b> : the New angular velocity in degrees/Second.</li>
+	</ul>
+	End Rem
+	Method SetAngularVelocity(omega:Float)
+		bmx_b2body_setangularvelocity(b2ObjectPtr, omega)
+	End Method
+
+	Rem
+	bbdoc: Get the angular velocity.
+	returns: The angular velocity in degrees/Second.
+	End Rem
+	Method GetAngularVelocity:Float()
+		Return bmx_b2body_getangularvelocity(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Apply a force at a world point.
+	about: 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.
+	<p>Parameters:
+	<ul>
+	<li><b>force </b> : the world force vector, usually in Newtons (N).</li>
+	<li><b>point </b> : the world position of the point of application.</li>
+	</ul>
+	</p>
+	End Rem
+	Method ApplyForce(force:b2Vec2, point:b2Vec2)
+		bmx_b2body_applyforce(b2ObjectPtr, force, point)
+	End Method
+
+	Rem
+	bbdoc: Apply a torque.
+	about: This affects the angular velocity without affecting the linear velocity of the center of mass.
+	This wakes up the body.
+	<p>Parameters:
+	<ul>
+	<li><b> torque </b> : about the z-axis (out of the screen), usually in N-m.</li>
+	</ul>
+	</p>
+	End Rem
+	Method ApplyTorque(torque:Float)
+		bmx_b2body_applytorque(b2ObjectPtr, torque)
+	End Method
+
+	Rem
+	bbdoc: Apply an impulse at a point.
+	about: 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.
+	<p>Parameters:
+	<ul>
+	<li><b> impulse </b> : the world impulse vector, usually in N-seconds Or kg-m/s.</li>
+	<li><b> point </b> : the world position of the point of application.</li>
+	</ul>
+	</p>
+	End Rem
+	Method ApplyImpulse(impulse:b2Vec2, point:b2Vec2)
+		bmx_b2body_applyimpulse(b2ObjectPtr, impulse, point)
+	End Method
+
+	Rem
+	bbdoc: Get the total mass of the body.
+	returns: The mass, usually in kilograms (kg).
+	End Rem
+	Method GetMass:Float()
+		Return bmx_b2body_getmass(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the central rotational inertia of the body.
+	returns: The rotational inertia, usually in kg-m^2.
+	End Rem
+	Method GetInertia:Float()
+		Return bmx_b2body_getinertia(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the world coordinates of a point given the local coordinates.
+	returns: The same point expressed in world coordinates.
+	about: Parameters:
+	<ul>
+	<li><b>localPoint </b> : a point on the body measured relative the the body's origin.</li>
+	</ul>
+	End Rem
+	Method GetWorldPoint:b2Vec2(localPoint:b2Vec2)
+		Return bmx_b2body_getworldpoint(b2ObjectPtr, localPoint)
+	End Method
+
+	Rem
+	bbdoc: Get the world coordinates of a vector given the local coordinates.
+	returns: The same vector expressed in world coordinates.
+	about: Parameters:
+	<ul>
+	<li><b>localVector </b> : a vector fixed in the body.</li>
+	</ul>
+	End Rem
+	Method GetWorldVector:b2Vec2(localVector:b2Vec2)
+		Return bmx_b2body_getworldvector(b2ObjectPtr, localVector)
+	End Method
+
+	Rem
+	bbdoc: Gets a local point relative to the body's origin given a world point.
+	returns: The corresponding local point relative to the body's origin.
+	about: Parameters:
+	<ul>
+	<li><b>worldPoint </b> : a point in world coordinates.</li>
+	</ul>
+	End Rem
+	Method GetLocalPoint:b2Vec2(worldPoint:b2Vec2)
+		Return bmx_b2body_getlocalpoint(b2ObjectPtr, worldPoint)
+	End Method
+
+	Rem
+	bbdoc: Gets a local vector given a world vector.
+	returns: The corresponding local vector.
+	about: Parameters:
+	<ul>
+	<li><b>worldVector </b> : a vector in world coordinates.</li>
+	</ul>
+	End Rem
+	Method GetLocalVector:b2Vec2(worldVector:b2Vec2)
+		Return bmx_b2body_getlocalvector(b2ObjectPtr, worldVector)
+	End Method
+
+	Rem
+	bbdoc: Is this body treated like a bullet for continuous collision detection?
+	End Rem
+	Method IsBullet:Int()
+		Return bmx_b2body_isbullet(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Should this body be treated like a bullet for continuous collision detection?
+	End Rem
+	Method SetBullet(flag:Int)
+		bmx_b2body_setbullet(b2ObjectPtr, flag)
+	End Method
+
+	Rem
+	bbdoc: Is this body static (immovable)?
+	End Rem
+	Method IsStatic:Int()
+		Return bmx_b2body_isstatic(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Is this body dynamic (movable)?
+	End Rem
+	Method IsDynamic:Int()
+		Return bmx_b2body_isdynamic(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Is this body frozen?
+	End Rem
+	Method IsFrozen:Int()
+		Return bmx_b2body_isfrozen(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Is this body sleeping (not simulating).
+	End Rem
+	Method IsSleeping:Int()
+		Return bmx_b2body_issleeping(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: You can disable sleeping on this body.
+	End Rem
+	Method AllowSleeping(flag:Int)
+		bmx_b2body_allowsleeping(b2ObjectPtr, flag)
+	End Method
+
+	Rem
+	bbdoc: Wake up this body so it will begin simulating.
+	End Rem
+	Method WakeUp()
+		bmx_b2body_wakeup(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Put this body to sleep so it will stop simulating.
+	about: This also sets the velocity to zero.
+	End Rem
+	Method PutToSleep()
+		bmx_b2body_puttosleep(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the list of all shapes attached to this body.
+	End Rem
+	Method GetShapeList:b2Shape()
+		Return b2Shape._create(bmx_b2body_getshapelist(b2ObjectPtr))
+	End Method
+
+	Rem
+	bbdoc: Get the list of all joints attached to this body.
+	End Rem
+	Method GetJointList:b2JointEdge()
+		Return b2JointEdge._create(bmx_b2body_getjointlist(b2ObjectPtr))
+	End Method
+
+	Rem
+	bbdoc: Get the next body in the world's body list.
+	End Rem
+	Method GetNext:b2Body()
+		Return _create(bmx_b2body_getnext(b2ObjectPtr))
+	End Method
+
+	Rem
+	bbdoc: Get the user data pointer that was provided in the body definition.
+	End Rem
+	Method GetUserData:Object()
+		Return userData
+	End Method
+
+	Rem
+	bbdoc: Get the body transform for the body's origin. 
+	End Rem
+	Method GetXForm:b2XForm()
+		Return bmx_b2body_getxform(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Set the position of the body's origin and rotation (degrees). 
+	about: This breaks any contacts and wakes the other bodies. 
+	End Rem
+	Method SetXForm:Int(position:b2Vec2, angle:Float)
+		Return bmx_b2body_setxform(b2ObjectPtr, position, angle)
+	End Method
+	
+	Rem
+	bbdoc: Get the parent world of this body.
+	End Rem
+	Method GetWorld:b2World()
+		Return b2World._create(bmx_b2body_getworld(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Set the mass properties.
+	about: Note that this changes the center of mass position.
+	<p>
+	If you are not sure how to compute mass properties, use SetMassFromShapes.
+	</p>
+	<p>
+	The inertia tensor is assumed to be relative to the center of mass.
+	</p>
+	End Rem
+	Method SetMass(massData:b2MassData)
+		bmx_b2body_setmass(b2ObjectPtr, massData.b2ObjectPtr)
+	End Method
+	
+End Type
+
+Rem
+bbdoc: A shape is used for collision detection. 
+about: Shapes are created in b2World. You can use shape for collision detection before they are attached to the world.
+<p>
+Warning: You cannot reuse shapes.
+</p>
+End Rem
+Type b2Shape
+
+	Field b2ObjectPtr:Byte Ptr
+	Field userData:Object
+
+	Function _create:b2Shape(b2ObjectPtr:Byte Ptr)
+		If b2ObjectPtr Then
+			Local shape:b2Shape = b2Shape(bmx_b2shape_getmaxshape(b2ObjectPtr))
+			If Not shape Then
+				shape = New b2Shape
+				shape.b2ObjectPtr = b2ObjectPtr
+			Else
+				If Not shape.b2ObjectPtr Then
+					shape.b2ObjectPtr = b2ObjectPtr
+				EndIf
+			End If
+			Return shape
+		End If
+	End Function
+
+	Rem
+	bbdoc: Is this shape a sensor (non-solid)? 
+	End Rem
+	Method IsSensor:Int()
+		Return bmx_b2shape_issensor(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the parent body of this shape. 
+	End Rem
+	Method GetBody:b2Body()
+		Return b2Body._create(bmx_b2shape_getbody(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Get the user data that was assigned in the shape definition.
+	End Rem
+	Method GetUserData:Object()
+		Return userData
+	End Method
+	
+	Rem
+	bbdoc: Sets the user data.
+	End Rem
+	Method SetUserData(data:Object)
+		userData = data
+	End Method
+	
+	Rem
+	bbdoc: Get the next shape in the parent body's shape list. 
+	End Rem
+	Method GetNext:b2Shape()
+		Return _create(bmx_b2shape_getnext(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Test a point for containment in this shape. 
+	about: This only works for convex shapes. 
+	End Rem
+	Method TestPoint:Int(xf:b2XForm, p:b2Vec2)
+		Return bmx_b2shape_testpoint(b2ObjectPtr, xf, p)
+	End Method
+	
+	Rem
+	bbdoc: Get the contact filtering data. 
+	End Rem
+	Method GetFilterData:b2FilterData()
+		Return b2FilterData._create(bmx_b2shape_getfilterdata(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Set the contact filtering data. 
+	about: You must call b2World::Refilter to correct existing contacts/non-contacts. 
+	End Rem
+	Method SetFilterData(data:b2FilterData)
+		bmx_b2shape_setfilterdata(b2ObjectPtr, data.b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: 
+	End Rem
+'	Method TestSegment:Int(xf:b2XForm, lambda:Float Var, normal:b2Vec2 Var, segment:b2Segment, maxLambda:Float)''
+'	End Method
+	
+	Rem
+	bbdoc: Get the maximum radius about the parent body's center of mass. 
+	End Rem
+	Method GetSweepRadius:Float()
+		Return bmx_b2shape_getsweepradius(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the coefficient of friction. 
+	End Rem
+	Method GetFriction:Float()
+		Return bmx_b2shape_getfriction(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Set the coefficient of friction.
+	End Rem
+	Method SetFriction(friction:Float)
+		bmx_b2shape_setfriction(b2ObjectPtr, friction)
+	End Method
+	
+	Rem
+	bbdoc: Get the coefficient of restitution. 
+	End Rem
+	Method GetRestitution:Float()
+		Return bmx_b2shape_getrestitution(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Set the coefficient of restitution.
+	End Rem
+	Method SetRestitution(restitution:Float)
+		bmx_b2shape_setrestitution(b2ObjectPtr, restitution)
+	End Method
+	
+	Rem
+	bbdoc: Given a transform, compute the associated axis aligned bounding box for this shape.
+	End Rem
+	Method ComputeAABB(aabb:b2AABB, xf:b2XForm)
+		bmx_b2shape_computeaabb(b2ObjectPtr, aabb, xf)
+	End Method
+
+	Rem
+	bbdoc: Given two transforms, compute the associated swept axis aligned bounding box for this shape. 
+	End Rem
+	Method ComputeSweptAABB(aabb:b2AABB, xf1:b2XForm, xf2:b2XForm)
+		bmx_b2shape_computesweptaabb(b2ObjectPtr, aabb, xf1, xf2)
+	End Method
+	
+	Rem
+	bbdoc: Compute the mass properties of this shape using its dimensions and density. 
+	returns: the mass data for this shape.
+	about: The inertia tensor is computed about the local origin, not the centroid. 
+	End Rem
+	Method ComputeMass(data:b2MassData)
+		bmx_b2shape_computemass(b2ObjectPtr, data.b2ObjectPtr)
+	End Method
+	
+End Type
+
+Rem
+bbdoc: Implement and register this type with a b2World to provide debug drawing of physics entities in your game. 
+End Rem
+Type b2DebugDraw
+
+	Field b2ObjectPtr:Byte Ptr
+
+	Const e_shapeBit:Int = $0001        ' draw shapes
+	Const e_jointBit:Int = $0002        ' draw joint connections
+	Const e_coreShapeBit:Int = $0004    ' draw core (TOI) shapes
+	Const e_aabbBit:Int = $0008         ' draw axis aligned bounding boxes
+	Const e_obbBit:Int = $0010          ' draw oriented bounding boxes
+	Const e_pairBit:Int = $0020         ' draw broad-phase pairs
+	Const e_centerOfMassBit:Int = $0040 ' draw center of mass frame
+	Const e_controllerBit:Int = $0080
+	
+	Method New()
+		b2ObjectPtr = bmx_b2debugdraw_create(Self)
+	End Method
+	
+	Rem
+	bbdoc: Set the drawing flags.
+	End Rem
+	Method SetFlags(flags:Int)
+		bmx_b2debugdraw_setflags(b2ObjectPtr, flags)
+	End Method
+	
+	Rem
+	bbdoc: Get the drawing flags.
+	End Rem
+	Method GetFlags:Int()
+		Return bmx_b2debugdraw_getflags(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Append flags to the current flags.
+	End Rem
+	Method AppendFlags(flags:Int)
+		bmx_b2debugdraw_appendflags(b2ObjectPtr, flags)
+	End Method
+	
+	Rem
+	bbdoc: Clear flags from the current flags.
+	End Rem
+	Method ClearFlags(flags:Int)
+		bmx_b2debugdraw_clearflags(b2ObjectPtr, flags)
+	End Method
+
+	Rem
+	bbdoc: Draw a closed polygon provided in CCW order. 
+	End Rem
+	Method DrawPolygon(vertices:b2Vec2[], color:b2Color) Abstract
+
+
+	Function _DrawPolygon(obj:b2DebugDraw , vertices:b2Vec2[], r:Int, g:Int, b:Int) { nomangle }
+		obj.DrawPolygon(vertices, b2Color.Set(r, g, b))
+	End Function
+	
+	Rem
+	bbdoc: Draw a solid closed polygon provided in CCW order
+	End Rem
+	Method DrawSolidPolygon(vertices:b2Vec2[], color:b2Color) Abstract
+
+	Function _DrawSolidPolygon(obj:b2DebugDraw , vertices:b2Vec2[], r:Int, g:Int, b:Int) { nomangle }
+		obj.DrawSolidPolygon(vertices, b2Color.Set(r, g, b))
+	End Function
+
+	Rem
+	bbdoc: Draw a circle.
+	End Rem
+	Method DrawCircle(center:b2Vec2, radius:Float, color:b2Color) Abstract
+	
+	Rem
+	bbdoc: Draw a solid circle.
+	End Rem
+	Method DrawSolidCircle(center:b2Vec2, radius:Float, axis:b2Vec2, color:b2Color) Abstract
+	
+	Function _DrawSolidCircle(obj:b2DebugDraw, center:b2Vec2, radius:Float, axis:b2Vec2, r:Int, g:Int, b:Int) { nomangle }
+		obj.DrawSolidCircle(center, radius, axis, b2Color.Set(r, g, b))
+	End Function
+	
+	Rem
+	bbdoc: Draw a line segment.
+	End Rem
+	Method DrawSegment(p1:b2Vec2, p2:b2Vec2, color:b2Color) Abstract
+
+	Function _DrawSegment(obj:b2DebugDraw, p1:b2Vec2, p2:b2Vec2, r:Int, g:Int, b:Int) { nomangle }
+		obj.DrawSegment(p1, p2, b2Color.Set(r, g, b))
+	End Function
+	
+	Rem
+	bbdoc: Draw a transform. Choose your own length scale.
+	/// @param xf a transform.
+	End Rem
+	Method DrawXForm(xf:b2XForm) Abstract
+
+
+End Type
+
+Rem
+bbdoc: Color for debug drawing.
+about: Each value has the range [0,1]. 
+End Rem
+Type b2Color
+	
+	Field red:Int, green:Int, blue:Int
+
+	Function Set:b2Color(r:Int, g:Int, b:Int)
+		Local this:b2Color = New b2Color
+		this.red = r
+		this.green = g
+		this.blue = b
+		Return this
+	End Function
+
+End Type
+
+Rem
+bbdoc: A body definition holds all the data needed to construct a rigid body. 
+about: You can safely re-use body definitions. 
+End Rem
+Type b2BodyDef
+
+	Field b2ObjectPtr:Byte Ptr
+	Field userData:Object
+
+	Method New()
+		b2ObjectPtr = bmx_b2bodydef_create()
+	End Method
+	
+	Rem
+	bbdoc: You can use this to initialize the mass properties of the body.
+	about: If you prefer, you can set the mass properties after the shapes have been added using b2Body.SetMassFromShapes.
+	End Rem
+	Method SetMassData(data:b2MassData)
+		bmx_b2bodydef_setmassdata(b2ObjectPtr, data.b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Returns mass property data.
+	End Rem
+	Method GetMassData:b2MassData()
+		Return b2MassData._create(bmx_b2bodydef_getmassdata(b2ObjectPtr))
+	End Method
+
+	Rem
+	bbdoc: Use this to store application specific body data.
+	End Rem
+	Method SetUserData(data:Object)
+		userData = data
+	End Method
+	
+	Rem
+	bbdoc: Returns the application specific body data, if any.
+	End Rem
+	Method GetUserData:Object()
+		Return userData
+	End Method
+	
+	Rem
+	bbdoc: The world position of the body.
+	about: Avoid creating bodies at the origin since this can lead to many overlapping shapes.
+	End Rem
+	Method SetPosition(position:b2Vec2)
+		bmx_b2bodydef_setposition(b2ObjectPtr, position)
+	End Method
+
+	Rem
+	bbdoc: The world position of the body.
+	about: Avoid creating bodies at the origin since this can lead to many overlapping shapes.
+	End Rem
+	Method SetPositionXY(x:Float, y:Float)
+		bmx_b2bodydef_setpositionxy(b2ObjectPtr, x, y)
+	End Method
+	
+	Rem
+	bbdoc: Returns the world position of the body. 
+	End Rem
+	Method GetPosition:b2Vec2()
+		Return bmx_b2bodydef_getposition(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The world angle of the body in degrees.
+	End Rem
+	Method SetAngle(angle:Float)
+		bmx_b2bodydef_setangle(b2ObjectPtr, angle)
+	End Method
+	
+	Rem
+	bbdoc: Returns the world angle of the body in degrees
+	End Rem
+	Method GetAngle:Float()
+		Return bmx_b2bodydef_getangle(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Linear damping is used to reduce the linear velocity.
+	about: The damping parameter can be larger than 1.0 but the damping effect becomes sensitive To the
+	time Step when the damping parameter is large.
+	End Rem
+	Method SetLinearDamping(damping:Float)
+		bmx_b2bodydef_setlineardamping(b2ObjectPtr, damping)
+	End Method
+	
+	Rem
+	bbdoc: Returns the linear damping.
+	End Rem
+	Method GetLinearDamping:Float()
+		Return bmx_b2bodydef_getlineardamping(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Angular damping is used to reduce the angular velocity.
+	about: The damping parameter can be larger than 1.0 but the damping effect becomes sensitive to the
+	time Step when the damping parameter is large.
+	End Rem
+	Method SetAngularDamping(damping:Float)
+		bmx_b2bodydef_setangulardamping(b2ObjectPtr, damping)
+	End Method
+	
+	Rem
+	bbdoc: Returns the angular damping.
+	End Rem
+	Method GetAngularDamping:Float()
+		Return bmx_b2bodydef_getangulardamping(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Set this flag to False if this body should never fall asleep.
+	about: Note that this increases CPU usage.
+	End Rem
+	Method SetAllowSleep(allow:Int)
+		bmx_b2bodydef_setallowsleep(b2ObjectPtr, allow)
+	End Method
+	
+	Rem
+	bbdoc: Returns true if the body is allowed to sleep.
+	End Rem
+	Method GetAllowSleep:Int()
+		Return bmx_b2bodydef_getallowsleep(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Is this body initially sleeping?
+	End Rem
+	Method isSleeping:Int()
+		Return bmx_b2bodydef_issleeping(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Enables/Disables the sleeping state of the body.
+	End Rem
+	Method SetIsSleeping(sleeping:Int)
+		bmx_b2bodydef_setissleeping(b2ObjectPtr, sleeping)
+	End Method
+
+	Rem
+	bbdoc: Should this body be prevented from rotating? Useful For characters.
+	End Rem
+	Method SetFixedRotation(fixed:Int)
+		bmx_b2bodydef_setfixedrotation(b2ObjectPtr, fixed)
+	End Method
+	
+	Rem
+	bbdoc: Returns True if rotation is fixed.
+	End Rem
+	Method GetFixedRotation:Int()
+		Return bmx_b2bodydef_getfixedrotation(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Is this a fast moving body that should be prevented from tunneling through other moving bodies?
+	about: Note that all bodies are prevented from tunneling through static bodies.
+	<p>
+	Warning: You should use this flag sparingly since it increases processing time.
+	</p>
+	End Rem
+	Method SetIsBullet(bullet:Int)
+		bmx_b2bodydef_setisbullet(b2ObjectPtr, bullet)
+	End Method
+	
+	Rem
+	bbdoc: Returns whether this is a bullet type body.
+	End Rem
+	Method GetIsBullet:Int()
+		Return bmx_b2bodydef_isbullet(b2ObjectPtr)
+	End Method
+	
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2bodydef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+	
+End Type
+
+Rem
+bbdoc: Joint definitions are used to construct joints. 
+End Rem
+Type b2JointDef
+
+	Field b2ObjectPtr:Byte Ptr
+	Field userData:Object
+
+	Rem
+	bbdoc: The First attached body.
+	End Rem
+	Method SetBody1(body:b2Body)
+		bmx_b2jointdef_setbody1(b2ObjectPtr, body.b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Returns the first attached body.
+	End Rem
+	Method GetBody1:b2Body()
+		Return b2Body._create(bmx_b2jointdef_getbody1(b2ObjectPtr))
+	End Method
+
+	Rem
+	bbdoc: The Second attached body.
+	End Rem
+	Method SetBody2(body:b2Body)
+		bmx_b2jointdef_setbody2(b2ObjectPtr, body.b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Returns the second attached body.
+	End Rem
+	Method GetBody2:b2Body()
+		Return b2Body._create(bmx_b2jointdef_getbody2(b2ObjectPtr))
+	End Method
+
+	Rem
+	bbdoc: Set this flag to True if the attached bodies should collide.
+	End Rem
+	Method SetCollideConnected(collideConnected:Int)
+		bmx_b2jointdef_setcollideconnected(b2ObjectPtr, collideConnected)
+	End Method
+
+	Rem
+	bbdoc: Returns True if the attached bodies should collide.
+	End Rem
+	Method GetCollideConnected:Int()
+		Return bmx_b2jointdef_getcollideconnected(b2ObjectPtr)
+	End Method
+
+End Type
+
+Rem
+bbdoc: A joint edge is used to connect bodies and joints together in a joint graph where each body is a node and each joint is an edge.
+about: A joint edge belongs to a doubly linked list maintained in each attached body. Each joint has two
+joint nodes, one for each attached body.
+End Rem
+Type b2JointEdge
+
+	Field b2ObjectPtr:Byte Ptr
+
+	Function _create:b2JointEdge(b2ObjectPtr:Byte Ptr)
+		If b2ObjectPtr Then
+			Local this:b2JointEdge = New b2JointEdge
+			this.b2ObjectPtr = b2ObjectPtr
+			Return this
+		End If
+	End Function
+
+	Rem
+	bbdoc: Provides quick access to the other body attached. 
+	End Rem
+	Method GetOther:b2Body()
+		Return b2Body._create(bmx_b2jointedge_getother(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Returns the joint.
+	End Rem
+	Method GetJoint:b2Joint()
+		Return b2Joint._create(bmx_b2jointedge_getjoint(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Returns the previous joint edge in the body's joint list.
+	End Rem
+	Method GetPrev:b2JointEdge()
+		Return b2JointEdge._create(bmx_b2jointedge_getprev(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Returns the next joint edge in the body's joint list.
+	End Rem
+	Method GetNext:b2JointEdge()
+		Return b2JointEdge._create(bmx_b2jointedge_getnext(b2ObjectPtr))
+	End Method
+	
+End Type
+
+Rem
+bbdoc: Holds the mass data computed for a shape.
+End Rem
+Type b2MassData
+
+	Field b2ObjectPtr:Byte Ptr
+	Field owner:Int
+
+	Function _create:b2MassData(b2ObjectPtr:Byte Ptr)
+		If b2ObjectPtr Then
+			Local this:b2MassData = New b2MassData
+			bmx_b2massdata_delete(this.b2ObjectPtr)
+			this.b2ObjectPtr = b2ObjectPtr
+			this.owner = False
+			Return this
+		End If
+	End Function
+
+	Method New()
+		b2ObjectPtr = bmx_b2massdata_new()
+		owner = True
+	End Method
+	
+	Method Delete()
+		If b2ObjectPtr Then
+			If owner Then
+			bmx_b2massdata_delete(b2ObjectPtr)
+			End If
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+	Rem
+	bbdoc: Sets the mass of the shape, usually in kilograms.
+	End Rem	
+	Method SetMass(mass:Float)	
+		bmx_b2massdata_setmass(b2ObjectPtr, mass)
+	End Method
+	
+	Rem
+	bbdoc: Sets the position of the shape's centroid relative to the shape's origin.
+	End Rem
+	Method SetCenter(center:b2Vec2)
+		bmx_b2massdata_setcenter(b2ObjectPtr, center)
+	End Method
+	
+	Rem
+	bbdoc: Sets the rotational inertia of the shape.
+	End Rem
+	Method SetRotationalInertia(i:Float)
+		bmx_b2massdata_seti(b2ObjectPtr, i)
+	End Method
+	
+End Type
+
+Rem
+bbdoc: A shape definition is used to construct a shape.
+about: You can reuse shape definitions safely. 
+End Rem
+Type b2ShapeDef
+
+	Field b2ObjectPtr:Byte Ptr
+	Field userData:Object
+
+	Rem
+	bbdoc: Sets the shape's friction coefficient, usually in the range [0,1].
+	End Rem
+	Method SetFriction(friction:Float)
+		bmx_b2shapedef_setfriction(b2ObjectPtr, friction)
+	End Method
+	
+	Rem
+	bbdoc: Gets the shape's friction coefficient, usually in the range [0,1].
+	End Rem
+	Method GetFriction:Float()
+		Return bmx_b2shapedef_getfriction(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the shape's restitution (elasticity) usually in the range [0,1]. 
+	End Rem
+	Method SetRestitution(restitution:Float)
+		bmx_b2shapedef_setrestitution(b2ObjectPtr, restitution)
+	End Method
+	
+	Rem
+	bbdoc: Gets the shape's restitution (elasticity) usually in the range [0,1]. 
+	End Rem
+	Method GetRestitution:Float()
+		Return bmx_b2shapedef_getrestitution(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the shape's density, usually in kg/m^2. 
+	End Rem
+	Method SetDensity(density:Float)
+		bmx_b2shapedef_setdensity(b2ObjectPtr, density)
+	End Method
+	
+	Rem
+	bbdoc: Gets the shape's density, usually in kg/m^2. 
+	End Rem
+	Method GetDensity:Float()
+		Return bmx_b2shapedef_getdensity(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the contact filtering data.
+	End Rem
+	Method SetFilter(filter:b2FilterData)
+		bmx_b2shapedef_setfilter(b2ObjectPtr, filter.b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Returns the contact filtering data.
+	End Rem
+	Method GetFilter:b2FilterData()
+		Return b2FilterData._create(bmx_b2shapedef_getfilter(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: A sensor shape collects contact information but never generates a collision response.
+	End Rem
+	Method SetIsSensor(sensor:Int)
+		bmx_b2shapedef_setissensor(b2ObjectPtr, sensor)
+	End Method
+	
+	Rem
+	bbdoc: Returns True if this shape is a sensor.
+	about: A sensor shape collects contact information but never generates a collision response.
+	End Rem
+	Method IsSensor:Int()
+		Return bmx_b2shapedef_issensor(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the user data.
+	End Rem
+	Method SetUserData(data:Object)
+		userData = data
+	End Method
+	
+End Type
+
+Rem
+bbdoc: This holds contact filtering data.
+End Rem
+Type b2FilterData
+
+	Field owner:Int
+	Field b2ObjectPtr:Byte Ptr
+
+	Function _create:b2FilterData(b2ObjectPtr:Byte Ptr)
+		If b2ObjectPtr Then
+			Local this:b2FilterData = New b2FilterData
+			this.Free()
+			this.owner = False
+			this.b2ObjectPtr = b2ObjectPtr
+			Return this
+		End If
+	End Function
+
+	Method New()
+		owner = True
+		b2ObjectPtr = bmx_b2filterdata_create()	
+	End Method
+	
+	Rem
+	bbdoc: Returns the collision category bits.
+	End Rem
+	Method GetCategoryBits:Short()
+		Return bmx_b2filterdata_getcategorybits(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the collision category bits.
+	about: Normally you would just set one bit.
+	End Rem
+	Method SetCategoryBits(categoryBits:Short)
+		bmx_b2filterdata_setcategorybits(b2ObjectPtr, categoryBits)
+	End Method
+	
+	Rem
+	bbdoc: Returns the collision mask bits.
+	about: This states the categories that this shape would accept for collision. 
+	End Rem
+	Method GetMaskBits:Short()
+		Return bmx_b2filterdata_getmaskbits(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the collision mask bits.
+	about: This states the categories that this shape would accept for collision. 
+	End Rem
+	Method SetMaskBits(maskBits:Short)
+		bmx_b2filterdata_setmaskbits(b2ObjectPtr, maskBits)
+	End Method
+	
+	Rem
+	bbdoc: Returns the collision group index.
+	about: Collision groups allow a certain group of objects to never collide (negative) or always collide (positive). 
+	<p>
+	Zero means no collision group. Non-zero group filtering always wins against the mask bits. 
+	</p>
+	End Rem
+	Method GetGroupIndex:Short()
+		Return bmx_b2filterdata_getgroupindex(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the collision group index.
+	about: Collision groups allow a certain group of objects to never collide (negative) or always collide (positive). 
+	<p>
+	Zero means no collision group. Non-zero group filtering always wins against the mask bits. 
+	</p>
+	End Rem
+	Method SetGroupIndex(index:Int)
+		bmx_b2filterdata_setgroupindex(b2ObjectPtr, index)
+	End Method
+
+	Method Free()
+		If b2ObjectPtr And owner Then
+			bmx_b2filterdata_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+	
+	Method Delete()
+		Free()
+	End Method
+	
+End Type
+
+Rem
+bbdoc: Convex polygon.
+about: Vertices must be in CCW order.
+End Rem
+Type b2PolygonDef Extends b2ShapeDef
+
+	Field _vertices:b2Vec2[]
+
+	Method New()
+		b2ObjectPtr = bmx_b2polygondef_create()
+	End Method
+	
+	Rem
+	bbdoc: Build vertices to represent an axis-aligned box. 
+	about: Parameters:
+	<ul>
+	<li><b>hx </b> : the half-width.</li>
+	<li><b>hy </b> : the half-height. </li>
+	</ul>
+	End Rem
+	Method SetAsBox(hx:Float, hy:Float)
+		bmx_b2polygondef_setasbox(b2ObjectPtr, hx, hy)
+	End Method
+
+	Rem
+	bbdoc: Build vertices to represent an oriented box. 
+	about: Parameters:
+	<ul>
+	<li><b>hx </b> : the half-width.</li>
+	<li><b>hy </b> : the half-height. </li>
+	<li><b>center </b> : the center of the box in local coordinates. </li>
+	<li><b>angle </b> : the rotation of the box in local coordinates. </li>
+	</ul>
+	End Rem
+	Method SetAsOrientedBox(hx:Float, hy:Float, center:b2Vec2, angle:Float)
+		bmx_b2polygondef_setasorientedbox(b2ObjectPtr, hx, hy, center, angle)
+	End Method
+	
+	Rem
+	bbdoc: Sets the polygon vertices in local coordinates.
+	End Rem
+	Method SetVertices(vertices:b2Vec2[])
+		_vertices = vertices
+		bmx_b2polygondef_setvertices(b2ObjectPtr, vertices)
+	End Method
+	
+	Rem
+	bbdoc: Gets the polygon vertices in local coordinates.
+	End Rem
+	Method GetVertices:b2Vec2[]()
+		Return _vertices
+	End Method
+
+	Method Delete()
+		If b2ObjectPtr Then
+			_vertices = Null
+			bmx_b2polygondef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+	
+End Type
+
+Rem
+bbdoc: A convex polygon.
+End Rem
+Type b2PolygonShape Extends b2Shape
+
+	Rem
+	bbdoc: Get the oriented bounding box relative to the parent body.
+	End Rem
+	Method GetOBB:b2OBB()
+		Return b2OBB._create(bmx_b2polygonshape_getobb(b2ObjectPtr))
+	End Method
+
+	Rem
+	bbdoc: Get local centroid relative to the parent body.
+	End Rem
+	Method GetCentroid:b2Vec2()
+		Return bmx_b2polygonshape_getcentroid(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the vertex count. 
+	End Rem
+	Method GetVertexCount:Int()
+		Return bmx_b2polygonshape_getvertexcount(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the vertices in local coordinates.
+	End Rem
+	Method GetVertices:b2Vec2[]()
+		Return bmx_b2polygonshape_getvertices(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the core vertices in local coordinates.
+	End Rem
+	Method GetCoreVertices:b2Vec2[]()
+		Return bmx_b2polygonshape_getcorevertices(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the edge normal vectors.
+	about: There is one for each vertex.
+	End Rem
+	Method GetNormals:b2Vec2[]()
+		Return bmx_b2polygonshape_getnormals(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the first vertex and apply the supplied transform.
+	End Rem
+	Method GetFirstVertex:b2Vec2(xf:b2XForm)
+		Return bmx_b2polygonshape_getfirstvertex(b2ObjectPtr, xf)
+	End Method
+
+	Rem
+	bbdoc: Get the centroid and apply the supplied transform.
+	End Rem
+	Method Centroid:b2Vec2(xf:b2XForm)
+		Return bmx_b2polygonshape_centroid(b2ObjectPtr, xf)
+	End Method
+
+	Rem
+	bbdoc: Get the support point in the given world direction.
+	End Rem
+	Method Support:b2Vec2(xf:b2XForm, d:b2Vec2)
+		Return bmx_b2polygonshape_support(b2ObjectPtr, xf, d)
+	End Method
+
+End Type
+
+Extern
+	Function bmx_b2polygondef_setvertices(handle:Byte Ptr, vertices:b2Vec2[])
+	Function bmx_b2world_query:Int(handle:Byte Ptr, aabb:b2AABB Var, shapes:b2Shape[])
+	Function bmx_b2world_raycast:Int(handle:Byte Ptr, segment:b2Segment Var, shapes:b2Shape[], solidShapes:Int)
+	Function bmx_b2polygonshape_getvertices:b2Vec2[](handle:Byte Ptr)
+	Function bmx_b2polygonshape_getcorevertices:b2Vec2[](handle:Byte Ptr)
+	Function bmx_b2polygonshape_getnormals:b2Vec2[](handle:Byte Ptr)
+	Function bmx_b2edgechaindef_setvertices(handle:Byte Ptr, vertices:b2Vec2[])
+End Extern
+
+Rem
+bbdoc: Used to build circle shapes.
+End Rem
+Type b2CircleDef Extends b2ShapeDef
+
+	Method New()
+		b2ObjectPtr = bmx_b2circledef_create()
+	End Method
+	
+	Rem
+	bbdoc: Sets the circle radius.
+	End Rem
+	Method SetRadius(radius:Float)
+		bmx_b2circledef_setradius(b2ObjectPtr, radius)
+	End Method
+	
+	Rem
+	bbdoc: Returns the circle radius.
+	End Rem
+	Method GetRadius:Float()
+		Return bmx_b2circledef_getradius(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the local position.
+	End Rem
+	Method SetLocalPosition(pos:b2Vec2)
+		bmx_b2circledef_setlocalposition(b2ObjectPtr, pos)
+	End Method
+	
+	Rem
+	bbdoc: Returns the local position.
+	End Rem
+	Method GetLocalPosition:b2Vec2()
+		Return bmx_b2circledef_getlocalposition(b2ObjectPtr)
+	End Method
+
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2circledef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: A circle shape.
+End Rem
+Type b2CircleShape Extends b2Shape
+
+	Rem
+	bbdoc: Get the local position of this circle in its parent body.
+	End Rem
+	Method GetLocalPosition:b2Vec2()
+		Return bmx_b2circleshape_getlocalposition(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the radius of this circle. 
+	End Rem
+	Method GetRadius:Float()
+		Return bmx_b2circleshape_getradius(b2ObjectPtr)
+	End Method
+
+End Type
+
+Rem
+bbdoc: 
+End Rem
+Type b2EdgeChainDef Extends b2ShapeDef
+
+	Field shapeDefPtr:Byte Ptr
+
+	Field vertices:b2Vec2[]
+
+	Method New()
+		shapeDefPtr = bmx_b2edgechaindef_create()
+		b2ObjectPtr = bmx_b2edgechaindef_getdef(shapeDefPtr)
+	End Method
+	
+	Rem
+	bbdoc: 
+	End Rem
+	Method SetVertices(vertices:b2Vec2[])
+		Self.vertices = vertices
+		bmx_b2edgechaindef_setvertices(shapeDefPtr, vertices)
+	End Method
+	
+	Rem
+	bbdoc: 
+	End Rem
+	Method GetVertices:b2Vec2[]()
+		Return vertices
+	End Method
+	
+	Rem
+	bbdoc: 
+	End Rem
+	Method isALoop:Int()
+		Return bmx_b2edgechaindef_isaloop(shapeDefPtr)
+	End Method
+	
+	Rem
+	bbdoc: 
+	End Rem
+	Method SetIsALoop(value:Int)
+		bmx_b2edgechaindef_setisaloop(shapeDefPtr, value)
+	End Method
+
+	Method Delete()
+		If b2ObjectPtr Then
+			vertices = Null
+			bmx_b2edgechaindef_delete(shapeDefPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: 
+End Rem
+Type b2EdgeShape Extends b2Shape
+
+	Function _create:b2EdgeShape(b2ObjectPtr:Byte Ptr)
+		If b2ObjectPtr Then
+			Local this:b2EdgeShape = New b2EdgeShape
+			this.b2ObjectPtr = b2ObjectPtr
+			Return this
+		End If
+	End Function
+
+	Method GetLength:Float()
+		Return bmx_b2edgeshape_getlength(b2ObjectPtr)
+	End Method
+
+	' Local position of vertex in parent body
+	Method GetVertex1:b2Vec2()
+		Return bmx_b2edgeshape_getvertex1(b2ObjectPtr)
+	End Method
+
+
+	' Local position of vertex in parent body
+	Method GetVertex2:b2Vec2()
+		Return bmx_b2edgeshape_getvertex2(b2ObjectPtr)
+	End Method
+
+
+	' "Core" vertex with TOI slop For b2Distance functions:
+	Method GetCoreVertex1:b2Vec2()
+		Return bmx_b2edgeshape_getcorevertex1(b2ObjectPtr)
+	End Method
+
+
+	' "Core" vertex with TOI slop For b2Distance functions:
+	Method GetCoreVertex2:b2Vec2()
+		Return bmx_b2edgeshape_getcorevertex2(b2ObjectPtr)
+	End Method
+
+	
+	' Perpendicular unit vector point, pointing from the solid side To the empty side: 
+	Method GetNormalVector:b2Vec2()
+		Return bmx_b2edgeshape_getnormalvector(b2ObjectPtr)
+	End Method
+
+	
+	' Parallel unit vector, pointing from vertex1 To vertex2:
+	Method GetDirectionVector:b2Vec2()
+		Return bmx_b2edgeshape_getdirectionvector(b2ObjectPtr)
+	End Method
+
+	
+	Method GetCorner1Vector:b2Vec2()
+		Return bmx_b2edgeshape_getcorner1vector(b2ObjectPtr)
+	End Method
+
+	
+	Method GetCorner2Vector:b2Vec2()
+		Return bmx_b2edgeshape_getcorner2vector(b2ObjectPtr)
+	End Method
+
+	
+	Method Corner1IsConvex:Int()
+		Return bmx_b2edgeshape_corner1isconvex(b2ObjectPtr)
+	End Method
+
+	
+	Method Corner2IsConvex:Int()
+		Return bmx_b2edgeshape_corner2isconvex(b2ObjectPtr)
+	End Method
+
+
+	Method GetFirstVertex:b2Vec2(xf:b2XForm)
+		Return bmx_b2edgeshape_getfirstvertex(b2ObjectPtr, xf)
+	End Method
+
+
+	Method Support:b2Vec2(xf:b2XForm, d:b2Vec2)
+		Return bmx_b2edgeshape_support(b2ObjectPtr, xf, d)
+	End Method
+
+	
+	' Get the Next edge in the chain.
+	Method GetNextEdge:b2EdgeShape()
+		Return b2EdgeShape._create(bmx_b2edgeshape_getnextedge(b2ObjectPtr))
+	End Method
+
+	
+	' Get the previous edge in the chain.
+	Method GetPrevEdge:b2EdgeShape()
+		Return b2EdgeShape._create(bmx_b2edgeshape_getprevedge(b2ObjectPtr))
+	End Method
+
+	
+End Type
+
+Rem
+bbdoc: Revolute joint definition. 
+about: This requires defining an anchor point where the bodies are joined. The definition uses local anchor points
+so that the initial configuration can violate the constraint slightly. You also need to specify the initial
+relative angle for joint limits. This helps when saving and loading a game. The local anchor points are measured
+from the body's origin rather than the center of mass because: 1. you might not know where the center of mass
+will be. 2. if you add/remove shapes from a body and recompute the mass, the joints will be broken. 
+End Rem
+Type b2RevoluteJointDef Extends b2JointDef
+
+	Method New()
+		b2ObjectPtr = bmx_b2revolutejointdef_create()
+	End Method
+	
+	Rem
+	bbdoc: Initialize the bodies, anchors, and reference angle using the world anchor.
+	End Rem
+	Method Initialize(body1:b2Body, body2:b2Body, anchor:b2Vec2)
+		bmx_b2revolutejointdef_initialize(b2ObjectPtr, body1.b2ObjectPtr, body2.b2ObjectPtr, anchor)
+	End Method
+	
+	Rem
+	bbdoc: The local anchor point relative to body1's origin.
+	end rem
+	Method GetLocalAnchor1:b2Vec2()
+		Return bmx_b2revolutejointdef_getlocalanchor1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the local anchor point relative to body1's origin.
+	End Rem
+	Method SetLocalAnchor1(anchor:b2Vec2)
+		bmx_b2revolutejointdef_setlocalanchor1(b2ObjectPtr, anchor)
+	End Method
+	
+	Rem
+	bbdoc: The local anchor point relative to body2's origin.
+	end rem
+	Method GetLocalAnchor2:b2Vec2()
+		Return bmx_b2revolutejointdef_getlocalanchor2(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the local anchor point relative to body2's origin.
+	End Rem
+	Method SetLocalAnchor2(anchor:b2Vec2)
+		bmx_b2revolutejointdef_setlocalanchor2(b2ObjectPtr, anchor)
+	End Method
+	
+	Rem
+	bbdoc: The body2 angle minus body1 angle in the reference state (degrees).
+	End Rem
+	Method GetReferenceAngle:Float()
+		Return bmx_b2revolutejointdef_getreferenceangle(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the body2 angle minus body1 angle in the reference state (degrees).
+	End Rem
+	Method SetReferenceAngle(angle:Float)
+		bmx_b2revolutejointdef_setreferenceangle(b2ObjectPtr, angle)
+	End Method
+	
+	Rem
+	bbdoc: A flag to enable joint limits.
+	end rem
+	Method IsLimitEnabled:Int()
+		Return bmx_b2revolutejointdef_islimitenabled(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Enables joint limits.
+	End Rem
+	Method EnableLimit(limit:Int)
+		bmx_b2revolutejointdef_enablelimit(b2ObjectPtr, limit)
+	End Method
+	
+	Rem
+	bbdoc: The lower angle for the joint limit (degrees).
+	End Rem
+	Method GetLowerAngle:Float()
+		Return bmx_b2revolutejointdef_getlowerangle(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the lower angle for the joint limit (degrees).
+	End Rem
+	Method SetLowerAngle(angle:Float)
+		bmx_b2revolutejointdef_setlowerangle(b2ObjectPtr, angle)
+	End Method
+	
+	Rem
+	bbdoc: The upper angle for the joint limit (degrees).
+	End Rem
+	Method GetUpperAngle:Float()
+		Return bmx_b2revolutejointdef_getupperangle(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the upper angle for the joint limit (degrees).
+	End Rem
+	Method SetUpperAngle(angle:Float)
+		bmx_b2revolutejointdef_setupperangle(b2ObjectPtr, angle)
+	End Method
+	
+	Rem
+	bbdoc: A flag to enable the joint motor.
+	end rem
+	Method IsMotorEnabled:Int()
+		Return bmx_b2revolutejointdef_ismotorenabled(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Enables the joint motor.
+	End Rem
+	Method EnableMotor(value:Int)
+		bmx_b2revolutejointdef_enablemotor(b2ObjectPtr, value)
+	End Method
+	
+	Rem
+	bbdoc: The desired motor speed, usually in degrees per second.
+	End Rem
+	Method GetMotorSpeed:Float()
+		Return bmx_b2revolutejointdef_getmotorspeed(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the desired motor speed, usually in degrees per second.
+	End Rem
+	Method SetMotorSpeed(speed:Float)
+		bmx_b2revolutejointdef_setmotorspeed(b2ObjectPtr, speed)
+	End Method
+	
+	Rem
+	bbdoc: The maximum motor torque used to achieve the desired motor speed, usually in N-m.
+	End Rem
+	Method GetMaxMotorTorque:Float()
+		Return bmx_b2revolutejointdef_getmaxmotortorque(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the maximum motor torque used to achieve the desired motor speed, usually in N-m.
+	End Rem
+	Method SetMaxMotorTorque(torque:Float)
+		bmx_b2revolutejointdef_setmaxmotortorque(b2ObjectPtr, torque)
+	End Method
+
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2revolutejointdef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+	
+End Type
+
+Rem
+bbdoc:Pulley joint definition. 
+about: This requires two ground anchors, two dynamic body anchor points, max lengths for each side, and a pulley ratio. 
+End Rem
+Type b2PulleyJointDef Extends b2JointDef
+
+	Method New()
+		b2ObjectPtr = bmx_b2pulleyjointdef_create()
+	End Method
+	
+	Rem
+	bbdoc: Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors.
+	End Rem
+	Method Initialize(body1:b2Body, body2:b2Body, groundAnchor1:b2Vec2, groundAnchor2:b2Vec2, ..
+	                anchor1:b2Vec2, anchor2:b2Vec2, ratio:Float)
+		bmx_b2pulleyjointdef_initialize(b2ObjectPtr, body1.b2ObjectPtr, body2.b2ObjectPtr, groundAnchor1, ..
+			groundAnchor2, anchor1, anchor2, ratio)
+	End Method
+	
+	Rem
+	bbdoc: The first ground anchor in world coordinates. This point never moves.
+	end rem
+	Method SetGroundAnchor1(anchor:b2Vec2)
+		bmx_b2pulleyjointdef_setgroundanchor1(b2ObjectPtr, anchor)
+	End Method
+	
+	Rem
+	bbdoc: Returns the first ground anchor, in world coordinates.
+	End Rem
+	Method GetGroundAnchor1:b2Vec2()
+		Return bmx_b2pulleyjointdef_getgroundanchor1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The second ground anchor in world coordinates. This point never moves.
+	end rem
+	Method SetGroundAnchor2(anchor:b2Vec2)
+		bmx_b2pulleyjointdef_setgroundanchor2(b2ObjectPtr, anchor)
+	End Method
+	
+	Rem
+	bbdoc: Returns the second ground anchor, in world coordinates.
+	End Rem
+	Method GetGroundAnchor2:b2Vec2()
+		Return bmx_b2pulleyjointdef_getgroundanchor2(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The local anchor point relative to body1's origin.
+	end rem
+	Method SetLocalAnchor1(anchor:b2Vec2)
+		bmx_b2pulleyjointdef_setlocalanchor1(b2ObjectPtr, anchor)
+	End Method
+	
+	Rem
+	bbdoc: Returns the local anchor point.
+	End Rem
+	Method GetLocalAnchor1:b2Vec2()
+		Return bmx_b2pulleyjointdef_getlocalanchor1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The local anchor point relative to body2's origin.
+	end rem
+	Method SetLocalAnchor2(anchor:b2Vec2)
+		bmx_b2pulleyjointdef_setlocalanchor2(b2ObjectPtr, anchor)
+	End Method
+	
+	Rem
+	bbdoc: Returns the local anchor point.
+	End Rem
+	Method GetLocalAnchor2:b2Vec2()
+		Return bmx_b2pulleyjointdef_getlocalanchor2(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The a reference length for the segment attached to body1.
+	end rem
+	Method SetLength1(length:Float)
+		bmx_b2pulleyjointdef_setlength1(b2ObjectPtr, length)
+	End Method
+	
+	Rem
+	bbdoc: Returns the reference length for the segment attached to body1.
+	End Rem
+	Method GetLength1:Float()
+		Return bmx_b2pulleyjointdef_getlength1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The maximum length of the segment attached to body1.
+	end rem
+	Method SetMaxLength1(maxLength:Float)
+		bmx_b2pulleyjointdef_setmaxlength1(b2ObjectPtr, maxLength)
+	End Method
+	
+	Rem
+	bbdoc: Returns the maximum length of the segment attached to body1.
+	End Rem
+	Method GetMaxLength1:Float()
+		Return bmx_b2pulleyjointdef_getmaxlength1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The a reference length for the segment attached to body2.
+	end rem
+	Method SetLength2(length:Float)
+		bmx_b2pulleyjointdef_setlength2(b2ObjectPtr, length)
+	End Method
+	
+	Rem
+	bbdoc: Returns the reference length for the segment attached to body2.
+	End Rem
+	Method GetLength2:Float()
+		Return bmx_b2pulleyjointdef_getlength2(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The maximum length of the segment attached to body2.
+	end rem
+	Method SetMaxLength2(maxLength:Float)
+		bmx_b2pulleyjointdef_setmaxlength2(b2ObjectPtr, maxLength)
+	End Method
+	
+	Rem
+	bbdoc: Returns the maximum length of the segment attached to body2.
+	End Rem
+	Method GetMaxLength2:Float()
+		Return bmx_b2pulleyjointdef_getmaxlength2(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The pulley ratio, used to simulate a block-and-tackle.
+	end rem
+	Method SetRatio(ratio:Float)
+		bmx_b2pulleyjointdef_setratio(b2ObjectPtr, ratio)
+	End Method
+	
+	Rem
+	bbdoc: Returns the pulley ratio.
+	End Rem
+	Method GetRatio:Float()
+		Return bmx_b2pulleyjointdef_getratio(b2ObjectPtr)
+	End Method
+
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2pulleyjointdef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+	
+End Type
+
+Rem
+bbdoc: Prismatic joint definition. 
+about: 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. 
+End Rem
+Type b2PrismaticJointDef Extends b2JointDef
+
+	Method New()
+		b2ObjectPtr = bmx_b2prismaticjointdef_create()
+	End Method
+	
+	Rem
+	bbdoc: Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis.
+	End Rem
+	Method Initialize(body1:b2Body, body2:b2Body, anchor:b2Vec2, axis:b2Vec2)
+		bmx_b2prismaticjointdef_initialize(b2ObjectPtr, body1.b2ObjectPtr, body2.b2ObjectPtr, ..
+				anchor, axis)
+	End Method
+	
+	Rem
+	bbdoc: The local anchor point relative to body1's origin.
+	End Rem
+	Method SetLocalAnchor1(anchor:b2Vec2)
+		bmx_b2prismaticjointdef_setlocalanchor1(b2ObjectPtr, anchor)
+	End Method
+	
+	Rem
+	bbdoc: Returns the local anchor point.
+	End Rem
+	Method GetLocalAnchor1:b2Vec2()
+		Return bmx_b2prismaticjointdef_getlocalanchor1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The local anchor point relative to body2's origin.
+	End Rem
+	Method SetLocalAnchor2(anchor:b2Vec2)
+		bmx_b2prismaticjointdef_setlocalanchor2(b2ObjectPtr, anchor)
+	End Method
+	
+	Rem
+	bbdoc: Returns the local anchor point.
+	End Rem
+	Method GetLocalAnchor2:b2Vec2()
+		Return bmx_b2prismaticjointdef_getlocalanchor2(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The local translation axis in body1.
+	End Rem
+	Method SetLocalAxis1(axis:b2Vec2)
+		bmx_b2prismaticjointdef_setlocalaxis1(b2ObjectPtr, axis)
+	End Method
+	
+	Rem
+	bbdoc: Returns the local translation axis in body1.
+	End Rem
+	Method GetLocalAxis1:b2Vec2()
+		Return bmx_b2prismaticjointdef_getlocalaxis1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The constrained angle between the bodies: body2_angle - body1_angle.
+	End Rem
+	Method SetReferenceAngle(angle:Float)
+		bmx_b2prismaticjointdef_setreferenceangle(b2ObjectPtr, angle)
+	End Method
+	
+	Rem
+	bbdoc: Returns the constrained angle between the bodies.
+	End Rem
+	Method GetReferenceAngle:Float()
+		Return bmx_b2prismaticjointdef_getreferenceangle(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Enable/disable the joint limit.
+	End Rem
+	Method EnableLimit(value:Int)
+		bmx_b2prismaticjointdef_enablelimit(b2ObjectPtr, value)
+	End Method
+	
+	Rem
+	bbdoc: Returns True if the joint limit is enabled.
+	End Rem
+	Method IsLimitEnabled:Int()
+		Return bmx_b2prismaticjointdef_islimitenabled(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The lower translation limit, usually in meters.
+	End Rem
+	Method SetLowerTranslation(Translation:Float)
+		bmx_b2prismaticjointdef_setlowertranslation(b2ObjectPtr, Translation)
+	End Method
+	
+	Rem
+	bbdoc: Returns the lower translation limit.
+	End Rem
+	Method GetLowerTranslation:Float()
+		Return bmx_b2prismaticjointdef_getlowertranslation(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The upper translation limit, usually in meters.
+	End Rem
+	Method SetUpperTranslation(Translation:Float)
+		bmx_b2prismaticjointdef_setuppertranslation(b2ObjectPtr, Translation)
+	End Method
+	
+	Rem
+	bbdoc: Returns the upper translation limit.
+	End Rem
+	Method GetUpperTranslation:Float()
+		Return bmx_b2prismaticjointdef_getuppertranslation(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Enable/disable the joint motor.
+	end rem
+	Method EnableMotor(value:Int)
+		bmx_b2prismaticjointdef_enablemotor(b2ObjectPtr, value)
+	End Method
+	
+	Rem
+	bbdoc: Returns true if the joint motor is enabled.
+	End Rem
+	Method IsMotorEnabled:Int()
+		Return bmx_b2prismaticjointdef_ismotorenabled(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The maximum motor torque, usually in N-m.
+	end rem
+	Method SetMaxMotorForce(force:Float)
+		bmx_b2prismaticjointdef_setmaxmotorforce(b2ObjectPtr, force)
+	End Method
+	
+	Rem
+	bbdoc: Returns the maximum motor torque.
+	End Rem
+	Method GetMaxMotorForce:Float()
+		Return bmx_b2prismaticjointdef_getmaxmotorforce(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The desired motor speed in degrees per second.
+	End Rem
+	Method SetMotorSpeed(speed:Float)
+		bmx_b2prismaticjointdef_setmotorspeed(b2ObjectPtr, speed)
+	End Method
+	
+	Rem
+	bbdoc: The motorspeed, in degrees per second.
+	End Rem
+	Method GetMotorSpeed:Float()
+		Return bmx_b2prismaticjointdef_getmotorspeed(b2ObjectPtr)
+	End Method
+
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2prismaticjointdef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: Mouse joint definition. 
+about: This requires a world target point, tuning parameters, and the time step. 
+End Rem
+Type b2MouseJointDef Extends b2JointDef
+	
+	Method New()
+		b2ObjectPtr = bmx_b2mousejointdef_new()
+	End Method
+
+	Rem
+	bbdoc: The initial world target point.
+	about: This is assumed to coincide with the body anchor initially.
+	End Rem
+	Method SetTarget(target:b2Vec2)
+		bmx_b2mousejointdef_settarget(b2ObjectPtr, target)
+	End Method
+	
+	Rem
+	bbdoc: Returns the initial world target point.
+	End Rem
+	Method GetTarget:b2Vec2()
+		Return bmx_b2mousejointdef_gettarget(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The maximum constraint force that can be exerted to move the candidate body.
+	about: Usually you will express as some multiple of the weight (multiplier * mass * gravity).
+	End Rem
+	Method SetMaxForce(maxForce:Float)
+		bmx_b2mousejointdef_setmaxforce(b2ObjectPtr, maxForce)
+	End Method
+	
+	Rem
+	bbdoc: Returns the maximum constraint force that can be exerted to move the candidate body.
+	End Rem
+	Method GetMaxForce:Float()
+		Return bmx_b2mousejointdef_getmaxforce(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The response speed.
+	end rem
+	Method SetFrequencyHz(frequency:Float)
+		bmx_b2mousejointdef_setfrequencyhz(b2ObjectPtr, frequency)
+	End Method
+	
+	Rem
+	bbdoc: Returns the response speed.
+	End Rem
+	Method GetFrequencyHz:Float()
+		Return bmx_b2mousejointdef_getfrequencyhz(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: The damping ratio.
+	about: 0 = no damping, 1 = critical damping.
+	End Rem
+	Method SetDampingRatio(ratio:Float)
+		bmx_b2mousejointdef_setdampingration(b2ObjectPtr, ratio)
+	End Method
+	
+	Rem
+	bbdoc: Returns the damping ratio.
+	End Rem
+	Method GetDampingRatio:Float()
+		Return bmx_b2mousejointdef_getdampingratio(b2ObjectPtr)
+	End Method
+	
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2mousejointdef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: Gear joint definition. 
+about: 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.
+End Rem
+Type b2GearJointDef Extends b2JointDef
+
+	Method New()
+		b2ObjectPtr = bmx_b2gearjointdef_new()
+	End Method
+	
+	Rem
+	bbdoc: Sets the first revolute/prismatic joint attached to the gear joint. 
+	End Rem
+	Method SetJoint1(joint:b2Joint)
+		bmx_b2gearjointdef_setjoint1(b2ObjectPtr, joint.b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the second revolute/prismatic joint attached to the gear joint. 
+	End Rem
+	Method SetJoint2(joint:b2Joint)
+		bmx_b2gearjointdef_setjoint2(b2ObjectPtr, joint.b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the gear ratio. 
+	End Rem
+	Method SetRatio(ratio:Float)
+		bmx_b2gearjointdef_setratio(b2ObjectPtr, ratio)
+	End Method
+
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2gearjointdef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: Line joint definition.
+about: 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.
+End Rem
+Type b2LineJointDef Extends b2JointDef
+
+	Method New()
+		b2ObjectPtr = bmx_b2linejointdef_create()
+	End Method
+	
+	Rem
+	bbdoc: Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis.
+	End Rem
+	Method Initialize(body1:b2Body, body2:b2Body, anchor:b2Vec2, axis:b2Vec2)
+		bmx_b2linejointdef_initialize(b2ObjectPtr, body1.b2ObjectPtr, body2.b2ObjectPtr, ..
+				anchor, axis)
+	End Method
+
+	Rem
+	bbdoc: Sets the local anchor point relative to body1's origin. 
+	End Rem
+	Method SetLocalAnchor1(anchor:b2Vec2)
+		bmx_b2linejointdef_setlocalanchor1(b2ObjectPtr, anchor)
+	End Method
+
+	Rem
+	bbdoc: Returns the local anchor point relative to body1's origin. 
+	End Rem
+	Method GetLocalAnchor1:b2Vec2()
+		Return bmx_b2linejointdef_getlocalanchor1(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Sets the Local anchor point relative to body2's origin.
+	End Rem
+	Method SetLocalAnchor2(anchor:b2Vec2)
+		bmx_b2linejointdef_setlocalanchor2(b2ObjectPtr, anchor)
+	End Method
+
+	Rem
+	bbdoc: Returns the Local anchor point relative to body2's origin.
+	End Rem
+	Method GetLocalAnchor2:b2Vec2()
+		Return bmx_b2linejointdef_getlocalanchor2(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Sets the local translation axis in body1.
+	End Rem
+	Method SetLocalAxis1(axis:b2Vec2)
+		bmx_b2linejointdef_setlocalaxis1(b2ObjectPtr, axis)
+	End Method
+
+	Rem
+	bbdoc: Returns the local translation axis in body1.
+	End Rem
+	Method GetLocalAxis1:b2Vec2()
+		Return bmx_b2linejointdef_getlocalaxis1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Enables/disables the joint limit.
+	End Rem
+	Method EnableLimit(limit:Int)
+		bmx_b2linejointdef_enablelimit(b2ObjectPtr, limit)
+	End Method
+	
+	Rem
+	bbdoc: Returns the joint limit.
+	End Rem
+	Method GetLimit:Int()
+		Return bmx_b2linejointdef_getlimit(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the lower translation limit, usually in meters.
+	End Rem
+	Method SetLowerTranslation(Translation:Float)
+		bmx_b2linejointdef_setlowertranslation(b2ObjectPtr, Translation)
+	End Method
+	
+	Rem
+	bbdoc: Gets the lower translation limit, usually in meters.
+	End Rem
+	Method GetLowerTranslation:Float()
+		Return bmx_b2linejointdef_getlowertranslation(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Sets the upper translation limit, usually in meters.
+	End Rem
+	Method SetUpperTranslation(Translation:Float)
+		bmx_b2linejointdef_setuppertranslation(b2ObjectPtr, Translation)
+	End Method
+	
+	Rem
+	bbdoc: Gets the upper translation limit, usually in meters.
+	End Rem
+	Method GetUpperTranslation:Float()
+		Return bmx_b2linejointdef_getuppertranslation(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Enables/disables the joint motor.
+	End Rem
+	Method EnableMotor(enable:Int)
+		bmx_b2linejointdef_enablemotor(b2ObjectPtr, enable)
+	End Method
+	
+	Rem
+	bbdoc: Is the motor enabled?
+	End Rem
+	Method IsMotorEnabled:Int()
+		Return bmx_b2linejointdef_ismotorenabled(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the maximum motor torque, usually in N-m.
+	End Rem
+	Method SetMaxMotorForce(maxForce:Float)
+		bmx_b2linejointdef_setmaxmotorforce(b2ObjectPtr, maxForce)
+	End Method
+	
+	Rem
+	bbdoc: Returns the maximum motor torque, usually in N-m.
+	End Rem
+	Method GetMaxMotorForce:Float()
+		Return bmx_b2linejointdef_getmaxmotorforce(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the desired motor speed, in degrees per second.
+	End Rem
+	Method SetMotorSpeed(speed:Float)
+		bmx_b2linejointdef_setmotorspeed(b2ObjectPtr, speed)
+	End Method
+	
+	Rem
+	bbdoc: Returns the desired motor speed, in degrees per second.
+	End Rem
+	Method GetMotorSpeed:Float()
+		Return bmx_b2linejointdef_getmotorspeed(b2ObjectPtr)
+	End Method
+
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2linejointdef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: A line joint.
+about: This joint provides one degree of freedom: translation along an axis fixed in body1. 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.
+End Rem
+Type b2LineJoint Extends b2Joint
+
+	Rem
+	bbdoc: 
+	End Rem
+	Method GetAnchor1:b2Vec2()
+		Return bmx_b2linejoint_getanchor1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: 
+	End Rem
+	Method GetAnchor2:b2Vec2()
+		Return bmx_b2linejoint_getanchor2(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: 
+	End Rem
+	Method GetReactionForce:b2Vec2(inv_dt:Float)
+		Return bmx_b2linejoint_getreactionforce(b2ObjectPtr, inv_dt)
+	End Method
+
+	Rem
+	bbdoc: 
+	End Rem
+	Method GetReactionTorque:Float(inv_dt:Float)
+		Return bmx_b2linejoint_getreactiontorque(b2ObjectPtr, inv_dt)
+	End Method
+
+	Rem
+	bbdoc: Get the current joint translation, usually in meters.
+	End Rem
+	Method GetJointTranslation:Float()
+		Return bmx_b2linejoint_getjointtranslation(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the current joint translation speed, usually in meters per second.
+	End Rem
+	Method GetJointSpeed:Float()
+		Return bmx_b2linejoint_getjointspeed(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Is the joint limit enabled?
+	End Rem
+	Method IsLimitEnabled:Int()
+		Return bmx_b2linejoint_islimitenabled(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Enable/disable the joint limit.
+	End Rem
+	Method EnableLimit(flag:Int)
+		bmx_b2linejoint_enablelimit(b2ObjectPtr, flag)
+	End Method
+
+	Rem
+	bbdoc: Get the lower joint limit, usually in meters.
+	End Rem
+	Method GetLowerLimit:Float()
+		Return bmx_b2linejoint_getlowerlimit(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Get the upper joint limit, usually in meters.
+	End Rem
+	Method GetUpperLimit:Float()
+		Return bmx_b2linejoint_getupperlimit(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Set the joint limits, usually in meters.
+	End Rem
+	Method SetLimits(_lower:Float, _upper:Float)
+		bmx_b2linejoint_setlimits(b2ObjectPtr, _lower, _upper)
+	End Method
+
+	Rem
+	bbdoc: Is the joint motor enabled?
+	End Rem
+	Method IsMotorEnabled:Int()
+		Return bmx_b2linejoint_ismotorenabled(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Enable/disable the joint motor.
+	End Rem
+	Method EnableMotor(flag:Int)
+		bmx_b2linejoint_enablemotor(b2ObjectPtr, flag)
+	End Method
+
+	Rem
+	bbdoc: Set the motor speed, usually in meters per second.
+	End Rem
+	Method SetMotorSpeed(speed:Float)
+		bmx_b2linejoint_setmotorspeed(b2ObjectPtr, speed)
+	End Method
+
+	Rem
+	bbdoc: Get the motor speed, usually in meters per second.
+	End Rem
+	Method GetMotorSpeed:Float()
+		Return bmx_b2linejoint_getmotorspeed(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Set the maximum motor force, usually in N.
+	End Rem
+	Method SetMaxMotorForce(force:Float)
+		bmx_b2linejoint_setmaxmotorforce(b2ObjectPtr, force)
+	End Method
+
+	Rem
+	bbdoc: Get the current motor force, usually in N.
+	End Rem
+	Method GetMotorForce:Float()
+		Return bmx_b2linejoint_getmotorforce(b2ObjectPtr)
+	End Method
+	
+End Type
+
+Rem
+bbdoc: Distance joint definition.
+about: This requires defining an anchor point on both bodies and the non-zero length of the
+distance joint. The definition uses local anchor points so that the initial configuration can violate the
+constraint slightly. This helps when saving and loading a game.
+<p>
+Warning: Do not use a zero or short length.
+</p>
+End Rem
+Type b2DistanceJointDef Extends b2JointDef
+
+	Method New()
+		b2ObjectPtr = bmx_b2distancejointdef_new()
+	End Method
+	
+	Rem
+	bbdoc: Initialize the bodies, anchors, and length using the world anchors. 
+	End Rem
+	Method Initialize(body1:b2Body, body2:b2Body, anchor1:b2Vec2, anchor2:b2Vec2)
+		bmx_b2distancejointdef_initialize(b2ObjectPtr, body1.b2ObjectPtr, body2.b2ObjectPtr, anchor1, anchor2)
+	End Method
+	
+	Rem
+	bbdoc: Sets the local anchor point relative to body1's origin. 
+	End Rem
+	Method SetLocalAnchor1(anchor:b2Vec2)
+		bmx_b2distancejointdef_setlocalanchor1(b2ObjectPtr, anchor)
+	End Method
+
+	Rem
+	bbdoc: Returns the local anchor point relative to body1's origin. 
+	End Rem
+	Method GetLocalAnchor1:b2Vec2()
+		Return bmx_b2distancejointdef_getlocalanchor1(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Sets the Local anchor point relative to body2's origin.
+	End Rem
+	Method SetLocalAnchor2(anchor:b2Vec2)
+		bmx_b2distancejointdef_setlocalanchor2(b2ObjectPtr, anchor)
+	End Method
+
+	Rem
+	bbdoc: Returns the Local anchor point relative to body2's origin.
+	End Rem
+	Method GetLocalAnchor2:b2Vec2()
+		Return bmx_b2distancejointdef_getlocalanchor2(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Sets the equilibrium length between the anchor points.
+	End Rem
+	Method SetLength(length:Float)
+		bmx_b2distancejointdef_setlength(b2ObjectPtr, length)
+	End Method
+
+	Rem
+	bbdoc: Returns the equilibrium length between the anchor points.
+	End Rem
+	Method GetLength:Float()
+		Return bmx_b2distancejointdef_getlength(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Sets the response speed.
+	End Rem
+	Method SetFrequencyHz(freq:Float)
+		bmx_b2distancejointdef_setfrequencyhz(b2ObjectPtr, freq)
+	End Method
+
+	Rem
+	bbdoc: Sets the damping ratio. 0 = no damping, 1 = critical damping.
+	End Rem
+	Method SetDampingRatio(ratio:Float)
+		bmx_b2distancejointdef_setdampingratio(b2ObjectPtr, ratio)
+	End Method
+
+	
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2distancejointdef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: A distance joint constrains two points on two bodies to remain at a fixed distance from each other. 
+about: You can view this as a massless, rigid rod. 
+End Rem
+Type b2DistanceJoint Extends b2Joint
+
+	Rem
+	bbdoc: Get the anchor point on body1 in world coordinates.
+	End Rem
+	Method GetAnchor1:b2Vec2()
+		Return bmx_b2distancejoint_getanchor1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the anchor point on body2 in world coordinates. 
+	End Rem
+	Method GetAnchor2:b2Vec2()
+		Return bmx_b2distancejoint_getanchor2(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the reaction force on body2 at the joint anchor. 
+	End Rem
+	Method GetReactionForce:b2Vec2(inv_dt:Float)
+		Return bmx_b2distancejoint_getreactionforce(b2ObjectPtr, inv_dt)
+	End Method
+	
+	Rem
+	bbdoc: Get the reaction torque on body2. 
+	End Rem
+	Method GetReactionTorque:Float(inv_dt:Float)
+		Return bmx_b2distancejoint_getreactiontorque(b2ObjectPtr, inv_dt)
+	End Method
+
+End Type
+
+Rem
+bbdoc: A revolute joint constrains to bodies to share a common point while they are free to rotate about the point. 
+about: 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 to drive the relative rotation
+about the shared point. A maximum motor torque is provided so that infinite forces are not generated. 
+End Rem
+Type b2RevoluteJoint Extends b2Joint
+	
+	Rem
+	bbdoc: Get the anchor point on body1 in world coordinates.
+	End Rem
+	Method GetAnchor1:b2Vec2()
+		Return bmx_b2revolutejoint_getanchor1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the anchor point on body2 in world coordinates. 
+	End Rem
+	Method GetAnchor2:b2Vec2()
+		Return bmx_b2revolutejoint_getanchor2(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the reaction force on body2 at the joint anchor. 
+	End Rem
+	Method GetReactionForce:b2Vec2(inv_dt:Float)
+		Return bmx_b2revolutejoint_getreactionforce(b2ObjectPtr, inv_dt)
+	End Method
+	
+	Rem
+	bbdoc: Get the reaction torque on body2. 
+	End Rem
+	Method GetReactionTorque:Float(inv_dt:Float)
+		Return bmx_b2revolutejoint_getreactiontorque(b2ObjectPtr, inv_dt)
+	End Method
+	
+	Rem
+	bbdoc: Get the current joint angle in degrees.
+	End Rem
+	Method GetJointAngle:Float()
+		Return bmx_b2revolutejoint_getjointangle(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the current joint angle speed in degrees per second.
+	End Rem
+	Method GetJointSpeed:Float()
+		Return bmx_b2revolutejoint_getjointspeed(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Is the joint limit enabled?
+	end rem
+	Method IsLimitEnabled:Int()
+		Return bmx_b2revolutejoint_islimitenabled(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Enable/disable the joint limit.
+	end rem
+	Method EnableLimit(flag:Int)
+		bmx_b2revolutejoint_enablelimit(b2ObjectPtr, flag)
+	End Method
+	
+	Rem
+	bbdoc: Get the lower joint limit in degrees.
+	End Rem
+	Method GetLowerLimit:Float()
+		Return bmx_b2revolutejoint_getlowerlimit(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the upper joint limit in degrees.
+	End Rem
+	Method GetUpperLimit:Float()
+		Return bmx_b2revolutejoint_getupperlimit(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Set the joint limits in degrees.
+	End Rem
+	Method SetLimits(lowerLimit:Float, upperLimit:Float)
+		bmx_b2revolutejoint_setlimits(b2ObjectPtr, lowerLimit, upperLimit)
+	End Method
+	
+	Rem
+	bbdoc: Is the joint motor enabled?
+	end rem
+	Method IsMotorEnabled:Int()
+		Return bmx_b2revolutejoint_ismotorenabled(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Enable/disable the joint motor.
+	end rem
+	Method EnableMotor(flag:Int)
+		bmx_b2revolutejoint_enablemotor(b2ObjectPtr, flag)
+	End Method
+	
+	Rem
+	bbdoc: Set the motor speed in radians per second.
+	end rem
+	Method SetMotorSpeed(speed:Float)
+		bmx_b2revolutejoint_setmotorspeed(b2ObjectPtr, speed)
+	End Method
+	
+	Rem
+	bbdoc: Get the motor speed in radians per second.
+	end rem
+	Method GetMotorSpeed:Float()
+		Return bmx_b2revolutejoint_getmotorspeed(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Set the maximum motor torque, usually in N-m.
+	end rem
+	Method SetMaxMotorTorque(torque:Float)
+		bmx_b2revolutejoint_setmaxmotortorque(b2ObjectPtr, torque)
+	End Method
+	
+	Rem
+	bbdoc: Get the current motor torque, usually in N-m.
+	end rem
+	Method GetMotorTorque:Float()
+		Return bmx_b2revolutejoint_getmotortorque(b2ObjectPtr)
+	End Method
+
+End Type
+
+Rem
+bbdoc: 
+End Rem
+Type b2PrismaticJoint Extends b2Joint
+	
+	Rem
+	bbdoc: Get the anchor point on body1 in world coordinates. 
+	End Rem
+	Method GetAnchor1:b2Vec2()
+		Return bmx_b2prismaticjoint_getanchor1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the anchor point on body2 in world coordinates. 
+	End Rem
+	Method GetAnchor2:b2Vec2()
+		Return bmx_b2prismaticjoint_getanchor2(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the reaction force on body2 at the joint anchor. 
+	End Rem
+	Method GetReactionForce:b2Vec2(inv_dt:Float)
+		Return bmx_b2prismaticjoint_getreactionforce(b2ObjectPtr, inv_dt)
+	End Method
+	
+	Rem
+	bbdoc: Get the reaction torque on body2. 
+	End Rem
+	Method GetReactionTorque:Float(inv_dt:Float)
+		Return bmx_b2prismaticjoint_getreactiontorque(b2ObjectPtr, inv_dt)
+	End Method
+	
+	Rem
+	bbdoc: Get the current joint translation, usually in meters.
+	End Rem
+	Method GetJointTranslation:Float()
+		Return bmx_b2prismaticjoint_getjointtranslation(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the current joint translation speed, usually in meters per second.
+	end rem
+	Method GetJointSpeed:Float()
+		Return bmx_b2prismaticjoint_getjointspeed(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Is the joint limit enabled?
+	end rem
+	Method IsLimitEnabled:Int()
+		Return bmx_b2prismaticjoint_islimitenabled(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Enable/disable the joint limit.
+	end rem
+	Method EnableLimit(flag:Int)
+		bmx_b2prismaticjoint_enablelimit(b2ObjectPtr, flag)
+	End Method
+	
+	Rem
+	bbdoc: Get the lower joint limit, usually in meters.
+	end rem
+	Method GetLowerLimit:Float()
+		Return bmx_b2prismaticjoint_getlowerlimit(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the upper joint limit, usually in meters.
+	end rem
+	Method GetUpperLimit:Float()
+		Return bmx_b2prismaticjoint_getupperlimit(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Set the joint limits, usually in meters.
+	end rem
+	Method SetLimits(lowerLimit:Float, upperLimit:Float)
+		bmx_b2prismaticjoint_setlimits(b2ObjectPtr, lowerLimit, upperLimit)
+	End Method
+	
+	Rem
+	bbdoc: Is the joint motor enabled?
+	end rem
+	Method IsMotorEnabled:Int()
+		Return bmx_b2prismaticjoint_ismotorenabled(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Enable/disable the joint motor.
+	end rem
+	Method EnableMotor(flag:Int)
+		bmx_b2prismaticjoint_enablemotor(b2ObjectPtr, flag)
+	End Method
+	
+	Rem
+	bbdoc: Set the motor speed, usually in meters per second.
+	end rem
+	Method SetMotorSpeed(speed:Float)
+		bmx_b2prismaticjoint_setmotorspeed(b2ObjectPtr, speed)
+	End Method
+	
+	Rem
+	bbdoc: Get the motor speed, usually in meters per second.
+	end rem
+	Method GetMotorSpeed:Float()
+		Return bmx_b2prismaticjoint_getmotorspeed(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Set the maximum motor force, usually in N.
+	end rem
+	Method SetMaxMotorForce(force:Float)
+		bmx_b2prismaticjoint_setmaxmotorforce(b2ObjectPtr, force)
+	End Method
+	
+	Rem
+	bbdoc: Get the current motor force, usually in N.
+	end rem
+	Method GetMotorForce:Float()
+		Return bmx_b2prismaticjoint_getmotorforce(b2ObjectPtr)
+	End Method
+
+End Type
+
+Rem
+bbdoc: The pulley joint is connected to two bodies and two fixed ground points. 
+about: The pulley supports a ratio such that:
+<pre>
+		length1 + ratio * length2 <= constant
+</pre>
+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. 
+End Rem
+Type b2PulleyJoint Extends b2Joint
+	
+	Rem
+	bbdoc: Get the anchor point on body1 in world coordinates. 
+	End Rem
+	Method GetAnchor1:b2Vec2()
+		Return bmx_b2pulleyjoint_getanchor1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the anchor point on body2 in world coordinates. 
+	End Rem
+	Method GetAnchor2:b2Vec2()
+		Return bmx_b2pulleyjoint_getanchor2(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the reaction force on body2 at the joint anchor. 
+	End Rem
+	Method GetReactionForce:b2Vec2(inv_dt:Float)
+		Return bmx_b2pulleyjoint_getreactionforce(b2ObjectPtr, inv_dt)
+	End Method
+	
+	Rem
+	bbdoc: Get the reaction torque on body2. 
+	End Rem
+	Method GetReactionTorque:Float(inv_dt:Float)
+		Return bmx_b2pulleyjoint_getreactiontorque(b2ObjectPtr, inv_dt)
+	End Method
+	
+	Rem
+	bbdoc: Get the first ground anchor.
+	End Rem
+	Method GetGroundAnchor1:b2Vec2()
+		Return bmx_b2pulleyjoint_getgroundanchor1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the second ground anchor.
+	end rem
+	Method GetGroundAnchor2:b2Vec2()
+		Return bmx_b2pulleyjoint_getgroundanchor2(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the current length of the segment attached to body1.
+	end rem
+	Method GetLength1:Float()
+		Return bmx_b2pulleyjoint_getlength1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the current length of the segment attached to body2.
+	end rem
+	Method GetLength2:Float()
+		Return bmx_b2pulleyjoint_getlength2(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the pulley ratio.
+	end rem
+	Method GetRatio:Float()
+		Return bmx_b2pulleyjoint_getratio(b2ObjectPtr)
+	End Method
+
+End Type
+
+Rem
+bbdoc: A mouse joint is used to make a point on a body track a specified world point. 
+about: This a soft constraint with a maximum force. This allows the constraint to stretch and without applying huge forces. 
+End Rem
+Type b2MouseJoint Extends b2Joint
+
+	Rem
+	bbdoc: Get the anchor point on body1 in world coordinates. 
+	End Rem
+	Method GetAnchor1:b2Vec2()
+		Return bmx_b2mousejoint_getanchor1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the anchor point on body2 in world coordinates. 
+	End Rem
+	Method GetAnchor2:b2Vec2()
+		Return bmx_b2mousejoint_getanchor2(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the reaction force on body2 at the joint anchor. 
+	End Rem
+	Method GetReactionForce:b2Vec2(inv_dt:Float)
+		Return bmx_b2mousejoint_getreactionforce(b2ObjectPtr, inv_dt)
+	End Method
+	
+	Rem
+	bbdoc: Get the reaction torque on body2. 
+	End Rem
+	Method GetReactionTorque:Float(inv_dt:Float)
+		Return bmx_b2mousejoint_getreactiontorque(b2ObjectPtr, inv_dt)
+	End Method
+	
+	Rem
+	bbdoc: Use this to update the target point.
+	End Rem
+	Method SetTarget(target:b2Vec2)
+		bmx_b2mousejoint_settarget(b2ObjectPtr, target)
+	End Method
+
+	Rem
+	bbdoc: Returns the target point.
+	End Rem
+	Method GetTarget:b2Vec2()
+		Return bmx_b2mousejoint_gettarget(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Returns the local anchor.
+	End Rem
+	Method GetLocalAnchor:b2Vec2()
+		Return bmx_b2mousejoint_getlocalanchor(b2ObjectPtr)
+	End Method
+	
+End Type
+
+Rem
+bbdoc: A gear joint is used to connect two joints together.
+about: Either joint can be a revolute or prismatic joint. You specify a gear ratio to bind the motions
+together:
+<pre>
+	coordinate1 + ratio * coordinate2 = constant
+</pre>
+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.
+<p>
+Warning: The revolute and prismatic joints must be attached to fixed bodies (which must be body1 on those
+joints).
+</p>
+End Rem
+Type b2GearJoint Extends b2Joint
+
+	Rem
+	bbdoc: Get the anchor point on body1 in world coordinates.
+	End Rem
+	Method GetAnchor1:b2Vec2()
+		Return bmx_b2gearjoint_getanchor1(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the anchor point on body2 in world coordinates. 
+	End Rem
+	Method GetAnchor2:b2Vec2()
+		Return bmx_b2gearjoint_getanchor2(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the reaction force on body2 at the joint anchor. 
+	End Rem
+	Method GetReactionForce:b2Vec2(inv_dt:Float)
+		Return bmx_b2gearjoint_getreactionforce(b2ObjectPtr, inv_dt)
+	End Method
+	
+	Rem
+	bbdoc: Get the reaction torque on body2.
+	End Rem
+	Method GetReactionTorque:Float(inv_dt:Float)
+		Return bmx_b2gearjoint_getreactiontorque(b2ObjectPtr, inv_dt)
+	End Method
+	
+	Rem
+	bbdoc: Get the gear ratio.
+	End Rem
+	Method GetRatio:Float()
+		Return bmx_b2gearjoint_getratio(b2ObjectPtr)
+	End Method
+
+End Type
+
+Rem
+bbdoc: A transform contains translation and rotation. 
+about: It is used to represent the position and orientation of rigid frames.
+End Rem
+Struct b2XForm
+	
+	Field position:b2Vec2
+	Field R:b2Mat22
+	
+	Rem
+	bbdoc: 
+	End Rem
+	Method Create:b2XForm()
+		Return Self
+	End Method
+	
+	Rem
+	bbdoc: 
+	End Rem
+	Method GetPosition:b2Vec2()
+		Return position
+	End Method
+	
+	Rem
+	bbdoc: 
+	End Rem
+	Method SetPosition(pos:b2Vec2)
+		position = pos
+	End Method
+	
+	Rem
+	bbdoc: 
+	End Rem
+	Method SetR(r:b2Mat22)
+		Self.R = r
+		'bmx_b2xform_setr(b2ObjectPtr, r.b2ObjectPtr)
+	End Method
+		
+End Struct
+
+Rem
+bbdoc: A 2-by-2 matrix.
+about: Stored in column-major order. 
+End Rem
+Struct b2Mat22
+
+	Field col1:b2Vec2
+	Field col2:b2Vec2
+	
+	Rem
+	bbdoc: Constructs the matrix using scalars.
+	End Rem
+	Method Create:b2Mat22(a11:Float = 0, a12:Float = 0, a21:Float = 0, a22:Float = 0)
+		col1.x = a11
+		col1.y = a21
+		
+		col2.x = a12
+		col2.y = a22
+		Return Self
+	End Method
+
+	Rem
+	bbdoc: Constructs the matrix using columns.
+	End Rem
+	Method CreateVec:b2Mat22(c1:b2Vec2, c2:b2Vec2)
+		col1 = c1
+		col2 = c2
+		Return Self
+	End Method
+
+	Rem
+	bbdoc: Constructs the matrix using an angle.
+	about: This matrix becomes an orthonormal rotation matrix.
+	End Rem
+	Method CreateAngle:b2Mat22(angle:Float)
+		bmx_b2mat22_createangle(Self, angle)
+		Return Self
+	End Method
+
+	Rem
+	bbdoc: Initialize this matrix using an angle.
+	about: This matrix becomes an orthonormal rotation matrix.
+	End Rem
+	Method SetAngle(angle:Float)
+		bmx_b2mat22_setangle(Self, angle)
+	End Method
+	
+	Rem
+	bbdoc: Returns the angle.
+	End Rem
+	Method GetAngle:Float()
+		Return bmx_b2mat22_getangle(Self)
+	End Method
+	
+	Rem
+	bbdoc: Set this to the identity matrix.
+	End Rem
+	Method SetIdentity()
+		col1.x = 1.0
+		col2.x = 0.0
+		col1.y = 0.0
+		col2.y = 1.0
+	End Method
+	
+	Rem
+	bbdoc: Set this matrix to all zeros.
+	End Rem
+	Method SetZero()
+		col1.x = 0.0
+		col2.x = 0.0
+		col1.y = 0.0
+		col2.y = 0.0
+	End Method
+	
+	Rem
+	bbdoc: Computes the inverse of this matrix, such that inv(A) * A = identity.
+	End Rem
+	Method GetInverse:b2Mat22()
+		Return bmx_b2mat22_getinverse(Self)
+	End Method
+
+End Struct
+
+Rem
+bbdoc: An oriented bounding box.
+End Rem
+Type b2OBB
+
+	Field b2ObjectPtr:Byte Ptr
+	
+	Function _create:b2OBB(b2ObjectPtr:Byte Ptr)
+		If b2ObjectPtr Then
+			Local this:b2OBB = New b2OBB
+			this.b2ObjectPtr = b2ObjectPtr
+			Return this
+		End If
+	End Function
+
+	Rem
+	bbdoc: Returns the rotation matrix.
+	End Rem
+	Method GetRotationMatrix:b2Mat22()
+		Return bmx_b2obb_getrotationmatrix(b2ObjectPtr)
+	End Method
+
+	Rem
+	bbdoc: Returns the local centroid.
+	End Rem
+	Method GetCenter:b2Vec2()
+		Return bmx_b2obb_getcenter(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Returns the half-widths.
+	End Rem
+	Method GetExtents:b2Vec2()
+		Return bmx_b2obb_getextents(b2ObjectPtr)
+	End Method
+
+End Type
+
+Rem
+bbdoc: A line segment.
+End Rem
+Struct b2Segment
+
+	Field p1:b2Vec2
+	Field p2:b2Vec2
+
+	Rem
+	bbdoc: Creates a new b2Segment object.
+	End Rem
+	Method CreateXY:b2Segment(x1:Float, y1:Float, x2:Float, y2:Float)
+		'b2ObjectPtr = bmx_b2segment_createxy(x1, y1, x2, y2)
+		p1.x = x1
+		p1.y = y1
+		p2.x = x2
+		p2.y = y2
+		Return Self
+	End Method
+	
+	Method Create:b2Segment()
+		Return Self
+	End Method
+
+	Rem
+	bbdoc: Creates a new b2Segment object.
+	End Rem
+	Method Create:b2Segment(p1:b2Vec2, p2:b2Vec2)
+		Self.p1 = p1
+		Self.p2 = p2
+		Return Self
+	End Method
+
+	Rem
+	bbdoc: Returns the start point of this segment.
+	End Rem
+	Method GetStartPoint:b2Vec2()
+		Return p1
+	End Method
+	
+	Rem
+	bbdoc: Returns the end point of this segment.
+	End Rem
+	Method GetEndPoint:b2Vec2()
+		Return p2
+	End Method
+	
+	Rem
+	bbdoc: Sets the start point of this segment.
+	End Rem
+	Method SetStartPoint(point:b2Vec2)
+		p1 = point
+	End Method
+	
+	Rem
+	bbdoc: Sets the end point of this segment.
+	End Rem
+	Method SetEndPoint(point:b2Vec2)
+		p2 = point
+	End Method
+	
+End Struct
+
+Rem
+bbdoc: A controller edge is used to connect bodies and controllers together in a bipartite graph.
+End Rem
+Type b2ControllerEdge
+
+	Field b2ObjectPtr:Byte Ptr
+
+	Function _create:b2ControllerEdge(b2ObjectPtr:Byte Ptr)
+		If b2ObjectPtr Then
+			Local this:b2ControllerEdge = New b2ControllerEdge
+			this.b2ObjectPtr = b2ObjectPtr
+			Return this
+		End If
+	End Function
+	
+	Rem
+	bbdoc: Provides quick access to other end of this edge.
+	End Rem
+	Method GetController:b2Controller()
+		Return b2Controller._create(bmx_b2controlleredge_getcontroller(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Returns the body.
+	End Rem
+	Method GetBody:b2Body()
+		Return b2Body._create(bmx_b2controlleredge_getbody(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Returns the previous controller edge in the controllers's joint list.
+	End Rem
+	Method GetPrevBody:b2ControllerEdge()
+		Return b2ControllerEdge._create(bmx_b2controlleredge_getprevbody(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Returns the next controller edge in the controllers's joint list.
+	End Rem
+	Method GetNexBody:b2ControllerEdge()
+		Return b2ControllerEdge._create(bmx_b2controlleredge_getnextbody(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Returns the previous controller edge in the body's joint list.
+	End Rem
+	Method GetPrevController:b2ControllerEdge()
+		Return b2ControllerEdge._create(bmx_b2controlleredge_getprevcontroller(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Returns the next controller edge in the body's joint list.
+	End Rem
+	Method GetNextController:b2ControllerEdge()
+		Return b2ControllerEdge._create(bmx_b2controlleredge_getnextcontroller(b2ObjectPtr))
+	End Method
+	
+End Type
+
+Type b2ControllerDef
+
+	Field b2ObjectPtr:Byte Ptr
+
+	Field userData:Object
+	
+	Field _type:Int
+
+End Type
+
+Rem
+bbdoc: Used to build buoyancy controllers
+End Rem
+Type b2BuoyancyControllerDef Extends b2ControllerDef
+
+	Method New()
+		b2ObjectPtr = bmx_b2buoyancycontrollerdef_create()
+		_type = e_buoyancyController
+	End Method
+	
+	Rem
+	bbdoc: Returns the outer surface normal.
+	End Rem
+	Method GetNormal:b2Vec2()
+		Return bmx_b2buoyancycontrollerdef_getnormal(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the outer surface normal.
+	End Rem
+	Method SetNormal(normal:b2Vec2)
+		bmx_b2buoyancycontrollerdef_setnormal(b2ObjectPtr, normal)
+	End Method
+	
+	Rem
+	bbdoc: Returns the height of the fluid surface along the normal.
+	End Rem
+	Method GetOffset:Float()
+		Return bmx_b2buoyancycontrollerdef_getoffset(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the height of the fluid surface along the normal.
+	End Rem
+	Method SetOffset(offset:Float)
+		bmx_b2buoyancycontrollerdef_setoffset(b2ObjectPtr, offset)
+	End Method
+	
+	Rem
+	bbdoc: Returns the fluid density.
+	End Rem
+	Method GetDensity:Float()
+		Return bmx_b2buoyancycontrollerdef_getdensity(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the fluid density.
+	End Rem
+	Method SetDensity(density:Float)
+		bmx_b2buoyancycontrollerdef_setdensity(b2ObjectPtr, density)
+	End Method
+	
+	Rem
+	bbdoc: Returns the fluid velocity, for drag calculations.
+	End Rem
+	Method GetVelocity:b2Vec2()
+		Return bmx_b2buoyancycontrollerdef_getvelocity(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the fluid velocity, for drag calculations.
+	End Rem
+	Method SetVelocity(velocity:b2Vec2)
+		bmx_b2buoyancycontrollerdef_setvelocity(b2ObjectPtr, velocity)
+	End Method
+	
+	Rem
+	bbdoc: Returns the linear drag co-efficient.
+	End Rem
+	Method GetLinearDrag:Float()
+		Return bmx_b2buoyancycontrollerdef_getlineardrag(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the linear drag co-efficient.
+	End Rem
+	Method SetLinearDrag(drag:Float)
+		bmx_b2buoyancycontrollerdef_setlineardrag(b2ObjectPtr, drag)
+	End Method
+	
+	Rem
+	bbdoc: Returns the angular drag co-efficient.
+	End Rem
+	Method GetAngularDrag:Float()
+		Return bmx_b2buoyancycontrollerdef_getangulardrag(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the angular drag co-efficient.
+	End Rem
+	Method SetAngularDrag(drag:Float)
+		bmx_b2buoyancycontrollerdef_setangulardrag(b2ObjectPtr, drag)
+	End Method
+	
+	Rem
+	bbdoc: Returns False if bodies are assumed to be uniformly dense, otherwise use the shapes densities.
+	End Rem
+	Method UsesDensity:Int()
+		Return bmx_b2buoyancycontrollerdef_usesdensity(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Set to False, if bodies are assumed to be uniformly dense, otherwise use the shapes densities.
+	End Rem
+	Method SetUsesDensity(value:Int)
+		bmx_b2buoyancycontrollerdef_setusesdensity(b2ObjectPtr, value)
+	End Method
+	
+	Rem
+	bbdoc: Returns True, if gravity is taken from the world instead of the gravity parameter.
+	End Rem
+	Method UsesWorldGravity:Int()
+		Return bmx_b2buoyancycontrollerdef_usesworldgravity(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Set to True, if gravity is to be taken from the world instead of the gravity parameter.
+	End Rem
+	Method SetUsesWorldGravity(value:Int)
+		bmx_b2buoyancycontrollerdef_setusesworldgravity(b2ObjectPtr, value)
+	End Method
+	
+	Rem
+	bbdoc: Returns the gravity vector, if the world's gravity is not used.
+	End Rem
+	Method GetGravity:b2Vec2()
+		Return bmx_b2buoyancycontrollerdef_getgravity(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Returns the gravity vector, if the world's gravity is not used.
+	End Rem
+	Method SetGravity(gravity:b2Vec2)
+		bmx_b2buoyancycontrollerdef_setgravity(b2ObjectPtr, gravity)
+	End Method
+
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2buoyancycontrollerdef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: Used to build tensor damping controllers.
+End Rem
+Type b2TensorDampingControllerDef Extends b2ControllerDef
+
+	Method New()
+		b2ObjectPtr = bmx_b2tensordampingcontrollerdef_create()
+		_type = e_tensorDampingController
+	End Method
+	
+	Rem
+	bbdoc: Returns the tensor to use in damping model.
+	End Rem
+	Method GetTensor:b2Mat22()
+		Return bmx_b2tensordampingcontrollerdef_gettensor(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the tensor to use in damping model.
+	about: Some examples (matrixes in format (row1; row2) )
+	<table>
+	<th><td>Matrix</td><td>Description</td></th>
+	<tr><td>(-a 0;0 -a)</td><td>Standard isotropic damping with strength a</td></tr>
+	<tr><td>(0 a;-a 0)</td><td>Electron in fixed field - a force at right angles to velocity with proportional magnitude</td></tr>
+	<tr><td>(-a 0;0 -b)</td><td>Differing x and y damping. Useful e.g. for top-down wheels.</td></tr>
+	</table>
+	<p>
+	By the way, tensor in this case just means matrix, don't let the terminology get you down.
+	</p>
+	End Rem
+	Method SetTensor(tensor:b2Mat22)
+		bmx_b2tensordampingcontrollerdef_settensor(b2ObjectPtr, tensor)
+	End Method
+	
+	Rem
+	bbdoc: Returns the maximum amount of damping.
+	End Rem
+	Method GetMaxTimestep:Float()
+		Return bmx_b2tensordampingcontrollerdef_getmaxtimestep(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Set this to a positive number to clamp the maximum amount of damping done.
+	End Rem
+	Method SetMaxTimestep(timestep:Float)
+		bmx_b2tensordampingcontrollerdef_setmaxtimestep(b2ObjectPtr, timestep)
+	End Method
+	
+	Rem
+	bbdoc: Sets damping independently along the x and y axes.
+	End Rem
+	Method SetAxisAligned(xDamping:Float, yDamping:Float)
+		bmx_b2tensordampingcontrollerdef_setaxisaligned(b2ObjectPtr, xDamping, yDamping)
+	End Method
+
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2tensordampingcontrollerdef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: Used to build gravity controllers.
+End Rem
+Type b2GravityControllerDef Extends b2ControllerDef
+
+	Method New()
+		b2ObjectPtr = bmx_b2gravitycontrollerdef_create()
+		_type = e_gravityController
+	End Method
+	
+	Rem
+	bbdoc: Returns the strength of the gravitiation force.
+	End Rem
+	Method GetForce:Float()
+		Return bmx_b2gravitycontrollerdef_getforce(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the strength of the gravitiation force.
+	End Rem
+	Method SetForce(force:Float)
+		bmx_b2gravitycontrollerdef_setforce(b2ObjectPtr, force)
+	End Method
+	
+	Rem
+	bbdoc: Returns whether gravity is proportional to r^-2 (True), otherwise r^-1 (False).
+	End Rem
+	Method IsInvSqr:Int()
+		Return bmx_b2gravitycontrollerdef_isinvsqr(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets whether gravity is proportional to r^-2 (True), otherwise r^-1 (False).
+	End Rem
+	Method SetIsInvSqr(value:Int)
+		bmx_b2gravitycontrollerdef_setisinvsqr(b2ObjectPtr, value)
+	End Method
+
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2gravitycontrollerdef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: Used to build constant force controllers.
+End Rem
+Type b2ConstantForceControllerDef Extends b2ControllerDef
+
+	Method New()
+		b2ObjectPtr = bmx_b2constantforcecontrollerdef_create()
+		_type = e_constantForceController
+	End Method
+
+	Rem
+	bbdoc: Returns the force to apply.
+	End Rem
+	Method GetForce:b2Vec2()
+		Return bmx_b2constantforcecontrollerdef_getforce(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the force to apply.
+	End Rem
+	Method SetForce(force:b2Vec2)
+		bmx_b2constantforcecontrollerdef_setforce(b2ObjectPtr, force)
+	End Method
+
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2constantforcecontrollerdef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: Used to build constant acceleration controllers.
+End Rem
+Type b2ConstantAccelControllerDef Extends b2ControllerDef
+
+	Method New()
+		b2ObjectPtr = bmx_b2constantaccelcontrollerdef_create()
+		_type = e_constantAccelController
+	End Method
+	
+	Rem
+	bbdoc: Returns the force to apply.
+	End Rem
+	Method GetForce:b2Vec2()
+		Return bmx_b2constantaccelcontrollerdef_getforce(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the force to apply.
+	End Rem
+	Method SetForce(force:b2Vec2)
+		bmx_b2constantaccelcontrollerdef_setforce(b2ObjectPtr, force)
+	End Method
+
+	Method Delete()
+		If b2ObjectPtr Then
+			bmx_b2constantaccelcontrollerdef_delete(b2ObjectPtr)
+			b2ObjectPtr = Null
+		End If
+	End Method
+
+End Type
+
+Rem
+bbdoc: Base type for controllers.
+about: Controllers are a convience for encapsulating common per-step functionality.
+End Rem
+Type b2Controller
+	
+	Field b2ObjectPtr:Byte Ptr
+	
+	Field userData:Object
+
+	Function _create:b2Controller(b2ObjectPtr:Byte Ptr)
+		If b2ObjectPtr Then
+			Local controller:b2Controller = b2Controller(bmx_b2controller_getmaxcontroller(b2ObjectPtr))
+			If Not controller Then
+				controller = New b2Controller
+				controller.b2ObjectPtr = b2ObjectPtr
+			Else
+				If Not controller.b2ObjectPtr Then
+					controller.b2ObjectPtr = b2ObjectPtr
+				EndIf
+			End If
+			Return controller
+		End If
+	End Function
+
+	Rem
+	bbdoc: Adds a body to the controller list.
+	End Rem
+	Method AddBody(body:b2Body)
+		bmx_b2controller_addbody(b2ObjectPtr, body.b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Removes a body from the controller list.
+	End Rem
+	Method RemoveBody(body:b2Body)
+		bmx_b2controller_removebody(b2ObjectPtr, body.b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Removes all bodies from the controller list.
+	End Rem
+	Method Clear()
+		bmx_b2controller_clear(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Get the next controller in the world's body list.
+	End Rem
+	Method GetNext:b2Controller()
+		Return b2Controller._create(bmx_b2controller_getnext(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Get the parent world of this body.
+	End Rem
+	Method GetWorld:b2World()
+		Return b2World._create(bmx_b2controller_getworld(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Get the attached body list.
+	End Rem
+	Method GetBodyList:b2ControllerEdge()
+		Return b2ControllerEdge._create(bmx_b2controller_getbodylist(b2ObjectPtr))
+	End Method
+	
+	Rem
+	bbdoc: Get the user data that was provided in the controller definition.
+	End Rem
+	Method GetUserData:Object()
+		Return userData
+	End Method
+
+End Type
+
+Rem
+bbdoc: Applies a force every frame
+End Rem
+Type b2ConstantAccelController Extends b2Controller
+
+	Rem
+	bbdoc: Returns the force to apply.
+	End Rem
+	Method GetForce:b2Vec2()
+		Return bmx_b2constantaccelcontroller_getforce(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the force to apply.
+	End Rem
+	Method SetForce(force:b2Vec2)
+		bmx_b2constantaccelcontroller_setforce(b2ObjectPtr, force)
+	End Method
+	
+End Type
+
+Rem
+bbdoc: Calculates buoyancy forces for fluids in the form of a half plane.
+End Rem
+Type b2BuoyancyController Extends b2Controller
+
+	Rem
+	bbdoc: Returns the outer surface normal.
+	End Rem
+	Method GetNormal:b2Vec2()
+		Return bmx_b2buoyancycontroller_getnormal(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the outer surface normal.
+	End Rem
+	Method SetNormal(normal:b2Vec2)
+		bmx_b2buoyancycontroller_setnormal(b2ObjectPtr, normal)
+	End Method
+	
+	Rem
+	bbdoc: Returns the height of the fluid surface along the normal.
+	End Rem
+	Method GetOffset:Float()
+		Return bmx_b2buoyancycontroller_getoffset(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the height of the fluid surface along the normal.
+	End Rem
+	Method SetOffset(offset:Float)
+		bmx_b2buoyancycontroller_setoffset(b2ObjectPtr, offset)
+	End Method
+	
+	Rem
+	bbdoc: Returns the fluid density.
+	End Rem
+	Method GetDensity:Float()
+		Return bmx_b2buoyancycontroller_getdensity(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the fluid density.
+	End Rem
+	Method SetDensity(density:Float)
+		bmx_b2buoyancycontroller_setdensity(b2ObjectPtr, density)
+	End Method
+	
+	Rem
+	bbdoc: Returns the fluid velocity, for drag calculations.
+	End Rem
+	Method GetVelocity:b2Vec2()
+		Return bmx_b2buoyancycontroller_getvelocity(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the fluid velocity, for drag calculations.
+	End Rem
+	Method SetVelocity(velocity:b2Vec2)
+		bmx_b2buoyancycontroller_setvelocity(b2ObjectPtr, velocity)
+	End Method
+	
+	Rem
+	bbdoc: Returns the linear drag co-efficient.
+	End Rem
+	Method GetLinearDrag:Float()
+		Return bmx_b2buoyancycontroller_getlineardrag(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the linear drag co-efficient.
+	End Rem
+	Method SetLinearDrag(drag:Float)
+		bmx_b2buoyancycontroller_setlineardrag(b2ObjectPtr, drag)
+	End Method
+	
+	Rem
+	bbdoc: Returns the angular drag co-efficient.
+	End Rem
+	Method GetAngularDrag:Float()
+		Return bmx_b2buoyancycontroller_getangulardrag(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the angular drag co-efficient.
+	End Rem
+	Method SetAngularDrag(drag:Float)
+		bmx_b2buoyancycontroller_setangulardrag(b2ObjectPtr, drag)
+	End Method
+	
+	Rem
+	bbdoc: Returns False if bodies are assumed to be uniformly dense, otherwise use the shapes densities.
+	End Rem
+	Method UsesDensity:Int()
+		Return bmx_b2buoyancycontroller_usesdensity(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Set to False, if bodies are assumed to be uniformly dense, otherwise use the shapes densities.
+	End Rem
+	Method SetUsesDensity(value:Int)
+		bmx_b2buoyancycontroller_setusesdensity(b2ObjectPtr, value)
+	End Method
+	
+	Rem
+	bbdoc: Returns True, if gravity is taken from the world instead of the gravity parameter.
+	End Rem
+	Method UsesWorldGravity:Int()
+		Return bmx_b2buoyancycontroller_usesworldgravity(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Set to True, if gravity is to be taken from the world instead of the gravity parameter.
+	End Rem
+	Method SetUsesWorldGravity(value:Int)
+		bmx_b2buoyancycontroller_setusesworldgravity(b2ObjectPtr, value)
+	End Method
+	
+	Rem
+	bbdoc: Returns the gravity vector, if the world's gravity is not used.
+	End Rem
+	Method GetGravity:b2Vec2()
+		Return bmx_b2buoyancycontroller_getgravity(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Returns the gravity vector, if the world's gravity is not used.
+	End Rem
+	Method SetGravity(gravity:b2Vec2)
+		bmx_b2buoyancycontroller_setgravity(b2ObjectPtr, gravity)
+	End Method
+
+End Type
+
+Rem
+bbdoc: Applies a force every frame.
+End Rem
+Type b2ConstantForceController Extends b2Controller
+
+	Rem
+	bbdoc: Returns the force to apply.
+	End Rem
+	Method GetForce:b2Vec2()
+		Return bmx_b2constantaccelcontroller_getforce(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the force to apply.
+	End Rem
+	Method SetForce(force:b2Vec2)
+		bmx_b2constantaccelcontroller_setforce(b2ObjectPtr, force)
+	End Method
+
+End Type
+
+Rem
+bbdoc: Applies simplified gravity between every pair of bodies.
+End Rem
+Type b2GravityController Extends b2Controller
+
+	Rem
+	bbdoc: Returns the strength of the gravitiation force.
+	End Rem
+	Method GetForce:Float()
+		Return bmx_b2gravitycontroller_getforce(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the strength of the gravitiation force.
+	End Rem
+	Method SetForce(force:Float)
+		bmx_b2gravitycontroller_setforce(b2ObjectPtr, force)
+	End Method
+	
+	Rem
+	bbdoc: Returns whether gravity is proportional to r^-2 (True), otherwise r^-1 (False).
+	End Rem
+	Method IsInvSqr:Int()
+		Return bmx_b2gravitycontroller_isinvsqr(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets whether gravity is proportional to r^-2 (True), otherwise r^-1 (False).
+	End Rem
+	Method SetIsInvSqr(value:Int)
+		bmx_b2gravitycontroller_setisinvsqr(b2ObjectPtr, value)
+	End Method
+
+End Type
+
+Rem
+bbdoc: Applies top down linear damping to the controlled bodies
+about: The damping is calculated by multiplying velocity by a matrix in local co-ordinates.
+End Rem
+Type b2TensorDampingController Extends b2Controller
+
+	Rem
+	bbdoc: Returns the tensor to use in damping model.
+	End Rem
+	Method GetTensor:b2Mat22()
+		Return bmx_b2tensordampingcontroller_gettensor(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Sets the tensor to use in damping model.
+	about: Some examples (matrixes in format (row1; row2) )
+	<table>
+	<th><td>Matrix</td><td>Description</td></th>
+	<tr><td>(-a 0;0 -a)</td><td>Standard isotropic damping with strength a</td></tr>
+	<tr><td>(0 a;-a 0)</td><td>Electron in fixed field - a force at right angles to velocity with proportional magnitude</td></tr>
+	<tr><td>(-a 0;0 -b)</td><td>Differing x and y damping. Useful e.g. for top-down wheels.</td></tr>
+	</table>
+	<p>
+	By the way, tensor in this case just means matrix, don't let the terminology get you down.
+	</p>
+	End Rem
+	Method SetTensor(tensor:b2Mat22)
+		bmx_b2tensordampingcontroller_settensor(b2ObjectPtr, tensor)
+	End Method
+	
+	Rem
+	bbdoc: Returns the maximum amount of damping.
+	End Rem
+	Method GetMaxTimestep:Float()
+		Return bmx_b2tensordampingcontroller_getmaxtimestep(b2ObjectPtr)
+	End Method
+	
+	Rem
+	bbdoc: Set this to a positive number to clamp the maximum amount of damping done.
+	End Rem
+	Method SetMaxTimestep(timestep:Float)
+		bmx_b2tensordampingcontroller_setmaxtimestep(b2ObjectPtr, timestep)
+	End Method
+
+End Type
+
+Rem
+bbdoc: Perform the cross product on a vector and a scalar.
+about: In 2D this produces a vector.
+End Rem
+Function b2Cross:b2Vec2(a:b2Vec2, s:Float)
+	Return bmx_b2cross(a, s)
+End Function
+
+Rem
+bbdoc: Perform the cross product on a scalar and a vector.
+about: In 2D this produces a vector.
+End Rem
+Function b2CrossF:b2Vec2(s:Float, a:b2Vec2)
+	Return bmx_b2crossf(s, a)
+End Function
+
+Rem
+bbdoc: Peform the dot product on two vectors.
+End Rem
+Function b2Dot:Float(a:b2Vec2, b:b2Vec2)
+	Return bmx_b2dot(a, b)
+End Function
+
+Rem
+bbdoc: Multiply a matrix times a vector.
+about: If a rotation matrix is provided, then this transforms the vector from one frame to another.
+End Rem
+Function b2Mul:b2Vec2(A:b2Mat22, v:b2Vec2)
+	Return bmx_b2mul(A, v)
+End Function
+
+Rem
+bbdoc: Multiply a matrix transpose times a vector.
+about: If a rotation matrix is provided, then this transforms the vector from one frame to another
+(inverse transform).
+End Rem
+Function b2MulT:b2Vec2(A:b2Mat22, v:b2Vec2)
+	Return bmx_b2mult(A, v)
+End Function
+
+Rem
+bbdoc: 
+end rem
+Function b2MulF:b2Vec2(T:b2XForm, v:b2Vec2)
+	Return bmx_b2mulf(T, v)
+End Function
+
+Rem
+bbdoc: 
+end rem
+Function b2MulTF:b2Vec2(T:b2XForm, v:b2Vec2)
+	Return bmx_b2multf(T, v)
+End Function
+
+Extern
+	Function bmx_b2world_create:Byte Ptr(worldAABB:b2AABB Var, gravity:b2Vec2 Var, doSleep:Int)
+	Function bmx_b2world_setgravity(handle:Byte Ptr, gravity:b2Vec2 Var)
+	Function bmx_b2world_raycastone:Byte Ptr(handle:Byte Ptr, segment:b2Segment Var, lambda:Float Ptr, normal:b2Vec2 Var, solidShapes:Int)
+	Function bmx_b2world_inrange:Int(handle:Byte Ptr, aabb:b2AABB Var)
+
+	Function bmx_b2abb_isvalid:Int(handle:b2AABB Var)
+
+	Function bmx_b2vec2_add(v:b2Vec2 Var, vec:b2Vec2 Var)
+	Function bmx_b2vec2_copy(v:b2Vec2 Var, vec:b2Vec2 Var)
+	Function bmx_b2vec2_set(v:b2Vec2 Var, x:Float, y:Float)
+	Function bmx_b2vec2_subtract:b2Vec2(v:b2Vec2 Var, vec:b2Vec2 Var)
+	Function bmx_b2vec2_length:Float(v:b2Vec2 Var)
+	Function bmx_b2vec2_multiply(v:b2Vec2 Var, value:Float)
+	Function bmx_b2vec2_plus:b2Vec2(v:b2Vec2 Var, vec:b2Vec2 Var)
+	Function bmx_b2vec2_normalize:Float(v:b2Vec2 Var)
+	Function bmx_b2vec2_lengthsquared:Float(v:b2Vec2 Var)
+	
+	Function bmx_b2mat22_createangle(handle:b2Mat22 Var, angle:Float)
+	Function bmx_b2mat22_setangle(handle:b2Mat22 Var, angle:Float)
+	Function bmx_b2mat22_getangle:Float(handle:b2Mat22 Var)
+	Function bmx_b2mat22_getinverse:b2Mat22(handle:b2Mat22 Var)
+
+	Function bmx_b2obb_getrotationmatrix:b2Mat22(handle:Byte Ptr)
+	Function bmx_b2obb_getcenter:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2obb_getextents:b2Vec2(handle:Byte Ptr)
+
+	Function bmx_b2revolutejointdef_initialize(handle:Byte Ptr, body1:Byte Ptr, body2:Byte Ptr, anchor:b2Vec2 Var)
+	Function bmx_b2revolutejointdef_setlocalanchor1(handle:Byte Ptr, anchor:b2Vec2 Var)
+	Function bmx_b2revolutejointdef_setlocalanchor2(handle:Byte Ptr, anchor:b2Vec2 Var)
+	Function bmx_b2revolutejointdef_getlocalanchor1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2revolutejointdef_getlocalanchor2:b2Vec2(handle:Byte Ptr)
+
+	Function bmx_b2cross:b2Vec2(a:b2Vec2 Var, s:Float)
+	Function bmx_b2crossf:b2Vec2(s:Float, a:b2Vec2 Var)
+	Function bmx_b2mul:b2Vec2(A:b2Mat22 Var, v:b2Vec2 Var)
+	Function bmx_b2mult:b2Vec2(A:b2Mat22 Var, v:b2Vec2 Var)
+	Function bmx_b2mulf:b2Vec2(T:b2XForm Var, v:b2Vec2 Var)
+	Function bmx_b2multf:b2Vec2(T:b2XForm Var, v:b2Vec2 Var)
+	Function bmx_b2dot:Float(a:b2Vec2 Var, b:b2Vec2 Var)
+
+	Function bmx_b2body_setlinearvelocity(handle:Byte Ptr, v:b2Vec2 Var)
+	Function bmx_b2body_getlinearvelocity:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2body_applyforce(handle:Byte Ptr, force:b2Vec2 Var, point:b2Vec2 Var)
+	Function bmx_b2body_applyimpulse(handle:Byte Ptr, impulse:b2Vec2 Var, point:b2Vec2 Var)
+	Function bmx_b2body_getworldpoint:b2Vec2(handle:Byte Ptr, localPoint:b2Vec2 Var)
+	Function bmx_b2body_getworldvector:b2Vec2(handle:Byte Ptr, localVector:b2Vec2 Var)
+	Function bmx_b2body_getlocalpoint:b2Vec2(handle:Byte Ptr, worldPoint:b2Vec2 Var)
+	Function bmx_b2body_getlocalvector:b2Vec2(handle:Byte Ptr, worldVector:b2Vec2 Var)
+	Function bmx_b2body_setxform:Int(handle:Byte Ptr, position:b2Vec2 Var, angle:Float)
+	Function bmx_b2body_getxform:b2XForm(handle:Byte Ptr)
+	Function bmx_b2body_getposition:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2body_getworldcenter:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2body_getlocalcenter:b2Vec2(handle:Byte Ptr)
+
+	Function bmx_b2shape_testpoint:Int(handle:Byte Ptr, xf:b2XForm Var, p:b2Vec2 Var)
+	Function bmx_b2shape_computeaabb(handle:Byte Ptr, aabb:b2AABB Var, xf:b2XForm Var)
+	Function bmx_b2shape_computesweptaabb(handle:Byte Ptr, aabb:b2AABB Var, xf1:b2XForm Var, xf2:b2XForm Var)
+	
+	Function bmx_b2bodydef_setposition(handle:Byte Ptr, position:b2Vec2 Var)
+	Function bmx_b2bodydef_getposition:b2Vec2(handle:Byte Ptr)
+
+	Function bmx_b2massdata_setcenter(handle:Byte Ptr, center:b2Vec2 Var)
+	
+	Function bmx_b2polygondef_setasorientedbox(handle:Byte Ptr, hx:Float, hy:Float, center:b2Vec2 Var, angle:Float)
+	
+	Function bmx_b2polygonshape_getcentroid:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2polygonshape_getfirstvertex:b2Vec2(handle:Byte Ptr, xf:b2XForm Var)
+	Function bmx_b2polygonshape_centroid:b2Vec2(handle:Byte Ptr, xf:b2XForm Var)
+	Function bmx_b2polygonshape_support:b2Vec2(handle:Byte Ptr, xf:b2XForm Var, d:b2Vec2 Var)
+
+	Function bmx_b2circledef_setlocalposition(handle:Byte Ptr, pos:b2Vec2 Var)
+	Function bmx_b2circledef_getlocalposition:b2Vec2(handle:Byte Ptr)
+
+	Function bmx_b2circleshape_getlocalposition:b2Vec2(handle:Byte Ptr)
+
+	Function bmx_b2distancejointdef_initialize(handle:Byte Ptr, body1:Byte Ptr, body2:Byte Ptr, anchor1:b2Vec2 Var, anchor2:b2Vec2 Var)
+	Function bmx_b2distancejointdef_setlocalanchor1(handle:Byte Ptr, anchor:b2Vec2 Var)
+	Function bmx_b2distancejointdef_getlocalanchor1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2distancejointdef_setlocalanchor2(handle:Byte Ptr, anchor:b2Vec2 Var)
+	Function bmx_b2distancejointdef_getlocalanchor2:b2Vec2(handle:Byte Ptr)
+
+	Function bmx_b2edgeshape_getvertex1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2edgeshape_getvertex2:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2edgeshape_getcorevertex1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2edgeshape_getcorevertex2:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2edgeshape_getnormalvector:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2edgeshape_getdirectionvector:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2edgeshape_getcorner1vector:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2edgeshape_getcorner2vector:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2edgeshape_getfirstvertex:b2Vec2(handle:Byte Ptr, xf:b2XForm Var)
+	Function bmx_b2edgeshape_support:b2Vec2(handle:Byte Ptr, xf:b2XForm Var, d:b2Vec2 Var)
+
+	Function bmx_b2pulleyjointdef_initialize(handle:Byte Ptr, body1:Byte Ptr, body2:Byte Ptr, groundAnchor1:b2Vec2 Var, ..
+		groundAnchor2:b2Vec2 Var, anchor1:b2Vec2 Var, anchor2:b2Vec2 Var, ratio:Float)
+	Function bmx_b2pulleyjointdef_setgroundanchor1(handle:Byte Ptr, anchor:b2Vec2 Var)
+	Function bmx_b2pulleyjointdef_getgroundanchor1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2pulleyjointdef_setgroundanchor2(handle:Byte Ptr, anchor:b2Vec2 Var)
+	Function bmx_b2pulleyjointdef_getgroundanchor2:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2pulleyjointdef_setlocalanchor1(handle:Byte Ptr, anchor:b2Vec2 Var)
+	Function bmx_b2pulleyjointdef_getlocalanchor1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2pulleyjointdef_setlocalanchor2(handle:Byte Ptr, anchor:b2Vec2 Var)
+	Function bmx_b2pulleyjointdef_getlocalanchor2:b2Vec2(handle:Byte Ptr)
+
+	Function bmx_b2prismaticjointdef_initialize(handle:Byte Ptr, body1:Byte Ptr, body2:Byte Ptr, ..
+			anchor:b2Vec2 Var, axis:b2Vec2 Var)
+	Function bmx_b2prismaticjointdef_setlocalanchor1(handle:Byte Ptr, anchor:b2Vec2 Var)
+	Function bmx_b2prismaticjointdef_getlocalanchor1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2prismaticjointdef_setlocalanchor2(handle:Byte Ptr, anchor:b2Vec2 Var)
+	Function bmx_b2prismaticjointdef_getlocalanchor2:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2prismaticjointdef_setlocalaxis1(handle:Byte Ptr, axis:b2Vec2 Var)
+	Function bmx_b2prismaticjointdef_getlocalaxis1:b2Vec2(handle:Byte Ptr)
+
+	Function bmx_b2mousejointdef_settarget(handle:Byte Ptr, target:b2Vec2 Var)
+	Function bmx_b2mousejointdef_gettarget:b2Vec2(handle:Byte Ptr)
+
+	Function bmx_b2linejointdef_initialize(handle:Byte Ptr, body1:Byte Ptr, body2:Byte Ptr, anchor:b2Vec2 Var, axis:b2Vec2 Var)
+	Function bmx_b2linejointdef_setlocalanchor1(handle:Byte Ptr, anchor:b2Vec2 Var)
+	Function bmx_b2linejointdef_getlocalanchor1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2linejointdef_setlocalanchor2(handle:Byte Ptr, anchor:b2Vec2 Var)
+	Function bmx_b2linejointdef_getlocalanchor2:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2linejointdef_setlocalaxis1(handle:Byte Ptr, axis:b2Vec2 Var)
+	Function bmx_b2linejointdef_getlocalaxis1:b2Vec2(handle:Byte Ptr)
+
+	Function bmx_b2linejoint_getanchor1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2linejoint_getanchor2:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2linejoint_getreactionforce:b2Vec2(handle:Byte Ptr, inv_dt:Float)
+
+	Function bmx_b2distancejoint_getanchor1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2distancejoint_getanchor2:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2distancejoint_getreactionforce:b2Vec2(handle:Byte Ptr, inv_dt:Float)
+
+	Function bmx_b2revolutejoint_getanchor1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2revolutejoint_getanchor2:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2revolutejoint_getreactionforce:b2Vec2(handle:Byte Ptr, inv_dt:Float)
+
+	Function bmx_b2prismaticjoint_getanchor1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2prismaticjoint_getanchor2:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2prismaticjoint_getreactionforce:b2Vec2(handle:Byte Ptr, inv_dt:Float)
+
+	Function bmx_b2gearjoint_getanchor1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2gearjoint_getanchor2:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2gearjoint_getreactionforce:b2Vec2(handle:Byte Ptr, inv_dt:Float)
+
+	Function bmx_b2mousejoint_getanchor1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2mousejoint_getanchor2:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2mousejoint_getreactionforce:b2Vec2(handle:Byte Ptr, inv_dt:Float)
+	Function bmx_b2mousejoint_getlocalanchor:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2mousejoint_settarget(handle:Byte Ptr, target:b2Vec2 Var)
+	Function bmx_b2mousejoint_gettarget:b2Vec2(handle:Byte Ptr)
+
+	Function bmx_b2pulleyjoint_getanchor1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2pulleyjoint_getanchor2:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2pulleyjoint_getreactionforce:b2Vec2(handle:Byte Ptr, inv_dt:Float)
+	Function bmx_b2pulleyjoint_getgroundanchor1:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2pulleyjoint_getgroundanchor2:b2Vec2(handle:Byte Ptr)
+
+	Function bmx_b2buoyancycontrollerdef_getnormal:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2buoyancycontrollerdef_setnormal(handle:Byte Ptr, normal:b2Vec2 Var)
+	Function bmx_b2buoyancycontrollerdef_getvelocity:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2buoyancycontrollerdef_setvelocity(handle:Byte Ptr, velocity:b2Vec2 Var)
+	Function bmx_b2buoyancycontrollerdef_getgravity:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2buoyancycontrollerdef_setgravity(handle:Byte Ptr, gravity:b2Vec2 Var)
+
+	Function bmx_b2tensordampingcontrollerdef_gettensor:b2Mat22(handle:Byte Ptr)
+	Function bmx_b2tensordampingcontrollerdef_settensor(handle:Byte Ptr, tensor:b2Mat22 Var)
+
+	Function bmx_b2constantforcecontrollerdef_getforce:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2constantforcecontrollerdef_setforce(handle:Byte Ptr, force:b2Vec2 Var)
+
+	Function bmx_b2constantforcecontroller_getforce:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2constantforcecontroller_setforce(handle:Byte Ptr, force:b2Vec2 Var)
+
+	Function bmx_b2constantaccelcontrollerdef_getforce:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2constantaccelcontrollerdef_setforce(handle:Byte Ptr, force:b2Vec2 Var)
+
+	Function bmx_b2constantaccelcontroller_getforce:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2constantaccelcontroller_setforce(handle:Byte Ptr, force:b2Vec2 Var)
+
+	Function bmx_b2buoyancycontroller_getnormal:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2buoyancycontroller_setnormal(handle:Byte Ptr, normal:b2Vec2 Var)
+	Function bmx_b2buoyancycontroller_getvelocity:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2buoyancycontroller_setvelocity(handle:Byte Ptr, velocity:b2Vec2 Var)
+	Function bmx_b2buoyancycontroller_getgravity:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2buoyancycontroller_setgravity(handle:Byte Ptr, gravity:b2Vec2 Var)
+
+	Function bmx_b2tensordampingcontroller_gettensor:b2Mat22(handle:Byte Ptr)
+	Function bmx_b2tensordampingcontroller_settensor(handle:Byte Ptr, tensor:b2Mat22 Var)
+
+	Function bmx_b2contactpoint_getposition:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2contactpoint_getvelocity:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2contactpoint_getnormal:b2Vec2(handle:Byte Ptr)
+
+	Function bmx_b2contactresult_getposition:b2Vec2(handle:Byte Ptr)
+	Function bmx_b2contactresult_getnormal:b2Vec2(handle:Byte Ptr)
+
+End Extern

+ 464 - 0
box2d.mod/common.bmx

@@ -0,0 +1,464 @@
+' Copyright (c) 2008-2021 Bruce A Henderson
+' 
+' 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.
+' 
+SuperStrict
+
+Import "source.bmx"
+
+Extern
+
+	Function bmx_b2world_createbody:Byte Ptr(handle:Byte Ptr, def:Byte Ptr, body:Object)
+	Function bmx_b2world_destroybody(handle:Byte Ptr, body:Byte Ptr)
+	Function bmx_b2world_getgroundbody:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2world_setwarmstarting(handle:Byte Ptr, flag:Int)
+	Function bmx_b2world_setcontinuousphysics(handle:Byte Ptr, flag:Int)
+	Function bmx_b2world_validate(handle:Byte Ptr)
+	Function bmx_b2world_setdebugDraw(handle:Byte Ptr, debugDraw:Byte Ptr)
+	Function bmx_b2world_createjoint:Byte Ptr(handle:Byte Ptr, def:Byte Ptr)
+	Function bmx_b2world_destroyjoint(handle:Byte Ptr, joint:Byte Ptr)
+	Function bmx_b2world_getbodylist:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2world_getjointlist:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2world_setfilter(handle:Byte Ptr, filter:Byte Ptr)
+	Function bmx_b2world_setcontactlistener(handle:Byte Ptr, listener:Byte Ptr)
+	Function bmx_b2world_setboundarylistener(handle:Byte Ptr, listener:Byte Ptr)
+	Function bmx_b2world_getcontactlist:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2world_getproxycount:Int(handle:Byte Ptr)
+	Function bmx_b2world_getpaircount:Int(handle:Byte Ptr)
+	Function bmx_b2world_getbodycount:Int(handle:Byte Ptr)
+	Function bmx_b2world_getjointcount:Int(handle:Byte Ptr)
+	Function bmx_b2world_free(handle:Byte Ptr)
+	Function bmx_b2world_setdestructionlistener(handle:Byte Ptr, listener:Byte Ptr)
+	Function bmx_b2world_refilter(handle:Byte Ptr, shape:Byte Ptr)
+	Function bmx_b2world_createcontroller:Byte Ptr(handle:Byte Ptr, def:Byte Ptr, _type:Int)
+	Function bmx_b2world_destroycontroller(handle:Byte Ptr, controller:Byte Ptr)
+
+	Function bmx_b2bodydef_create:Byte Ptr()
+	Function bmx_b2bodydef_delete(handle:Byte Ptr)
+	Function bmx_b2bodydef_setpositionxy(handle:Byte Ptr, x:Float, y:Float)
+	Function bmx_b2bodydef_setangle(handle:Byte Ptr, angle:Float)
+	Function bmx_b2bodydef_setmassdata(handle:Byte Ptr, data:Byte Ptr)
+	Function bmx_b2bodydef_issleeping:Int(handle:Byte Ptr)
+	Function bmx_b2bodydef_setissleeping(handle:Byte Ptr, sleeping:Int)
+	Function bmx_b2bodydef_setfixedrotation(handle:Byte Ptr, fixed:Int)
+	Function bmx_b2bodydef_getfixedrotation:Int(handle:Byte Ptr)
+	Function bmx_b2bodydef_setisbullet(handle:Byte Ptr, bullet:Int)
+	Function bmx_b2bodydef_setlineardamping(handle:Byte Ptr, damping:Float)
+	Function bmx_b2bodydef_getlineardamping:Float(handle:Byte Ptr)
+	Function bmx_b2bodydef_setangulardamping(handle:Byte Ptr, damping:Float)
+	Function bmx_b2bodydef_getangulardamping:Float(handle:Byte Ptr)
+	Function bmx_b2bodydef_setallowsleep(handle:Byte Ptr, allow:Int)
+	Function bmx_b2bodydef_getallowsleep:Int(handle:Byte Ptr)
+	Function bmx_b2bodydef_getangle:Float(handle:Byte Ptr)
+	Function bmx_b2bodydef_isbullet:Int(handle:Byte Ptr)
+	Function bmx_b2bodydef_getmassdata:Byte Ptr(handle:Byte Ptr)
+
+	Function bmx_b2world_dostep(handle:Byte Ptr, timeStep:Float, velocityIterations:Int, positionIterations:Int)
+
+	Function bmx_b2shapedef_setfriction(handle:Byte Ptr, friction:Float)
+	Function bmx_b2shapedef_setrestitution(handle:Byte Ptr, restitution:Float)
+	Function bmx_b2shapedef_setdensity(handle:Byte Ptr, density:Float)
+	Function bmx_b2shapedef_setfilter(handle:Byte Ptr, filter:Byte Ptr)
+	Function bmx_b2shapedef_getfilter:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2shapedef_setissensor(handle:Byte Ptr, sensor:Int)
+	Function bmx_b2shapedef_issensor:Int(handle:Byte Ptr)
+	Function bmx_b2shapedef_getfriction:Float(handle:Byte Ptr)
+	Function bmx_b2shapedef_getrestitution:Float(handle:Byte Ptr)
+	Function bmx_b2shapedef_getdensity:Float(handle:Byte Ptr)
+
+	Function bmx_b2polygondef_create:Byte Ptr()
+	Function bmx_b2polygondef_setasbox(handle:Byte Ptr, hx:Float, hy:Float)
+	Function bmx_b2polygondef_delete(handle:Byte Ptr)
+
+	Function bmx_b2body_createshape:Byte Ptr(handle:Byte Ptr, def:Byte Ptr)
+	Function bmx_b2body_destroyshape(handle:Byte Ptr, shape:Byte Ptr)
+	Function bmx_b2body_setmassfromshapes(handle:Byte Ptr)
+	Function bmx_b2body_getangle:Float(handle:Byte Ptr)
+	Function bmx_b2body_getmaxbody:Object(handle:Byte Ptr)
+	Function bmx_b2body_getnext:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2body_getshapelist:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2body_isstatic:Int(handle:Byte Ptr)
+	Function bmx_b2body_isdynamic:Int(handle:Byte Ptr)
+	Function bmx_b2body_isfrozen:Int(handle:Byte Ptr)
+	Function bmx_b2body_issleeping:Int(handle:Byte Ptr)
+	Function bmx_b2body_allowsleeping(handle:Byte Ptr, flag:Int)
+	Function bmx_b2body_wakeup(handle:Byte Ptr)
+	Function bmx_b2body_puttosleep(handle:Byte Ptr)
+	Function bmx_b2body_isbullet:Int(handle:Byte Ptr)
+	Function bmx_b2body_setbullet(handle:Byte Ptr, flag:Int)
+	Function bmx_b2body_setangularvelocity(handle:Byte Ptr, omega:Float)
+	Function bmx_b2body_getangularvelocity:Float(handle:Byte Ptr)
+	Function bmx_b2body_applytorque(handle:Byte Ptr, torque:Float)
+	Function bmx_b2body_getmass:Float(handle:Byte Ptr)
+	Function bmx_b2body_getinertia:Float(handle:Byte Ptr)
+	Function bmx_b2body_getjointlist:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2body_getworld:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2body_setmass(handle:Byte Ptr, massData:Byte Ptr)
+
+	Function bmx_b2debugdraw_create:Byte Ptr(handle:Object)
+	Function bmx_b2debugdraw_setflags(handle:Byte Ptr, flags:Int)
+	Function bmx_b2debugdraw_getflags:Int(handle:Byte Ptr)
+	Function bmx_b2debugdraw_appendflags(handle:Byte Ptr, flags:Int)
+	Function bmx_b2debugdraw_clearflags(handle:Byte Ptr, flags:Int)
+
+	Function bmx_b2circledef_create:Byte Ptr()
+	Function bmx_b2circledef_setradius(handle:Byte Ptr, radius:Float)
+	Function bmx_b2circledef_delete(handle:Byte Ptr)
+	Function bmx_b2circledef_getradius:Float(handle:Byte Ptr)
+
+	Function bmx_b2shape_issensor:Int(handle:Byte Ptr)
+	Function bmx_b2shape_getbody:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2shape_getmaxshape:Object(handle:Byte Ptr)
+	Function bmx_b2shape_getnext:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2shape_getsweepradius:Float(handle:Byte Ptr)
+	Function bmx_b2shape_getfriction:Float(handle:Byte Ptr)
+	Function bmx_b2shape_getrestitution:Float(handle:Byte Ptr)
+	Function bmx_b2shape_computemass(handle:Byte Ptr, data:Byte Ptr)
+	Function bmx_b2shape_getfilterdata:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2shape_setfilterdata(handle:Byte Ptr, data:Byte Ptr)
+	Function bmx_b2shape_setfriction(handle:Byte Ptr, friction:Float)
+	Function bmx_b2shape_setrestitution(handle:Byte Ptr, restitution:Float)
+	Function bmx_b2shape_getdensity:Float(handle:Byte Ptr)
+	Function bmx_b2shape_setdensity(handle:Byte Ptr, density:Float)
+
+	Function bmx_b2jointdef_setcollideconnected(handle:Byte Ptr, collideConnected:Int)
+	Function bmx_b2jointdef_getcollideconnected:Int(handle:Byte Ptr)
+	Function bmx_b2jointdef_setbody1(handle:Byte Ptr, body:Byte Ptr)
+	Function bmx_b2jointdef_getbody1:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2jointdef_setbody2(handle:Byte Ptr, body:Byte Ptr)
+	Function bmx_b2jointdef_getbody2:Byte Ptr(handle:Byte Ptr)
+
+	Function bmx_b2revolutejointdef_create:Byte Ptr()
+	Function bmx_b2revolutejointdef_delete(handle:Byte Ptr)
+	Function bmx_b2revolutejointdef_islimitenabled:Int(handle:Byte Ptr)
+	Function bmx_b2revolutejointdef_enablelimit(handle:Byte Ptr, limit:Int)
+	Function bmx_b2revolutejointdef_getlowerangle:Float(handle:Byte Ptr)
+	Function bmx_b2revolutejointdef_setlowerangle(handle:Byte Ptr, angle:Float)
+	Function bmx_b2revolutejointdef_getupperangle:Float(handle:Byte Ptr)
+	Function bmx_b2revolutejointdef_setupperangle(handle:Byte Ptr, angle:Float)
+	Function bmx_b2revolutejointdef_ismotorenabled:Int(handle:Byte Ptr)
+	Function bmx_b2revolutejointdef_enablemotor(handle:Byte Ptr, value:Int)
+	Function bmx_b2revolutejointdef_getmotorspeed:Float(handle:Byte Ptr)
+	Function bmx_b2revolutejointdef_setmotorspeed(handle:Byte Ptr, speed:Float)
+	Function bmx_b2revolutejointdef_getmaxmotortorque:Float(handle:Byte Ptr)
+	Function bmx_b2revolutejointdef_setmaxmotortorque(handle:Byte Ptr, torque:Float)
+	Function bmx_b2revolutejointdef_getreferenceangle:Float(handle:Byte Ptr)
+	Function bmx_b2revolutejointdef_setreferenceangle(handle:Byte Ptr, angle:Float)
+
+	Function bmx_b2joint_getmaxjoint:Object(handle:Byte Ptr)
+	Function bmx_b2joint_getbody1:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2joint_getbody2:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2joint_getnext:Byte Ptr(handle:Byte Ptr)
+
+	Function bmx_b2massdata_new:Byte Ptr()
+	Function bmx_b2massdata_delete(handle:Byte Ptr)
+	Function bmx_b2massdata_setmass(handle:Byte Ptr, mass:Float)
+	Function bmx_b2massdata_seti(handle:Byte Ptr, i:Float)
+
+	Function bmx_b2jointedge_getother:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2jointedge_getjoint:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2jointedge_getprev:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2jointedge_getnext:Byte Ptr(handle:Byte Ptr)
+
+	Function bmx_b2contactfilter_new:Byte Ptr(handle:Object)
+	Function bmx_b2contactfilter_delete(handle:Byte Ptr)
+
+	Function bmx_b2contactlistener_new:Byte Ptr(handle:Object)
+	Function bmx_b2contactlistener_delete(handle:Byte Ptr)
+
+	Function bmx_b2boundarylistener_new:Byte Ptr(handle:Object)
+	Function bmx_b2boundarylistener_delete(handle:Byte Ptr)
+
+	Function bmx_b2distancejointdef_new:Byte Ptr()
+	Function bmx_b2distancejointdef_setlength(handle:Byte Ptr, length:Float)
+	Function bmx_b2distancejointdef_getlength:Float(handle:Byte Ptr)
+	Function bmx_b2distancejointdef_delete(handle:Byte Ptr)
+	Function bmx_b2distancejointdef_setfrequencyhz(handle:Byte Ptr, freq:Float)
+	Function bmx_b2distancejointdef_setdampingratio(handle:Byte Ptr, ratio:Float)
+
+	Function bmx_b2prismaticjointdef_create:Byte Ptr()
+	Function bmx_b2prismaticjointdef_enablelimit(handle:Byte Ptr, value:Int)
+	Function bmx_b2prismaticjointdef_islimitenabled:Int(handle:Byte Ptr)
+	Function bmx_b2prismaticjointdef_setlowertranslation(handle:Byte Ptr, Translation:Float)
+	Function bmx_b2prismaticjointdef_getlowertranslation:Float(handle:Byte Ptr)
+	Function bmx_b2prismaticjointdef_setuppertranslation(handle:Byte Ptr, Translation:Float)
+	Function bmx_b2prismaticjointdef_getuppertranslation:Float(handle:Byte Ptr)
+	Function bmx_b2prismaticjointdef_enablemotor(handle:Byte Ptr, value:Int)
+	Function bmx_b2prismaticjointdef_ismotorenabled:Int(handle:Byte Ptr)
+	Function bmx_b2prismaticjointdef_setmaxmotorforce(handle:Byte Ptr, force:Float)
+	Function bmx_b2prismaticjointdef_getmaxmotorforce:Float(handle:Byte Ptr)
+	Function bmx_b2prismaticjointdef_setmotorspeed(handle:Byte Ptr, speed:Float)
+	Function bmx_b2prismaticjointdef_getmotorspeed:Float(handle:Byte Ptr)
+	Function bmx_b2prismaticjointdef_delete(handle:Byte Ptr)
+	Function bmx_b2prismaticjointdef_setreferenceangle(handle:Byte Ptr, angle:Float)
+	Function bmx_b2prismaticjointdef_getreferenceangle:Float(handle:Byte Ptr)
+
+	Function bmx_b2revolutejoint_getlowerlimit:Float(handle:Byte Ptr)
+	Function bmx_b2revolutejoint_getupperlimit:Float(handle:Byte Ptr)
+	Function bmx_b2revolutejoint_setlimits(handle:Byte Ptr, lowerLimit:Float, upperLimit:Float)
+	Function bmx_b2revolutejoint_ismotorenabled:Int(handle:Byte Ptr)
+	Function bmx_b2revolutejoint_enablemotor(handle:Byte Ptr, flag:Int)
+	Function bmx_b2revolutejoint_setmotorspeed(handle:Byte Ptr, speed:Float)
+	Function bmx_b2revolutejoint_getmotorspeed:Float(handle:Byte Ptr)
+	Function bmx_b2revolutejoint_setmaxmotortorque(handle:Byte Ptr, torque:Float)
+	Function bmx_b2revolutejoint_getmotortorque:Float(handle:Byte Ptr)
+	Function bmx_b2revolutejoint_islimitenabled:Int(handle:Byte Ptr)
+	Function bmx_b2revolutejoint_enablelimit(handle:Byte Ptr, flag:Int)
+	Function bmx_b2revolutejoint_getreactiontorque:Float(handle:Byte Ptr, inv_dt:Float)
+	Function bmx_b2revolutejoint_getjointangle:Float(handle:Byte Ptr)
+	Function bmx_b2revolutejoint_getjointspeed:Float(handle:Byte Ptr)
+
+	Function bmx_b2prismaticjoint_getjointspeed:Float(handle:Byte Ptr)
+	Function bmx_b2prismaticjoint_islimitenabled:Int(handle:Byte Ptr)
+	Function bmx_b2prismaticjoint_enablelimit(handle:Byte Ptr, flag:Int)
+	Function bmx_b2prismaticjoint_getlowerlimit:Float(handle:Byte Ptr)
+	Function bmx_b2prismaticjoint_getupperlimit:Float(handle:Byte Ptr)
+	Function bmx_b2prismaticjoint_setlimits(handle:Byte Ptr, lowerLimit:Float, upperLimit:Float)
+	Function bmx_b2prismaticjoint_ismotorenabled:Int(handle:Byte Ptr)
+	Function bmx_b2prismaticjoint_enablemotor(handle:Byte Ptr, flag:Int)
+	Function bmx_b2prismaticjoint_setmotorspeed(handle:Byte Ptr, speed:Float)
+	Function bmx_b2prismaticjoint_getmotorspeed:Float(handle:Byte Ptr)
+	Function bmx_b2prismaticjoint_setmaxmotorforce(handle:Byte Ptr, force:Float)
+	Function bmx_b2prismaticjoint_getmotorforce:Float(handle:Byte Ptr)
+	Function bmx_b2prismaticjoint_getreactiontorque:Float(handle:Byte Ptr, inv_dt:Float)
+	Function bmx_b2prismaticjoint_getjointtranslation:Float(handle:Byte Ptr)
+
+	Function bmx_b2xform_create:Byte Ptr()
+	Function bmx_b2xform_getposition:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2xform_setposition(handle:Byte Ptr, pos:Byte Ptr)
+	Function bmx_b2xform_getr:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2xform_setr(handle:Byte Ptr, r:Byte Ptr)
+	Function bmx_b2xform_delete(handle:Byte Ptr)
+
+	Function bmx_b2contact_getshape1:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2contact_getshape2:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2contact_getnext:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2contact_issolid:Int(handle:Byte Ptr)
+	Function bmx_b2contact_getmanifoldcount:Int(handle:Byte Ptr)
+
+	Function bmx_b2contactresult_getshape1:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2contactresult_getshape2:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2contactresult_getnormalimpulse:Float(handle:Byte Ptr)
+	Function bmx_b2contactresult_gettangentimpulse:Float(handle:Byte Ptr)
+
+	Function bmx_b2contactpoint_getshape1:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2contactpoint_getshape2:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2contactpoint_getseparation:Float(handle:Byte Ptr)
+	Function bmx_b2contactpoint_getfriction:Float(handle:Byte Ptr)
+	Function bmx_b2contactpoint_getrestitution:Float(handle:Byte Ptr)
+
+	Function bmx_b2filterdata_create:Byte Ptr()
+	Function bmx_b2filterdata_getcategorybits:Short(handle:Byte Ptr)
+	Function bmx_b2filterdata_setcategorybits(handle:Byte Ptr, categoryBits:Short)
+	Function bmx_b2filterdata_getmaskbits:Short(handle:Byte Ptr)
+	Function bmx_b2filterdata_setmaskbits(handle:Byte Ptr, maskBits:Short)
+	Function bmx_b2filterdata_getgroupindex:Short(handle:Byte Ptr)
+	Function bmx_b2filterdata_setgroupindex(handle:Byte Ptr, index:Int)
+	Function bmx_b2filterdata_delete(handle:Byte Ptr)
+
+	Function bmx_b2gearjointdef_new:Byte Ptr()
+	Function bmx_b2gearjointdef_setjoint1(handle:Byte Ptr, joint:Byte Ptr)
+	Function bmx_b2gearjointdef_setjoint2(handle:Byte Ptr, joint:Byte Ptr)
+	Function bmx_b2gearjointdef_setratio(handle:Byte Ptr, ratio:Float)
+	Function bmx_b2gearjointdef_delete(handle:Byte Ptr)
+
+	Function bmx_b2gearjoint_getreactiontorque:Float(handle:Byte Ptr, inv_dt:Float)
+	Function bmx_b2gearjoint_getratio:Float(handle:Byte Ptr)
+
+	Function bmx_b2mousejoint_getreactiontorque:Float(handle:Byte Ptr, inv_dt:Float)
+
+	Function bmx_b2pulleyjoint_getreactiontorque:Float(handle:Byte Ptr, inv_dt:Float)
+	Function bmx_b2pulleyjoint_getlength1:Float(handle:Byte Ptr)
+	Function bmx_b2pulleyjoint_getlength2:Float(handle:Byte Ptr)
+	Function bmx_b2pulleyjoint_getratio:Float(handle:Byte Ptr)
+
+	Function bmx_b2distancejoint_getreactiontorque:Float(handle:Byte Ptr, inv_dt:Float)
+
+	Function bmx_b2mousejointdef_new:Byte Ptr()
+	Function bmx_b2mousejointdef_setmaxforce(handle:Byte Ptr, maxForce:Float)
+	Function bmx_b2mousejointdef_getmaxforce:Float(handle:Byte Ptr)
+	Function bmx_b2mousejointdef_setfrequencyhz(handle:Byte Ptr, frequency:Float)
+	Function bmx_b2mousejointdef_getfrequencyhz:Float(handle:Byte Ptr)
+	Function bmx_b2mousejointdef_setdampingration(handle:Byte Ptr, ratio:Float)
+	Function bmx_b2mousejointdef_getdampingratio:Float(handle:Byte Ptr)
+	Function bmx_b2mousejointdef_delete(handle:Byte Ptr)
+
+	Function bmx_b2pulleyjointdef_create:Byte Ptr()
+	Function bmx_b2pulleyjointdef_setlength1(handle:Byte Ptr, length:Float)
+	Function bmx_b2pulleyjointdef_getlength1:Float(handle:Byte Ptr)
+	Function bmx_b2pulleyjointdef_setmaxlength1(handle:Byte Ptr, maxLength:Float)
+	Function bmx_b2pulleyjointdef_getmaxlength1:Float(handle:Byte Ptr)
+	Function bmx_b2pulleyjointdef_setlength2(handle:Byte Ptr, length:Float)
+	Function bmx_b2pulleyjointdef_getlength2:Float(handle:Byte Ptr)
+	Function bmx_b2pulleyjointdef_setmaxlength2(handle:Byte Ptr, maxLength:Float)
+	Function bmx_b2pulleyjointdef_getmaxlength2:Float(handle:Byte Ptr)
+	Function bmx_b2pulleyjointdef_setratio(handle:Byte Ptr, ratio:Float)
+	Function bmx_b2pulleyjointdef_getratio:Float(handle:Byte Ptr)
+	Function bmx_b2pulleyjointdef_delete(handle:Byte Ptr)
+
+	Function bmx_b2destructionlistener_new:Byte Ptr(handle:Object)
+	Function bmx_b2destructionlistener_delete(handle:Byte Ptr)
+
+	Function bmx_b2polygonshape_getobb:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2polygonshape_getvertexcount:Int(handle:Byte Ptr)
+
+	Function bmx_b2circleshape_getradius:Float(handle:Byte Ptr)
+
+	Function bmx_b2segment_createxy:Byte Ptr(x1:Float, y1:Float, x2:Float, y2:Float)
+	Function bmx_b2segment_create:Byte Ptr(p1:Byte Ptr, p2:Byte Ptr)
+	Function bmx_b2segment_getstartpoint:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2segment_getendpoint:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2segment_setstartpoint(handle:Byte Ptr, point:Byte Ptr)
+	Function bmx_b2segment_setendpoint(handle:Byte Ptr, point:Byte Ptr)
+	Function bmx_b2segment_delete(handle:Byte Ptr)
+
+	Function bmx_b2linejointdef_create:Byte Ptr()
+	Function bmx_b2linejointdef_enablelimit(handle:Byte Ptr, limit:Int)
+	Function bmx_b2linejointdef_getlimit:Int(handle:Byte Ptr)
+	Function bmx_b2linejointdef_setlowertranslation(handle:Byte Ptr, Translation:Float)
+	Function bmx_b2linejointdef_getlowertranslation:Float(handle:Byte Ptr)
+	Function bmx_b2linejointdef_setuppertranslation(handle:Byte Ptr, Translation:Float)
+	Function bmx_b2linejointdef_getuppertranslation:Float(handle:Byte Ptr)
+	Function bmx_b2linejointdef_enablemotor(handle:Byte Ptr, enable:Int)
+	Function bmx_b2linejointdef_ismotorenabled:Int(handle:Byte Ptr)
+	Function bmx_b2linejointdef_setmaxmotorforce(handle:Byte Ptr, maxForce:Float)
+	Function bmx_b2linejointdef_getmaxmotorforce:Float(handle:Byte Ptr)
+	Function bmx_b2linejointdef_setmotorspeed(handle:Byte Ptr, speed:Float)
+	Function bmx_b2linejointdef_getmotorspeed:Float(handle:Byte Ptr)
+	Function bmx_b2linejointdef_delete(handle:Byte Ptr)
+
+	Function bmx_b2linejoint_getreactiontorque:Float(handle:Byte Ptr, inv_dt:Float)
+	Function bmx_b2linejoint_getjointtranslation:Float(handle:Byte Ptr)
+	Function bmx_b2linejoint_getjointspeed:Float(handle:Byte Ptr)
+	Function bmx_b2linejoint_islimitenabled:Int(handle:Byte Ptr)
+	Function bmx_b2linejoint_enablelimit(handle:Byte Ptr, flag:Int)
+	Function bmx_b2linejoint_getlowerlimit:Float(handle:Byte Ptr)
+	Function bmx_b2linejoint_getupperlimit:Float(handle:Byte Ptr)
+	Function bmx_b2linejoint_setlimits(handle:Byte Ptr, _lower:Float, _upper:Float)
+	Function bmx_b2linejoint_ismotorenabled:Int(handle:Byte Ptr)
+	Function bmx_b2linejoint_enablemotor(handle:Byte Ptr, flag:Int)
+	Function bmx_b2linejoint_setmotorspeed(handle:Byte Ptr, speed:Float)
+	Function bmx_b2linejoint_getmotorspeed:Float(handle:Byte Ptr)
+	Function bmx_b2linejoint_setmaxmotorforce(handle:Byte Ptr, force:Float)
+	Function bmx_b2linejoint_getmotorforce:Float(handle:Byte Ptr)
+
+	Function bmx_b2edgechaindef_create:Byte Ptr()
+	Function bmx_b2edgechaindef_getdef:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2edgechaindef_isaloop:Int(handle:Byte Ptr)
+	Function bmx_b2edgechaindef_setisaloop(handle:Byte Ptr, value:Int)
+	Function bmx_b2edgechaindef_delete(handle:Byte Ptr)
+
+	Function bmx_b2edgeshape_getlength:Float(handle:Byte Ptr)
+	Function bmx_b2edgeshape_corner1isconvex:Int(handle:Byte Ptr)
+	Function bmx_b2edgeshape_corner2isconvex:Int(handle:Byte Ptr)
+	Function bmx_b2edgeshape_getnextedge:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2edgeshape_getprevedge:Byte Ptr(handle:Byte Ptr)
+
+	Function bmx_b2buoyancycontrollerdef_create:Byte Ptr()
+	Function bmx_b2buoyancycontrollerdef_getoffset:Float(handle:Byte Ptr)
+	Function bmx_b2buoyancycontrollerdef_setoffset(handle:Byte Ptr, offset:Float)
+	Function bmx_b2buoyancycontrollerdef_getdensity:Float(handle:Byte Ptr)
+	Function bmx_b2buoyancycontrollerdef_setdensity(handle:Byte Ptr, density:Float)
+	Function bmx_b2buoyancycontrollerdef_getlineardrag:Float(handle:Byte Ptr)
+	Function bmx_b2buoyancycontrollerdef_setlineardrag(handle:Byte Ptr, drag:Float)
+	Function bmx_b2buoyancycontrollerdef_getangulardrag:Float(handle:Byte Ptr)
+	Function bmx_b2buoyancycontrollerdef_setangulardrag(handle:Byte Ptr, drag:Float)
+	Function bmx_b2buoyancycontrollerdef_usesdensity:Int(handle:Byte Ptr)
+	Function bmx_b2buoyancycontrollerdef_setusesdensity(handle:Byte Ptr, value:Int)
+	Function bmx_b2buoyancycontrollerdef_usesworldgravity:Int(handle:Byte Ptr)
+	Function bmx_b2buoyancycontrollerdef_setusesworldgravity(handle:Byte Ptr, value:Int)
+	Function bmx_b2buoyancycontrollerdef_delete(handle:Byte Ptr)
+
+	Function bmx_b2buoyancycontroller_getoffset:Float(handle:Byte Ptr)
+	Function bmx_b2buoyancycontroller_setoffset(handle:Byte Ptr, offset:Float)
+	Function bmx_b2buoyancycontroller_getdensity:Float(handle:Byte Ptr)
+	Function bmx_b2buoyancycontroller_setdensity(handle:Byte Ptr, density:Float)
+	Function bmx_b2buoyancycontroller_getlineardrag:Float(handle:Byte Ptr)
+	Function bmx_b2buoyancycontroller_setlineardrag(handle:Byte Ptr, drag:Float)
+	Function bmx_b2buoyancycontroller_getangulardrag:Float(handle:Byte Ptr)
+	Function bmx_b2buoyancycontroller_setangulardrag(handle:Byte Ptr, drag:Float)
+	Function bmx_b2buoyancycontroller_usesdensity:Int(handle:Byte Ptr)
+	Function bmx_b2buoyancycontroller_setusesdensity(handle:Byte Ptr, value:Int)
+	Function bmx_b2buoyancycontroller_usesworldgravity:Int(handle:Byte Ptr)
+	Function bmx_b2buoyancycontroller_setusesworldgravity(handle:Byte Ptr, value:Int)
+
+	Function bmx_b2tensordampingcontrollerdef_create:Byte Ptr()
+	Function bmx_b2tensordampingcontrollerdef_delete(handle:Byte Ptr)
+	Function bmx_b2tensordampingcontrollerdef_getmaxtimestep:Float(handle:Byte Ptr)
+	Function bmx_b2tensordampingcontrollerdef_setmaxtimestep(handle:Byte Ptr, timestep:Float)
+	Function bmx_b2tensordampingcontrollerdef_setaxisaligned(handle:Byte Ptr, xDamping:Float, yDamping:Float)
+
+	Function bmx_b2tensordampingcontroller_getmaxtimestep:Float(handle:Byte Ptr)
+	Function bmx_b2tensordampingcontroller_setmaxtimestep(handle:Byte Ptr, timestep:Float)
+
+	Function bmx_b2gravitycontrollerdef_create:Byte Ptr()
+	Function bmx_b2gravitycontrollerdef_delete(handle:Byte Ptr)
+	Function bmx_b2gravitycontrollerdef_getforce:Float(handle:Byte Ptr)
+	Function bmx_b2gravitycontrollerdef_setforce(handle:Byte Ptr, force:Float)
+	Function bmx_b2gravitycontrollerdef_isinvsqr:Int(handle:Byte Ptr)
+	Function bmx_b2gravitycontrollerdef_setisinvsqr(handle:Byte Ptr, value:Int)
+
+	Function bmx_b2gravitycontroller_getforce:Float(handle:Byte Ptr)
+	Function bmx_b2gravitycontroller_setforce(handle:Byte Ptr, force:Float)
+	Function bmx_b2gravitycontroller_isinvsqr:Int(handle:Byte Ptr)
+	Function bmx_b2gravitycontroller_setisinvsqr(handle:Byte Ptr, value:Int)
+
+	Function bmx_b2constantforcecontrollerdef_create:Byte Ptr()
+	Function bmx_b2constantforcecontrollerdef_delete(handle:Byte Ptr)
+
+	Function bmx_b2constantaccelcontrollerdef_create:Byte Ptr()
+	Function bmx_b2constantaccelcontrollerdef_delete(handle:Byte Ptr)
+
+	Function bmx_b2controlleredge_getcontroller:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2controlleredge_getbody:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2controlleredge_getprevbody:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2controlleredge_getnextbody:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2controlleredge_getprevcontroller:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2controlleredge_getnextcontroller:Byte Ptr(handle:Byte Ptr)
+
+	Function bmx_b2controller_getmaxcontroller:Object(handle:Byte Ptr)
+	Function bmx_b2controller_addbody(handle:Byte Ptr, body:Byte Ptr)
+	Function bmx_b2controller_removebody(handle:Byte Ptr, body:Byte Ptr)
+	Function bmx_b2controller_clear(handle:Byte Ptr)
+	Function bmx_b2controller_getnext:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2controller_getworld:Byte Ptr(handle:Byte Ptr)
+	Function bmx_b2controller_getbodylist:Byte Ptr(handle:Byte Ptr)
+
+End Extern
+
+Const e_unknownJoint:Int = 0
+Const e_revoluteJoint:Int = 1
+Const e_prismaticJoint:Int = 2
+Const e_distanceJoint:Int = 3
+Const e_pulleyJoint:Int = 4
+Const e_mouseJoint:Int = 5
+Const e_gearJoint:Int = 6
+Const e_lineJoint:Int = 7
+
+Const e_unknownShape:Int = -1
+Const e_circleShape:Int = 0
+Const e_polygonShape:Int = 1
+Const e_edgeShape:Int = 2
+
+Const e_buoyancyController:Int = 1
+Const e_constantAccelController:Int = 2
+Const e_tensorDampingController:Int = 3
+Const e_gravityController:Int = 4
+Const e_constantForceController:Int = 5
+

BIN
box2d.mod/doc/box2d_logo.gif


BIN
box2d.mod/doc/images/bodyOrigin.gif


BIN
box2d.mod/doc/images/convex_concave.gif


BIN
box2d.mod/doc/images/distanceJoint.gif


BIN
box2d.mod/doc/images/gearJoint.gif


BIN
box2d.mod/doc/images/prismaticJoint.gif


BIN
box2d.mod/doc/images/pulleyJoint.gif


BIN
box2d.mod/doc/images/revoluteJoint.gif


+ 4486 - 0
box2d.mod/doc/intro.bbdoc

@@ -0,0 +1,4486 @@
+<link rel="stylesheet" href="manual.css" type="text/css">
+<a href="www.box2d.org/"><img src="box2d_logo.gif" align="right" border="0" /></a>
+<p>
+Box2D is a 2D rigid body simulation library for games. It can be used to make objects move in believable ways and make the world seem more interactive. From the game's point of view a physics engine is just a system for procedural animation. Rather than paying (or begging) an animator to move your actors around, you can let Sir Isaac Newton do the directing.
+</p>
+<p>
+Physics.Box2D is a BlitzMax language binding (wrapper) of the Box2D library. The documentation is derived from Box2D's accompanying manual and API guide, by Erin Catto.
+</p>
+<p>
+	<b>Table of Contents</b>
+</p>
+<dl>
+	<dt>
+		<span class="chapter">
+			<a href="#d0e15">1. Introduction</a>
+		</span>
+	</dt>
+	<dd>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e28">1.1. Prerequisites</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e44">1.2. Core Concepts</a>
+				</span>
+			</dt>
+		</dl>
+	</dd>
+	<dt>
+		<span class="chapter">
+			<a href="#d0e110">2. Hello Box2D</a>
+		</span>
+	</dt>
+	<dd>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e118">2.1. Creating a World</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e143">2.2. Creating a Ground Box</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e203">2.3. Creating a Dynamic Body</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e227">
+						2.4. Simulating the World (of Box2D)
+					</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e257">2.5. Cleanup</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e265">2.6. The Examples</a>
+				</span>
+			</dt>
+		</dl>
+	</dd>
+	<dt>
+		<span class="chapter">
+			<a href="#d0e305">3. API Design</a>
+		</span>
+	</dt>
+	<dd>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e308">3.1. Memory Management</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e348">3.2. Factories and Definitions</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#units">3.3. Units</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e397">3.4. User Data</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e451">3.5. Strawman</a>
+				</span>
+			</dt>
+		</dl>
+	</dd>
+	<dt>
+		<span class="chapter">
+			<a href="#d0e459">4. The World</a>
+		</span>
+	</dt>
+	<dd>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e462">4.1. About</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e473">
+						4.2. Creating and Destroying a World
+					</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e496">4.3. Using a World</a>
+				</span>
+			</dt>
+			<dd>
+				<dl>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e504">4.3.1. Simulation</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e517">
+								4.3.2. Exploring the World
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e544">4.3.3. AABB Queries</a>
+						</span>
+					</dt>
+				</dl>
+			</dd>
+		</dl>
+	</dd>
+	<dt>
+		<span class="chapter">
+			<a href="#d0e560">5. Bodies</a>
+		</span>
+	</dt>
+	<dd>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e563">5.1. About</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e575">5.2. Body Definition</a>
+				</span>
+			</dt>
+			<dd>
+				<dl>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e587">5.2.1. Mass Properties</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e612">
+								5.2.2. Position and Angle
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e635">5.2.3. Damping</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e649">
+								5.2.4. Sleep Parameters
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#bullets">5.2.5. Bullets</a>
+						</span>
+					</dt>
+				</dl>
+			</dd>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e683">5.3. Body Factory</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e720">5.4. Using a Body</a>
+				</span>
+			</dt>
+			<dd>
+				<dl>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e725">5.4.1. Mass Data</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e740">
+								5.4.2. State Information
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e753">
+								5.4.3. Position and Velocity
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e768">
+								5.4.4. Forces and Impulses
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e779">
+								5.4.5. Coordinate Transformations
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e786">5.4.6. Lists</a>
+						</span>
+					</dt>
+				</dl>
+			</dd>
+		</dl>
+	</dd>
+	<dt>
+		<span class="chapter">
+			<a href="#shapes">6. Shapes</a>
+		</span>
+	</dt>
+	<dd>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e798">6.1. About</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e807">6.2. The Shape Definition</a>
+				</span>
+			</dt>
+			<dd>
+				<dl>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e815">
+								6.2.1. Friction and Restitution
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e837">6.2.2. Density</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e845">6.2.3. Filtering</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e889">6.2.4. Sensors</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e898">
+								6.2.5. Circle Definitions
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e910">
+								6.2.6. Polygon Definitions
+							</a>
+						</span>
+					</dt>
+				</dl>
+			</dd>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e950">6.3. Shape Factory</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e976">6.4. Using a Shape</a>
+				</span>
+			</dt>
+		</dl>
+	</dd>
+	<dt>
+		<span class="chapter">
+			<a href="#d0e984">7. Joints</a>
+		</span>
+	</dt>
+	<dd>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e987">7.1. About</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e996">7.2. The Joint Definition</a>
+				</span>
+			</dt>
+			<dd>
+				<dl>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1018">7.2.1. Distance Joint</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1034">7.2.2. Revolute Joint</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1077">
+								7.2.3. Prismatic Joint
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1097">7.2.4. Pulley Joint</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1123">7.2.5. Gear Joint</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1150">7.2.6. Mouse Joint</a>
+						</span>
+					</dt>
+				</dl>
+			</dd>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e1155">7.3. Joint Factory</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e1187">7.4. Using Joints</a>
+				</span>
+			</dt>
+			<dd>
+				<dl>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1200">
+								7.4.1. Using Distance Joints
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1205">
+								7.4.2. Using Revolute Joints
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1226">
+								7.4.3. Using Prismatic Joints
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1233">
+								7.4.4. Using Pulley Joints
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1240">
+								7.4.5. Using Gear Joints
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1248">
+								7.4.6. Using Mouse Joints
+							</a>
+						</span>
+					</dt>
+				</dl>
+			</dd>
+		</dl>
+	</dd>
+	<dt>
+		<span class="chapter">
+			<a href="#d0e1253">8. Contacts</a>
+		</span>
+	</dt>
+	<dd>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e1256">8.1. About</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e1310">8.2. Contact Listener</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e1359">8.3. Contact Filtering</a>
+				</span>
+			</dt>
+		</dl>
+	</dd>
+	<dt>
+		<span class="chapter">
+			<a href="#d0e1390">9. Loose Ends</a>
+		</span>
+	</dt>
+	<dd>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#world_boundary">9.1. World Boundary</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#implicit_destruction">
+						9.2. Implicit Destruction
+					</a>
+				</span>
+			</dt>
+		</dl>
+	</dd>
+	<dt>
+		<span class="chapter">
+			<a href="#d0e1465">10. Settings</a>
+		</span>
+	</dt>
+	<dd>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e1468">10.1. About</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e1481">10.2. Tolerances</a>
+				</span>
+			</dt>
+		</dl>
+	</dd>
+	<dt>
+		<span class="chapter">
+			<a href="#d0e1513">11. Debug Drawing</a>
+		</span>
+	</dt>
+</dl>
+</div>
+<div class="chapter" lang="en">
+	<div class="titlepage">
+		<div>
+			<div>
+				<h2 class="title">
+					<a name="d0e15"></a>
+					Chapter 1. Introduction
+				</h2>
+			</div>
+		</div>
+	</div>
+	<div class="toc">
+		<p>
+			<b>Table of Contents</b>
+		</p>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e28">1.1. Prerequisites</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e44">1.2. Core Concepts</a>
+				</span>
+			</dt>
+		</dl>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e28"></a>
+						1.1. Prerequisites
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			In this manual it is assumed you are familiar with basic
+			physics concepts, such as mass, force, torque, and impulses.
+			If not, please first consult the many tutorials provided by
+			Chris Hecker and David Baraff (google these names). You do
+			not need to understand their tutorials in great detail, but
+			they do a good job of laying out the basic concepts that
+			will help you use Box2D.
+		</p>
+		<p>
+			<a href="http://wikipedia.org" target="_top">Wikipedia</a>
+			is also an excellent source of physics and mathematics
+			knowledge. In some ways it is more useful than Google,
+			because it has carefully crafted content.
+		</p>
+		<p>
+			This is not a prerequisite, but if you are curious about the
+			about the inner workings of Box2D, you can look at these
+			<a href="http://www.gphysics.com/downloads" target="_top">
+				articles
+			</a>
+			.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e44"></a>
+						1.2. Core Concepts
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Box2D works with several fundamental objects. We briefly
+			define these objects here and more details are given later
+			in this document.
+		</p>
+		<div class="glosslist">
+			<dl>
+				<dt>rigid body</dt>
+				<dd>
+					<p>
+						A chunk of matter that is so strong that the
+						distance between any two bits of matter on the
+						chunk is completely constant. They are hard like
+						a diamond. In the following discussion we use
+						<span class="emphasis">
+							<em>body</em>
+						</span>
+						interchangably with rigid body.
+					</p>
+				</dd>
+				<dt>shape</dt>
+				<dd>
+					<p>
+						A 2D piece of collision geometry that is rigidly
+						attached to a body. Shapes have material
+						properties of friction and restitution.
+					</p>
+				</dd>
+				<dt>constraint</dt>
+				<dd>
+					<p>
+						A constraint is a physical connection that
+						removes degrees of freedom from bodies. In 2D a
+						body has 3 degrees of freedom. If we take a body
+						and pin it to the wall (like a pendulum) we have
+						<span class="emphasis">
+							<em>constrained</em>
+						</span>
+						the body to the wall. At this point the body can
+						only rotate about the pin, so the constraint has
+						removed 2 degrees of freedom.
+					</p>
+				</dd>
+				<dt>contact constraint</dt>
+				<dd>
+					<p>
+						A special constraint designed to prevent
+						penetration of rigid bodies and to simulate
+						friction and restitution. You will never create
+						a contact constraint, they are created
+						automatically by Box2D.
+					</p>
+				</dd>
+				<dt>joint</dt>
+				<dd>
+					<p>
+						This is a contraint used to hold two or more
+						bodies together. Box2D supports these joint
+						types: revolute, prismatic, distance, and more.
+						Joints may support
+						<span class="emphasis">
+							<em>limits</em>
+						</span>
+						and
+						<span class="emphasis">
+							<em>motors</em>
+						</span>
+						.
+					</p>
+				</dd>
+				<dt>joint limit</dt>
+				<dd>
+					<p>
+						A joint limit restricts the range of motion of a
+						joint. For example, the human elbow only allows
+						a certain range of angles.
+					</p>
+				</dd>
+				<dt>joint motor</dt>
+				<dd>
+					<p>
+						A joint motor drives the motion of the connected
+						bodies according to the joint's degrees of
+						freedom. For example, you can use a motor to
+						drive the rotation of an elbow.
+					</p>
+				</dd>
+				<dt>world</dt>
+				<dd>
+					<p>
+						A physics world is a collection of bodies,
+						shapes, and constraints that interact together.
+						Box2D supports the creation of multiple worlds,
+						but this is usually not necessary or desirable.
+					</p>
+				</dd>
+			</dl>
+		</div>
+	</div>
+</div>
+<div class="chapter" lang="en">
+	<div class="titlepage">
+		<div>
+			<div>
+				<h2 class="title">
+					<a name="d0e110"></a>
+					Chapter 2. Hello Box2D
+				</h2>
+			</div>
+		</div>
+	</div>
+	<div class="toc">
+		<p>
+			<b>Table of Contents</b>
+		</p>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e118">2.1. Creating a World</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e143">2.2. Creating a Ground Box</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e203">2.3. Creating a Dynamic Body</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e227">
+						2.4. Simulating the World (of Box2D)
+					</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e257">2.5. Cleanup</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e265">2.6. The Examples</a>
+				</span>
+			</dt>
+		</dl>
+	</div>
+	<p>
+		In the distribution of Box2D is a
+		<span class="emphasis">
+			<em>Hello World</em>
+		</span>
+		project. The program creates a large ground box and a small
+		dynamic box. This code does not contain any graphics, so prepare
+		to be underwelmed. :)
+	</p>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e118"></a>
+						2.1. Creating a World
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Every Box2D program begins with the creation of a world
+			object. This is the physics hub that manages memory,
+			objects, and simulation.
+		</p>
+		<p>
+			To create a world object, first we need to define a bounding
+			box for the world. Box2D uses the bounding box to accelerate
+			collision detection. The size isn't critical, but a better
+			fit will improve performance. It is better to make the box
+			too big than to make it too small.
+		</p>
+		<pre class="programlisting">
+Local worldAABB:b2AABB = New b2AABB
+worldAABB.SetLowerBound(-100.0, -100.0)
+worldAABB.SetUpperBound(100.0, 100.0)
+		</pre>
+		<div class="caution"
+			style="margin-left: 0.5in; margin-right: 0.5in;">
+			<h3 class="title">Caution</h3>
+			<p>
+				The
+				<span class="emphasis">
+					<em>world AABB</em>
+				</span>
+				should always be bigger then the region where your
+				bodies are located. It is better to make the world AABB
+				too big than too small. If a body reaches the boundary
+				of the world AABB it will be frozen and will stop
+				simulating.
+			</p>
+		</div>
+		<p>
+			Next we define the gravity vector. Yes, you can make gravity
+			go sideways (or you could just rotate your monitor). Also we
+			tell the world to allow bodies to sleep when they come to
+			rest. A sleeping body doesn't require any simulation.
+		</p>
+		<pre class="programlisting">
+Local gravity:b2Vec2 = New b2Vec2(0.0, -10.0)
+Local doSleep:int = true
+		</pre>
+		<p>
+			Now we create the world object. Normally you would create
+			the world on the heap and store the pointer in one of your
+			game structures. However, creating the world on the stack
+			works fine in this example.
+		</p>
+		<pre class="programlisting">
+Local world:b2World = New b2World.Create(worldAABB, gravity, doSleep)
+		</pre>
+		<p>
+			So now we have our physics world, let's start adding some
+			stuff to it.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e143"></a>
+						2.2. Creating a Ground Box
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>Bodies are built using the following steps:</p>
+		<div class="orderedlist">
+			<ol type="1">
+				<li>
+					<p>Define a body with a position, damping, etc.</p>
+				</li>
+				<li>
+					<p>Use the world object to create the body.</p>
+				</li>
+				<li>
+					<p>
+						Define shapes with geometry, friction, density,
+						etc.
+					</p>
+				</li>
+				<li>
+					<p>Create shapes on the body.</p>
+				</li>
+				<li>
+					<p>
+						Optionally adjust the body's mass to match the
+						attached shapes.
+					</p>
+				</li>
+			</ol>
+		</div>
+		<p>
+			For step 1 we create the ground body. For this we need a
+			<span class="emphasis">
+				<em>body definition</em>
+			</span>
+			. With the body definition we specify the initial position
+			of the ground body.
+		</p>
+		<pre class="programlisting">
+Local groundBodyDef:b2BodyDef = New b2BodyDef
+groundBodyDef.SetPositionXY(0.0, -10.0)
+		</pre>
+		<p>
+			For step 2 the body definition is passed to the world object
+			to create the ground body. The world object does not keep a
+			reference to the body definition. The ground body is created
+			as a static body. Static bodies don't collide with other
+			static bodies and are immovable. Box2D determines that a
+			body is static when it has zero mass. Bodies have zero mass
+			by default, therefore they are static by default.
+		</p>
+		<pre class="programlisting">
+Local groundBody:b2Body = world.CreateBody(groundBodyDef)
+		</pre>
+		<p>
+			For step 3 we create a ground polygon definition. We use the
+			<tt class="literal">SetAsBox</tt>
+			shortcut to form the ground polygon into a box shape, with
+			the box centered on the origin of the parent body.
+		</p>
+		<pre class="programlisting">
+Local groundShapeDef:b2PolygonDef = New b2PolygonDef
+groundShapeDef.SetAsBox(50.0, 10.0)
+		</pre>
+		<p>
+			The
+			<tt class="function">SetAsBox</tt>
+			function takes the half-width and half-height. So in this
+			case the ground box is 100 units wide (x-axis) and 20 units
+			tall (y-axis). Box2D is tuned for meters, kilograms, and
+			seconds. So you can consider the extents to be in meters.
+			However, it is possible to change unit systems, as discussed
+			later in this document
+		</p>
+		<p>
+			We finish the ground body in step 4 by creating the ground
+			polygon shape on the ground body.
+		</p>
+		<pre class="programlisting">
+groundBody.CreateShape(groundShapeDef)
+		</pre>
+		<p>
+			Again, Box2D does not keep a reference to the shape or body
+			definitions. It copies the data into the
+			<tt class="classname">b2Body</tt>
+			structure.
+		</p>
+		<p>
+			Note that every shape must have a parent body, even shapes
+			that are static. However, you can attach all static shapes
+			to a single static body. This need for static bodies is done
+			to make the Box2D code more uniform internally, reducing the
+			number of potential bugs.
+		</p>
+		<p>
+			You might notice a pattern here. Most Box2D types are
+			prefixed with
+			<tt class="literal">b2</tt>
+			. This is done to reduce the chance for naming conflicts
+			with your code.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e203"></a>
+						2.3. Creating a Dynamic Body
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			So now we have a ground body. We can use the same technique
+			to create a dynamic body. The main difference, besides
+			dimensions, is that we must establish the dynamic body's
+			mass properties.
+		</p>
+		<p>
+			First we create the body using
+			<tt class="function">CreateBody</tt>
+			.
+		</p>
+		<pre class="programlisting">
+Local bodyDef:b2BodyDef = new b2BodyDef
+bodyDef.SetPositionXY(0.0, 4.0)
+Local body:b2Body = world.CreateBody(bodyDef)
+		</pre>
+		<p>
+			Next we create and attach a polygon shape. Notice that we
+			set density to 1. The default density is zero. Also, the
+			friction on the shape is set to 0.3. Once the shape is
+			attached, we instruct the body to compute it's mass
+			properties from the attached shapes using the method
+			<tt class="function">SetMassFromShapes</tt>
+			. This gives you a hint that you can attach more than one
+			shape per body. If the computed mass is zero, then the body
+			becomes truly static. Bodies have a mass of zero by default,
+			that's why we didn't need to call
+			<tt class="function">SetMassFromShapes</tt>
+			for the ground body.
+		</p>
+		<pre class="programlisting">
+Local shapeDef:b2PolygonDef = New b2PolygonDef
+shapeDef.SetAsBox(1.0, 1.0)
+shapeDef.SetDensity(1.0)
+shapeDef.SetFriction(0.3)
+body.CreateShape(shapeDef)
+body.SetMassFromShapes()
+		</pre>
+		<p>
+			That's it for initialization. We are now ready to begin
+			simulating.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e227"></a>
+						2.4. Simulating the World (of Box2D)
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			So we have initialized the ground box and a dynamic box. Now
+			we are ready to set Newton loose to do his thing. We just
+			have a couple more issues to consider.
+		</p>
+		<p>
+			Box2D uses a bit of numerical code called an
+			<span class="emphasis">
+				<em>integrator</em>
+			</span>
+			. Integrators simulate the physics equations at discrete
+			points of time. This goes along with the traditional game
+			loop where we essentially have a flip book of movement on
+			the screen. So we need to pick a time step for Box2D.
+			Generally physics engines for games like a time step at
+			least as fast as 60Hz or 1/60 seconds. You can get away with
+			larger time steps, but you will have to be more careful
+			about setting up the definitions for your world. We also
+			don't like the time step to change much. So don't tie the
+			time step to your frame rate (unless you really, really have
+			to). Without further ado, here is the time step.
+		</p>
+		<pre class="programlisting">
+Local timeStep:Float = 1.0 / 60.0
+		</pre>
+		<p>
+		In addition to the integrator, Box2D also uses a larger bit
+		of code called a <span class="emphasis"><em>constraint solver</em></span>.
+		The constraint solver solves all the constraints in the simulation, one
+		at a time. A single constraint can be solved perfectly. However, when we
+		solve one constraint, we slightly disrupt other constraints. To get a good
+		solution, we need to iterate over all constraints a number of times.
+		</p>
+		<p>
+		There are two phases in the constraint solver: a velocity phase and a
+		position phase. In the velocity phase the solver computes the impulses
+		necessary for the bodies to move correctly. In the position phase the
+		solver adjusts the positions of the bodies to reduce overlap and joint
+		detachment. Each phase has its own iteration count. In addition, the
+		position phase will exit iteraions early if the errors are small.
+		</p>
+		<p>
+		The suggested iteration count for Box2D is 10 for both velocity and
+		position. You can tune this number to your liking, just keep in mind
+		that this has a trade-off between speed and accuracy. Using fewer
+		iterations increases performance but accuracy suffers. Likewise, using
+		more iterations decreases performance but improves the quality of your
+		simulation. For this simple example, we don't need many iterations.
+		Here are our chosen iteration counts.
+		</p>
+		<pre class="programlisting">
+Local velocityIterations:Int = 8
+Local positionIterations:Int = 1
+		</pre>
+		<p>
+		Note that the time step and the iteration count are completely
+		unrelated. An iteration is not a sub-step. One iteration is a single
+		pass over all the constraints withing a time step. You can have multiple
+		passes over the constraints within a single time step.
+		</p>
+		<p>
+		We are now ready to begin the simulation loop. In your game the
+		simulation loop can be merged with your game loop. In each pass through
+		your game loop you call <tt class="literal">b2World::Step</tt>. Just
+		one call is usually enough, depending on your frame rate and your
+		physics time step.
+		</p>
+		<p>
+		The Hello World program was designed to be dead simple, so it has
+		no graphical output. Rather that being utterly boring by producing
+		no output, the code prints out the position and rotation of the dynamic
+		body. Yay! Here is the simulation loop that simulates 60 time steps
+		for a total of 1 second of simulated time.
+		</p>
+<pre class="programlisting">
+For Local i:Int = 0 Until 60
+	world.DoStep(timeStep, velocityIterations, positionIterations)
+	Local position:b2Vec2 = body.GetPosition()
+	Local angle:Float = body.GetAngle()
+	Print position.x + " " + position.y + " " + angle
+Next
+		</pre>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e257"></a>
+						2.5. Cleanup
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			When a world leaves scope or is deleted by calling
+			<tt class="literal">delete</tt>
+			on a pointer, all the memory reserved for bodies and joints
+			is freed. This is done to make your life easier. However,
+			you will need to nullify any body, shape, or joint pointers
+			you have because they will become invalid.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e265"></a>
+						2.6. The Examples
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Once you have conquered the HelloWorld example, you should
+			start looking at Box2D's examples. 
+		</p>
+		<p>
+			The testbed has many examples of Box2D usage in the test
+			cases and the framework itself. I encourage you to explore
+			and tinker with the testbed as you learn Box2D.
+		</p>
+	</div>
+</div>
+<div class="chapter" lang="en">
+	<div class="titlepage">
+		<div>
+			<div>
+				<h2 class="title">
+					<a name="d0e305"></a>
+					Chapter 3. API Design
+				</h2>
+			</div>
+		</div>
+	</div>
+	<div class="toc">
+		<p>
+			<b>Table of Contents</b>
+		</p>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e308">3.1. Memory Management</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e348">3.2. Factories and Definitions</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#units">3.3. Units</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e397">3.4. User Data</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e451">3.5. Strawman</a>
+				</span>
+			</dt>
+		</dl>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e308"></a>
+						3.1. Memory Management
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			A large number of the decisions about the design of Box2D
+			were based on the need for quick and efficient use of
+			memory. In this section I will discuss how and why Box2D
+			allocates memory.
+		</p>
+		<p>
+			Box2D tends to allocate a large number of small objects
+			(around 50-300 bytes). Using the system heap through
+			<tt class="literal">malloc</tt>
+			or
+			<tt class="literal">new</tt>
+			for small objects is inefficient and can cause
+			fragmentation. Many of these small objects may have a short
+			life span, such as contacts, but can persist for several
+			time steps. So we need an allocator that can efficiently
+			provide heap memory for these objects.
+		</p>
+		<p>
+			Box2D's solution is to use a
+			<span class="emphasis">
+				<em>small object</em>
+			</span>
+			allocator (SOA). The SOA keeps a number of growable pools of
+			varying sizes. When a request is made for memory, the SOA
+			returns a block of memory that best fits the requested size.
+			When a block is freed, it is returned to the pool. Both of
+			these operations are fast and cause little heap traffic.
+		</p>
+		<p>
+		Since Box2D uses a SOA, you should never 
+		<span class="emphasis"><em>new</em></span>
+		or <span class="emphasis"><em>malloc</em></span>
+		a body, shape, or joint. You do have to allocate a 
+		<tt class="classname">b2World</tt>. The <tt class="classname">b2World</tt> 
+		class provides factories for you to create bodies, shapes, and 
+		joints. This allows Box2D to use the SOA and hide the gory details
+		from you. Never, ever, call <tt class="literal">delete</tt> or 
+		<tt class="literal">free</tt> on a body, shape, or joint.
+		</p>
+		<p>
+			While executing a time step, Box2D needs some temporary
+			workspace memory. For this, it uses a stack allocator to
+			avoid per-step heap allocations. You don't need to interact
+			with the stack allocator, but it's good to know it's there.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e348"></a>
+						3.2. Factories and Definitions
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			As mentioned above, memory management plays a central role
+			in the design of the Box2D API. So when you create a
+			<tt class="classname">b2Body</tt>
+			or a
+			<tt class="classname">b2Joint</tt>
+			, you need to call the factory methods on
+			<tt class="classname">b2World</tt>
+			.
+		</p>
+		<p>There are creation methods:</p>
+		<pre class="programlisting">
+Method CreateBody:b2Body(def:b2BodyDef)
+Method CreateJoint:b2Joint(def:b2JointDef)
+		</pre>
+		<p>And there are corresponding destruction methods:</p>
+		<pre class="programlisting">
+Method DestroyBody(body:b2Body)
+Method DestroyJoint(joint:b2Joint)
+		</pre>
+		<p>
+			When you create a body or joint, you need to provide a
+			<span class="emphasis">
+				<em>definition</em>
+			</span>
+			or
+			<span class="emphasis">
+				<em>def</em>
+			</span>
+			for short. These definitions contain all the information
+			needed to build the body or joint. By using this approach we
+			can prevent construction errors, keep the number of function
+			parameters small, provide sensible defaults, and reduce the
+			number of accessors.
+		</p>
+		<p>
+			Since shapes musted be parented to a body, they are created
+			and destroyed using a factory method on
+			<tt class="classname">b2Body</tt>
+			:
+		</p>
+		<pre class="programlisting">
+Method CreateShape:b2Shape(def:b2ShapeDef)
+Method DestroyShape(shape:b2Shape)
+		</pre>
+		<p>
+			Factories do not retain references to the definitions. So
+			you can create and re-use definitions and keep them in
+			temporary resources.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="units"></a>
+						3.3. Units
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Box2D works with floating point numbers, so some tolerances
+			have to be used to make Box2D perform well. These tolerance
+			have been tuned to work well with meters-kilogram-second
+			(MKS) units. In particular, Box2D has been tuned to work
+			well with moving objects between 0.1 and 10 meters. So this
+			means objects between soup cans and buses in size should
+			work well.
+		</p>
+		<p>
+			Being a 2D physics engine it is tempting to use pixels as
+			your units. Unfortunately this will lead to a poor
+			simulation and possibly weird behavior. An object of length
+			200 pixels would be seen by Box2D as the size of a 45 story
+			building. Imagine trying to simulate the movement of a
+			high-rise building with an engine that is tuned to simulate
+			ragdolls and barrels. It isn't pretty.
+		</p>
+		<div class="caution"
+			style="margin-left: 0.5in; margin-right: 0.5in;">
+			<h3 class="title">Caution</h3>
+			<p>
+				Box2D is tuned for MKS units. Keep the size of moving
+				objects roughly between 0.1 and 10 meters. You'll need
+				to use some scaling system when you render your
+				environment and actors.
+			</p>
+		</div>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e397"></a>
+						3.4. User Data
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			The
+			<tt class="classname">b2Shape</tt>
+			,
+			<tt class="classname">b2Body</tt>
+			, and
+			<tt class="classname">b2Joint</tt>
+			classes allow you to attach user data as a
+			<tt class="literal">void</tt>
+			pointer. This is handy when you are examining Box2D data
+			structures and you want to determine how they relate to the
+			data structures in your game engine.
+		</p>
+		<p>
+			For example, it is typical to attach an
+			<span class="emphasis">
+				<em>actor</em>
+			</span>
+			pointer to the rigid body on that actor. This sets up a
+			circular reference. If you have the actor, you can get the
+			body. If you have the body, you can get the actor.
+		</p>
+		<pre class="programlisting">
+Local actor:GameActor = GameCreateActor()
+Local bodyDef:b2BodyDef = new b2BodyDef
+bodyDef.SetUserData(actor)
+actor.body = box2Dworld.CreateBody(bodyDef)
+		</pre>
+		<p>
+			Here are some examples of cases where you would need the
+			user data:
+		</p>
+		<div class="itemizedlist">
+			<ul type="disc">
+				<li>
+					<p>
+						Applying damage to an actor using a collision
+						result.
+					</p>
+				</li>
+				<li>
+					<p>
+						Playing a scripted event if the player is inside
+						an axis-aligned box.
+					</p>
+				</li>
+				<li>
+					<p>
+						Accessing a game structure when Box2D notifies
+						you that a joint is going to be destroyed.
+					</p>
+				</li>
+			</ul>
+		</div>
+		<p>
+			Keep in mind that user data is optional and you can put
+			anything in it. However, you should be consistent. For
+			example, if you want to store an actor pointer on one body,
+			you should keep an actor pointer on all bodies. Don't store
+			an actor pointer on one body, and a foo pointer on another
+			body. This will likely lead to a crash if you try to cast an
+			actor pointer into a foo pointer.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e451"></a>
+						3.5. Strawman
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			If you don't like this API design, that's ok! You have the
+			source code! Seriously, if you have feedback about anything
+			related to Box2D, please leave a comment in the
+			<a href="http://www.box2d.org/forum" target="_top">forum</a>
+			.
+		</p>
+	</div>
+</div>
+<div class="chapter" lang="en">
+	<div class="titlepage">
+		<div>
+			<div>
+				<h2 class="title">
+					<a name="d0e459"></a>
+					Chapter 4. The World
+				</h2>
+			</div>
+		</div>
+	</div>
+	<div class="toc">
+		<p>
+			<b>Table of Contents</b>
+		</p>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e462">4.1. About</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e473">
+						4.2. Creating and Destroying a World
+					</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e496">4.3. Using a World</a>
+				</span>
+			</dt>
+			<dd>
+				<dl>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e504">4.3.1. Simulation</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e517">
+								4.3.2. Exploring the World
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e544">4.3.3. AABB Queries</a>
+						</span>
+					</dt>
+				</dl>
+			</dd>
+		</dl>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e462"></a>
+						4.1. About
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			The
+			<tt class="classname">b2World</tt>
+			class contains the bodies and joints. It manages all aspects
+			of the simulation and allows for asynchronous queries (like
+			AABB queries). Much of your interactions with Box2D will be
+			with a
+			<tt class="classname">b2World</tt>
+			object.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e473"></a>
+						4.2. Creating and Destroying a World
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Creating a world is fairly simple. You need to provide a
+			bounding box and a gravity vector.
+		</p>
+		<p>
+			The axis-aligned bounding box should encapsulate the world.
+			You can improve performance by making the bounding box a bit
+			bigger than your world, say 2x just to be safe. If you have
+			lots of bodies that fall into the abyss, your should detect
+			this and remove the bodies. This will improve performance
+			and prevent floating point overflow.
+		</p>
+		<p>
+			To create and destory a world you need to use
+			<tt class="literal">Create</tt>
+			and
+			<tt class="literal">Free</tt>
+			.
+		</p>
+		<pre class="programlisting">
+Local myWorld:b2World = new b2World.Create(aabb, gravity, doSleep);
+... do stuff ...
+myWorld.Free()
+		</pre>
+		<div class="caution"
+			style="margin-left: 0.5in; margin-right: 0.5in;">
+			<h3 class="title">Caution</h3>
+			<p>
+				Recall that the
+				<span class="emphasis">
+					<em>world AABB</em>
+				</span>
+				should always be bigger then the region where your
+				bodies are located. If bodies leave the world AABB, then
+				they will be frozen. This is not a bug.
+			</p>
+		</div>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e496"></a>
+						4.3. Using a World
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			The world class contains factories for creating and
+			destroying bodies and joints. These factories are discussed
+			later in the sections on bodies and joints. There are some
+			other interactions with
+			<tt class="classname">b2World</tt>
+			that I will cover now.
+		</p>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e504"></a>
+							4.3.1. Simulation
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				The world class is used to drive the simulation. You
+				specify a time step and an iteration count. For example:
+			</p>
+			<pre class="programlisting">
+Local timeStep:Float = 1.0 / 60.0
+Local iterationCount:Int = 10
+myWorld.DoStep(timeStep, iterationCount)
+			</pre>
+			<p>
+				After the time step you can examine your bodies and
+				joints for information. Most likely you will grab the
+				position off the bodies so that you can update your
+				actors and render them. You can perform the time step
+				anywhere in your game loop, but you should be aware of
+				the order of things. For example, you must create bodies
+				before the time step if you want to get collision
+				results for the new bodies in that frame.
+			</p>
+			<p>
+				As I discussed above in the HelloWorld tutorial, you
+				should use a fixed time step. By using a larger time
+				step you can improve performance in low frame rate
+				scenarios. But generally you should use a time step no
+				larger than 1/30 seconds. A time step of 1/60 seconds
+				will usually deliver a high quality simulation.
+			</p>
+			<p>
+				The iteration count controls how many times the
+				constraint solver sweeps over all the contacts and
+				joints in the world. More iterations always yields a
+				better simulation. But don't trade a small time step for
+				a large iteration count. 60Hz and 10 iterations is far
+				better than 30Hz and 20 iterations.
+			</p>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e517"></a>
+							4.3.2. Exploring the World
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				As mentioned before, the world is a container for bodies
+				and joints. You can grab the body and joint lists off
+				the world and iterate over them. For example, this code
+				wakes up all the bodies in the world:
+			</p>
+			<pre class="programlisting">
+Local b:b2Body = myWorld.GetBodyList()
+While b
+	b.WakeUp()
+	b = b.GetNext()
+Wend
+			</pre>
+			<p>
+				Unfortunately life can be more complicated. For example,
+				the following code is broken:
+			</p>
+			<pre class="programlisting">
+Local b:b2Body = myWorld.GetBodyList()
+While b
+	Local myActor:GameActor = GameActor(b.GetUserData())
+	If myActor.IsDead() Then
+		myWorld.DestroyBody(b) ' ERROR: now GetNext returns garbage.
+	End If
+	b = b.GetNext()
+Wend
+			</pre>
+			<p>
+				Everything goes ok until a body is destroyed. Once a
+				body is destroyed, its next pointer becomes invalid. So
+				the call to
+				<tt class="methodname">b2Body::GetNext()</tt>
+				will return garbage. The solution to this is to copy the
+				next pointer before destroying the body.
+			</p>
+			<pre class="programlisting">
+Local node:b2Body = myWorld.GetBodyList()
+While (node)
+	Local b:b2Body = node
+	node = node.GetNext()
+
+	Local myActor:GameActor = GameActor(b.GetUserData())
+	If myActor.IsDead() Then
+		myWorld.DestroyBody(b)
+	End If
+Wend
+			</pre>
+			<p>
+				This safely destroys the current body. However, you may
+				want to call a game function that may destroy multiple
+				bodies. In this case you need to be very careful. The
+				solution is application specific, but for convenience
+				I'll show one method of solving the problem.
+			</p>
+			<pre class="programlisting">
+Local node:b2Body = myWorld.GetBodyList()
+While node
+	Local b:b2Body = node
+	node = node.GetNext()
+
+	Local myActor:GameActor = GameActor(b.GetUserData())
+	If myActor.IsDead() Then
+		Local otherBodiesDestroyed:Int = GameCrazyBodyDestroyer(b)
+		If otherBodiesDestroyed Then
+			node = myWorld.GetBodyList()
+		End If
+	End If
+Wend
+			</pre>
+			<p>
+				Obviously to make this work,
+				<tt class="function">GameCrazyBodyDestroyer</tt>
+				must be honest about what it has destroyed.
+			</p>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e544"></a>
+							4.3.3. AABB Queries
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				Sometimes you want to determine all the shapes in a
+				region. The
+				<tt class="classname">b2World</tt>
+				class has a fast log(N) method for this using the
+				<span class="emphasis">
+					<em>broad-phase</em>
+				</span>
+				data structure. You provide an AABB in world coordinates
+				and
+				<tt class="classname">b2World</tt>
+				returns an array of all the shapes that potentially
+				intersect the AABB. This is not exact because what the
+				function actually does is return all the shapes whose
+				AABBs intersect the specified AABB. For example, the
+				following code finds all the shapes that potentially
+				intersect a specified AABB and wakes up all of the
+				associated bodies.
+			</p>
+			<pre class="programlisting">
+Local aabb:b2AABB = new b2AABB
+aabb.SetLowerBound(-1.0, -1.0)
+aabb.SetUpperBound(1.0, 1.0)
+Local k_bufferSize:Int = 10
+Local buffer:b2Shape[] = New b2Shape[k_bufferSize]
+Local count:Int = myWorld.Query(aabb, buffer)
+For Local i:Int = 0 Until count
+	buffer[i].GetBody().WakeUp()
+Next
+			</pre>
+		</div>
+	</div>
+</div>
+<div class="chapter" lang="en">
+	<div class="titlepage">
+		<div>
+			<div>
+				<h2 class="title">
+					<a name="d0e560"></a>
+					Chapter 5. Bodies
+				</h2>
+			</div>
+		</div>
+	</div>
+	<div class="toc">
+		<p>
+			<b>Table of Contents</b>
+		</p>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e563">5.1. About</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e575">5.2. Body Definition</a>
+				</span>
+			</dt>
+			<dd>
+				<dl>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e587">5.2.1. Mass Properties</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e612">
+								5.2.2. Position and Angle
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e635">5.2.3. Damping</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e649">
+								5.2.4. Sleep Parameters
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#bullets">5.2.5. Bullets</a>
+						</span>
+					</dt>
+				</dl>
+			</dd>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e683">5.3. Body Factory</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e720">5.4. Using a Body</a>
+				</span>
+			</dt>
+			<dd>
+				<dl>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e725">5.4.1. Mass Data</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e740">
+								5.4.2. State Information
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e753">
+								5.4.3. Position and Velocity
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e768">
+								5.4.4. Forces and Impulses
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e779">
+								5.4.5. Coordinate Transformations
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e786">5.4.6. Lists</a>
+						</span>
+					</dt>
+				</dl>
+			</dd>
+		</dl>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e563"></a>
+						5.1. About
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Bodies have position and velocity. You can apply forces,
+			torques, and impulses to bodies. Bodies can be static or
+			dynamic. Static bodies never move and don't collide with
+			other static bodies.
+		</p>
+		<p>
+			Bodies are the backbone for shapes. Bodies carry shapes and
+			move them around in the world. Bodies are always
+			<span class="emphasis">
+				<em>rigid bodies</em>
+			</span>
+			in Box2D. That means that two shapes attached to the same
+			rigid body never move relative to each other.
+		</p>
+		<p>
+			You usually keep references to all the bodies you create. This
+			way you can query the body positions to update the positions
+			of your graphical entities. You should also keep body
+			references so you can destroy them when you are done with
+			them.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e575"></a>
+						5.2. Body Definition
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Before a body is created you must create a body definition (
+			<tt class="classname">b2BodyDef</tt>
+			). You can create a body definition on the stack or build it
+			into your game's data structures. The choice is up to you.
+		</p>
+		<p>
+			Box2D copies the data out of the body definition, it does
+			not keep a pointer to the body definition. This means you
+			can recycle a body definition to create multiple bodies.
+		</p>
+		<p>
+			Lets go over some of the key members of the body definition.
+		</p>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e587"></a>
+							5.2.1. Mass Properties
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				There are a few ways to establish the mass properties
+				for a body.
+			</p>
+			<div class="orderedlist">
+				<ol type="1">
+					<li>
+						<p>
+							Set the mass properties explicitly in the
+							body definition.
+						</p>
+					</li>
+					<li>
+						<p>
+							Set the mass properties explicitly on the
+							body (after it has been created).
+						</p>
+					</li>
+					<li>
+						<p>
+							Set the mass properties based on the density
+							of the attaced shapes.
+						</p>
+					</li>
+				</ol>
+			</div>
+			<p>
+				In many game scenarios it makes sense to compute mass
+				based on shape densities. This helps to ensure that
+				bodies have reasonable and consistent mass values.
+			</p>
+			<p>
+				However, other game scenarios may require specific mass
+				values. For example, you may have a mechanism, like a
+				scale that needs precises mass values.
+			</p>
+			<p>
+				You can explicitly set the mass properties in the body
+				definition as follows:
+			</p>
+			<pre class="programlisting">
+bodyDef.GetMassData().SetMass(2.0) ' the body's mass in kg
+bodyDef.SetCenter(b2Vec2.ZERO)     ' the center of mass in local coordinates
+bodyDef.SetRotationalInertia(3.0)  ' the rotational inertia in kg*m^2.
+			</pre>
+			<p>
+				The other methods of setting the mass properties are
+				covered elsewhere in this document.
+			</p>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e612"></a>
+							5.2.2. Position and Angle
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				The body definition gives you the chance to initialize
+				the position of the body on creation. This has better
+				performance than creating the body at the world origin
+				and then moving the body.
+			</p>
+			<p>
+				A body has two main points of interest. The first point
+				is the body's
+				<span class="emphasis">
+					<em>origin</em>
+				</span>
+				. Shapes and joints are attached relative to the body's
+				origin. The second point of interest is the
+				<span class="emphasis">
+					<em>center of mass</em>
+				</span>
+				. The center of mass is determined from mass
+				distribution of the attached shapes or is explicitly set
+				with
+				<tt class="classname">b2MassData</tt>
+				. Much of Box2D's internal computations use the center
+				of mass position. For example
+				<tt class="classname">b2Body</tt>
+				stores the linear velocity for the center of mass.
+			</p>
+			<p>
+				When you are building the body definition, you may not
+				know where the center of mass is located. Therefore you
+				specify the position of the body's origin. You may also
+				specify the body's angle in radians, which is not
+				affected by the position of the center of mass. If you
+				later change the mass properties of the body, then the
+				center of mass may move on the body, but the origin
+				position does not change and the attached shapes and
+				joints do not move.
+			</p>
+			<pre class="programlisting">
+bodyDef.SetPositionXY(0.0, 2.0) ' the body's origin position
+bodyDef.SetAngle(45)            ' the body's angle in degrees.
+			</pre>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e635"></a>
+							5.2.3. Damping
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				Damping is used to reduce the world velocity of bodies.
+				Damping is different than friction because friction only
+				occurs with contact and damping is much cheaper to
+				simulate than friction. However, damping is not a
+				replacement for friction and the two effects should be
+				used together.
+			</p>
+			<p>
+				Damping parameters should be between 0 and infinity,
+				with 0 meaning no damping, and infinity meaning full
+				damping. Normally you will use a damping value between 0
+				and 0.1. I generally do not use linear damping because
+				it makes bodies look
+				<span class="emphasis">
+					<em>floaty</em>
+				</span>
+				.
+			</p>
+			<pre class="programlisting">
+bodyDef.SetLinearDamping(0.0)
+bodyDef.SetAngularDamping(0.01)
+			</pre>
+			<p>
+				Damping is approximated for stability and performance.
+				At small damping values the damping effect is mostly
+				independent of the time step. At larger damping values,
+				the damping effect will vary with the time step. This is
+				not an issue if you use a fixed time step (recommended).
+			</p>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e649"></a>
+							5.2.4. Sleep Parameters
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				What does sleep mean? Well it is expensive to simulate
+				bodies, so the less we have to simulate the better. When
+				a body comes to rest we would like to stop simulating
+				it.
+			</p>
+			<p>
+				When Box2D determines that a body (or group of bodies)
+				has come to rest, the body enters a sleep state which
+				has very little CPU overhead. If an awake body collides
+				with a sleeping body, then the sleeping body wakes up.
+				Bodies will also wake up if a joint or contact attached
+				to them is destroyed. You can also wake a body manually.
+			</p>
+			<p>
+				The body definition lets you specify whether a body can
+				<span class="emphasis">
+					<em>sleep</em>
+				</span>
+				and whether a body is created sleeping.
+			</p>
+			<pre class="programlisting">
+bodyDef.SetAllowSleep(True)
+bodyDef.SetIsSleeping(False)
+			</pre>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="bullets"></a>
+							5.2.5. Bullets
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				Game simulation usually generates a sequence of images
+				that are played at some frame rate. In this setting
+				rigid bodies can move by a large amount in one time
+				step. If a physics engine doesn't account for the large
+				motion, you may see some objects incorrectly pass
+				through each other. This effect is called
+				<span class="emphasis">
+					<em>tunneling</em>
+				</span>
+				.
+			</p>
+			<p>
+				By default, Box2D uses continuous collision detection
+				(CCD) to prevent dynamic bodies from tunneling through
+				static bodies. This is done by sweeping shapes from
+				their old position to their new positions. The engine
+				looks for new collisions during the sweep and computes
+				the time of impact (TOI) for these collisions. Bodies
+				are moved to their first TOI and then simulated to the
+				end of the original time step. This process is repeated
+				as necessary.
+			</p>
+			<p>
+				Normally CCD is not used between dynamic bodies. This is
+				done to keep performance reasonable. In some game
+				scenarios you need dynamic bodies to use CCD. For
+				example, you may want to shoot a high speed bullet at a
+				thin wall. Without CCD, the bullet my tunnel through the
+				wall.
+			</p>
+			<p>
+				Fast moving objects in Box2D are called bullets. You
+				should decide what bodies should be bullets based on
+				your game design. If you decide a body should be treated
+				as a bullet, use the following setting.
+			</p>
+			<pre class="programlisting">
+bodyDef.SetIsBullet(True)
+</pre>
+			<p>The bullet flag only affects dynamic bodies.</p>
+			<p>
+				CCD is expensive so you probably don't want all moving
+				bodies to be bullets. So by default Box2D only uses CCD
+				between moving bodies and static bodies. This is an
+				effective approach to prevent bodies from escaping your
+				game world. However, you may have some fast moving
+				bodies that that require CCD all the time.
+			</p>
+		</div>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e683"></a>
+						5.3. Body Factory
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Bodies are created and destroyed using a body factory
+			provided by the world class. This lets the world create the
+			body with an efficient allocator and add the body to the
+			world data structure.
+		</p>
+		<p>
+			Bodies can be dynamic or static depending on the mass
+			properties. Both body types use the same creation and
+			destruction methods.
+		</p>
+		<pre class="programlisting">
+Local dynamicBody:b2Body = myWorld.CreateBody(bodyDef)
+... do stuff ... 
+myWorld.DestroyBody(dynamicBody)
+dynamicBody = NULL
+		</pre>
+		<p>
+			Static bodies do not move under the influence of other
+			bodies. You may manually move static bodies, but you should
+			be careful so that you don't squash dynamic bodies between
+			two or more static bodies. Friction will not work correctly
+			if you move a static body. Static bodies never simulate on
+			their own and they never collide with other static bodies.
+			It is faster to attach several shapes to a static body than
+			to create several static bodies with a single shape on each
+			one. Interally, Box2D sets the mass and inverse mass of
+			static bodies to zero. This makes the math work out so that
+			most algorithms don't need to treat static bodies as a
+			special case.
+		</p>
+		<p>
+			Box2D does not keep a reference to the body definition or
+			any of the data it holds (except user data references). So you
+			can create temporary body definitions and reuse the same
+			body definitions.
+		</p>
+		<p>
+			Box2D allows you to avoid destroying bodies by deleting your
+			<tt class="classname">b2World</tt>
+			object, which does all the cleanup work for you. However,
+			you should be mindful to nullify any body references that you
+			keep in your game engine.
+		</p>
+		<p>
+			When you destroy a body, the attached shapes and joints are
+			automatically destroyed. This has important implications for
+			how you manage shape and joint references. See
+			<a href="#implicit_destruction"
+				title="9.2. Implicit Destruction">
+				Section 9.2, &#8220;Implicit Destruction&#8221;
+			</a>
+			for details.
+		</p>
+		<p>
+			Suppose you want to connect a dynamic body to ground with a
+			joint. You'll need to connect the joint to a static body. If
+			you don't have a static body, you can get a shared ground
+			body from your world object. You can also attach static
+			shapes to the ground body.
+		</p>
+		<pre class="programlisting">
+Local ground:b2Body = myWorld.GetGroundBody()
+... build a joint using the ground body ...
+		</pre>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e720"></a>
+						5.4. Using a Body
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			After creating a body, there are many operations you can
+			perform on the body. These include setting mass properties,
+			accessing position and velocity, applying forces, and
+			transforming points and vectors.
+		</p>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e725"></a>
+							5.4.1. Mass Data
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				You can adjust the mass of a body at run-time. This is
+				usually done when you create or destroy shapes on a
+				body. You may want to adjust the mass of the body based
+				on the current shapes.
+			</p>
+			<pre class="programlisting">
+Method SetMassFromShapes()
+</pre>
+			<p>
+				You may also want to set the mass properties directly.
+				For example, you may change the shapes, but want to use
+				your own mass formulas.
+			</p>
+			<pre class="programlisting">
+Method SetMass(massData:b2MassData)
+			</pre>
+			<p>
+				The body's mass data is available through the following
+				functions:
+			</p>
+			<pre class="programlisting">
+Method GetMass:Float()
+Method GetInertia:Float()
+Method GetLocalCenter:b2Vec2()
+			</pre>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e740"></a>
+							5.4.2. State Information
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				There are many aspects to the body's state. You can
+				access this state data efficient through the following
+				functions:
+			</p>
+			<pre class="programlisting">
+Method IsBullet:Int()
+Method SetBullet(flag:Int)
+
+Method IsStatic:Int()
+Method IsDynamic:Int()
+
+Method IsFrozen:Int()
+
+Method IsSleeping:Int()
+Method AllowSleeping(flag:Int)
+Method WakeUp()
+			</pre>
+			<p>
+				The bullet state is described in
+				<a href="#bullets" title="5.2.5. Bullets">
+					Section 5.2.5, &#8220;Bullets&#8221;
+				</a>
+				. The frozen state is described in
+				<a href="#world_boundary"
+					title="9.1. World Boundary">
+					Section 9.1, &#8220;World Boundary&#8221;
+				</a>
+				.
+			</p>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e753"></a>
+							5.4.3. Position and Velocity
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				You access the position and rotation of a body. This is
+				common when rendering your associated game actor. You
+				can also set the position, although this is less common
+				since you will normally use Box2D to simulate movement.
+			</p>
+			<pre class="programlisting">
+Method SetXForm:Int(position:b2Vec2, angle:Float)
+Method GetXForm:b2XForm()
+Method GetPosition:b2Vec2()
+Method GetAngle:Float()
+			</pre>
+			<p>
+				You can access the center of mass position in world
+				coordinates. Much of the internal simulation in Box2D
+				uses the center of mass. However, you should normally
+				not need to access it. Instead you will usually work
+				with the body transform.
+			</p>
+			<pre class="programlisting">
+Method GetWorldCenter:b2Vec2()
+			</pre>
+			<p>
+				You can access the linear and angular velocity. The
+				linear velocity is for the center of mass.
+			</p>
+			<pre class="programlisting">
+Method SetLinearVelocity(v:b2Vec2)
+Method GetLinearVelocity:b2Vec2()
+Method SetAngularVelocity(omega:Float)
+Method GetAngularVelocity:Float()
+			</pre>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e768"></a>
+							5.4.4. Forces and Impulses
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				You can apply forces, torques, and impulses to a body.
+				When you apply a force or an impulse, you provide a
+				world point where the load is applied. This often
+				results in a torque about the center of mass.
+			</p>
+			<pre class="programlisting">
+Method ApplyForce(force:b2Vec2, point:b2Vec2)
+Method ApplyTorque(float32 torque:Float)
+Method ApplyImpulse(impulse:b2Vec2, point:b2Vec2)
+			</pre>
+			<p>
+				Applying a force, torque, or impulse wakes the body.
+				Sometimes this is undesirable. For example, you may be
+				applying a steady force and want to allow the body to
+				sleep to improve performance. In this case you can use
+				the following code.
+			</p>
+			<pre class="programlisting">
+If Not myBody.IsSleeping() Then
+	myBody.ApplyForce(myForce, myPoint)
+End If
+			</pre>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e779"></a>
+							5.4.5. Coordinate Transformations
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				The body class has some utility functions to help you
+				transform points and vectors between local and world
+				space. If you don't understand these concepts, please
+				read "Essential Mathematics for Games and Interactive
+				Applications" by Jim Van Verth and Lars Bishop. These
+				functions are efficient, so use them with impunity.
+			</p>
+			<pre class="programlisting">
+Method GetWorldPoint:b2Vec2(localPoint:b2Vec2)
+Method GetWorldVector:b2Vec2(localVector:b2Vec2)
+Method GetLocalPoint:b2Vec2(worldPoint:b2Vec2)
+Method GetLocalVector:b2Vec2(worldVector:b2Vec2)
+			</pre>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e786"></a>
+							5.4.6. Lists
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				You can iterate over a body's shapes. This is mainly
+				useful if you need to access the shape's user data.
+			</p>
+			<pre class="programlisting">
+Local s:b2Shape = body.GetShapeList()
+While s
+	Local data:MyShapeData = MyShapeData(s.GetUserData())
+	... do something with data ...
+	s = s.GetNext()
+Wend
+			</pre>
+			<p>You can similarly iterate over the body's joint list.</p>
+		</div>
+	</div>
+</div>
+<div class="chapter" lang="en">
+	<div class="titlepage">
+		<div>
+			<div>
+				<h2 class="title">
+					<a name="shapes"></a>
+					Chapter 6. Shapes
+				</h2>
+			</div>
+		</div>
+	</div>
+	<div class="toc">
+		<p>
+			<b>Table of Contents</b>
+		</p>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e798">6.1. About</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e807">6.2. The Shape Definition</a>
+				</span>
+			</dt>
+			<dd>
+				<dl>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e815">
+								6.2.1. Friction and Restitution
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e837">6.2.2. Density</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e845">6.2.3. Filtering</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e889">6.2.4. Sensors</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e898">
+								6.2.5. Circle Definitions
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e910">
+								6.2.6. Polygon Definitions
+							</a>
+						</span>
+					</dt>
+				</dl>
+			</dd>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e950">6.3. Shape Factory</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e976">6.4. Using a Shape</a>
+				</span>
+			</dt>
+		</dl>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e798"></a>
+						6.1. About
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Shapes are the collision geometry attached to bodies. Shapes
+			are also used to define the mass of a body. This lets you
+			specify the density and let Box2D do the work of computing
+			the mass properties.
+		</p>
+		<p>
+			Shapes have properties of friction and restitution. Shapes
+			carry collision filtering information to let you prevent
+			collisions between certain game objects.
+		</p>
+		<p>
+			Shapes are always owned by a body. You can attach multiple
+			shapes to a single body. Shapes are abstract classes so that
+			many types of shapes can be implemented in Box2D. If you are
+			brave, you can implement your own shape type (and collision
+			algorithms).
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e807"></a>
+						6.2. The Shape Definition
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Shape definitions are used to create shapes. There is common
+			shape data held by
+			<tt class="classname">b2ShapeDef</tt>
+			and specific shape data held by derived classes.
+		</p>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e815"></a>
+							6.2.1. Friction and Restitution
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				Friction is used to make objects slide along each other
+				realistically. Box2D supports static and dynamic
+				friction, but uses the same parameter for both. Friction
+				is simulated accurately in Box2D and the friction
+				strength is proportional to the normal force (this is
+				called
+				<span class="emphasis">
+					<em>Coulomb friction</em>
+				</span>
+				). The friction parameter is usually set between 0 and
+				1. A value of zero turns off friction and a value of one
+				makes the friction strong. When the friction is computed
+				between two shapes, Box2D must combine the friction
+				parameters of the two shapes. This is done with the
+				following formula:
+			</p>
+			<pre class="programlisting">
+Local friction:Float = Sqr(shape1.GetFriction() * shape2.GetFriction())
+			</pre>
+			<p>
+				Restitution is used to make objects bounce. The
+				restitution value is usually set to be between 0 and 1.
+				Consider dropping a ball on a table. A value of zero
+				means the ball won't bounce. This is called an
+				<span class="emphasis">
+					<em>inelastic</em>
+				</span>
+				collision. A value of one means the ball's velocity will
+				be exactly reflected. This is called a
+				<span class="emphasis">
+					<em>perfectly elastic</em>
+				</span>
+				collision. Restitution is combined using the following
+				formula.
+			</p>
+			<pre class="programlisting">
+Local restitution:Float = b2Max(shape1.GetRestitution(), shape2.GetRestitution())
+			</pre>
+			<p>
+				When a shape develops multiple contacts, restitution is
+				simulated approximately. This is because Box2D uses an
+				iterative solver. Box2D also uses inelastic collisions
+				when the collision velocity is small. This is done to
+				prevent jitter.
+			</p>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e837"></a>
+							6.2.2. Density
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				Box2D optionally computes the mass and rotational
+				inertia of bodies using the mass distribution implied by
+				the attached shapes. Specifying mass directly can often
+				lead to poorly tuned simulations. Therefore, the
+				recommended way of specifying body mass is by setting
+				the shape densities and calling
+				<tt class="literal">b2Body::SetMassFromShape</tt>
+				once all the shapes are attached to the body.
+			</p>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e845"></a>
+							6.2.3. Filtering
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				Collision filtering is a system for preventing collision
+				between shapes. For example, say you make a character
+				that rides a bicycle. You want the bicycle to collide
+				with the terrain and the character to collide with the
+				terrain, but you don't want the character to collide
+				with the bicycle (because they must overlap). Box2D
+				supports such collision filtering using categories and
+				groups.
+			</p>
+			<p>
+				Box2D supports 16 collision categories. For each shape
+				you can specify which category it belongs to. You also
+				specify what other categories this shape can collide
+				with. For example, you could specify in a multiplayer
+				game that all players don't collide with each other and
+				monsters don't collide with each other, but players and
+				monsters should collide. This is done with
+				<span class="emphasis">
+					<em>masking bits</em>
+				</span>
+				. For example:
+			</p>
+			<pre class="programlisting">
+playerShapeDef.GetFilter().SetCategoryBits($0002)
+monsterShapeDef.GetFilter().SetCategoryBits($0004)
+playerShape.GetFilter().SetMaskBits($0004)
+monsterShapeDef.GetFilter().SetMaskBits($0002)
+			</pre>
+			<p>
+				Collision groups let you specify an integral group
+				index. You can have all shapes with the same group index
+				always collide (positive index) or never collide
+				(negative index). Group indices are usually used for
+				things that are somehow related, like the parts of a
+				bicycle. In the following example, shape1 and shape2
+				always collide, but shape3 and shape4 never collide.
+			</p>
+			<pre class="programlisting">
+shape1Def.GetFilter().SetGroupIndex(2)
+shape2Def.GetFilter().SetGroupIndex(2)
+shape3Def.GetFilter().SetGroupIndex(-8)
+shape4Def.GetFilter().SetGroupIndex(-8)
+			</pre>
+			<p>
+				Collisions between shapes of different group indices are
+				filtered according the category and mask bits. In other
+				words, group filtering has higher precendence than
+				category filtering.
+			</p>
+			<p>
+				Note that additional collision filtering occurs in
+				Box2D. Here is a list:
+			</p>
+			<div class="itemizedlist">
+				<ul type="disc">
+					<li>
+						<p>
+							A shape on a static body never collides with
+							a shape on another static body.
+						</p>
+					</li>
+					<li>
+						<p>
+							Shapes on the same body never collide with
+							each other.
+						</p>
+					</li>
+					<li>
+						<p>
+							You can optionally enable/disable collision
+							between shapes on bodies connected by a
+							joint.
+						</p>
+					</li>
+				</ul>
+			</div>
+			<p>
+				Sometimes you might need to change collision filtering
+				after a shape has already been created. You can get and
+				set the
+				<span class="structname">b2FilterData</span>
+				structure on an existing shape using
+				<tt class="function">b2Shape::GetFilterData</tt>
+				and
+				<tt class="function">b2Shape::SetFilterData</tt>
+				. Box2D caches filtering results, so you must manually
+				re-filter a shape using
+				<tt class="function">b2World::Refilter</tt>
+				.
+			</p>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e889"></a>
+							6.2.4. Sensors
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				Some times game logic needs to know when two shapes
+				overlap yet there should be no collision response. This
+				is done by using sensors. A sensor is a shape that
+				detects collision but does not produce a response.
+			</p>
+			<p>
+				You can flag any shape as being a sensor. Sensors may be
+				static or dynamic. Remember that you may have multiple
+				shapes per body and you can have any mix of sensors and
+				solid shapes.
+			</p>
+			<pre class="programlisting">
+myShapeDef.SetIsSensor(True)
+			</pre>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e898"></a>
+							6.2.5. Circle Definitions
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				<tt class="classname">b2CircleDef</tt>
+				extends
+				<tt class="classname">b2ShapeDef</tt>
+				and adds a radius and a local position.
+			</p>
+			<pre class="programlisting">
+Local def:b2CircleDef = New b2CircleDef
+def.SetRadius(1.5)
+def.SetLocalPosition(Vec2(1.0, 0.0))
+			</pre>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e910"></a>
+							6.2.6. Polygon Definitions
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				<tt class="classname">b2PolyDef</tt>
+				is used to implement convex polygons. They are a bit
+				tricky to use correctly, so please read closely. The
+				maximum vertex count is defined by
+				<tt class="literal">b2_maxPolyVertices</tt>
+				which is currently 8. If you need to use more vertices,
+				you must modify
+				<tt class="literal">b2_maxPolyVertices</tt>
+				in
+				<tt class="literal">b2Settings.h</tt>
+				.
+			</p>
+			<p>
+				When you build a polygon definition you must specify the
+				number of vertices you will use. The vertices must be
+				specified in
+				<span class="emphasis">
+					<em>counter-clockwise</em>
+				</span>
+				(CCW) order about the z-axis of a right-handed
+				coordinate system. This might turn out to be clockwise
+				on your screen, depending on your coordinate system
+				conventions.
+			</p>
+			<p>
+				Polygons must be
+				<span class="emphasis">
+					<em>convex</em>
+				</span>
+				. In other words, each vertex must point outwards to
+				some degree. Finally, you must not overlap any vertices.
+				Box2D will automatically close the loop.
+			</p>
+			<div class="informalfigure">
+				<div class="mediaobject">
+					<img src="images/convex_concave.gif"></div>
+			</div>
+			<p>
+				Here is an example of a polygon definition of a
+				triangle:
+			</p>
+			<pre class="programlisting">
+Local triangleDef:b2PolygonDef = New b2PolygonDef
+Local vertices:b2Vec2[] = New b2Vec2[3]
+vertices[0] = Vec2(-1.0, 0.0)
+vertices[1] = Vec2(1.0, 0.0)
+vertices[2] = Vec2(0.0, 2.0)
+triangleDef.SetVertices(vertices)
+			</pre>
+			<p>
+				The vertices are defined in the coordinate system of the
+				parent body. If you need to offset a polygon within the
+				parent body, then just offset all the vertices.
+			</p>
+			<p>
+				For convenience, there are functions to initialize
+				polygons as boxes. You can have either an axis-aligned
+				box centered at the body origin or an oriented box
+				offset from the body origin.
+			</p>
+			<pre class="programlisting">
+Local alignedBoxDef:b2PolygonDef = New b2PolygonDef
+Local hx:Float = 1.0 ' half-width
+Local hy:Float = 2.0 ' half-height
+alignedBoxDef.SetAsBox(hx, hy)
+
+Local orientedBoxDef:b2PolygonDef = New b2PolygonDef
+Local center:b2Vec2 = Vec2(-1.5, 0.0)
+Local angle:Float = 90
+orientedBoxDef.SetAsOrientedBox(hx, hy, center, angle)
+			</pre>
+		</div>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e950"></a>
+						6.3. Shape Factory
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Shapes are created by initializing a shape definition and
+			then passing the definition to the parent body.
+		</p>
+		<pre class="programlisting">
+Local circleDef:b2CircleDef = new b2CircleDef
+circleDef.SetRadius(3.0)
+circleDef.SetDensity(2.5)
+Local myShape:b2Shape = myBody.CreateShape(circleDef)
+[optionally store shape reference somewhere]
+		</pre>
+		<p>
+			This creates the shape and attaches it to the body. You do
+			not need to store the shape pointer since the shape will
+			automatically be destroyed when the parent body is destroyed
+			(see
+			<a href="#implicit_destruction"
+				title="9.2. Implicit Destruction">
+				Section 9.2, &#8220;Implicit Destruction&#8221;
+			</a>
+			).
+		</p>
+		<p>
+			After you finish adding shapes to a body, you may want to
+			recompute the mass properties of the body based on the child
+			shapes.
+		</p>
+		<pre class="programlisting">
+myBody.SetMassFromShapes()
+		</pre>
+		<p>
+			This function is expensive, so you should only call it when
+			necessary.
+		</p>
+		<p>
+			You can destroy a shape on the parent body easily. You may
+			do this to model a breakable object. Otherwise you can just
+			leave the shape alone and let the body destruction take care
+			of destroying the attached shapes.
+		</p>
+		<pre class="programlisting">
+myBody.DestroyShape(myShape)
+		</pre>
+		<p>
+			After removing shapes from a body, you may want to call
+			<tt class="literal">SetMassFromShapes</tt>
+			again.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e976"></a>
+						6.4. Using a Shape
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			There's not much to say here. You can get a shape's type and
+			its parent body. You can also test a point to see if it is
+			contained within the shape. Look at
+			<tt class="literal">b2Shape.h</tt>
+			for details.
+		</p>
+	</div>
+</div>
+<div class="chapter" lang="en">
+	<div class="titlepage">
+		<div>
+			<div>
+				<h2 class="title">
+					<a name="d0e984"></a>
+					Chapter 7. Joints
+				</h2>
+			</div>
+		</div>
+	</div>
+	<div class="toc">
+		<p>
+			<b>Table of Contents</b>
+		</p>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e987">7.1. About</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e996">7.2. The Joint Definition</a>
+				</span>
+			</dt>
+			<dd>
+				<dl>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1018">7.2.1. Distance Joint</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1034">7.2.2. Revolute Joint</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1077">
+								7.2.3. Prismatic Joint
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1097">7.2.4. Pulley Joint</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1123">7.2.5. Gear Joint</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1150">7.2.6. Mouse Joint</a>
+						</span>
+					</dt>
+				</dl>
+			</dd>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e1155">7.3. Joint Factory</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e1187">7.4. Using Joints</a>
+				</span>
+			</dt>
+			<dd>
+				<dl>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1200">
+								7.4.1. Using Distance Joints
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1205">
+								7.4.2. Using Revolute Joints
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1226">
+								7.4.3. Using Prismatic Joints
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1233">
+								7.4.4. Using Pulley Joints
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1240">
+								7.4.5. Using Gear Joints
+							</a>
+						</span>
+					</dt>
+					<dt>
+						<span class="sect2">
+							<a href="#d0e1248">
+								7.4.6. Using Mouse Joints
+							</a>
+						</span>
+					</dt>
+				</dl>
+			</dd>
+		</dl>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e987"></a>
+						7.1. About
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Joints are used to constrain bodies to the world or to each
+			other. Typical examples in games include ragdolls, teeters,
+			and pulleys. Joints can be combined in many different ways
+			to create interesting motions.
+		</p>
+		<p>
+			Some joints provide limits so you can control the range of
+			motion. Some joint provide motors which can be used to drive
+			the joint at a prescribed speed until a prescribed
+			force/torque is exceeded.
+		</p>
+		<p>
+			Joint motors can be used in many ways. You can use motors to
+			control position by specifying a joint velocity that is
+			proportional to the difference between the actual and
+			desired position. You can also use motors to simulate joint
+			friction: set the joint velocity to zero and provide a
+			small, but significant maximum motor force/torque. Then the
+			motor will attempt to keep the joint from moving until the
+			load becomes too strong.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e996"></a>
+						7.2. The Joint Definition
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Each joint type has a definition that derives from
+			<tt class="classname">b2JointDef</tt>
+			. All joints are connected between two different bodies. One
+			body may static. If you want to waste memory, then create a
+			joint between two static bodies. :)
+		</p>
+		<p>
+			You can specify user data for any joint type and you can
+			provide a flag to prevent the attached bodies from colliding
+			with each other. This is actually the default behavior and
+			you must set the
+			<tt class="literal">collideConnected</tt>
+			Boolean to allow collision between to connected bodies.
+		</p>
+		<p>
+			Many joint definitions require that you provide some
+			geometric data. Often a joint will be defined by
+			<span class="emphasis">
+				<em>anchor points</em>
+			</span>
+			. These are points fixed in the attached bodies. Box2D
+			requires these points to be specified in local coordinates.
+			This way the joint can be specified even when the current
+			body transforms violate the joint constraint --- a common
+			ocurrence when a game is saved and reloaded. Additionally,
+			some joint definitions need to know the default relative
+			angle between the bodies. This is necessary to constraint
+			rotation correctly via joint limits or a fixed relative
+			angle.
+		</p>
+		<p>
+			Initializing the geometric data can be tedious, so many
+			joints have initialization functions that use the current
+			body transforms to remove much of the work. However, these
+			initialization functions should usually only be used for
+			prototyping. Production code should define the geometry
+			directly. This will make joint behavior more robust.
+		</p>
+		<p>
+			The rest of the joint definition data depends on the joint
+			type. We cover these now.
+		</p>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e1018"></a>
+							7.2.1. Distance Joint
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				One of the simplest joint is a distance joint which says
+				that the distance between two points on two bodies must
+				be constant. When you specify a distance joint the two
+				bodies should already be in place. Then you specify the
+				two
+				<span class="emphasis">
+					<em>anchor</em>
+				</span>
+				points in world coordinates. The first anchor point is
+				connected to body 1, and the second anchor point is
+				connected to body 2. These points imply the length of
+				the distance constraint.
+			</p>
+			<div class="informalfigure">
+				<div class="mediaobject">
+					<img src="images/distanceJoint.gif"></div>
+			</div>
+			<p>
+				Here is an example of a distance joint definition. In
+				this case we decide to allow the bodies to collide.
+			</p>
+			<pre class="programlisting">
+Local jointDef:b2DistanceJointDef = New b2DistanceJointDef
+jointDef.Initialize(myBody1, myBody2, worldAnchorOnBody1, worldAnchorOnBody2)
+jointDef.SetCollideConnected(True)
+			</pre>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e1034"></a>
+							7.2.2. Revolute Joint
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				A revolute joint forces two bodies to share a common
+				anchor point, often called a
+				<span class="emphasis">
+					<em>hinge point</em>
+				</span>
+				. The revolute joint has a single degree of freedom: the
+				relative rotation of the two bodies. This is called the
+				<span class="emphasis">
+					<em>joint angle</em>
+				</span>
+				.
+			</p>
+			<div class="informalfigure">
+				<div class="mediaobject">
+					<img src="images/revoluteJoint.gif"></div>
+			</div>
+			<p>
+				To specify a revolute you need to provide two bodies and
+				a single anchor point in world space. The initialization
+				function assumes that the bodies are already in the
+				correct position.
+			</p>
+			<p>
+				In this example, two bodies are connected by a revolute
+				joint at the first body's center of mass.
+			</p>
+			<pre class="programlisting">
+Local jointDef:b2RevoluteJointDef = New b2RevoluteJointDef
+jointDef.Initialize(myBody1, myBody2, myBody1.GetWorldCenter())
+			</pre>
+			<p>
+				The revolute joint angle is positive when body2 rotates
+				CCW about the angle point. Like all angles in Box2D, the
+				revolute angle is measured in radians. By convention the
+				revolute joint angle is zero when the joint is created
+				using
+				<tt class="literal">Initialize()</tt>
+				, regardless of the current rotation of the two bodies.
+			</p>
+			<p>
+				In some cases you might wish to control the joint angle.
+				For this, the revolute joint can optionally simulate a
+				joint limit and/or a motor.
+			</p>
+			<p>
+				A joint limit forces the joint angle to remain between
+				an lower and upper bound. The limit will apply as much
+				torque as needed to make this happen. The limit range
+				should include zero, otherwise the joint will lurch when
+				the simulation begins.
+			</p>
+			<p>
+				A joint motor allows you to specify the joint speed (the
+				time derivative of the angle). The speed can be negative
+				or positive. A motor can have infinite force, but this
+				is usually not desirable. Have you ever heard the
+				expression:
+			</p>
+			<div class="caution"
+				style="margin-left: 0.5in; margin-right: 0.5in;">
+				<h3 class="title">Caution</h3>
+				<p>
+					"What happens when an irresistible force meets an
+					immovable object?"
+				</p>
+			</div>
+			<p>
+				I can tell you it's not pretty. So you can provide a
+				maximum torque for the joint motor. The joint motor will
+				maintain the specified speed unless the required torque
+				exceeds the specified maximum. When the maximum torque
+				is exceeded, the joint will slow down and can even
+				reverse.
+			</p>
+			<p>
+				You can use a joint motor to simulate joint friction.
+				Just set the joint speed to zero, and set the maximum
+				torque to some small, but significant value. The motor
+				will try to prevent the joint from rotating, but will
+				yield to a significant load.
+			</p>
+			<p>
+				Here's a revision of the revolute joint definition
+				above; this time the joint has a limit and a motor
+				enabled. The motor is setup to simulate joint friction.
+			</p>
+			<pre class="programlisting">
+Local jointDef:b2RevoluteJointDef = New b2RevoluteJointDef
+jointDef.Initialize(body1, body2, myBody1.GetWorldCenter())
+jointDef.SetLowerAngle(-90)
+jointDef.SetUpperAngle(45)
+jointDef.EnableLimit(True)
+jointDef.SetMaxMotorTorque(10.0)
+jointDef.SetMotorSpeed(0.0)
+jointDef.EnableMotor(True)
+			</pre>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e1077"></a>
+							7.2.3. Prismatic Joint
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				A prismatic joint allows for relative translation of two
+				bodies along a specified axis. A prismatic joint
+				prevents relative rotation. Therefore, a prismatic joint
+				has a single degree of freedom.
+			</p>
+			<div class="informalfigure">
+				<div class="mediaobject">
+					<img src="images/prismaticJoint.gif"></div>
+			</div>
+			<p>
+				The prismatic joint definition is similar to the
+				revolute joint description; just substitute translation
+				for angle and force for torque. Using this analogy
+				provides an example prismatic joint definition with a
+				joint limit and a friction motor:
+			</p>
+			<pre class="programlisting">
+Local jointDef:b2PrismaticJointDef = new b2PrismaticJointDef
+Local worldAxis:b2Vec2 = new b2Vec2.Create(1.0, 0.0)
+jointDef.Initialize(myBody1, myBody2, myBody1.GetWorldCenter(), worldAxis)
+jointDef.SetLowerTranslation(-5.0)
+jointDef.SetUpperTranslation(2.5)
+jointDef.SetEnableLimit(True)
+jointDef.SetMotorForce(1.0)
+jointDef.SetMotorSpeed(0.0)
+jointDef.EnableMotor(True)
+			</pre>
+			<p>
+				The revolute joint has an implicit axis coming out of
+				the screen. The prismatic joint needs an explicit axis
+				parallel to the screen. This axis is fixed in the two
+				bodies and follows their motion.
+			</p>
+			<p>
+				Like the revolute joint, the prismatic joint translation
+				is zero when the joint is created using
+				<tt class="literal">Initialize()</tt>
+				. So be sure zero is between your lower and upper
+				translation limits.
+			</p>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e1097"></a>
+							7.2.4. Pulley Joint
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				A pulley is used to create an idealized pulley. The
+				pulley connects two bodies to ground and to each other.
+				As one body goes up, the other goes down. The total
+				length of the pulley rope is conserved according to the
+				initial configuration.
+			</p>
+			<pre class="programlisting">
+length1 + length2 = constant
+			</pre>
+			<div class="informalfigure">
+				<div class="mediaobject">
+					<img src="images/pulleyJoint.gif"></div>
+			</div>
+			<p>
+				You can supply a ratio that simulates a
+				<span class="emphasis">
+					<em>block and tackle</em>
+				</span>
+				. This causes one side of the pulley to extend faster
+				than the other. At the same time the constraint force is
+				smaller on one side than the other. You can use this to
+				create mechanical leverage.
+			</p>
+			<pre class="programlisting">
+length1 + ratio * length2 = constant
+			</pre>
+			<p>
+				For example, if the ratio is 2, then length1 will vary
+				at twice the rate of length2. Also the force in the rope
+				attached to body1 will have half the constraint force as
+				the rope attached to body2.
+			</p>
+			<p>
+				Pulleys can be troublesome when one side is fully
+				extended. The rope on the other side will have zero
+				length. At this point the constraint equations become
+				singular (bad). Therefore the pulley joint constrains
+				the maximum length that either side can attain. Also,
+				you may want to control the maximum lengths for gameplay
+				reasons. So the maximum lengths improve stability and
+				give you more control.
+			</p>
+			<p>Here is an example pulley definition:</p>
+			<pre class="programlisting">
+Local anchor1:b2Vec2 = myBody1.GetWorldCenter()
+Local anchor2:b2Vec2 = myBody2.GetWorldCenter()
+Local groundAnchor1:b2Vec2 = new b2Vec2(p1.x, p1.y + 10.0)
+Local groundAnchor2:b2Vec2 = new b2Vec2(p2.x, p2.y + 12.0)
+Local ratio:Float = 1.0
+Local jointDef:b2PulleyJointDef = new b2PulleyJointDef
+jointDef.Initialize(myBody1, myBody2, groundAnchor1, groundAnchor2, anchor1, anchor2, ratio)
+jointDef.SetMaxLength1(18.0)
+jointDef.SetMaxLength2(20.0)
+			</pre>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e1123"></a>
+							7.2.5. Gear Joint
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				If you want to create a sophisticated mechanical
+				contraption you might want to use a gears. In principle
+				you can create gears in Box2D by using compound shapes
+				to model gear teeth. This is not very efficient and
+				might be tedious to author. You also have to be careful
+				to line up the gears so the teeth mesh smoothly. Box2D
+				has a simpler method of creating gears: the
+				<span class="emphasis">
+					<em>gear joint</em>
+				</span>
+				.
+			</p>
+			<div class="informalfigure">
+				<div class="mediaobject">
+					<img src="images/gearJoint.gif"></div>
+			</div>
+			<p>
+				The gear joint requires the you have two bodies
+				connected to ground by a revolute or prismatic joint.
+				You can use any combination of those joint types. Also,
+				Box2D requires that the revolute and prismatic joints
+				were created with the ground as body1.
+			</p>
+			<p>
+				Like the pulley ratio, you can specify a gear ratio.
+				However, in this case the gear ratio can be negative.
+				Also keep in mind that when one joint is a revolute
+				joint (angular) and the other joint is prismatic
+				(translation), then the gear ratio with have units of
+				length or one over length.
+			</p>
+			<pre class="programlisting">
+coordinate1 + ratio * coordinate2 = constant
+			</pre>
+			<p>Here is an example gear joint:</p>
+			<pre class="programlisting">
+Local jointDef:b2GearJointDef = new b2GearJointDef
+jointDef.SetBody1(myBody1)
+jointDef.SetBody2(myBody2)
+jointDef.SetJoint1(myRevoluteJoint)
+jointDef.SetJoint2(myPrismaticJoint)
+jointDef.SetRatio(2.0 * Pi / myLength)
+			</pre>
+			<p>
+				Note that the gear joint depends on two other joints.
+				This creates a fragile situation. What happens if those
+				joints are deleted?
+			</p>
+			<div class="caution"
+				style="margin-left: 0.5in; margin-right: 0.5in;">
+				<h3 class="title">Caution</h3>
+				<p>
+					Always delete gear joints before the
+					revolute/prismatic joints on the gears. Otherwise
+					your code will crash in a bad way due to the
+					orphaned joint references in the gear joint. You
+					should also delete the gear joint before you delete
+					any of the bodies involved.
+				</p>
+			</div>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e1150"></a>
+							7.2.6. Mouse Joint
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				The mouse joint is used in the examples to manipulate
+				bodies with the mouse.
+			</p>
+		</div>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e1155"></a>
+						7.3. Joint Factory
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Joints are created and destroyed using the world factory
+			methods. This brings up an old issue:
+		</p>
+		<div class="caution"
+			style="margin-left: 0.5in; margin-right: 0.5in;">
+			<h3 class="title">Caution</h3>
+			<p>
+				You must create and destroy bodies and joints using
+				the create and destroy methods of the
+				<tt class="classname">b2World</tt>
+				class.
+			</p>
+		</div>
+		<p>Here's an example of the lifetime of a revolute joint:</p>
+		<pre class="programlisting">
+Local jointDef:b2RevoluteJointDef = new b2RevoluteJointDef
+jointDef.SetBody1(myBody1)
+jointDef.SetBody2(myBody2)
+jointDef.SetAnchorPoint(myBody1.GetCenterPosition())
+Local joint:b2RevoluteJoint = myWorld.CreateJoint(jointDef)
+... do stuff ...
+myWorld.DestroyJoint(joint)
+joint = Null
+		</pre>
+		<p>
+			It is always good to nullify your pointer after they are
+			destroyed. This will make the program crash in a controlled
+			manner if you try to reuse the pointer.
+		</p>
+		<p>
+			The lifetime of a joint is not simple. Heed this warning
+			well:
+		</p>
+		<div class="caution"
+			style="margin-left: 0.5in; margin-right: 0.5in;">
+			<h3 class="title">Caution</h3>
+			<p>
+				Joints are destroyed when an attached body is destroyed.
+			</p>
+		</div>
+		<p>
+			This precaution is not always necessary. You may organize
+			your game engine so that joints are always destroyed before
+			the attached bodies. In this case you don't need to
+			implement the listener class. See
+			<a href="#implicit_destruction"
+				title="9.2 Implicit Destruction">
+				Section 9.2, &quote;Implicit Destruction&quote;
+			</a>
+			for details.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e1187"></a>
+						7.4. Using Joints
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Many simulations create the joints and don't access them
+			again until they are detroyed. However, there is a lot of
+			useful data contained in joints that you can use to create a
+			rich simulation.
+		</p>
+		<p>
+			First of all, you can get the bodies, anchor points, and
+			user data from a joint.
+		</p>
+		<pre class="programlisting">
+Method GetBody1:b2Body()
+Method GetBody2:b2Body()
+Method GetAnchor1:b2Vec2()
+Method GetAnchor2:b2Vec2()
+Method GetUserData:Object()
+		</pre>
+		<p>
+			All joints have a reaction force and torque. This the
+			reaction force applied to body 2 at the anchor point. You
+			can use reaction forces to break joints or trigger other
+			game events. These functions may do some computations, so
+			don't call them if you don't need the result.
+		</p>
+		<pre class="programlisting">
+Method GetReactionForce:b2Vec2()
+Method GetReactionTorque:Float()
+		</pre>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e1200"></a>
+							7.4.1. Using Distance Joints
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				Distance joints don't have motors or limits, so there
+				are no extra runtime methods for distance joints.
+			</p>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e1205"></a>
+							7.4.2. Using Revolute Joints
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				You can access a revolute joint's angle, speed, and
+				motor torque.
+			</p>
+			<pre class="programlisting">
+Method GetJointAngle:Float()
+Method GetJointSpeed:Float()
+Method GetMotorTorque:Float()
+			</pre>
+			<p>You also update the motor parameters each step.</p>
+			<pre class="programlisting">
+Method SetMotorSpeed(speed:Float)
+Method SetMaxMotorTorque(torque:Float)
+			</pre>
+			<p>
+				Joint motors have some interesting abilities. You can
+				update the joint speed every time step so you can make
+				the joint move back-and-forth like a sine-wave or
+				according to whatever function you want.
+			</p>
+			<pre class="programlisting">
+... Game Loop Begin ...
+myJoint.SetMotorSpeed(Cos(0.5 * time))
+ ... Game Loop End ...
+			</pre>
+			<p>
+				You can also use joint motors to track a desired joint
+				angle. For example:
+			</p>
+			<pre class="programlisting">
+... Game Loop Begin ...
+Local angleError:Float = myJoint.GetJointAngle() - angleTarget
+Local gain:Float = 0.1
+myJoint.SetMotorSpeed(-gain * angleError)
+... Game Loop End ...
+			</pre>
+			<p>
+				Generally your gain parameter should not be too large.
+				Otherwise your joint may become unstable.
+			</p>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e1226"></a>
+							7.4.3. Using Prismatic Joints
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				Using a prismatic joint is similar to using a revolute
+				joint. Here are the relevant member functions:
+			</p>
+			<pre class="programlisting">
+Method GetJointTranslation:Float()
+Method GetJointSpeed:Float()
+Method GetMotorForce:Float()
+Method SetMotorSpeed(speed:Float)
+Method SetMotorForce(force:Float)
+			</pre>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e1233"></a>
+							7.4.4. Using Pulley Joints
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>Pully joints provide the current lengths.</p>
+			<pre class="programlisting">
+Method GetLength1:Float()
+Method GetLength2:Float()
+			</pre>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e1240"></a>
+							7.4.5. Using Gear Joints
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				Gear joints don't provide any information beyond the
+				functions defined in
+				<tt class="classname">b2Joint</tt>
+				.
+			</p>
+		</div>
+		<div class="sect2" lang="en">
+			<div class="titlepage">
+				<div>
+					<div>
+						<h3 class="title">
+							<a name="d0e1248"></a>
+							7.4.6. Using Mouse Joints
+						</h3>
+					</div>
+				</div>
+			</div>
+			<p>
+				The mouse joint is able to manipulate the attached body
+				by updating the target point each time step.
+			</p>
+		</div>
+	</div>
+</div>
+<div class="chapter" lang="en">
+	<div class="titlepage">
+		<div>
+			<div>
+				<h2 class="title">
+					<a name="d0e1253"></a>
+					Chapter 8. Contacts
+				</h2>
+			</div>
+		</div>
+	</div>
+	<div class="toc">
+		<p>
+			<b>Table of Contents</b>
+		</p>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e1256">8.1. About</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e1310">8.2. Contact Listener</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e1359">8.3. Contact Filtering</a>
+				</span>
+			</dt>
+		</dl>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e1256"></a>
+						8.1. About
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Contacts are objects created by Box2D to manage collision
+			between shapes. There are different kinds of contacts,
+			derived from
+			<tt class="classname">b2Contact</tt>
+			, for managing contact between different kinds of shapes.
+			For example there is a contact class for managing
+			polygon-polygon collision and another contact class for
+			managing circle-circle collision. This is normally not
+			important to you, I just thought you might like to know.
+		</p>
+		<p>
+			Here is some terminlogy associated with contacts. This
+			terminology is particular to Box2D, but you might find
+			similar terminology in other physics engines.
+		</p>
+		<div class="glosslist">
+			<dl>
+				<dt>contact point</dt>
+				<dd>
+					<p>
+						A contact point is a point where two shapes
+						touch. In reality objects may touch over regions
+						when surfaces touch. Box2D approximates contact
+						with a small number of points.
+					</p>
+				</dd>
+				<dt>contact normal</dt>
+				<dd>
+					<p>
+						A contact normal is a unit vector that points
+						from shape1 to shape2.
+					</p>
+				</dd>
+				<dt>contact separation</dt>
+				<dd>
+					<p>
+						Separation is the opposite of penetration.
+						Separation is negative when shapes overlap. It
+						is possible that future versions of Box2D will
+						create contact points with positive separation,
+						so you may want to check the sign when contact
+						points are reported.
+					</p>
+				</dd>
+				<dt>normal force</dt>
+				<dd>
+					<p>
+						Box2D use an iterative contact solver and stores
+						the results with the contact points. You can
+						safely use the normal force to guage the
+						collision intensity. For example, you can use
+						the force to trigger breakables or to play
+						collision sounds.
+					</p>
+				</dd>
+				<dt>tangent force</dt>
+				<dd>
+					<p>
+						The tangent force is the contact solver's
+						estimate of the friction force.
+					</p>
+				</dd>
+				<dt>contact ids</dt>
+				<dd>
+					<p>
+						Box2D tries to re-use the contact force results
+						from a time step as the initial guess for the
+						next time step. Box2D uses contact ids to match
+						contact points across time steps. The ids
+						contain geometric features indices that help to
+						distinguish one contact point from another.
+					</p>
+				</dd>
+			</dl>
+		</div>
+		<p>
+			Contacts are created when two shape's AABBs overlap.
+			Sometimes collision filtering will prevent the creation of
+			contacts. Box2D sometimes needs to create a contact even
+			though the collision is filtered. In this case it uses a
+			<tt class="classname">b2NullContact</tt>
+			that prevents collision from occuring. Contacts are
+			destroyed with the AABBs cease to overlap.
+		</p>
+		<p>
+			So you might gather that there may be contacts created for
+			shapes that are not touching (just their AABBs). Well, this
+			is correct. It's a "chicken or egg" problem. We don't know
+			if we need a contact object until one is created to analyze
+			the collision. We could delete the contact right away if the
+			shapes are not touching, or we can just wait until the AABBS
+			stop overlapping. Box2D takes the latter approach.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e1310"></a>
+						8.2. Contact Listener
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			You can receive contact data by implementing
+			<tt class="classname">b2ContactListener</tt>
+			. This listener reports a contact point when it is created,
+			when it persists for more than one time step, and when it is
+			destroyed. Keep in mind that two shapes may have multiple
+			contact points.
+		</p>
+		<pre class="programlisting">
+Type MyContactListener Extends b2ContactListener
+
+	Method Add(point:b2ContactPoint)
+		' handle add point
+	End Method
+	
+	Method Persist(point:b2ContactPoint)
+		' handle persist point
+	End Method
+	
+	Method Remove(point:b2ContactPoint)
+		' handle remove point
+	End Method
+	
+	Method Result(point:b2ContactResult)
+		' handle results
+	End Method
+
+End Type
+		</pre>
+		<div class="caution"
+			style="margin-left: 0.5in; margin-right: 0.5in;">
+			<h3 class="title">Caution</h3>
+			<p>
+				Do not keep a reference to the contact points returned
+				to
+				<tt class="classname">b2ContactListener</tt>
+				. Instead make a deep copy of the contact point data
+				into your own buffer. The example below shows one way of
+				doing this.
+			</p>
+		</div>
+		<p>
+			Continuous physics uses sub-stepping, so a contact point may
+			be added and removed within the same time step. This is
+			normally not a problem, but your code should handle this
+			gracefully.
+		</p>
+		<p>
+			Contact points are reported immediately when they are added,
+			persisted, or removed. This occurs before the solver is
+			called, so the
+			<span class="structname">b2ContactPoint</span>
+			object does not contain the computed impulse. However, the
+			relative velocity at the contact point is provided so that
+			you can estimated the contact impulse. If you implement the
+			<tt class="function">Result</tt>
+			listener function, you will receive
+			<span class="structname">b2ContactResult</span>
+			objects for solid contact points after the solver has been
+			called. These result structures contain the sub-step
+			impulses. Again, due to continuous physics you may receive
+			multiple results per contact point per
+			<tt class="function">b2World::DoStep</tt>
+			.
+		</p>
+		<p>
+			It is tempting to implement game logic that alters the
+			physics world inside a contact callback. For example, you
+			may have a collision that applies
+			<span class="emphasis">
+				<em>damage</em>
+			</span>
+			and try to destroy the associated actor and its rigid body.
+			However, Box2D does not allow you to alter the physics world
+			inside a callback because you might destroy objects that
+			Box2D is currently processing, leading to orphaned references.
+		</p>
+		<p>
+			The recommended practice for processing contact points is to
+			buffer all contact points that you care about and process
+			them after the time step. You should always process the
+			contact points immediately after the time step, otherwise
+			some other client code might alter the physics world,
+			invalidating the contact buffer. When you process the
+			contact point buffer you can alter the physics world, but
+			you still need to be careful that you don't orphan references
+			stored in the contact point buffer. The testbed has example
+			contact point processing that is safe from orphaned
+			references.
+		</p>
+		<p>
+			This code from the CollisionProcessing test shows how to
+			handle orphaned bodies when processing the contact buffer.
+			Here is an excerpt. Be sure to read the comments in the
+			listing. This code assumes that all contact points have been
+			buffered in the
+			<tt class="classname">b2ContactPoint</tt>
+			array
+			<tt class="varname">m_points</tt>
+			.
+		</p>
+		<pre class="programlisting">
+' We are going to destroy some bodies according to contact
+' points. We must buffer the bodies that should be destroyed
+' because they may belong to multiple contact points.
+Local k_maxNuke:Int = 6
+Local nuke:b2Body[] = new b2Body[k_maxNuke]
+Local nukeCount:Int = 0
+
+' Traverse the contact buffer. Destroy bodies that
+' are touching heavier bodies.
+For Local i:Int = 0 Until m_pointCount
+
+	Local point:ContactPoint = m_points[i]
+	
+	Local body1:b2Body = point.GetShape1().GetBody()
+	Local body2:b2Body = point.GetShape2().GetBody()
+	Local mass1:Float = body1.GetMass()
+	Local mass2:Float = body2.GetMass()
+	
+	If mass1 &gt; 0.0 And mass2 &gt; 0.0 Then
+	
+		If mass2 &gt; mass1 Then
+			nuke[nukeCount] = body1
+		Else
+			nuke[nukeCount] = body2
+		End If
+		nukeCount:+ 1
+	
+		If nukeCount = k_maxNuke Then
+			Exit
+		End If
+	
+Next
+
+' Sort the nuke array to group duplicates.
+'std::sort(nuke, nuke + nukeCount); .. .TODO
+
+' Destroy the bodies, skipping duplicates.
+Local i:Int = 0
+While i &lt; nukeCount
+	Local b:b2Body = nuke[i]
+	i:+ 1
+	While i &lt; nukeCount And nuke[i] = b
+		i:+ 1
+	Wend
+
+	m_world.DestroyBody(b)
+Wend
+
+		</pre>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e1359"></a>
+						8.3. Contact Filtering
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Often in a game you don't want all objects to collide. For
+			example, you may want to create a door that only certain
+			characters can pass through. This is called contact
+			filtering, because some interactions are
+			<span class="emphasis">
+				<em>filtered out</em>
+			</span>
+			.
+		</p>
+		<p>
+			Box2D allows you to achieve custom contact filtering by
+			implementing a
+			<tt class="classname">b2ContactFilter</tt>
+			class. This class requires you to implement a
+			<tt class="methodname">ShouldCollide</tt>
+			method that receives two
+			<tt class="classname">b2Shape</tt>
+			references. Your method returns true if the shapes should
+			collide.
+		</p>
+		<p>
+			The default implementation of
+			<tt class="methodname">ShouldCollide</tt>
+			uses the
+			<span class="structname">b2FilterData</span>
+			defined in
+			<a href="#shapes" title="Chapter 6. Shapes">
+				Chapter 6,
+				<i>Shapes</i>
+			</a>
+			.
+		</p>
+		<pre class="programlisting">
+Method ShouldCollide:Int(shape1:b2Shape, shape2:b2Shape)
+
+	Local filter1:b2FilterData = shape1.GetFilterData()
+	Local filter2:b2FilterData = shape2.GetFilterData()
+
+	If filter1.GetGroupIndex() = filter2.GetGroupIndex() And filter1.GetGroupIndex() &lt;&gt; 0 Then
+		return filter1.GetGroupIndex() &lt; $7FFF
+	End If
+
+	Local collide:Int = (filter1.GetMaskBits() &amp; filter2.GetCategoryBits()) &lt;&gt; 0 And ..
+		(filter1.GetCategoryBits() &amp; filter2.GetMaskBits()) &lt;&gt; 0
+	return collide
+	
+End Method
+
+		</pre>
+	</div>
+</div>
+<div class="chapter" lang="en">
+	<div class="titlepage">
+		<div>
+			<div>
+				<h2 class="title">
+					<a name="d0e1390"></a>
+					Chapter 9. Loose Ends
+				</h2>
+			</div>
+		</div>
+	</div>
+	<div class="toc">
+		<p>
+			<b>Table of Contents</b>
+		</p>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#world_boundary">9.1. World Boundary</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#implicit_destruction">
+						9.2. Implicit Destruction
+					</a>
+				</span>
+			</dt>
+		</dl>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="world_boundary"></a>
+						9.1. World Boundary
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			You can implement a
+			<tt class="classname">b2BoundaryListener</tt>
+			that allows
+			<tt class="classname">b2World</tt>
+			to inform you when a body has gone outside the world AABB.
+			When you get the callback, you shouldn't try to delete the
+			body, instead you should mark the parent actor for deletion
+			or error handling. After the physics time step, you should
+			handle the event.
+		</p>
+		<pre class="programlisting">
+Type MyBoundaryListener Extends b2BoundaryListener
+
+	Method Violation(body:b2Body)
+		Local myActor:MyActor = MyActor(body.GetUserData())
+		myActor.MarkForErrorHandling()
+	End Method
+
+End Type
+		</pre>
+		<p>
+			You can then register an instance of your boundary listener
+			with your world object. You should do this during world
+			initialization.
+		</p>
+		<pre class="programlisting">
+myWorld.SetBoundaryListener(myBoundaryListener)
+		</pre>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="implicit_destruction"></a>
+						9.2. Implicit Destruction
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			Box2D doesn't use reference counting. So if you destroy a
+			body it is really gone. Accessing a pointer to a destroyed
+			body has undefined behavior. In other words, your program
+			will likely crash and burn. To help fix these problems, the
+			debug build memory manager fills destroyed entities with
+			<tt class="literal">FDFDFDFD</tt>
+			. This can help find problems more easily in some cases.
+		</p>
+		<p>
+			If you destroy a Box2D entity, it is up to you to make sure
+			you remove all references to the destroyed object. This is
+			easy if you only have a single reference to the entity. If
+			you have multiple references, you might consider
+			implementing a
+			<span class="emphasis">
+				<em>handle</em>
+			</span>
+			class to wrap the raw pointer.
+		</p>
+		<p>
+			Often when using Box2D you will create and destroy many
+			bodies, shapes, and joints. Managing these entities is
+			somewhat automated by Box2D. If you destroy a body then all
+			associated shapes and joints are automatically destroyed.
+			This is called
+			<span class="emphasis">
+				<em>implicit destruction</em>
+			</span>
+			.
+		</p>
+		<p>
+			When you destroy a body, all its attached shapes, joints,
+			and contacts are destroyed. This is called
+			<span class="emphasis">
+				<em>implicit destruction</em>
+			</span>
+			. Any body connected to one of those joints and/or contacts
+			is woken. This process is usually convenient. However, you
+			must be aware of one crucial issue:
+		</p>
+		<div class="caution"
+			style="margin-left: 0.5in; margin-right: 0.5in;">
+			<h3 class="title">Caution</h3>
+			<p>
+				When a body is destroyed, all shapes and joints attached
+				to the body are automatically destroyed. You must
+				nullify any references you have to those shapes and
+				joints. Otherwise, your program will
+				<span class="emphasis">
+					<em>die horribly</em>
+				</span>
+				if you try to access or destroy those shapes or joints
+				later.
+			</p>
+		</div>
+		<p>
+			To help you nullify your joint references, Box2D provides a
+			listener class named
+			<tt class="classname">b2WorldListener</tt>
+			that you can implement and provide to your world object.
+			Then the world object will notify you when a joint is going
+			to be implicity destroyed.
+		</p>
+		<p>
+			Implicit destruction is a great convenience in many cases.
+			It can also make your program fall apart. You may store
+			references to shapes and joints somewhere in your code. These
+			references become orphaned when an associated body is
+			destroyed. The situation becomes worse when you consider
+			that joints are often created by a part of the code
+			unrelated to management of the associated body. For example,
+			the testbed creates a
+			<tt class="classname">b2MouseJoint</tt>
+			for interactive manipulation of bodies on the screen.
+		</p>
+		<p>
+			Box2D provides a callback mechanism to inform your
+			application when implicit destruction occurs. This gives
+			your application a chance to nullify the orphaned pointers.
+			This callback mechanism is described later in this manual.
+		</p>
+		<p>
+			You can implement a
+			<tt class="classname">b2DestructionListener</tt>
+			that allows
+			<tt class="classname">b2World</tt>
+			to inform you when a shape or joint is implicitly destroyed
+			because an associated body was destroyed. This will help
+			prevent your code from accessing orphaned pointers.
+		</p>
+		<pre class="programlisting">
+Type MyDestructionListener Extends b2DestructionListener
+
+	Method SayGoodbye(joint:b2Joint)
+		' remove all references to joint.
+	End Method
+
+End Type
+		</pre>
+		<p>
+			You can then register an instance of your destruction
+			listener with your world object. You should do this during
+			world initialization.
+		</p>
+		<pre class="programlisting">
+myWorld.SetDestructionListener(myDestructionListener)
+		</pre>
+	</div>
+</div>
+<div class="chapter" lang="en">
+	<div class="titlepage">
+		<div>
+			<div>
+				<h2 class="title">
+					<a name="d0e1465"></a>
+					Chapter 10. Settings
+				</h2>
+			</div>
+		</div>
+	</div>
+	<div class="toc">
+		<p>
+			<b>Table of Contents</b>
+		</p>
+		<dl>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e1468">10.1. About</a>
+				</span>
+			</dt>
+			<dt>
+				<span class="sect1">
+					<a href="#d0e1481">10.2. Tolerances</a>
+				</span>
+			</dt>
+		</dl>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e1468"></a>
+						10.1. About
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			There are two source files included in Box2D that are
+			supplied specifically for user customization. These are
+			<tt class="filename">b2Settings.h</tt>
+			and
+			<tt class="filename">b2Settings.cpp</tt>
+			.
+		</p>
+		<p>
+			Box2D works with floating point numbers, so some tolerances
+			have to be used to make Box2D perform well.
+		</p>
+	</div>
+	<div class="sect1" lang="en">
+		<div class="titlepage">
+			<div>
+				<div>
+					<h2 class="title" style="clear: both">
+						<a name="d0e1481"></a>
+						10.2. Tolerances
+					</h2>
+				</div>
+			</div>
+		</div>
+		<p>
+			There are many tolerances settings that depend on using MKS
+			units. See
+			<a href="#units" title="3.3. Units">
+				Section 3.3, &#8220;Units&#8221;
+			</a>
+			for a deeper explanation of the unit system. See the doxygen
+			docs for explanation of the individual tolerances.
+		</p>
+	</div>
+</div>
+<div class="chapter" lang="en">
+	<div class="titlepage">
+		<div>
+			<div>
+				<h2 class="title">
+					<a name="d0e1513"></a>
+					Chapter 11. Debug Drawing
+				</h2>
+			</div>
+		</div>
+	</div>
+	<p>
+		You can implement the
+		<tt class="classname">b2DebugDraw</tt>
+		class to get detailed drawing of the physics world. Here are the
+		available entities:
+	</p>
+	<div class="itemizedlist">
+		<ul type="disc">
+			<li>
+				<p>shape outlines</p>
+			</li>
+			<li>
+				<p>joint connectivity</p>
+			</li>
+			<li>
+				<p>core shapes (for continuous collision)</p>
+			</li>
+			<li>
+				<p>
+					broad-phase axis-aligned bounding boxes (AABBs),
+					including the world AABB
+				</p>
+			</li>
+			<li>
+				<p>polygon oriented bounding boxes (OBBs)</p>
+			</li>
+			<li>
+				<p>broad-phase pairs (potential contacts)</p>
+			</li>
+			<li>
+				<p>center of mass</p>
+			</li>
+		</ul>
+	</div>
+	<p>
+		This the preferred method of drawing these physics entities,
+		rather than accessing the data directly. The reason is that much
+		of the necessary data is internal and subject to change.
+	</p>
+	<p>
+		The testbed draws physics entities using the debug draw facility
+		and the contact listener, so it serves as the primary example of
+		how to implement debug drawing as well as how to draw contact
+		points.
+	</p>
+</div>
+</div>

+ 75 - 0
box2d.mod/doc/manual.css

@@ -0,0 +1,75 @@
+div.caution p {
+	border: 1px solid Gray;
+	background-color: InfoBackground;
+	padding: 6px;
+}
+
+pre.programlisting {
+	padding: 6px;
+	background-color: #E8E8E8;
+	border: 1pt solid Gray;
+	font-family: monospace;
+}
+
+div.book div.titlepage h1.title {
+	font-weight: bold;
+	font-size: xx-large;
+	text-align: center;
+	padding: 10px 0px 10px 0px;
+}
+
+div.book div.titlepage h3.author {
+	font-size: large;
+	text-align: center;
+	padding: 10px 0px 10px 0px;
+}
+
+div.book div.titlepage p.copyright {
+	font-size: small;
+	text-align: center;
+	padding: 0px 0px 50px 0px;
+}
+
+div.chapter div.titlepage h2.title {
+	color: Navy;
+	margin: 55px 0px 0px 0px;
+	padding: 5px 0px 5px 5px;
+	font: bold x-large sans-serif;
+	border-bottom: 3px double #D3D3D3;
+}
+
+div.chapter div.sect1 div.titlepage h2.title {
+	color: Navy;
+	background-color: transparent;
+	padding: 5px 0px 0px 0px;
+	font: bold large sans-serif;
+	border-bottom: 1px solid #D3D3D3;
+}
+
+div.chapter div.sect1 div.sect2 div.titlepage h3.title {
+	color: Black;
+	background-color: transparent;
+	padding: 5px 0px 0px 0px;
+	font: bold medium serif;
+}
+
+div.glosslist dt
+{
+	font-weight: bold;
+}
+
+div.toc span.part {
+	font-family: Tahoma, Ariel, Helvetica, sans-serif;
+	font-weight: bold;
+	font-size: 20;
+	margin-top: 1in;
+}
+
+div.toc span.chapter {
+	color: Navy;
+	font-weight: bold;
+}
+
+div.informalfigure {
+	margin: 20px 0px 10px 60px;
+}

BIN
box2d.mod/examples/04B_03__.ttf


+ 111 - 0
box2d.mod/examples/applyforce.bmx

@@ -0,0 +1,111 @@
+SuperStrict
+
+Framework BaH.Box2d
+Import BRL.GLMax2D
+
+Import "test.bmx"
+Import brl.standardio
+
+Graphics 800,600, 0
+SetBlend alphablend
+
+
+Run(New ApplyForce.Create(), New TSettings)
+
+
+Type ApplyForce Extends Test
+
+	Field m_body:b2Body
+
+
+	Method Create:ApplyForce()
+	
+		Init(12, 12)
+						
+		m_world.SetGravity(New b2Vec2.Create(0.0, 0.0))
+
+		Const k_restitution:Float = 0.4
+
+		Local bd:b2BodyDef = New b2BodyDef
+		bd.SetPosition(New b2Vec2.Create(0.0, 20.0))
+		Local ground:b2Body = m_world.CreateBody(bd)
+
+		Local sd:b2PolygonDef = New b2PolygonDef
+		sd.SetDensity(0.0)
+		sd.SetRestitution(k_restitution)
+
+		sd.SetAsOrientedBox(0.2, 20.0, New b2Vec2.Create(-20.0, 0.0), 0.0)
+		ground.CreateShape(sd)
+
+		sd.SetAsOrientedBox(0.2, 20.0, New b2Vec2.Create(20.0, 0.0), 0.0)
+		ground.CreateShape(sd)
+
+		sd.SetAsOrientedBox(0.2, 20.0, New b2Vec2.Create(0.0, -20.0), 90)
+		ground.CreateShape(sd)
+
+		sd.SetAsOrientedBox(0.2, 20.0, New b2Vec2.Create(0.0, 20.0), 90)
+		ground.CreateShape(sd)
+		
+
+		Local xf1:b2XForm = New b2XForm.Create()
+
+		xf1.R.SetAngle(63.432)
+		xf1.SetPosition(b2Mul(xf1.R, New b2Vec2.Create(1.0, 0.0)))
+
+		Local sd1:b2PolygonDef = New b2PolygonDef
+		Local vertices:b2Vec2[] = New b2Vec2[3]
+
+		vertices[0] = b2MulF(xf1, New b2Vec2.Create(-1.0, 0.0))
+		vertices[1] = b2MulF(xf1, New b2Vec2.Create(1.0, 0.0))
+		vertices[2] = b2MulF(xf1, New b2Vec2.Create(0.0, 0.5))
+		sd1.SetVertices(vertices)
+		sd1.SetDensity(2.0)
+
+		Local xf2:b2XForm = New b2XForm.Create()
+		xf2.R.SetAngle(-63.432)
+		xf2.SetPosition(b2Mul(xf2.R, New b2Vec2.Create(-1.0, 0.0)))
+
+		Local sd2:b2PolygonDef = New b2PolygonDef
+		vertices = New b2Vec2[3]
+		vertices[0] = b2MulF(xf2, New b2Vec2.Create(-1.0, 0.0))
+		vertices[1] = b2MulF(xf2, New b2Vec2.Create(1.0, 0.0))
+		vertices[2] = b2MulF(xf2, New b2Vec2.Create(0.0, 0.5))
+
+		sd2.SetVertices(vertices)
+		sd2.SetDensity(2.0)
+
+		bd = New b2BodyDef
+		bd.SetAngularDamping(2.0)
+		bd.SetLinearDamping(0.1)
+
+		bd.SetPosition(New b2Vec2.Create(0.0, 1.05))
+		bd.SetAngle(180)
+		m_body = m_world.CreateBody(bd)
+		m_body.CreateShape(sd1)
+		m_body.CreateShape(sd2)
+		m_body.SetMassFromShapes()
+		
+		Return Self
+	End Method
+	
+	Method Keyboard()
+		Super.Keyboard()
+		
+		If KeyDown(KEY_W) Then
+			Local f:b2Vec2 = m_body.GetWorldVector(New b2Vec2(0.0, -50.0))
+			Local p:b2Vec2 = m_body.GetWorldPoint(New b2Vec2(0.0, 1.0))
+			m_body.ApplyForce(f, p)
+		End If
+
+		If KeyDown(KEY_A)
+			m_body.ApplyTorque(10.0)
+		End If
+
+		If KeyDown(KEY_D)
+			m_body.ApplyTorque(-10.0)
+		End If
+
+	End Method
+
+End Type
+

+ 94 - 0
box2d.mod/examples/bridge.bmx

@@ -0,0 +1,94 @@
+SuperStrict
+
+Framework BaH.Box2d
+Import BRL.GLMax2D
+
+Import "test.bmx"
+
+
+Graphics 800,600, 0
+SetBlend alphablend
+
+Run(New Bridge.Create(), New TSettings)
+
+
+Type Bridge Extends Test
+
+	Method Create:Bridge()
+	
+		Init(22, 22)
+	
+		Local ground:b2Body
+		
+		Local sd:b2PolygonDef = New b2PolygonDef
+		sd.SetAsBox(50.0, 10.0)
+
+		Local bd:b2BodyDef = New b2BodyDef
+		bd.SetPosition(New b2Vec2.Create(0.0, -10.0))
+		ground = m_world.CreateBody(bd)
+		ground.CreateShape(sd)
+		
+		
+		sd = New b2PolygonDef
+		sd.SetAsBox(0.5, 0.125)
+		sd.SetDensity(20.0)
+		sd.SetFriction(0.2)
+		
+		Local jd:b2RevoluteJointDef = New b2RevoluteJointDef
+		Local numPlanks:Int = 30
+		
+		Local prevBody:b2Body = ground
+		For Local i:Int = 0 Until numPlanks
+		
+			bd = New b2BodyDef
+			bd.SetPosition(New b2Vec2.Create(-14.5 + 1.0 * i, 5.0))
+			Local body:b2Body = m_world.CreateBody(bd)
+			body.CreateShape(sd)
+			body.SetMassFromShapes()
+		
+			Local anchor:b2Vec2 = New b2Vec2.Create(-15.0 + 1.0 * i, 5.0)
+			jd.Initialize(prevBody, body, anchor)
+			m_world.CreateJoint(jd)
+
+			prevBody = body
+		Next
+		
+		Local anchor:b2Vec2 = New b2Vec2.Create(-15.0 + 1.0 * numPlanks, 5.0)
+		jd.Initialize(prevBody, ground, anchor)
+		m_world.CreateJoint(jd)
+
+		For Local i:Int = 0 Until 2
+	
+			Local sd:b2PolygonDef = New b2PolygonDef
+			Local vertices:b2Vec2[] = New b2Vec2[3]
+			vertices[0] = Vec2(-0.5, 0.0)
+			vertices[1] = Vec2(0.5, 0.0)
+			vertices[2] = Vec2(0.0, 1.5)
+			sd.SetVertices(vertices)
+			sd.SetDensity(1.0)
+			
+			Local bd:b2BodyDef = New b2BodyDef
+			bd.SetPositionXY(-8.0 + 8.0 * i, 12.0)
+			Local body:b2Body = m_world.CreateBody(bd)
+			body.CreateShape(sd)
+			body.SetMassFromShapes()
+		Next
+		
+		For Local i:Int = 0 Until 3
+			Local sd1:b2CircleDef = New b2CircleDef
+			sd1.SetRadius(0.5)
+			sd1.SetDensity(1.0)
+			
+			Local bd:b2BodyDef = New b2BodyDef
+			bd.SetPositionXY(-6.0 + 6.0 * i, 10.0)
+			Local body:b2Body = m_world.CreateBody(bd)
+			body.CreateShape(sd1)
+			body.SetMassFromShapes()
+		Next
+		
+		Return Self
+		
+	End Method
+
+
+End Type

+ 114 - 0
box2d.mod/examples/buoyancy.bmx

@@ -0,0 +1,114 @@
+SuperStrict
+
+Framework BaH.Box2d
+Import BRL.GLMax2D
+
+Import "test.bmx"
+
+
+Graphics 800,600, 0
+SetBlend alphablend
+
+Run(New Buoyancy.Create(), New TSettings)
+
+
+Type Buoyancy Extends Test
+
+	Method Create:Buoyancy()
+	
+		Init(12, 12)
+	
+	
+		Local bcd:b2BuoyancyControllerDef = New b2BuoyancyControllerDef
+
+		bcd.SetOffset(15)
+		bcd.SetNormal(Vec2(0,1))
+		bcd.SetDensity(2)
+		bcd.SetLinearDrag(2)
+		bcd.SetAngularDrag(1)
+
+
+		Local bc:b2BuoyancyController = b2BuoyancyController(m_world.CreateController(bcd))
+	
+		Local ground:b2Body
+		
+		Local sd:b2PolygonDef = New b2PolygonDef
+		sd.SetAsBox(50.0, 10.0)
+
+		Local bd:b2BodyDef = New b2BodyDef
+		bd.SetPositionXY(0.0, -10.0)
+		ground = m_world.CreateBody(bd)
+		ground.CreateShape(sd)
+		
+		
+		sd = New b2PolygonDef
+		sd.SetAsBox(0.5, 0.125)
+		sd.SetDensity(2.0)
+		sd.SetFriction(0.2)
+		
+		Local jd:b2RevoluteJointDef = New b2RevoluteJointDef
+		Local numPlanks:Int = 30
+		
+		Local prevBody:b2Body = ground
+		For Local i:Int = 0 Until numPlanks
+			bd = New b2BodyDef
+			bd.SetPositionXY(-14.5 + 1.0 * i, 5.0)
+			Local body:b2Body = m_world.CreateBody(bd)
+			body.CreateShape(sd)
+			body.SetMassFromShapes()
+			
+			Local anchor:b2Vec2 = New b2Vec2.Create(-15.0 + 1.0 * i, 5.0)
+			jd.Initialize(prevBody, body, anchor)
+			m_world.CreateJoint(jd)
+			
+			prevBody = body
+			
+			bc.AddBody(body)
+		Next
+		
+		Local anchor:b2Vec2 = New b2Vec2.Create(-15.0 + 1.0 * numPlanks, 5.0)
+		jd.Initialize(prevBody, ground, anchor)
+		m_world.CreateJoint(jd)
+		
+		For Local i:Int = 0 Until 2
+			sd = New b2PolygonDef
+			Local vertices:b2Vec2[] = New b2Vec2[3]
+			vertices[0] = Vec2(-0.5, 0.0)
+			vertices[1] = Vec2(0.5, 0.0)
+			vertices[2] = Vec2(0.0, 1.5)
+			
+			sd.SetVertices(vertices)
+			sd.SetDensity(1.0)
+
+			bd = New b2BodyDef
+			bd.SetPositionXY(-8.0 + 8.0 * i, 12.0)
+			Local body:b2Body = m_world.CreateBody(bd)
+			body.CreateShape(sd)
+			body.SetMassFromShapes()
+
+			bc.AddBody(body)
+		Next
+
+		For Local i:Int = 0 Until 3
+			Local cd:b2CircleDef = New b2CircleDef
+			cd.SetRadius(0.5)
+			cd.SetDensity(1.0)
+
+			bd = New b2BodyDef
+			bd.SetPositionXY(-6.0 + 6.0 * i, 10.0)
+			Local body:b2Body = m_world.CreateBody(bd)
+			body.CreateShape(cd)
+			body.SetMassFromShapes()
+
+			bc.AddBody(body)
+		Next
+
+		
+		Return Self
+	End Method
+
+End Type
+
+
+
+

+ 214 - 0
box2d.mod/examples/car.bmx

@@ -0,0 +1,214 @@
+SuperStrict
+
+Framework BaH.Box2d
+Import BRL.GLMax2D
+
+Import "test.bmx"
+
+
+Graphics 800,600, 0
+SetBlend alphablend
+
+
+Run(New SliderCrank.Create(), New TSettings)
+
+
+Type SliderCrank Extends Test
+
+	Field m_leftWheel:b2Body
+	Field m_rightWheel:b2Body
+	Field m_vehicle:b2Body
+	Field m_leftJoint:b2RevoluteJoint
+	Field m_rightJoint:b2RevoluteJoint
+
+	
+	Method Create:SliderCrank()
+	
+		Init(8, 8)
+				
+		' car body
+		Local poly1:b2PolygonDef = New b2PolygonDef
+		Local poly2:b2PolygonDef = New b2PolygonDef
+		
+		' bottom half
+		Local vertices:b2Vec2[] = New b2Vec2[5]
+		vertices[4] = Vec2(-2.2,-0.74)
+		vertices[3] = Vec2(-2.2,0)
+		vertices[2] = Vec2(1.0,0)
+		vertices[1] = Vec2(2.2,-0.2)
+		vertices[0] = Vec2(2.2,-0.74)
+		poly1.SetVertices(vertices)
+		poly1.GetFilter().SetGroupIndex(-1)
+		
+		poly1.SetDensity(20.0)
+		poly1.SetFriction(0.68)
+		poly1.GetFilter().SetGroupIndex(-1)
+		
+		' top half
+		vertices = New b2Vec2[4]
+		vertices[3] = Vec2(-1.7,0)
+		vertices[2] = Vec2(-1.3,0.7)
+		vertices[1] = Vec2(0.5,0.74)
+		vertices[0] = Vec2(1.0,0)
+		poly2.SetVertices(vertices)
+		poly2.GetFilter().SetGroupIndex(-1)
+		
+		poly2.SetDensity(5.0)
+		poly2.SetFriction(0.68)
+		poly2.GetFilter().SetGroupIndex(-1)
+		
+		Local bd:b2BodyDef = New b2BodyDef
+		bd.SetPositionXY(-35.0, 2.8)
+		
+		m_vehicle = m_world.CreateBody(bd)
+		m_vehicle.CreateShape(poly1)
+		m_vehicle.CreateShape(poly2)
+		m_vehicle.SetMassFromShapes()
+	
+		' vehicle wheels
+		Local circ:b2CircleDef = New b2CircleDef
+		circ.SetDensity(40.0)
+		circ.SetRadius(0.38608)
+		circ.SetFriction(0.8)
+		circ.GetFilter().SetGroupIndex(-1)
+		
+		bd = New b2BodyDef
+		bd.SetAllowSleep(False)
+		bd.SetPositionXY(-33.8, 2.0)
+		
+		m_rightWheel = m_world.CreateBody(bd)
+		m_rightWheel.CreateShape(circ)
+		m_rightWheel.SetMassFromShapes()
+		
+		bd.SetPositionXY(-36.2, 2.0)
+		m_leftWheel = m_world.CreateBody(bd)
+		m_leftWheel.CreateShape(circ)
+		m_leftWheel.SetMassFromShapes()
+		
+
+		' join wheels to chassis
+		Local anchor:b2Vec2 = New b2Vec2.Create()
+		Local jd:b2RevoluteJointDef= New b2RevoluteJointDef
+		jd.Initialize(m_vehicle, m_leftWheel, m_leftWheel.GetWorldCenter())
+		jd.SetCollideConnected(False)
+		jd.EnableMotor(True)
+		jd.SetMaxMotorTorque(10.0)
+		jd.SetMotorSpeed(0.0)
+		m_leftJoint = b2RevoluteJoint(m_world.CreateJoint(jd))
+		
+		jd.Initialize(m_vehicle, m_rightWheel, m_rightWheel.GetWorldCenter())
+		jd.SetCollideConnected(False)
+		m_rightJoint = b2RevoluteJoint(m_world.CreateJoint(jd))
+		
+		
+		' ground
+		Local box:b2PolygonDef = New b2PolygonDef
+		box.SetAsBox(19.5, 0.5)
+		box.SetFriction(0.62)
+		
+		bd = New b2BodyDef 
+		bd.SetPositionXY(-25.0, 1.0)
+		
+		Local ground:b2Body = m_world.CreateBody(bd)
+		ground.CreateShape(box)
+		
+		
+		' more ground
+		box = New b2PolygonDef
+		bd = New b2BodyDef 
+		
+		box.SetAsOrientedBox(9.5, 0.5, b2Vec2.ZERO, 18)
+		box.SetFriction(0.62)
+		bd.SetPositionXY(27.0 - 30.0, 3.1)
+		
+		ground = m_world.CreateBody(bd)
+		ground.CreateShape(box)
+		
+		
+		' more ground
+		box = New b2PolygonDef
+		bd = New b2BodyDef 
+		
+		box.SetAsOrientedBox(9.5, 0.5, b2Vec2.ZERO, -18)
+		box.SetFriction(0.62)
+		bd.SetPositionXY(55.0 - 30.0, 3.1)
+		
+		ground = m_world.CreateBody(bd)
+		ground.CreateShape(box)
+		
+		
+		' more ground
+		box = New b2PolygonDef
+		bd = New b2BodyDef 
+		
+		box.SetAsOrientedBox(9.5, 0.5, b2Vec2.ZERO, 5.4)
+		box.SetFriction(0.62)
+		bd.SetPositionXY(41.0, 2.0)
+		
+		ground = m_world.CreateBody(bd)
+		ground.CreateShape(box)
+		
+		
+		' more ground
+		box = New b2PolygonDef
+		bd = New b2BodyDef 
+		
+		box.SetAsOrientedBox(5.0, 0.5, b2Vec2.ZERO, 27)
+		box.SetFriction(0.62)
+		bd.SetPositionXY(50.0, 4.0)
+		
+		ground = m_world.CreateBody(bd)
+		ground.CreateShape(box)
+		
+		
+		' more ground
+		box = New b2PolygonDef
+		bd = New b2BodyDef 
+		
+		box.SetAsBox(20.0, 0.5)
+		box.SetFriction(0.62)
+		bd.SetPositionXY(85.0, 2.0)
+		
+		ground = m_world.CreateBody(bd)
+		ground.CreateShape(box)
+		
+				
+		Return Self
+	End Method
+	
+	Method Keyboard()
+		Super.Keyboard()
+		
+		If KeyHit(KEY_A) Then
+			m_leftJoint.SetMaxMotorTorque(800.0)
+			m_leftJoint.SetMotorSpeed(687.549354)
+		End If
+
+		If KeyHit(KEY_S) Then
+			m_leftJoint.SetMaxMotorTorque(100.0)
+			m_leftJoint.SetMotorSpeed(0.0)
+		End If
+
+		If KeyHit(KEY_D) Then
+			m_leftJoint.SetMaxMotorTorque(1200.0)
+			m_leftJoint.SetMotorSpeed(-2062.64806)
+		End If
+
+	End Method
+
+	Method DoStep(settings:TSettings)
+
+		Super.DoStep(settings)
+
+		DrawString "Keys: left = a, brake = s, right = d", 5, m_textLine
+
+		m_textLine :+ 12
+
+	End Method
+
+
+End Type
+
+
+
+

+ 73 - 0
box2d.mod/examples/ccdtest.bmx

@@ -0,0 +1,73 @@
+SuperStrict
+
+Framework BaH.Box2d
+Import BRL.GLMax2D
+
+Import "test.bmx"
+
+
+Graphics 800,600, 0
+SetBlend alphablend
+
+
+Run(New CCDTest.Create(), New TSettings)
+
+
+Type CCDTest Extends Test
+
+	Method Create:CCDTest()
+	
+		Init(15, 15)
+
+		Const k_restitution:Float = 1.4
+		
+
+		Local bd:b2BodyDef = New b2BodyDef
+		bd.SetPosition(New b2Vec2.Create(0.0, 20.0))
+		Local body:b2Body = m_world.CreateBody(bd)
+
+		Local sd:b2PolygonDef = New b2PolygonDef
+		sd.SetDensity(0.0)
+		sd.SetRestitution(k_restitution)
+
+		sd.SetAsOrientedBox(0.1, 10.0, New b2Vec2.Create(-10.0, 0.0), 0.0)
+		body.CreateShape(sd)
+
+		sd.SetAsOrientedBox(0.1, 10.0, New b2Vec2.Create(10.0, 0.0), 0.0)
+		body.CreateShape(sd)
+
+		sd.SetAsOrientedBox(0.1, 10.0, New b2Vec2.Create(0.0, -10.0), 90)
+		body.CreateShape(sd)
+
+		sd.SetAsOrientedBox(0.1, 10.0, New b2Vec2.Create(0.0, 10.0), 270)
+		body.CreateShape(sd)
+
+
+
+		Local sd_bottom:b2PolygonDef = New b2PolygonDef
+		sd_bottom.SetAsBox( 1.5, 0.15 )
+		sd_bottom.SetDensity(4.0)
+
+		Local sd_left:b2PolygonDef = New b2PolygonDef
+		sd_left.SetAsOrientedBox(0.15, 2.7, New b2Vec2.Create(-1.45, 2.35), 11.4591513)
+		sd_left.SetDensity(4.0)
+
+		Local sd_right:b2PolygonDef = New b2PolygonDef
+		sd_right.SetAsOrientedBox(0.15, 2.7, New b2Vec2.Create(1.45, 2.35), -11.4591513)
+		sd_right.SetDensity(4.0)
+
+		bd = New b2BodyDef
+		bd.SetPosition(New b2Vec2.Create(0.0, 15.0))
+		body = m_world.CreateBody(bd)
+		body.CreateShape(sd_bottom)
+		body.CreateShape(sd_left)
+		body.CreateShape(sd_right)
+		body.SetMassFromShapes()
+
+		Return Self
+		
+	End Method
+
+
+End Type
+

Some files were not shown because too many files changed in this diff