code:
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef POLY_SHAPES_H
#define POLY_SHAPES_H

/// This tests stacking. It also shows how to use b2World::Query
/// and b2TestOverlap.

const int32 k_maxBodies = 256;

/// This callback is called by b2World::QueryAABB. We find all the fixtures
/// that overlap an AABB. Of those, we use b2TestOverlap to determine which fixtures
/// overlap a circle. Up to 4 overlapped fixtures will be highlighted with a yellow border.
class PolyShapesCallback : public b2QueryCallback
{
public:

	enum
	{
		e_maxCount = 4
	};

	PolyShapesCallback()
	{
		m_count = 0;
	}

	void DrawFixture(b2Fixture* fixture)
	{
		b2Color color(0.95f, 0.95f, 0.6f);
		const b2Transform& xf = fixture->GetBody()->GetTransform();

		switch (fixture->GetType())
		{
		case b2Shape::e_circle:
			{
				b2CircleShape* circle = (b2CircleShape*)fixture->GetShape();

				b2Vec2 center = b2Mul(xf, circle->m_p);
				float32 radius = circle->m_radius;

				m_debugDraw->DrawCircle(center, radius, color);
			}
			break;

		case b2Shape::e_polygon:
			{
				b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape();
				int32 vertexCount = poly->m_vertexCount;
				b2Assert(vertexCount <= b2_maxPolygonVertices);
				b2Vec2 vertices[b2_maxPolygonVertices];

				for (int32 i = 0; i < vertexCount; ++i)
				{
					vertices[i] = b2Mul(xf, poly->m_vertices[i]);
				}

				m_debugDraw->DrawPolygon(vertices, vertexCount, color);
			}
			break;

		default:
			break;
		}
	}

	/// Called for each fixture found in the query AABB.
	/// @return false to terminate the query.
	bool ReportFixture(b2Fixture* fixture)
	{
		if (m_count == e_maxCount)
		{
			return false;
		}

		b2Body* body = fixture->GetBody();
		b2Shape* shape = fixture->GetShape();

		bool overlap = b2TestOverlap(shape, 0, &m_circle, 0, body->GetTransform(), m_transform);

		if (overlap)
		{
			DrawFixture(fixture);
			++m_count;
		}

		return true;
	}

	b2CircleShape m_circle;
	b2Transform m_transform;
	b2Draw* m_debugDraw;
	int32 m_count;
};

class PolyShapes : public Test
{
public:
	PolyShapes()
	{
		// Ground body
		{
			b2BodyDef bd;
			b2Body* ground = m_world->CreateBody(&bd);

			b2EdgeShape shape;
			shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			b2Vec2 vertices[3];
			vertices[0].Set(-0.5f, 0.0f);
			vertices[1].Set(0.5f, 0.0f);
			vertices[2].Set(0.0f, 1.5f);
			m_polygons[0].Set(vertices, 3);
		}

		{
			b2Vec2 vertices[3];
			vertices[0].Set(-0.1f, 0.0f);
			vertices[1].Set(0.1f, 0.0f);
			vertices[2].Set(0.0f, 1.5f);
			m_polygons[1].Set(vertices, 3);
		}

		{
			float32 w = 1.0f;
			float32 b = w / (2.0f + b2Sqrt(2.0f));
			float32 s = b2Sqrt(2.0f) * b;

			b2Vec2 vertices[8];
			vertices[0].Set(0.5f * s, 0.0f);
			vertices[1].Set(0.5f * w, b);
			vertices[2].Set(0.5f * w, b + s);
			vertices[3].Set(0.5f * s, w);
			vertices[4].Set(-0.5f * s, w);
			vertices[5].Set(-0.5f * w, b + s);
			vertices[6].Set(-0.5f * w, b);
			vertices[7].Set(-0.5f * s, 0.0f);

			m_polygons[2].Set(vertices, 8);
		}

		{
			m_polygons[3].SetAsBox(0.5f, 0.5f);
		}

		{
			m_circle.m_radius = 0.5f;
		}

		m_bodyIndex = 0;
		memset(m_bodies, 0, sizeof(m_bodies));
	}

	void Create(int32 index)
	{
		if (m_bodies[m_bodyIndex] != NULL)
		{
			m_world->DestroyBody(m_bodies[m_bodyIndex]);
			m_bodies[m_bodyIndex] = NULL;
		}

		b2BodyDef bd;
		bd.type = b2_dynamicBody;

		float32 x = RandomFloat(-2.0f, 2.0f);
		bd.position.Set(x, 10.0f);
		bd.angle = RandomFloat(-b2_pi, b2_pi);

		if (index == 4)
		{
			bd.angularDamping = 0.02f;
		}

		m_bodies[m_bodyIndex] = m_world->CreateBody(&bd);

		if (index < 4)
		{
			b2FixtureDef fd;
			fd.shape = m_polygons + index;
			fd.density = 1.0f;
			fd.friction = 0.3f;
			m_bodies[m_bodyIndex]->CreateFixture(&fd);
		}
		else
		{
			b2FixtureDef fd;
			fd.shape = &m_circle;
			fd.density = 1.0f;
			fd.friction = 0.3f;

			m_bodies[m_bodyIndex]->CreateFixture(&fd);
		}

		m_bodyIndex = (m_bodyIndex + 1) % k_maxBodies;
	}

	void DestroyBody()
	{
		for (int32 i = 0; i < k_maxBodies; ++i)
		{
			if (m_bodies[i] != NULL)
			{
				m_world->DestroyBody(m_bodies[i]);
				m_bodies[i] = NULL;
				return;
			}
		}
	}

	void Keyboard(unsigned char key)
	{
		switch (key)
		{
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
			Create(key - '1');
			break;

		case 'a':
			for (int32 i = 0; i < k_maxBodies; i += 2)
			{
				if (m_bodies[i])
				{
					bool active = m_bodies[i]->IsActive();
					m_bodies[i]->SetActive(!active);
				}
			}
			break;

		case 'd':
			DestroyBody();
			break;
		}
	}

	void Step(Settings* settings)
	{
		Test::Step(settings);

		PolyShapesCallback callback;
		callback.m_circle.m_radius = 2.0f;
		callback.m_circle.m_p.Set(0.0f, 1.1f);
		callback.m_transform.SetIdentity();
		callback.m_debugDraw = &m_debugDraw;

		b2AABB aabb;
		callback.m_circle.ComputeAABB(&aabb, callback.m_transform, 0);

		m_world->QueryAABB(&callback, aabb);

		b2Color color(0.4f, 0.7f, 0.8f);
		m_debugDraw.DrawCircle(callback.m_circle.m_p, callback.m_circle.m_radius, color);

		m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stuff");
		m_textLine += 15;
		m_debugDraw.DrawString(5, m_textLine, "Press 'a' to (de)activate some bodies");
		m_textLine += 15;
		m_debugDraw.DrawString(5, m_textLine, "Press 'd' to destroy a body");
		m_textLine += 15;
	}

	static Test* Create()
	{
		return new PolyShapes;
	}

	int32 m_bodyIndex;
	b2Body* m_bodies[k_maxBodies];
	b2PolygonShape m_polygons[4];
	b2CircleShape m_circle;
};

#endif


code:
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef PRISMATIC_H
#define PRISMATIC_H

// The motor in this test gets smoother with higher velocity iterations.
class Prismatic : public Test
{
public:
	Prismatic()
	{
		b2Body* ground = NULL;
		{
			b2BodyDef bd;
			ground = m_world->CreateBody(&bd);

			b2EdgeShape shape;
			shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			b2PolygonShape shape;
			shape.SetAsBox(2.0f, 0.5f);

			b2BodyDef bd;
			bd.type = b2_dynamicBody;
			bd.position.Set(-10.0f, 10.0f);
			bd.angle = 0.5f * b2_pi;
			bd.allowSleep = false;
			b2Body* body = m_world->CreateBody(&bd);
			body->CreateFixture(&shape, 5.0f);

			b2PrismaticJointDef pjd;

			// Bouncy limit
			b2Vec2 axis(2.0f, 1.0f);
			axis.Normalize();
			pjd.Initialize(ground, body, b2Vec2(0.0f, 0.0f), axis);

			// Non-bouncy limit
			//pjd.Initialize(ground, body, b2Vec2(-10.0f, 10.0f), b2Vec2(1.0f, 0.0f));

			pjd.motorSpeed = 10.0f;
			pjd.maxMotorForce = 10000.0f;
			pjd.enableMotor = true;
			pjd.lowerTranslation = 0.0f;
			pjd.upperTranslation = 20.0f;
			pjd.enableLimit = true;

			m_joint = (b2PrismaticJoint*)m_world->CreateJoint(&pjd);
		}
	}

	void Keyboard(unsigned char key)
	{
		switch (key)
		{
		case 'l':
			m_joint->EnableLimit(!m_joint->IsLimitEnabled());
			break;

		case 'm':
			m_joint->EnableMotor(!m_joint->IsMotorEnabled());
			break;

		case 's':
			m_joint->SetMotorSpeed(-m_joint->GetMotorSpeed());
			break;
		}
	}

	void Step(Settings* settings)
	{
		Test::Step(settings);
		m_debugDraw.DrawString(5, m_textLine, "Keys: (l) limits, (m) motors, (s) speed");
		m_textLine += 15;
		float32 force = m_joint->GetMotorForce(settings->hz);
		m_debugDraw.DrawString(5, m_textLine, "Motor Force = %4.0f", (float) force);
		m_textLine += 15;
	}

	static Test* Create()
	{
		return new Prismatic;
	}

	b2PrismaticJoint* m_joint;
};

#endif

license: mit


code:
/*
* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef PULLEYS_H
#define PULLEYS_H

class Pulleys : public Test
{
public:
	Pulleys()
	{
		float32 y = 16.0f;
		float32 L = 12.0f;
		float32 a = 1.0f;
		float32 b = 2.0f;

		b2Body* ground = NULL;
		{
			b2BodyDef bd;
			ground = m_world->CreateBody(&bd);

			b2EdgeShape edge;
			edge.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
			//ground->CreateFixture(&shape, 0.0f);

			b2CircleShape circle;
			circle.m_radius = 2.0f;

			circle.m_p.Set(-10.0f, y + b + L);
			ground->CreateFixture(&circle, 0.0f);

			circle.m_p.Set(10.0f, y + b + L);
			ground->CreateFixture(&circle, 0.0f);
		}

		{

			b2PolygonShape shape;
			shape.SetAsBox(a, b);

			b2BodyDef bd;
			bd.type = b2_dynamicBody;

			//bd.fixedRotation = true;
			bd.position.Set(-10.0f, y);
			b2Body* body1 = m_world->CreateBody(&bd);
			body1->CreateFixture(&shape, 5.0f);

			bd.position.Set(10.0f, y);
			b2Body* body2 = m_world->CreateBody(&bd);
			body2->CreateFixture(&shape, 5.0f);

			b2PulleyJointDef pulleyDef;
			b2Vec2 anchor1(-10.0f, y + b);
			b2Vec2 anchor2(10.0f, y + b);
			b2Vec2 groundAnchor1(-10.0f, y + b + L);
			b2Vec2 groundAnchor2(10.0f, y + b + L);
			pulleyDef.Initialize(body1, body2, groundAnchor1, groundAnchor2, anchor1, anchor2, 1.5f);

			m_joint1 = (b2PulleyJoint*)m_world->CreateJoint(&pulleyDef);
		}
	}

	void Keyboard(unsigned char key)
	{
		switch (key)
		{
		case 0:
			break;
		}
	}

	void Step(Settings* settings)
	{
		Test::Step(settings);

		float32 ratio = m_joint1->GetRatio();
		float32 L = m_joint1->GetLengthA() + ratio * m_joint1->GetLengthB();
		m_debugDraw.DrawString(5, m_textLine, "L1 + %4.2f * L2 = %4.2f", (float) ratio, (float) L);
		m_textLine += 15;
	}

	static Test* Create()
	{
		return new Pulleys;
	}

	b2PulleyJoint* m_joint1;
};

#endif


code:
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef PYRAMID_H
#define PYRAMID_H

class Pyramid : public Test
{
public:
	enum
	{
		e_count = 20
	};

	Pyramid()
	{
		{
			b2BodyDef bd;
			b2Body* ground = m_world->CreateBody(&bd);

			b2EdgeShape shape;
			shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			float32 a = 0.5f;
			b2PolygonShape shape;
			shape.SetAsBox(a, a);

			b2Vec2 x(-7.0f, 0.75f);
			b2Vec2 y;
			b2Vec2 deltaX(0.5625f, 1.25f);
			b2Vec2 deltaY(1.125f, 0.0f);

			for (int32 i = 0; i < e_count; ++i)
			{
				y = x;

				for (int32 j = i; j < e_count; ++j)
				{
					b2BodyDef bd;
					bd.type = b2_dynamicBody;
					bd.position = y;
					b2Body* body = m_world->CreateBody(&bd);
					body->CreateFixture(&shape, 5.0f);

					y += deltaY;
				}

				x += deltaX;
			}
		}
	}

	void Step(Settings* settings)
	{
		Test::Step(settings);

		//b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree;

		//if (m_stepCount == 400)
		//{
		//	tree->RebuildBottomUp();
		//}
	}

	static Test* Create()
	{
		return new Pyramid;
	}
};

#endif


code:
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef RAY_CAST_H
#define RAY_CAST_H

// This test demonstrates how to use the world ray-cast feature.
// NOTE: we are intentionally filtering one of the polygons, therefore
// the ray will always miss one type of polygon.

// This callback finds the closest hit. Polygon 0 is filtered.
class RayCastClosestCallback : public b2RayCastCallback
{
public:
	RayCastClosestCallback()
	{
		m_hit = false;
	}

	float32 ReportFixture(	b2Fixture* fixture, const b2Vec2& point,
		const b2Vec2& normal, float32 fraction)
	{
		b2Body* body = fixture->GetBody();
		void* userData = body->GetUserData();
		if (userData)
		{
			int32 index = *(int32*)userData;
			if (index == 0)
			{
				// filter
				return -1.0f;
			}
		}

		m_hit = true;
		m_point = point;
		m_normal = normal;
		return fraction;
	}

	bool m_hit;
	b2Vec2 m_point;
	b2Vec2 m_normal;
};

// This callback finds any hit. Polygon 0 is filtered.
class RayCastAnyCallback : public b2RayCastCallback
{
public:
	RayCastAnyCallback()
	{
		m_hit = false;
	}

	float32 ReportFixture(	b2Fixture* fixture, const b2Vec2& point,
		const b2Vec2& normal, float32 fraction)
	{
		b2Body* body = fixture->GetBody();
		void* userData = body->GetUserData();
		if (userData)
		{
			int32 index = *(int32*)userData;
			if (index == 0)
			{
				// filter
				return -1.0f;
			}
		}

		m_hit = true;
		m_point = point;
		m_normal = normal;
		return 0.0f;
	}

	bool m_hit;
	b2Vec2 m_point;
	b2Vec2 m_normal;
};

// This ray cast collects multiple hits along the ray. Polygon 0 is filtered.
class RayCastMultipleCallback : public b2RayCastCallback
{
public:
	enum
	{
		e_maxCount = 3
	};

	RayCastMultipleCallback()
	{
		m_count = 0;
	}

	float32 ReportFixture(	b2Fixture* fixture, const b2Vec2& point,
		const b2Vec2& normal, float32 fraction)
	{
		b2Body* body = fixture->GetBody();
		void* userData = body->GetUserData();
		if (userData)
		{
			int32 index = *(int32*)userData;
			if (index == 0)
			{
				// filter
				return -1.0f;
			}
		}

		b2Assert(m_count < e_maxCount);

		m_points[m_count] = point;
		m_normals[m_count] = normal;
		++m_count;

		if (m_count == e_maxCount)
		{
			return 0.0f;
		}

		return 1.0f;
	}

	b2Vec2 m_points[e_maxCount];
	b2Vec2 m_normals[e_maxCount];
	int32 m_count;
};

class RayCast : public Test
{
public:

	enum
	{
		e_maxBodies = 256
	};

	enum Mode
	{
		e_closest,
		e_any,
		e_multiple
	};

	RayCast()
	{
		// Ground body
		{
			b2BodyDef bd;
			b2Body* ground = m_world->CreateBody(&bd);

			b2EdgeShape shape;
			shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			b2Vec2 vertices[3];
			vertices[0].Set(-0.5f, 0.0f);
			vertices[1].Set(0.5f, 0.0f);
			vertices[2].Set(0.0f, 1.5f);
			m_polygons[0].Set(vertices, 3);
		}

		{
			b2Vec2 vertices[3];
			vertices[0].Set(-0.1f, 0.0f);
			vertices[1].Set(0.1f, 0.0f);
			vertices[2].Set(0.0f, 1.5f);
			m_polygons[1].Set(vertices, 3);
		}

		{
			float32 w = 1.0f;
			float32 b = w / (2.0f + b2Sqrt(2.0f));
			float32 s = b2Sqrt(2.0f) * b;

			b2Vec2 vertices[8];
			vertices[0].Set(0.5f * s, 0.0f);
			vertices[1].Set(0.5f * w, b);
			vertices[2].Set(0.5f * w, b + s);
			vertices[3].Set(0.5f * s, w);
			vertices[4].Set(-0.5f * s, w);
			vertices[5].Set(-0.5f * w, b + s);
			vertices[6].Set(-0.5f * w, b);
			vertices[7].Set(-0.5f * s, 0.0f);

			m_polygons[2].Set(vertices, 8);
		}

		{
			m_polygons[3].SetAsBox(0.5f, 0.5f);
		}

		{
			m_circle.m_radius = 0.5f;
		}

		m_bodyIndex = 0;
		memset(m_bodies, 0, sizeof(m_bodies));

		m_angle = 0.0f;

		m_mode = e_closest;
	}

	void Create(int32 index)
	{
		if (m_bodies[m_bodyIndex] != NULL)
		{
			m_world->DestroyBody(m_bodies[m_bodyIndex]);
			m_bodies[m_bodyIndex] = NULL;
		}

		b2BodyDef bd;

		float32 x = RandomFloat(-10.0f, 10.0f);
		float32 y = RandomFloat(0.0f, 20.0f);
		bd.position.Set(x, y);
		bd.angle = RandomFloat(-b2_pi, b2_pi);

		m_userData[m_bodyIndex] = index;
		bd.userData = m_userData + m_bodyIndex;

		if (index == 4)
		{
			bd.angularDamping = 0.02f;
		}

		m_bodies[m_bodyIndex] = m_world->CreateBody(&bd);

		if (index < 4)
		{
			b2FixtureDef fd;
			fd.shape = m_polygons + index;
			fd.friction = 0.3f;
			m_bodies[m_bodyIndex]->CreateFixture(&fd);
		}
		else
		{
			b2FixtureDef fd;
			fd.shape = &m_circle;
			fd.friction = 0.3f;

			m_bodies[m_bodyIndex]->CreateFixture(&fd);
		}

		m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies;
	}

	void DestroyBody()
	{
		for (int32 i = 0; i < e_maxBodies; ++i)
		{
			if (m_bodies[i] != NULL)
			{
				m_world->DestroyBody(m_bodies[i]);
				m_bodies[i] = NULL;
				return;
			}
		}
	}

	void Keyboard(unsigned char key)
	{
		switch (key)
		{
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
			Create(key - '1');
			break;

		case 'd':
			DestroyBody();
			break;

		case 'm':
			if (m_mode == e_closest)
			{
				m_mode = e_any;
			}
			else if (m_mode == e_any)
			{
				m_mode = e_multiple;
			}
			else if (m_mode == e_multiple)
			{
				m_mode = e_closest;
			}
		}
	}

	void Step(Settings* settings)
	{
		bool advanceRay = settings->pause == 0 || settings->singleStep;

		Test::Step(settings);
		m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stuff, m to change the mode");
		m_textLine += 15;
		m_debugDraw.DrawString(5, m_textLine, "Mode = %d", m_mode);
		m_textLine += 15;

		float32 L = 11.0f;
		b2Vec2 point1(0.0f, 10.0f);
		b2Vec2 d(L * cosf(m_angle), L * sinf(m_angle));
		b2Vec2 point2 = point1 + d;

		if (m_mode == e_closest)
		{
			RayCastClosestCallback callback;
			m_world->RayCast(&callback, point1, point2);

			if (callback.m_hit)
			{
				m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f));
				m_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f));
				b2Vec2 head = callback.m_point + 0.5f * callback.m_normal;
				m_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f));
			}
			else
			{
				m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f));
			}
		}
		else if (m_mode == e_any)
		{
			RayCastAnyCallback callback;
			m_world->RayCast(&callback, point1, point2);

			if (callback.m_hit)
			{
				m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f));
				m_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f));
				b2Vec2 head = callback.m_point + 0.5f * callback.m_normal;
				m_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f));
			}
			else
			{
				m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f));
			}
		}
		else if (m_mode == e_multiple)
		{
			RayCastMultipleCallback callback;
			m_world->RayCast(&callback, point1, point2);
			m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f));

			for (int32 i = 0; i < callback.m_count; ++i)
			{
				b2Vec2 p = callback.m_points[i];
				b2Vec2 n = callback.m_normals[i];
				m_debugDraw.DrawPoint(p, 5.0f, b2Color(0.4f, 0.9f, 0.4f));
				m_debugDraw.DrawSegment(point1, p, b2Color(0.8f, 0.8f, 0.8f));
				b2Vec2 head = p + 0.5f * n;
				m_debugDraw.DrawSegment(p, head, b2Color(0.9f, 0.9f, 0.4f));
			}
		}

		if (advanceRay)
		{
			m_angle += 0.25f * b2_pi / 180.0f;
		}

#if 0
		// This case was failing.
		{
			b2Vec2 vertices[4];
			//vertices[0].Set(-22.875f, -3.0f);
			//vertices[1].Set(22.875f, -3.0f);
			//vertices[2].Set(22.875f, 3.0f);
			//vertices[3].Set(-22.875f, 3.0f);

			b2PolygonShape shape;
			//shape.Set(vertices, 4);
			shape.SetAsBox(22.875f, 3.0f);

			b2RayCastInput input;
			input.p1.Set(10.2725f,1.71372f);
			input.p2.Set(10.2353f,2.21807f);
			//input.maxFraction = 0.567623f;
			input.maxFraction = 0.56762173f;

			b2Transform xf;
			xf.SetIdentity();
			xf.position.Set(23.0f, 5.0f);

			b2RayCastOutput output;
			bool hit;
			hit = shape.RayCast(&output, input, xf);
			hit = false;

			b2Color color(1.0f, 1.0f, 1.0f);
			b2Vec2 vs[4];
			for (int32 i = 0; i < 4; ++i)
			{
				vs[i] = b2Mul(xf, shape.m_vertices[i]);
			}

			m_debugDraw.DrawPolygon(vs, 4, color);
			m_debugDraw.DrawSegment(input.p1, input.p2, color);
		}
#endif
	}

	static Test* Create()
	{
		return new RayCast;
	}

	int32 m_bodyIndex;
	b2Body* m_bodies[e_maxBodies];
	int32 m_userData[e_maxBodies];
	b2PolygonShape m_polygons[4];
	b2CircleShape m_circle;

	float32 m_angle;

	Mode m_mode;
};

#endif


code:
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef REVOLUTE_H
#define REVOLUTE_H

class Revolute : public Test
{
public:
	Revolute()
	{
		b2Body* ground = NULL;
		{
			b2BodyDef bd;
			ground = m_world->CreateBody(&bd);

			b2EdgeShape shape;
			shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));

			b2FixtureDef fd;
			fd.shape = &shape;
			//fd.filter.categoryBits = 2;

			ground->CreateFixture(&fd);
		}

		{
			b2CircleShape shape;
			shape.m_radius = 0.5f;

			b2BodyDef bd;
			bd.type = b2_dynamicBody;

			b2RevoluteJointDef rjd;

			bd.position.Set(-10.0f, 20.0f);
			b2Body* body = m_world->CreateBody(&bd);
			body->CreateFixture(&shape, 5.0f);

			float32 w = 100.0f;
			body->SetAngularVelocity(w);
			body->SetLinearVelocity(b2Vec2(-8.0f * w, 0.0f));

			rjd.Initialize(ground, body, b2Vec2(-10.0f, 12.0f));
			rjd.motorSpeed = 1.0f * b2_pi;
			rjd.maxMotorTorque = 10000.0f;
			rjd.enableMotor = false;
			rjd.lowerAngle = -0.25f * b2_pi;
			rjd.upperAngle = 0.5f * b2_pi;
			rjd.enableLimit = true;
			rjd.collideConnected = true;

			m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&rjd);
		}

		{
			b2CircleShape circle_shape;
			circle_shape.m_radius = 3.0f;

			b2BodyDef circle_bd;
			circle_bd.type = b2_dynamicBody;
			circle_bd.position.Set(5.0f, 30.0f);

			b2FixtureDef fd;
			fd.density = 5.0f;
			fd.filter.maskBits = 1;
			fd.shape = &circle_shape;

			m_ball = m_world->CreateBody(&circle_bd);
			m_ball->CreateFixture(&fd);

			b2PolygonShape polygon_shape;
			polygon_shape.SetAsBox(10.0f, 0.2f, b2Vec2 (-10.0f, 0.0f), 0.0f);

			b2BodyDef polygon_bd;
			polygon_bd.position.Set(20.0f, 10.0f);
			polygon_bd.type = b2_dynamicBody;
			polygon_bd.bullet = true;
			b2Body* polygon_body = m_world->CreateBody(&polygon_bd);
			polygon_body->CreateFixture(&polygon_shape, 2.0f);

			b2RevoluteJointDef rjd;
			rjd.Initialize(ground, polygon_body, b2Vec2(20.0f, 10.0f));
			rjd.lowerAngle = -0.25f * b2_pi;
			rjd.upperAngle = 0.0f * b2_pi;
			rjd.enableLimit = true;
			m_world->CreateJoint(&rjd);
		}

		// Tests mass computation of a small object far from the origin
		{
			b2BodyDef bodyDef;
			bodyDef.type = b2_dynamicBody;
			b2Body* body = m_world->CreateBody(&bodyDef);

			b2PolygonShape polyShape;
			b2Vec2 verts[3];
			verts[0].Set( 17.63f, 36.31f );
			verts[1].Set( 17.52f, 36.69f );
			verts[2].Set( 17.19f, 36.36f );
			polyShape.Set(verts, 3);

			b2FixtureDef polyFixtureDef;
			polyFixtureDef.shape = &polyShape;
			polyFixtureDef.density = 1;

			body->CreateFixture(&polyFixtureDef);	//assertion hits inside here
		}

	}

	void Keyboard(unsigned char key)
	{
		switch (key)
		{
		case 'l':
			m_joint->EnableLimit(!m_joint->IsLimitEnabled());
			break;

		case 'm':
			m_joint->EnableMotor(!m_joint->IsMotorEnabled());
			break;
		}
	}

	void Step(Settings* settings)
	{
		Test::Step(settings);
		m_debugDraw.DrawString(5, m_textLine, "Keys: (l) limits, (m) motor");
		m_textLine += 15;

		//if (m_stepCount == 360)
		//{
		//	m_ball->SetTransform(b2Vec2(0.0f, 0.5f), 0.0f);
		//}

		//float32 torque1 = m_joint1->GetMotorTorque();
		//m_debugDraw.DrawString(5, m_textLine, "Motor Torque = %4.0f, %4.0f : Motor Force = %4.0f", (float) torque1, (float) torque2, (float) force3);
		//m_textLine += 15;
	}

	static Test* Create()
	{
		return new Revolute;
	}

	b2Body* m_ball;
	b2RevoluteJoint* m_joint;
};

#endif


code:
/*
* Copyright (c) 2011 Erin Catto http://box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef ROPE_H
#define ROPE_H

///
class Rope : public Test
{
public:
	Rope()
	{
		const int32 N = 40;
		b2Vec2 vertices[N];
		float32 masses[N];

		for (int32 i = 0; i < N; ++i)
		{
			vertices[i].Set(0.0f, 20.0f - 0.25f * i);
			masses[i] = 1.0f;
		}
		masses[0] = 0.0f;
		masses[1] = 0.0f;

		b2RopeDef def;
		def.vertices = vertices;
		def.count = N;
		def.gravity.Set(0.0f, -10.0f);
		def.masses = masses;
		def.damping = 0.1f;
		def.k2 = 1.0f;
		def.k3 = 0.5f;

		m_rope.Initialize(&def);

		m_angle = 0.0f;
		m_rope.SetAngle(m_angle);
	}

	void Keyboard(unsigned char key)
	{
		switch (key)
		{
		case 'q':
			m_angle = b2Max(-b2_pi, m_angle - 0.05f * b2_pi);
			m_rope.SetAngle(m_angle);
			break;

		case 'e':
			m_angle = b2Min(b2_pi, m_angle + 0.05f * b2_pi);
			m_rope.SetAngle(m_angle);
			break;
		}
	}

	void Step(Settings* settings)
	{
		float32 dt = settings->hz > 0.0f ? 1.0f / settings->hz : 0.0f;

		if (settings->pause == 1 && settings->singleStep == 0)
		{
			dt = 0.0f;
		}

		m_rope.Step(dt, 1);

		Test::Step(settings);

		m_rope.Draw(&m_debugDraw);

		m_debugDraw.DrawString(5, m_textLine, "Press (q,e) to adjust target angle");
		m_textLine += 15;
		m_debugDraw.DrawString(5, m_textLine, "Target angle = %g degrees", m_angle * 180.0f / b2_pi);
		m_textLine += 15;
	}

	static Test* Create()
	{
		return new Rope;
	}

	b2Rope m_rope;
	float32 m_angle;
};

#endif


code:
/*
* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef ROPE_JOINT_H
#define ROPE_JOINT_H

/// This test shows how a rope joint can be used to stabilize a chain of
/// bodies with a heavy payload. Notice that the rope joint just prevents
/// excessive stretching and has no other effect.
/// By disabling the rope joint you can see that the Box2D solver has trouble
/// supporting heavy bodies with light bodies. Try playing around with the
/// densities, time step, and iterations to see how they affect stability.
/// This test also shows how to use contact filtering. Filtering is configured
/// so that the payload does not collide with the chain.
class RopeJoint : public Test
{
public:
	RopeJoint()
	{
		b2Body* ground = NULL;
		{
			b2BodyDef bd;
			ground = m_world->CreateBody(&bd);

			b2EdgeShape shape;
			shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			b2PolygonShape shape;
			shape.SetAsBox(0.5f, 0.125f);

			b2FixtureDef fd;
			fd.shape = &shape;
			fd.density = 20.0f;
			fd.friction = 0.2f;
			fd.filter.categoryBits = 0x0001;
			fd.filter.maskBits = 0xFFFF & ~0x0002;

			b2RevoluteJointDef jd;
			jd.collideConnected = false;

			const int32 N = 10;
			const float32 y = 15.0f;
			m_ropeDef.localAnchorA.Set(0.0f, y);

			b2Body* prevBody = ground;
			for (int32 i = 0; i < N; ++i)
			{
				b2BodyDef bd;
				bd.type = b2_dynamicBody;
				bd.position.Set(0.5f + 1.0f * i, y);
				if (i == N - 1)
				{
					shape.SetAsBox(1.5f, 1.5f);
					fd.density = 100.0f;
					fd.filter.categoryBits = 0x0002;
					bd.position.Set(1.0f * i, y);
					bd.angularDamping = 0.4f;
				}

				b2Body* body = m_world->CreateBody(&bd);

				body->CreateFixture(&fd);

				b2Vec2 anchor(float32(i), y);
				jd.Initialize(prevBody, body, anchor);
				m_world->CreateJoint(&jd);

				prevBody = body;
			}

			m_ropeDef.localAnchorB.SetZero();

			float32 extraLength = 0.01f;
			m_ropeDef.maxLength = N - 1.0f + extraLength;
			m_ropeDef.bodyB = prevBody;
		}

		{
			m_ropeDef.bodyA = ground;
			m_rope = m_world->CreateJoint(&m_ropeDef);
		}
	}

	void Keyboard(unsigned char key)
	{
		switch (key)
		{
		case 'j':
			if (m_rope)
			{
				m_world->DestroyJoint(m_rope);
				m_rope = NULL;
			}
			else
			{
				m_rope = m_world->CreateJoint(&m_ropeDef);
			}
			break;
		}
	}

	void Step(Settings* settings)
	{
		Test::Step(settings);
		m_debugDraw.DrawString(5, m_textLine, "Press (j) to toggle the rope joint.");
		m_textLine += 15;
		if (m_rope)
		{
			m_debugDraw.DrawString(5, m_textLine, "Rope ON");
		}
		else
		{
			m_debugDraw.DrawString(5, m_textLine, "Rope OFF");
		}
		m_textLine += 15;
	}

	static Test* Create()
	{
		return new RopeJoint;
	}

	b2RopeJointDef m_ropeDef;
	b2Joint* m_rope;
};

#endif


code:
/*
* Copyright (c) 2008-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef SENSOR_TEST_H
#define SENSOR_TEST_H

// This is used to test sensor shapes.
class SensorTest : public Test
{
public:

	enum
	{
		e_count = 7
	};

	SensorTest()
	{
		{
			b2BodyDef bd;
			b2Body* ground = m_world->CreateBody(&bd);

			{
				b2EdgeShape shape;
				shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
				ground->CreateFixture(&shape, 0.0f);
			}

#if 0
			{
				b2FixtureDef sd;
				sd.SetAsBox(10.0f, 2.0f, b2Vec2(0.0f, 20.0f), 0.0f);
				sd.isSensor = true;
				m_sensor = ground->CreateFixture(&sd);
			}
#else
			{
				b2CircleShape shape;
				shape.m_radius = 5.0f;
				shape.m_p.Set(0.0f, 10.0f);

				b2FixtureDef fd;
				fd.shape = &shape;
				fd.isSensor = true;
				m_sensor = ground->CreateFixture(&fd);
			}
#endif
		}

		{
			b2CircleShape shape;
			shape.m_radius = 1.0f;

			for (int32 i = 0; i < e_count; ++i)
			{
				b2BodyDef bd;
				bd.type = b2_dynamicBody;
				bd.position.Set(-10.0f + 3.0f * i, 20.0f);
				bd.userData = m_touching + i;

				m_touching[i] = false;
				m_bodies[i] = m_world->CreateBody(&bd);

				m_bodies[i]->CreateFixture(&shape, 1.0f);
			}
		}
	}

	// Implement contact listener.
	void BeginContact(b2Contact* contact)
	{
		b2Fixture* fixtureA = contact->GetFixtureA();
		b2Fixture* fixtureB = contact->GetFixtureB();

		if (fixtureA == m_sensor)
		{
			void* userData = fixtureB->GetBody()->GetUserData();
			if (userData)
			{
				bool* touching = (bool*)userData;
				*touching = true;
			}
		}

		if (fixtureB == m_sensor)
		{
			void* userData = fixtureA->GetBody()->GetUserData();
			if (userData)
			{
				bool* touching = (bool*)userData;
				*touching = true;
			}
		}
	}

	// Implement contact listener.
	void EndContact(b2Contact* contact)
	{
		b2Fixture* fixtureA = contact->GetFixtureA();
		b2Fixture* fixtureB = contact->GetFixtureB();

		if (fixtureA == m_sensor)
		{
			void* userData = fixtureB->GetBody()->GetUserData();
			if (userData)
			{
				bool* touching = (bool*)userData;
				*touching = false;
			}
		}

		if (fixtureB == m_sensor)
		{
			void* userData = fixtureA->GetBody()->GetUserData();
			if (userData)
			{
				bool* touching = (bool*)userData;
				*touching = false;
			}
		}
	}

	void Step(Settings* settings)
	{
		Test::Step(settings);

		// Traverse the contact results. Apply a force on shapes
		// that overlap the sensor.
		for (int32 i = 0; i < e_count; ++i)
		{
			if (m_touching[i] == false)
			{
				continue;
			}

			b2Body* body = m_bodies[i];
			b2Body* ground = m_sensor->GetBody();

			b2CircleShape* circle = (b2CircleShape*)m_sensor->GetShape();
			b2Vec2 center = ground->GetWorldPoint(circle->m_p);

			b2Vec2 position = body->GetPosition();

			b2Vec2 d = center - position;
			if (d.LengthSquared() < FLT_EPSILON * FLT_EPSILON)
			{
				continue;
			}

			d.Normalize();
			b2Vec2 F = 100.0f * d;
			body->ApplyForce(F, position);
		}
	}

	static Test* Create()
	{
		return new SensorTest;
	}

	b2Fixture* m_sensor;
	b2Body* m_bodies[e_count];
	bool m_touching[e_count];
};

#endif


code:
/*
* Copyright (c) 2008-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef SHAPE_EDITING_H
#define SHAPE_EDITING_H

class ShapeEditing : public Test
{
public:

	ShapeEditing()
	{
		{
			b2BodyDef bd;
			b2Body* ground = m_world->CreateBody(&bd);

			b2EdgeShape shape;
			shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
			ground->CreateFixture(&shape, 0.0f);
		}

		b2BodyDef bd;
		bd.type = b2_dynamicBody;
		bd.position.Set(0.0f, 10.0f);
		m_body = m_world->CreateBody(&bd);

		b2PolygonShape shape;
		shape.SetAsBox(4.0f, 4.0f, b2Vec2(0.0f, 0.0f), 0.0f);
		m_fixture1 = m_body->CreateFixture(&shape, 10.0f);

		m_fixture2 = NULL;

		m_sensor = false;
	}

	void Keyboard(unsigned char key)
	{
		switch (key)
		{
		case 'c':
			if (m_fixture2 == NULL)
			{
				b2CircleShape shape;
				shape.m_radius = 3.0f;
				shape.m_p.Set(0.5f, -4.0f);
				m_fixture2 = m_body->CreateFixture(&shape, 10.0f);
				m_body->SetAwake(true);
			}
			break;

		case 'd':
			if (m_fixture2 != NULL)
			{
				m_body->DestroyFixture(m_fixture2);
				m_fixture2 = NULL;
				m_body->SetAwake(true);
			}
			break;

		case 's':
			if (m_fixture2 != NULL)
			{
				m_sensor = !m_sensor;
				m_fixture2->SetSensor(m_sensor);
			}
			break;
		}
	}

	void Step(Settings* settings)
	{
		Test::Step(settings);
		m_debugDraw.DrawString(5, m_textLine, "Press: (c) create a shape, (d) destroy a shape.");
		m_textLine += 15;
		m_debugDraw.DrawString(5, m_textLine, "sensor = %d", m_sensor);
		m_textLine += 15;
	}

	static Test* Create()
	{
		return new ShapeEditing;
	}

	b2Body* m_body;
	b2Fixture* m_fixture1;
	b2Fixture* m_fixture2;
	bool m_sensor;
};

#endif


code:
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef SLIDER_CRANK_H
#define SLIDER_CRANK_H

// A motor driven slider crank with joint friction.

class SliderCrank : public Test
{
public:
	SliderCrank()
	{
		b2Body* ground = NULL;
		{
			b2BodyDef bd;
			ground = m_world->CreateBody(&bd);

			b2EdgeShape shape;
			shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			b2Body* prevBody = ground;

			// Define crank.
			{
				b2PolygonShape shape;
				shape.SetAsBox(0.5f, 2.0f);

				b2BodyDef bd;
				bd.type = b2_dynamicBody;
				bd.position.Set(0.0f, 7.0f);
				b2Body* body = m_world->CreateBody(&bd);
				body->CreateFixture(&shape, 2.0f);

				b2RevoluteJointDef rjd;
				rjd.Initialize(prevBody, body, b2Vec2(0.0f, 5.0f));
				rjd.motorSpeed = 1.0f * b2_pi;
				rjd.maxMotorTorque = 10000.0f;
				rjd.enableMotor = true;
				m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&rjd);

				prevBody = body;
			}

			// Define follower.
			{
				b2PolygonShape shape;
				shape.SetAsBox(0.5f, 4.0f);

				b2BodyDef bd;
				bd.type = b2_dynamicBody;
				bd.position.Set(0.0f, 13.0f);
				b2Body* body = m_world->CreateBody(&bd);
				body->CreateFixture(&shape, 2.0f);

				b2RevoluteJointDef rjd;
				rjd.Initialize(prevBody, body, b2Vec2(0.0f, 9.0f));
				rjd.enableMotor = false;
				m_world->CreateJoint(&rjd);

				prevBody = body;
			}

			// Define piston
			{
				b2PolygonShape shape;
				shape.SetAsBox(1.5f, 1.5f);

				b2BodyDef bd;
				bd.type = b2_dynamicBody;
				bd.fixedRotation = true;
				bd.position.Set(0.0f, 17.0f);
				b2Body* body = m_world->CreateBody(&bd);
				body->CreateFixture(&shape, 2.0f);

				b2RevoluteJointDef rjd;
				rjd.Initialize(prevBody, body, b2Vec2(0.0f, 17.0f));
				m_world->CreateJoint(&rjd);

				b2PrismaticJointDef pjd;
				pjd.Initialize(ground, body, b2Vec2(0.0f, 17.0f), b2Vec2(0.0f, 1.0f));

				pjd.maxMotorForce = 1000.0f;
				pjd.enableMotor = true;

				m_joint2 = (b2PrismaticJoint*)m_world->CreateJoint(&pjd);
			}

			// Create a payload
			{
				b2PolygonShape shape;
				shape.SetAsBox(1.5f, 1.5f);

				b2BodyDef bd;
				bd.type = b2_dynamicBody;
				bd.position.Set(0.0f, 23.0f);
				b2Body* body = m_world->CreateBody(&bd);
				body->CreateFixture(&shape, 2.0f);
			}
		}
	}

	void Keyboard(unsigned char key)
	{
		switch (key)
		{
		case 'f':
			m_joint2->EnableMotor(!m_joint2->IsMotorEnabled());
			m_joint2->GetBodyB()->SetAwake(true);
			break;

		case 'm':
			m_joint1->EnableMotor(!m_joint1->IsMotorEnabled());
			m_joint1->GetBodyB()->SetAwake(true);
			break;
		}
	}

	void Step(Settings* settings)
	{
		Test::Step(settings);
		m_debugDraw.DrawString(5, m_textLine, "Keys: (f) toggle friction, (m) toggle motor");
		m_textLine += 15;
		float32 torque = m_joint1->GetMotorTorque(settings->hz);
		m_debugDraw.DrawString(5, m_textLine, "Motor Torque = %5.0f", (float) torque);
		m_textLine += 15;
	}

	static Test* Create()
	{
		return new SliderCrank;
	}

	b2RevoluteJoint* m_joint1;
	b2PrismaticJoint* m_joint2;
};

#endif


code:
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef SPHERE_STACK_H
#define SPHERE_STACK_H

class SphereStack : public Test
{
public:

	enum
	{
		e_count = 10
	};

	SphereStack()
	{
		{
			b2BodyDef bd;
			b2Body* ground = m_world->CreateBody(&bd);

			b2EdgeShape shape;
			shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			b2CircleShape shape;
			shape.m_radius = 1.0f;

			for (int32 i = 0; i < e_count; ++i)
			{
				b2BodyDef bd;
				bd.type = b2_dynamicBody;
				bd.position.Set(0.0, 4.0f + 3.0f * i);

				m_bodies[i] = m_world->CreateBody(&bd);

				m_bodies[i]->CreateFixture(&shape, 1.0f);

				m_bodies[i]->SetLinearVelocity(b2Vec2(0.0f, -50.0f));
			}
		}
	}

	void Step(Settings* settings)
	{
		Test::Step(settings);

		//for (int32 i = 0; i < e_count; ++i)
		//{
		//	printf("%g ", m_bodies[i]->GetWorldCenter().y);
		//}

		//for (int32 i = 0; i < e_count; ++i)
		//{
		//	printf("%g ", m_bodies[i]->GetLinearVelocity().y);
		//}

		//printf("\n");
	}

	static Test* Create()
	{
		return new SphereStack;
	}

	b2Body* m_bodies[e_count];
};

#endif


code:
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

// Inspired by a contribution by roman_m
// Dimensions scooped from APE (http://www.cove.org/ape/index.htm)

#ifndef THEO_JANSEN_H
#define THEO_JANSEN_H

class TheoJansen : public Test
{
public:

	void CreateLeg(float32 s, const b2Vec2& wheelAnchor)
	{
		b2Vec2 p1(5.4f * s, -6.1f);
		b2Vec2 p2(7.2f * s, -1.2f);
		b2Vec2 p3(4.3f * s, -1.9f);
		b2Vec2 p4(3.1f * s, 0.8f);
		b2Vec2 p5(6.0f * s, 1.5f);
		b2Vec2 p6(2.5f * s, 3.7f);

		b2FixtureDef fd1, fd2;
		fd1.filter.groupIndex = -1;
		fd2.filter.groupIndex = -1;
		fd1.density = 1.0f;
		fd2.density = 1.0f;

		b2PolygonShape poly1, poly2;

		if (s > 0.0f)
		{
			b2Vec2 vertices[3];

			vertices[0] = p1;
			vertices[1] = p2;
			vertices[2] = p3;
			poly1.Set(vertices, 3);

			vertices[0] = b2Vec2_zero;
			vertices[1] = p5 - p4;
			vertices[2] = p6 - p4;
			poly2.Set(vertices, 3);
		}
		else
		{
			b2Vec2 vertices[3];

			vertices[0] = p1;
			vertices[1] = p3;
			vertices[2] = p2;
			poly1.Set(vertices, 3);

			vertices[0] = b2Vec2_zero;
			vertices[1] = p6 - p4;
			vertices[2] = p5 - p4;
			poly2.Set(vertices, 3);
		}

		fd1.shape = &poly1;
		fd2.shape = &poly2;

		b2BodyDef bd1, bd2;
		bd1.type = b2_dynamicBody;
		bd2.type = b2_dynamicBody;
		bd1.position = m_offset;
		bd2.position = p4 + m_offset;

		bd1.angularDamping = 10.0f;
		bd2.angularDamping = 10.0f;

		b2Body* body1 = m_world->CreateBody(&bd1);
		b2Body* body2 = m_world->CreateBody(&bd2);

		body1->CreateFixture(&fd1);
		body2->CreateFixture(&fd2);

		b2DistanceJointDef djd;

		// Using a soft distance constraint can reduce some jitter.
		// It also makes the structure seem a bit more fluid by
		// acting like a suspension system.
		djd.dampingRatio = 0.5f;
		djd.frequencyHz = 10.0f;

		djd.Initialize(body1, body2, p2 + m_offset, p5 + m_offset);
		m_world->CreateJoint(&djd);

		djd.Initialize(body1, body2, p3 + m_offset, p4 + m_offset);
		m_world->CreateJoint(&djd);

		djd.Initialize(body1, m_wheel, p3 + m_offset, wheelAnchor + m_offset);
		m_world->CreateJoint(&djd);

		djd.Initialize(body2, m_wheel, p6 + m_offset, wheelAnchor + m_offset);
		m_world->CreateJoint(&djd);

		b2RevoluteJointDef rjd;

		rjd.Initialize(body2, m_chassis, p4 + m_offset);
		m_world->CreateJoint(&rjd);
	}

	TheoJansen()
	{
		m_offset.Set(0.0f, 8.0f);
		m_motorSpeed = 2.0f;
		m_motorOn = true;
		b2Vec2 pivot(0.0f, 0.8f);

		// Ground
		{
			b2BodyDef bd;
			b2Body* ground = m_world->CreateBody(&bd);

			b2EdgeShape shape;
			shape.Set(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f));
			ground->CreateFixture(&shape, 0.0f);

			shape.Set(b2Vec2(-50.0f, 0.0f), b2Vec2(-50.0f, 10.0f));
			ground->CreateFixture(&shape, 0.0f);

			shape.Set(b2Vec2(50.0f, 0.0f), b2Vec2(50.0f, 10.0f));
			ground->CreateFixture(&shape, 0.0f);
		}

		// Balls
		for (int32 i = 0; i < 40; ++i)
		{
			b2CircleShape shape;
			shape.m_radius = 0.25f;

			b2BodyDef bd;
			bd.type = b2_dynamicBody;
			bd.position.Set(-40.0f + 2.0f * i, 0.5f);

			b2Body* body = m_world->CreateBody(&bd);
			body->CreateFixture(&shape, 1.0f);
		}

		// Chassis
		{
			b2PolygonShape shape;
			shape.SetAsBox(2.5f, 1.0f);

			b2FixtureDef sd;
			sd.density = 1.0f;
			sd.shape = &shape;
			sd.filter.groupIndex = -1;
			b2BodyDef bd;
			bd.type = b2_dynamicBody;
			bd.position = pivot + m_offset;
			m_chassis = m_world->CreateBody(&bd);
			m_chassis->CreateFixture(&sd);
		}

		{
			b2CircleShape shape;
			shape.m_radius = 1.6f;

			b2FixtureDef sd;
			sd.density = 1.0f;
			sd.shape = &shape;
			sd.filter.groupIndex = -1;
			b2BodyDef bd;
			bd.type = b2_dynamicBody;
			bd.position = pivot + m_offset;
			m_wheel = m_world->CreateBody(&bd);
			m_wheel->CreateFixture(&sd);
		}

		{
			b2RevoluteJointDef jd;
			jd.Initialize(m_wheel, m_chassis, pivot + m_offset);
			jd.collideConnected = false;
			jd.motorSpeed = m_motorSpeed;
			jd.maxMotorTorque = 400.0f;
			jd.enableMotor = m_motorOn;
			m_motorJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd);
		}

		b2Vec2 wheelAnchor;

		wheelAnchor = pivot + b2Vec2(0.0f, -0.8f);

		CreateLeg(-1.0f, wheelAnchor);
		CreateLeg(1.0f, wheelAnchor);

		m_wheel->SetTransform(m_wheel->GetPosition(), 120.0f * b2_pi / 180.0f);
		CreateLeg(-1.0f, wheelAnchor);
		CreateLeg(1.0f, wheelAnchor);

		m_wheel->SetTransform(m_wheel->GetPosition(), -120.0f * b2_pi / 180.0f);
		CreateLeg(-1.0f, wheelAnchor);
		CreateLeg(1.0f, wheelAnchor);
	}

	void Step(Settings* settings)
	{
		m_debugDraw.DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d, toggle motor = m");
		m_textLine += 15;

		Test::Step(settings);
	}

	void Keyboard(unsigned char key)
	{
		switch (key)
		{
		case 'a':
			m_motorJoint->SetMotorSpeed(-m_motorSpeed);
			break;

		case 's':
			m_motorJoint->SetMotorSpeed(0.0f);
			break;

		case 'd':
			m_motorJoint->SetMotorSpeed(m_motorSpeed);
			break;

		case 'm':
			m_motorJoint->EnableMotor(!m_motorJoint->IsMotorEnabled());
			break;
		}
	}

	static Test* Create()
	{
		return new TheoJansen;
	}

	b2Vec2 m_offset;
	b2Body* m_chassis;
	b2Body* m_wheel;
	b2RevoluteJoint* m_motorJoint;
	bool m_motorOn;
	float32 m_motorSpeed;
};

#endif // THEO_JANSEN_H


code:
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef TILES_H
#define TILES_H

/// This stress tests the dynamic tree broad-phase. This also shows that tile
/// based collision is _not_ smooth due to Box2D not knowing about adjacency.
class Tiles : public Test
{
public:
	enum
	{
		e_count = 20
	};

	Tiles()
	{
		m_fixtureCount = 0;
		b2Timer timer;

		{
			float32 a = 0.5f;
			b2BodyDef bd;
			bd.position.y = -a;
			b2Body* ground = m_world->CreateBody(&bd);

#if 1
			int32 N = 200;
			int32 M = 10;
			b2Vec2 position;
			position.y = 0.0f;
			for (int32 j = 0; j < M; ++j)
			{
				position.x = -N * a;
				for (int32 i = 0; i < N; ++i)
				{
					b2PolygonShape shape;
					shape.SetAsBox(a, a, position, 0.0f);
					ground->CreateFixture(&shape, 0.0f);
					++m_fixtureCount;
					position.x += 2.0f * a;
				}
				position.y -= 2.0f * a;
			}
#else
			int32 N = 200;
			int32 M = 10;
			b2Vec2 position;
			position.x = -N * a;
			for (int32 i = 0; i < N; ++i)
			{
				position.y = 0.0f;
				for (int32 j = 0; j < M; ++j)
				{
					b2PolygonShape shape;
					shape.SetAsBox(a, a, position, 0.0f);
					ground->CreateFixture(&shape, 0.0f);
					position.y -= 2.0f * a;
				}
				position.x += 2.0f * a;
			}
#endif
		}

		{
			float32 a = 0.5f;
			b2PolygonShape shape;
			shape.SetAsBox(a, a);

			b2Vec2 x(-7.0f, 0.75f);
			b2Vec2 y;
			b2Vec2 deltaX(0.5625f, 1.25f);
			b2Vec2 deltaY(1.125f, 0.0f);

			for (int32 i = 0; i < e_count; ++i)
			{
				y = x;

				for (int32 j = i; j < e_count; ++j)
				{
					b2BodyDef bd;
					bd.type = b2_dynamicBody;
					bd.position = y;

					//if (i == 0 && j == 0)
					//{
					//	bd.allowSleep = false;
					//}
					//else
					//{
					//	bd.allowSleep = true;
					//}

					b2Body* body = m_world->CreateBody(&bd);
					body->CreateFixture(&shape, 5.0f);
					++m_fixtureCount;
					y += deltaY;
				}

				x += deltaX;
			}
		}

		m_createTime = timer.GetMilliseconds();
	}

	void Step(Settings* settings)
	{
		const b2ContactManager& cm = m_world->GetContactManager();
		int32 height = cm.m_broadPhase.GetTreeHeight();
		int32 leafCount = cm.m_broadPhase.GetProxyCount();
		int32 minimumNodeCount = 2 * leafCount - 1;
		float32 minimumHeight = ceilf(logf(float32(minimumNodeCount)) / logf(2.0f));
		m_debugDraw.DrawString(5, m_textLine, "dynamic tree height = %d, min = %d", height, int32(minimumHeight));
		m_textLine += 15;

		Test::Step(settings);

		m_debugDraw.DrawString(5, m_textLine, "create time = %6.2f ms, fixture count = %d",
			m_createTime, m_fixtureCount);
		m_textLine += 15;

		//b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree;

		//if (m_stepCount == 400)
		//{
		//	tree->RebuildBottomUp();
		//}
	}

	static Test* Create()
	{
		return new Tiles;
	}

	int32 m_fixtureCount;
	float32 m_createTime;
};

#endif


code:
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef TIME_OF_IMPACT_H
#define TIME_OF_IMPACT_H

class TimeOfImpact : public Test
{
public:
	TimeOfImpact()
	{
		m_shapeA.SetAsBox(25.0f, 5.0f);
		m_shapeB.SetAsBox(2.5f, 2.5f);
	}

	static Test* Create()
	{
		return new TimeOfImpact;
	}

	void Step(Settings* settings)
	{
		Test::Step(settings);

		b2Sweep sweepA;
		sweepA.c0.Set(24.0f, -60.0f);
		sweepA.a0 = 2.95f;
		sweepA.c = sweepA.c0;
		sweepA.a = sweepA.a0;
		sweepA.localCenter.SetZero();

		b2Sweep sweepB;
		sweepB.c0.Set(53.474274f, -50.252514f);
		sweepB.a0 = 513.36676f; // - 162.0f * b2_pi;
		sweepB.c.Set(54.595478f, -51.083473f);
		sweepB.a = 513.62781f; //  - 162.0f * b2_pi;
		sweepB.localCenter.SetZero();

		//sweepB.a0 -= 300.0f * b2_pi;
		//sweepB.a -= 300.0f * b2_pi;

		b2TOIInput input;
		input.proxyA.Set(&m_shapeA, 0);
		input.proxyB.Set(&m_shapeB, 0);
		input.sweepA = sweepA;
		input.sweepB = sweepB;
		input.tMax = 1.0f;

		b2TOIOutput output;

		b2TimeOfImpact(&output, &input);

		m_debugDraw.DrawString(5, m_textLine, "toi = %g", output.t);
		m_textLine += 15;

		extern int32 b2_toiMaxIters, b2_toiMaxRootIters;
		m_debugDraw.DrawString(5, m_textLine, "max toi iters = %d, max root iters = %d", b2_toiMaxIters, b2_toiMaxRootIters);
		m_textLine += 15;

		b2Vec2 vertices[b2_maxPolygonVertices];

		b2Transform transformA;
		sweepA.GetTransform(&transformA, 0.0f);
		for (int32 i = 0; i < m_shapeA.m_vertexCount; ++i)
		{
			vertices[i] = b2Mul(transformA, m_shapeA.m_vertices[i]);
		}
		m_debugDraw.DrawPolygon(vertices, m_shapeA.m_vertexCount, b2Color(0.9f, 0.9f, 0.9f));

		b2Transform transformB;
		sweepB.GetTransform(&transformB, 0.0f);

		b2Vec2 localPoint(2.0f, -0.1f);
		b2Vec2 rB = b2Mul(transformB, localPoint) - sweepB.c0;
		float32 wB = sweepB.a - sweepB.a0;
		b2Vec2 vB = sweepB.c - sweepB.c0;
		b2Vec2 v = vB + b2Cross(wB, rB);

		for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i)
		{
			vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]);
		}
		m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0.5f, 0.9f, 0.5f));

		sweepB.GetTransform(&transformB, output.t);
		for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i)
		{
			vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]);
		}
		m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0.5f, 0.7f, 0.9f));

		sweepB.GetTransform(&transformB, 1.0f);
		for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i)
		{
			vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]);
		}
		m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0.9f, 0.5f, 0.5f));

#if 0
		for (float32 t = 0.0f; t < 1.0f; t += 0.1f)
		{
			sweepB.GetTransform(&transformB, t);
			for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i)
			{
				vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]);
			}
			m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0.9f, 0.5f, 0.5f));
		}
#endif
	}

	b2PolygonShape m_shapeA;
	b2PolygonShape m_shapeB;
};

#endif


code:
/*
* Copyright (c) 2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef TUMBLER_H
#define TUMBLER_H

class Tumbler : public Test
{
public:

	enum
	{
		e_count = 800
	};

	Tumbler()
	{
		b2Body* ground = NULL;
		{
			b2BodyDef bd;
			ground = m_world->CreateBody(&bd);
		}

		{
			b2BodyDef bd;
			bd.type = b2_dynamicBody;
			bd.allowSleep = false;
			bd.position.Set(0.0f, 10.0f);
			b2Body* body = m_world->CreateBody(&bd);

			b2PolygonShape shape;
			shape.SetAsBox(0.5f, 10.0f, b2Vec2( 10.0f, 0.0f), 0.0);
			body->CreateFixture(&shape, 5.0f);
			shape.SetAsBox(0.5f, 10.0f, b2Vec2(-10.0f, 0.0f), 0.0);
			body->CreateFixture(&shape, 5.0f);
			shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, 10.0f), 0.0);
			body->CreateFixture(&shape, 5.0f);
			shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, -10.0f), 0.0);
			body->CreateFixture(&shape, 5.0f);

			b2RevoluteJointDef jd;
			jd.bodyA = ground;
			jd.bodyB = body;
			jd.localAnchorA.Set(0.0f, 10.0f);
			jd.localAnchorB.Set(0.0f, 0.0f);
			jd.referenceAngle = 0.0f;
			jd.motorSpeed = 0.05f * b2_pi;
			jd.maxMotorTorque = 1e8f;
			jd.enableMotor = true;
			m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&jd);
		}

		m_count = 0;
	}

	void Step(Settings* settings)
	{
		Test::Step(settings);

		if (m_count < e_count)
		{
			b2BodyDef bd;
			bd.type = b2_dynamicBody;
			bd.position.Set(0.0f, 10.0f);
			b2Body* body = m_world->CreateBody(&bd);

			b2PolygonShape shape;
			shape.SetAsBox(0.125f, 0.125f);
			body->CreateFixture(&shape, 1.0f);

			++m_count;
		}
	}

	static Test* Create()
	{
		return new Tumbler;
	}

	b2RevoluteJoint* m_joint;
	int32 m_count;
};

#endif


code:
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef VARYING_FRICTION_H
#define VARYING_FRICTION_H

class VaryingFriction : public Test
{
public:

	VaryingFriction()
	{
		{
			b2BodyDef bd;
			b2Body* ground = m_world->CreateBody(&bd);

			b2EdgeShape shape;
			shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			b2PolygonShape shape;
			shape.SetAsBox(13.0f, 0.25f);

			b2BodyDef bd;
			bd.position.Set(-4.0f, 22.0f);
			bd.angle = -0.25f;

			b2Body* ground = m_world->CreateBody(&bd);
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			b2PolygonShape shape;
			shape.SetAsBox(0.25f, 1.0f);

			b2BodyDef bd;
			bd.position.Set(10.5f, 19.0f);

			b2Body* ground = m_world->CreateBody(&bd);
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			b2PolygonShape shape;
			shape.SetAsBox(13.0f, 0.25f);

			b2BodyDef bd;
			bd.position.Set(4.0f, 14.0f);
			bd.angle = 0.25f;

			b2Body* ground = m_world->CreateBody(&bd);
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			b2PolygonShape shape;
			shape.SetAsBox(0.25f, 1.0f);

			b2BodyDef bd;
			bd.position.Set(-10.5f, 11.0f);

			b2Body* ground = m_world->CreateBody(&bd);
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			b2PolygonShape shape;
			shape.SetAsBox(13.0f, 0.25f);

			b2BodyDef bd;
			bd.position.Set(-4.0f, 6.0f);
			bd.angle = -0.25f;

			b2Body* ground = m_world->CreateBody(&bd);
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			b2PolygonShape shape;
			shape.SetAsBox(0.5f, 0.5f);

			b2FixtureDef fd;
			fd.shape = &shape;
			fd.density = 25.0f;

			float friction[5] = {0.75f, 0.5f, 0.35f, 0.1f, 0.0f};

			for (int i = 0; i < 5; ++i)
			{
				b2BodyDef bd;
				bd.type = b2_dynamicBody;
				bd.position.Set(-15.0f + 4.0f * i, 28.0f);
				b2Body* body = m_world->CreateBody(&bd);

				fd.friction = friction[i];
				body->CreateFixture(&fd);
			}
		}
	}

	static Test* Create()
	{
		return new VaryingFriction;
	}
};

#endif


code:
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef VARYING_RESTITUTION_H
#define VARYING_RESTITUTION_H

// Note: even with a restitution of 1.0, there is some energy change
// due to position correction.
class VaryingRestitution : public Test
{
public:

	VaryingRestitution()
	{
		{
			b2BodyDef bd;
			b2Body* ground = m_world->CreateBody(&bd);

			b2EdgeShape shape;
			shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			b2CircleShape shape;
			shape.m_radius = 1.0f;

			b2FixtureDef fd;
			fd.shape = &shape;
			fd.density = 1.0f;

			float32 restitution[7] = {0.0f, 0.1f, 0.3f, 0.5f, 0.75f, 0.9f, 1.0f};

			for (int32 i = 0; i < 7; ++i)
			{
				b2BodyDef bd;
				bd.type = b2_dynamicBody;
				bd.position.Set(-10.0f + 3.0f * i, 20.0f);

				b2Body* body = m_world->CreateBody(&bd);

				fd.restitution = restitution[i];
				body->CreateFixture(&fd);
			}
		}
	}

	static Test* Create()
	{
		return new VaryingRestitution;
	}
};

#endif


code:
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef VERTICAL_STACK_H
#define VERTICAL_STACK_H

class VerticalStack : public Test
{
public:

	enum
	{
		e_columnCount = 5,
		e_rowCount = 16
		//e_columnCount = 1,
		//e_rowCount = 1
	};

	VerticalStack()
	{
		{
			b2BodyDef bd;
			b2Body* ground = m_world->CreateBody(&bd);

			b2EdgeShape shape;
			shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
			ground->CreateFixture(&shape, 0.0f);

			shape.Set(b2Vec2(20.0f, 0.0f), b2Vec2(20.0f, 20.0f));
			ground->CreateFixture(&shape, 0.0f);
		}

		float32 xs[5] = {0.0f, -10.0f, -5.0f, 5.0f, 10.0f};

		for (int32 j = 0; j < e_columnCount; ++j)
		{
			b2PolygonShape shape;
			shape.SetAsBox(0.5f, 0.5f);

			b2FixtureDef fd;
			fd.shape = &shape;
			fd.density = 1.0f;
			fd.friction = 0.3f;

			for (int i = 0; i < e_rowCount; ++i)
			{
				b2BodyDef bd;
				bd.type = b2_dynamicBody;

				int32 n = j * e_rowCount + i;
				b2Assert(n < e_rowCount * e_columnCount);
				m_indices[n] = n;
				bd.userData = m_indices + n;

				float32 x = 0.0f;
				//float32 x = RandomFloat(-0.02f, 0.02f);
				//float32 x = i % 2 == 0 ? -0.025f : 0.025f;
				bd.position.Set(xs[j] + x, 0.752f + 1.54f * i);
				b2Body* body = m_world->CreateBody(&bd);

				m_bodies[n] = body;

				body->CreateFixture(&fd);
			}
		}

		m_bullet = NULL;
	}

	void Keyboard(unsigned char key)
	{
		switch (key)
		{
		case ',':
			if (m_bullet != NULL)
			{
				m_world->DestroyBody(m_bullet);
				m_bullet = NULL;
			}

			{
				b2CircleShape shape;
				shape.m_radius = 0.25f;

				b2FixtureDef fd;
				fd.shape = &shape;
				fd.density = 20.0f;
				fd.restitution = 0.05f;

				b2BodyDef bd;
				bd.type = b2_dynamicBody;
				bd.bullet = true;
				bd.position.Set(-31.0f, 5.0f);

				m_bullet = m_world->CreateBody(&bd);
				m_bullet->CreateFixture(&fd);

				m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f));
			}
			break;
		}
	}

	void Step(Settings* settings)
	{
		Test::Step(settings);
		m_debugDraw.DrawString(5, m_textLine, "Press: (,) to launch a bullet.");
		m_textLine += 15;

		//if (m_stepCount == 300)
		//{
		//	if (m_bullet != NULL)
		//	{
		//		m_world->DestroyBody(m_bullet);
		//		m_bullet = NULL;
		//	}

		//	{
		//		b2CircleShape shape;
		//		shape.m_radius = 0.25f;

		//		b2FixtureDef fd;
		//		fd.shape = &shape;
		//		fd.density = 20.0f;
		//		fd.restitution = 0.05f;

		//		b2BodyDef bd;
		//		bd.type = b2_dynamicBody;
		//		bd.bullet = true;
		//		bd.position.Set(-31.0f, 5.0f);

		//		m_bullet = m_world->CreateBody(&bd);
		//		m_bullet->CreateFixture(&fd);

		//		m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f));
		//	}
		//}
	}

	static Test* Create()
	{
		return new VerticalStack;
	}

	b2Body* m_bullet;
	b2Body* m_bodies[e_rowCount * e_columnCount];
	int32 m_indices[e_rowCount * e_columnCount];
};

#endif


code:
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef WEB_H
#define WEB_H

// This tests distance joints, body destruction, and joint destruction.
class Web : public Test
{
public:
	Web()
	{
		b2Body* ground = NULL;
		{
			b2BodyDef bd;
			ground = m_world->CreateBody(&bd);

			b2EdgeShape shape;
			shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
			ground->CreateFixture(&shape, 0.0f);
		}

		{
			b2PolygonShape shape;
			shape.SetAsBox(0.5f, 0.5f);

			b2BodyDef bd;
			bd.type = b2_dynamicBody;

			bd.position.Set(-5.0f, 5.0f);
			m_bodies[0] = m_world->CreateBody(&bd);
			m_bodies[0]->CreateFixture(&shape, 5.0f);

			bd.position.Set(5.0f, 5.0f);
			m_bodies[1] = m_world->CreateBody(&bd);
			m_bodies[1]->CreateFixture(&shape, 5.0f);

			bd.position.Set(5.0f, 15.0f);
			m_bodies[2] = m_world->CreateBody(&bd);
			m_bodies[2]->CreateFixture(&shape, 5.0f);

			bd.position.Set(-5.0f, 15.0f);
			m_bodies[3] = m_world->CreateBody(&bd);
			m_bodies[3]->CreateFixture(&shape, 5.0f);

			b2DistanceJointDef jd;
			b2Vec2 p1, p2, d;

			jd.frequencyHz = 2.0f;
			jd.dampingRatio = 0.0f;

			jd.bodyA = ground;
			jd.bodyB = m_bodies[0];
			jd.localAnchorA.Set(-10.0f, 0.0f);
			jd.localAnchorB.Set(-0.5f, -0.5f);
			p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
			p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
			d = p2 - p1;
			jd.length = d.Length();
			m_joints[0] = m_world->CreateJoint(&jd);

			jd.bodyA = ground;
			jd.bodyB = m_bodies[1];
			jd.localAnchorA.Set(10.0f, 0.0f);
			jd.localAnchorB.Set(0.5f, -0.5f);
			p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
			p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
			d = p2 - p1;
			jd.length = d.Length();
			m_joints[1] = m_world->CreateJoint(&jd);

			jd.bodyA = ground;
			jd.bodyB = m_bodies[2];
			jd.localAnchorA.Set(10.0f, 20.0f);
			jd.localAnchorB.Set(0.5f, 0.5f);
			p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
			p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
			d = p2 - p1;
			jd.length = d.Length();
			m_joints[2] = m_world->CreateJoint(&jd);

			jd.bodyA = ground;
			jd.bodyB = m_bodies[3];
			jd.localAnchorA.Set(-10.0f, 20.0f);
			jd.localAnchorB.Set(-0.5f, 0.5f);
			p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
			p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
			d = p2 - p1;
			jd.length = d.Length();
			m_joints[3] = m_world->CreateJoint(&jd);

			jd.bodyA = m_bodies[0];
			jd.bodyB = m_bodies[1];
			jd.localAnchorA.Set(0.5f, 0.0f);
			jd.localAnchorB.Set(-0.5f, 0.0f);;
			p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
			p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
			d = p2 - p1;
			jd.length = d.Length();
			m_joints[4] = m_world->CreateJoint(&jd);

			jd.bodyA = m_bodies[1];
			jd.bodyB = m_bodies[2];
			jd.localAnchorA.Set(0.0f, 0.5f);
			jd.localAnchorB.Set(0.0f, -0.5f);
			p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
			p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
			d = p2 - p1;
			jd.length = d.Length();
			m_joints[5] = m_world->CreateJoint(&jd);

			jd.bodyA = m_bodies[2];
			jd.bodyB = m_bodies[3];
			jd.localAnchorA.Set(-0.5f, 0.0f);
			jd.localAnchorB.Set(0.5f, 0.0f);
			p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
			p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
			d = p2 - p1;
			jd.length = d.Length();
			m_joints[6] = m_world->CreateJoint(&jd);

			jd.bodyA = m_bodies[3];
			jd.bodyB = m_bodies[0];
			jd.localAnchorA.Set(0.0f, -0.5f);
			jd.localAnchorB.Set(0.0f, 0.5f);
			p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
			p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
			d = p2 - p1;
			jd.length = d.Length();
			m_joints[7] = m_world->CreateJoint(&jd);
		}
	}

	void Keyboard(unsigned char key)
	{
		switch (key)
		{
		case 'b':
			for (int32 i = 0; i < 4; ++i)
			{
				if (m_bodies[i])
				{
					m_world->DestroyBody(m_bodies[i]);
					m_bodies[i] = NULL;
					break;
				}
			}
			break;

		case 'j':
			for (int32 i = 0; i < 8; ++i)
			{
				if (m_joints[i])
				{
					m_world->DestroyJoint(m_joints[i]);
					m_joints[i] = NULL;
					break;
				}
			}
			break;
		}
	}

	void Step(Settings* settings)
	{
		Test::Step(settings);
		m_debugDraw.DrawString(5, m_textLine, "This demonstrates a soft distance joint.");
		m_textLine += 15;
		m_debugDraw.DrawString(5, m_textLine, "Press: (b) to delete a body, (j) to delete a joint");
		m_textLine += 15;
	}

	void JointDestroyed(b2Joint* joint)
	{
		for (int32 i = 0; i < 8; ++i)
		{
			if (m_joints[i] == joint)
			{
				m_joints[i] = NULL;
				break;
			}
		}
	}

	static Test* Create()
	{
		return new Web;
	}

	b2Body* m_bodies[4];
	b2Joint* m_joints[8];
};

#endif


code:
//
//  Bug-1159.m
//  Z-Fighting in iPad 2
// http://code.google.com/p/cocos2d-iphone/issues/detail?id=1159
//
//  Created by Greg Woods on 4/5/11.
//  Copyright 2011 Westlake Design. All rights reserved.
//

#include "Bug-1159.h"

CCScene* Bug1159Layer::scene()
{
    CCScene *pScene = CCScene::node();
    Bug1159Layer* layer = Bug1159Layer::node();
	pScene->addChild(layer);

    return pScene;
}

bool Bug1159Layer::init()
{
    if (BugsTestBaseLayer::init())
	{
        CCSize s = CCDirector::sharedDirector()->getWinSize();

        CCLayerColor *background = CCLayerColor::layerWithColor(ccc4f(255, 0, 255, 255));
		addChild(background);

        CCLayerColor *sprite_a = CCLayerColor::layerWithColorWidthHeight(ccc4f(255, 0, 0, 255), 700, 700);
		sprite_a->setAnchorPoint(ccp(0.5f, 0.5f));
		sprite_a->setIsRelativeAnchorPoint(true);
		sprite_a->setPosition(ccp(0.0f, s.height/2));
		addChild(sprite_a);

        sprite_a->runAction(CCRepeatForever::actionWithAction((CCActionInterval*) CCSequence::actions(
                                                               CCMoveTo::actionWithDuration(1.0f, ccp(1024.0f, 384.0f)),
                                                               CCMoveTo::actionWithDuration(1.0f, ccp(0.0f, 384.0f)),
															   NULL)));

        CCLayerColor *sprite_b = CCLayerColor::layerWithColorWidthHeight(ccc4f(0, 0, 255, 255), 400, 400);
		sprite_b->setAnchorPoint(ccp(0.5f, 0.5f));
		sprite_b->setIsRelativeAnchorPoint(true);
		sprite_b->setPosition(ccp(s.width/2, s.height/2));
		addChild(sprite_b);

        CCMenuItemLabel *label = CCMenuItemLabel::itemWithLabel(CCLabelTTF::labelWithString("Flip Me", "Helvetica", 24), this, menu_selector(Bug1159Layer::callBack));
        CCMenu *menu = CCMenu::menuWithItems(label, NULL);
		menu->setPosition(ccp(s.width - 200.0f, 50.0f));
		addChild(menu);

        return true;
	}

	return false;
}

void Bug1159Layer::callBack(CCObject* pSender)
{
    CCDirector::sharedDirector()->replaceScene(CCTransitionPageTurn::transitionWithDuration(1.0f, Bug1159Layer::scene(), false));
}


code:
#ifndef __BUG_1159_H__
#define __BUG_1159_H__

#include "BugsTest.h"

class Bug1159Layer : public BugsTestBaseLayer
{
public:
    virtual bool init();
    static CCScene* scene();
    void callBack(CCObject* pSender);

    LAYER_NODE_FUNC(Bug1159Layer);
};

#endif // __BUG_1159_H__


code:
//
// Bug-1174
// http://code.google.com/p/cocos2d-iphone/issues/detail?id=1174
//

#include "Bug-1174.h"

int check_for_error( CCPoint p1, CCPoint p2, CCPoint p3, CCPoint p4, float s, float t );

int check_for_error( CCPoint p1, CCPoint p2, CCPoint p3, CCPoint p4, float s, float t )
{
	//	the hit point is		p3 + t * (p4 - p3);
	//	the hit point also is	p1 + s * (p2 - p1);

	CCPoint p4_p3 = ccpSub( p4, p3);
	CCPoint p4_p3_t = ccpMult(p4_p3, t);
	CCPoint hitPoint1 = ccpAdd( p3, p4_p3_t);

	CCPoint p2_p1 = ccpSub( p2, p1);
	CCPoint p2_p1_s = ccpMult(p2_p1, s);
	CCPoint hitPoint2 = ccpAdd( p1, p2_p1_s);

	// Since float has rounding errors, only check if diff is < 0.05
	if( (fabs( hitPoint1.x - hitPoint2.x) > 0.1f) || ( fabs(hitPoint1.y - hitPoint2.y) > 0.1f) )
    {
		CCLog("ERROR: (%f,%f) != (%f,%f)", hitPoint1.x, hitPoint1.y, hitPoint2.x, hitPoint2.y);
		return 1;
	}

	return 0;
}

bool Bug1174Layer::init()
{
    if (BugsTestBaseLayer::init())
    {
// 		// seed
// 		srand(0);

		CCPoint A,B,C,D,p1,p2,p3,p4;
		float s,t;

		int err=0;
		int ok=0;

		//
		// Test 1.
		//
		CCLog("Test1 - Start");
		for( int i=0; i < 10000; i++)
        {
			// A | b
			// -----
			// c | d
			float ax = CCRANDOM_0_1() * -5000;
			float ay = CCRANDOM_0_1() * 5000;

			// a | b
			// -----
			// c | D
			float dx = CCRANDOM_0_1() * 5000;
			float dy = CCRANDOM_0_1() * -5000;

			// a | B
			// -----
			// c | d
			float bx = CCRANDOM_0_1() * 5000;
			float by = CCRANDOM_0_1() * 5000;

			// a | b
			// -----
			// C | d
			float cx = CCRANDOM_0_1() * -5000;
			float cy = CCRANDOM_0_1() * -5000;

			A = ccp(ax,ay);
			B = ccp(bx,by);
			C = ccp(cx,cy);
			D = ccp(dx,dy);
			if( ccpLineIntersect( A, D, B, C, &s, &t) ) {
				if( check_for_error(A, D, B, C, s, t) )
					err++;
				else
					ok++;
			}
		}
		CCLog("Test1 - End. OK=%i, Err=%i", ok, err);

		//
		// Test 2.
		//
		CCLog("Test2 - Start");

		p1 = ccp(220,480);
		p2 = ccp(304,325);
		p3 = ccp(264,416);
		p4 = ccp(186,416);
		s = 0.0f;
		t = 0.0f;
		if( ccpLineIntersect(p1, p2, p3, p4, &s, &t) )
			check_for_error(p1, p2, p3, p4, s,t );

		CCLog("Test2 - End");

		//
		// Test 3
		//
		CCLog("Test3 - Start");

		ok=0;
		err=0;
		for( int i=0;i<10000;i++)
        {
			// A | b
			// -----
			// c | d
			float ax = CCRANDOM_0_1() * -500;
			float ay = CCRANDOM_0_1() * 500;
			p1 = ccp(ax,ay);

			// a | b
			// -----
			// c | D
			float dx = CCRANDOM_0_1() * 500;
			float dy = CCRANDOM_0_1() * -500;
			p2 = ccp(dx,dy);

			//////

			float y = ay - ((ay - dy) /2.0f);

			// a | b
			// -----
			// C | d
			float cx = CCRANDOM_0_1() * -500;
			p3 = ccp(cx,y);

			// a | B
			// -----
			// c | d
			float bx = CCRANDOM_0_1() * 500;
			p4 = ccp(bx,y);

			s = 0.0f;
			t = 0.0f;
			if( ccpLineIntersect(p1, p2, p3, p4, &s, &t) ) {
				if( check_for_error(p1, p2, p3, p4, s,t ) )
					err++;
				else
					ok++;
			}
		}

		CCLog("Test3 - End. OK=%i, err=%i", ok, err);
        return true;
	}

	return false;
}


code:
#ifndef __BUG_1174_H__
#define __BUG_1174_H__

#include "BugsTest.h"

class Bug1174Layer : public BugsTestBaseLayer
{
public:
    virtual bool init();
};

#endif // __BUG_1174_H__


code:
//
// Bug-350
// http://code.google.com/p/cocos2d-iphone/issues/detail?id=350
//

#include "Bug-350.h"

bool Bug350Layer::init()
{
    if (BugsTestBaseLayer::init())
    {
        CCSize size = CCDirector::sharedDirector()->getWinSize();
        CCSprite *background = CCSprite::spriteWithFile("Hello.png");
		background->setPosition(ccp(size.width/2, size.height/2));
		addChild(background);
        return true;
	}

	return false;
}


code:
#ifndef __BUG_350_H__
#define __BUG_350_H__

#include "BugsTest.h"

class Bug350Layer : public BugsTestBaseLayer
{
public:
    virtual bool init();
};

#endif // __BUG_350_H__


code:
//
// Bug-422 test case by lhunath
// http://code.google.com/p/cocos2d-iphone/issues/detail?id=422
//

#include "Bug-422.h"

bool Bug422Layer::init()
{
    if (BugsTestBaseLayer::init())
    {
		reset();
        return true;
	}

	return false;
}

void Bug422Layer::reset()
{
	static int localtag = 0;
	localtag++;

	// TO TRIGGER THE BUG:
	// remove the itself from parent from an action
	// The menu will be removed, but the instance will be alive
	// and then a new node will be allocated occupying the memory.
	// => CRASH BOOM BANG
	CCNode *node = getChildByTag(localtag-1);
	CCLog("Menu: %p", node);
	removeChild(node, false);
//	[self removeChildByTag:localtag-1 cleanup:NO];

    CCMenuItem *item1 = CCMenuItemFont::itemFromString("One", this, menu_selector(Bug422Layer::menuCallback));
	CCLog("MenuItemFont: %p", item1);
    CCMenuItem *item2 = CCMenuItemFont::itemFromString("Two", this, menu_selector(Bug422Layer::menuCallback));
    CCMenu *menu = CCMenu::menuWithItems(item1, item2, NULL);
	menu->alignItemsVertically();

	float x = CCRANDOM_0_1() * 50;
	float y = CCRANDOM_0_1() * 50;
	menu->setPosition(ccpAdd( menu->getPosition(), ccp(x,y)));
    addChild(menu, 0, localtag);

    //[self check:self];
}

void Bug422Layer::check(CCNode* t)
{
	CCArray *array = t->getChildren();
    CCObject* pChild = NULL;
    CCARRAY_FOREACH(array, pChild)
    {
        CC_BREAK_IF(! pChild);
        CCNode* pNode = (CCNode*) pChild;
        CCLog("%p, rc: %d", pNode, pNode->retainCount());
        check(pNode);
    }
}

void Bug422Layer::menuCallback(CCObject* sender)
{
	reset();
}


code:
#ifndef __BUG_422_H__
#define __BUG_422_H__

#include "BugsTest.h"

class Bug422Layer : public BugsTestBaseLayer
{
public:
    virtual bool init();

    void reset();
    void check(CCNode* target);
    void menuCallback(CCObject* sender);
};

#endif // __BUG_422_H__


code:
//
// Bug-458 test case by nedrafehi
// http://code.google.com/p/cocos2d-iphone/issues/detail?id=458
//

#include "Bug-458.h"
#include "QuestionContainerSprite.h"

bool Bug458Layer::init()
{
    if(BugsTestBaseLayer::init())
    {
		// ask director the the window size
        CCSize size = CCDirector::sharedDirector()->getWinSize();

        QuestionContainerSprite* question = new QuestionContainerSprite();
        QuestionContainerSprite* question2 = new QuestionContainerSprite();
        question->init();
        question2->init();

//		[question setContentSize:CGSizeMake(50,50)];
//		[question2 setContentSize:CGSizeMake(50,50)];

        CCMenuItemSprite* sprite = CCMenuItemSprite::itemFromNormalSprite(question2, question, this, menu_selector(Bug458Layer::selectAnswer));
        CCLayerColor* layer = CCLayerColor::layerWithColorWidthHeight(ccc4f(0,0,255,255), 100, 100);
		question->release();
		question2->release();

        CCLayerColor* layer2 = CCLayerColor::layerWithColorWidthHeight(ccc4f(255,0,0,255), 100, 100);
        CCMenuItemSprite* sprite2 = CCMenuItemSprite::itemFromNormalSprite(layer, layer2, this, menu_selector(Bug458Layer::selectAnswer));
        CCMenu* menu = CCMenu::menuWithItems(sprite, sprite2, NULL);
        menu->alignItemsVerticallyWithPadding(100);
        menu->setPosition(ccp(size.width / 2, size.height / 2));

		// add the label as a child to this Layer
		addChild(menu);

        return true;
	}
	return false;
}

void Bug458Layer::selectAnswer(CCObject* sender)
{
    CCLog("Selected");
}


code:
#ifndef __BUG_458_H__
#define __BUG_458_H__

#include "../BugsTest.h"

class Bug458Layer : public BugsTestBaseLayer
{
public:
    virtual bool init();
    void selectAnswer(CCObject* sender);
};

#endif // __BUG_458_H__


code:
#include "QuestionContainerSprite.h"

#define kLabelTag

using namespace cocos2d;

bool QuestionContainerSprite::init()
{
    if (CCSprite::init())
    {
        //Add label
        CCLabelTTF* label = CCLabelTTF::labelWithString("Answer 1", "Arial", 12);
        label->setTag(100);

        //Add the background
        CCSize size = CCDirector::sharedDirector()->getWinSize();
        CCSprite* corner = CCSprite::spriteWithFile("Images/bugs/corner.png");

        int width = size.width * 0.9f - (corner->getContentSize().width * 2);
        int height = size.height * 0.15f  - (corner->getContentSize().height * 2);
        CCLayerColor* layer = CCLayerColor::layerWithColorWidthHeight(ccc4f(255, 255, 255, 255 * .75), width, height);
        layer->setPosition(ccp(-width / 2, -height / 2));

        //First button is blue,
        //Second is red
        //Used for testing - change later
        static int a = 0;

        if (a == 0)
            label->setColor(ccBLUE);
        else
        {
            CCLog("Color changed");
            label->setColor(ccRED);
        }
        a++;
        addChild(layer);

        corner->setPosition(ccp(-(width / 2 + corner->getContentSize().width / 2), -(height / 2 + corner->getContentSize().height / 2)));
        addChild(corner);

        CCSprite* corner2 = CCSprite::spriteWithFile("Images/bugs/corner.png");
        corner2->setPosition(ccp(-corner->getPosition().x, corner->getPosition().y));
        corner2->setFlipX(true);
        addChild(corner2);

        CCSprite* corner3 = CCSprite::spriteWithFile("Images/bugs/corner.png");
        corner3->setPosition(ccp(corner->getPosition().x, -corner->getPosition().y));
        corner3->setFlipY(true);
        addChild(corner3);

        CCSprite* corner4 = CCSprite::spriteWithFile("Images/bugs/corner.png");
        corner4->setPosition(ccp(corner2->getPosition().x, -corner2->getPosition().y));
        corner4->setFlipX(true);
        corner4->setFlipY(true);
        addChild(corner4);

        CCSprite* edge = CCSprite::spriteWithFile("Images/bugs/edge.png");
        edge->setScaleX(width);
        edge->setPosition(ccp(corner->getPosition().x + (corner->getContentSize().width / 2) + (width / 2), corner->getPosition().y));
        addChild(edge);

        CCSprite* edge2 = CCSprite::spriteWithFile("Images/bugs/edge.png");
        edge2->setScaleX(width);
        edge2->setPosition(ccp(corner->getPosition().x + (corner->getContentSize().width / 2) + (width / 2), -corner->getPosition().y));
        edge2->setFlipY(true);
        addChild(edge2);

        CCSprite* edge3 = CCSprite::spriteWithFile("Images/bugs/edge.png");
        edge3->setRotation(90);
        edge3->setScaleX(height);
        edge3->setPosition(ccp(corner->getPosition().x, corner->getPosition().y + (corner->getContentSize().height / 2) + (height / 2)));
        addChild(edge3);

        CCSprite* edge4 = CCSprite::spriteWithFile("Images/bugs/edge.png");
        edge4->setRotation(270);
        edge4->setScaleX(height);
        edge4->setPosition(ccp(-corner->getPosition().x, corner->getPosition().y + (corner->getContentSize().height / 2) + (height / 2)));
        addChild(edge4);

        addChild(label);
        return true;
    }

    return false;
}


code:
#ifndef __QUESTION_CONTAINER_SPRITE_H__
#define __QUESTION_CONTAINER_SPRITE_H__

#include "cocos2d.h"

class QuestionContainerSprite : public cocos2d::CCSprite
{
public:
    virtual bool init();
};

#endif // __QUESTION_CONTAINER_SPRITE_H__


code:
//
// Bug-624
// http://code.google.com/p/cocos2d-iphone/issues/detail?id=624
//

#include "Bug-624.h"

////////////////////////////////////////////////////////
//
// Bug624Layer
//
////////////////////////////////////////////////////////
bool Bug624Layer::init()
{
    if(BugsTestBaseLayer::init())
    {
        CCSize size = CCDirector::sharedDirector()->getWinSize();
        CCLabelTTF *label = CCLabelTTF::labelWithString("Layer1", "Marker Felt", 36);

		label->setPosition(ccp(size.width/2, size.height/2));
		addChild(label);
		setIsAccelerometerEnabled(true);
        schedule(schedule_selector(Bug624Layer::switchLayer), 5.0f);

        return true;
	}

	return false;
}

void Bug624Layer::switchLayer(ccTime dt)
{
	unschedule(schedule_selector(Bug624Layer::switchLayer));

    CCScene *scene = CCScene::node();
    scene->addChild(Bug624Layer2::node(), 0);
    CCDirector::sharedDirector()->replaceScene(CCTransitionFade::transitionWithDuration(2.0f, scene, ccWHITE));
}

void Bug624Layer::didAccelerate(CCAcceleration* acceleration)
{
	CCLog("Layer1 accel");
}

////////////////////////////////////////////////////////
//
// Bug624Layer2
//
////////////////////////////////////////////////////////
bool Bug624Layer2::init()
{
    if(BugsTestBaseLayer::init())
    {
        CCSize size = CCDirector::sharedDirector()->getWinSize();
        CCLabelTTF *label = CCLabelTTF::labelWithString("Layer2", "Marker Felt", 36);

        label->setPosition(ccp(size.width/2, size.height/2));
        addChild(label);
        setIsAccelerometerEnabled(true);
        schedule(schedule_selector(Bug624Layer2::switchLayer), 5.0f);

        return true;
    }

    return false;
}

void Bug624Layer2::switchLayer(ccTime dt)
{
    unschedule(schedule_selector(Bug624Layer::switchLayer));

    CCScene *scene = CCScene::node();
    scene->addChild(Bug624Layer::node(), 0);
    CCDirector::sharedDirector()->replaceScene(CCTransitionFade::transitionWithDuration(2.0f, scene, ccRED));
}

void Bug624Layer2::didAccelerate(CCAcceleration* acceleration)
{
	CCLog("Layer2 accel");
}


code:
#ifndef __BUG_624_H__
#define __BUG_624_H__

#include "BugsTest.h"

class Bug624Layer : public BugsTestBaseLayer
{
public:
    virtual bool init();
    void switchLayer(ccTime dt);
    virtual void didAccelerate(CCAcceleration* pAccelerationValue);

    LAYER_NODE_FUNC(Bug624Layer);
};

class Bug624Layer2 : public BugsTestBaseLayer
{
public:
    virtual bool init();
    void switchLayer(ccTime dt);
    virtual void didAccelerate(CCAcceleration* pAccelerationValue);

    LAYER_NODE_FUNC(Bug624Layer2);
};

#endif // __BUG_624_H__


code:
//
// Bug-886
// http://code.google.com/p/cocos2d-iphone/issues/detail?id=886
//

#include "Bug-886.h"

bool Bug886Layer::init()
{
    if(BugsTestBaseLayer::init())
    {
		// ask director the the window size
		//		CGSize size = [[CCDirector sharedDirector] winSize];

        CCSprite* sprite = CCSprite::spriteWithFile("Images/bugs/bug886.jpg");
		sprite->setAnchorPoint(CCPointZero);
		sprite->setPosition(CCPointZero);
		sprite->setScaleX(0.6f);
		addChild(sprite);

        CCSprite* sprite2 = CCSprite::spriteWithFile("Images/bugs/bug886.png");
		sprite2->setAnchorPoint(CCPointZero);
		sprite2->setScaleX(0.6f);
		sprite2->setPosition(ccp(sprite->getContentSize().width * 0.6f + 10, 0));
		addChild(sprite2);

        return true;
	}

	return false;
}


code:
#ifndef __BUG_886_H__
#define __BUG_886_H__

#include "BugsTest.h"

class Bug886Layer : public BugsTestBaseLayer
{
public:
    virtual bool init();
};

#endif // __BUG_886_H__


code:
//
// Bug-899
// http://code.google.com/p/cocos2d-iphone/issues/detail?id=899
//
// Test coded by: JohnnyFlash
//

#include "Bug-899.h"

bool Bug899Layer::init()
{
    CCDirector::sharedDirector()->enableRetinaDisplay(true);
    if (BugsTestBaseLayer::init())
    {
        CCSprite *bg = CCSprite::spriteWithFile("Images/bugs/RetinaDisplay.jpg");
		addChild(bg, 0);
		bg->setAnchorPoint(CCPointZero);

        return true;
	}
	return false;
}


code:
#ifndef __BUG_899_H__
#define __BUG_899_H__

#include "BugsTest.h"

class Bug899Layer : public BugsTestBaseLayer
{
public:
    virtual bool init();
};

#endif // __BUG_899_H__


code:
//
//  HelloWorldLayer.m
//  EAGLViewBug
//
//  Created by Wylan Werth on 7/5/10.
//  Copyright BanditBear Games 2010. All rights reserved.
//

// Import the interfaces
#include"Bug-914.h"

CCScene* Bug914Layer::scene()
{
	// 'scene' is an autorelease object.
    CCScene *pScene = CCScene::node();
	// 'layer' is an autorelease object.
    Bug914Layer* layer = Bug914Layer::node();

	// add layer as a child to scene
	pScene->addChild(layer);

	// return the scene
	return pScene;
}

// on "init" you need to initialize your instance
bool Bug914Layer::init()
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
    if (BugsTestBaseLayer::init())
    {
		setIsTouchEnabled(true);
		// ask director the the window size
        CCSize size = CCDirector::sharedDirector()->getWinSize();
		CCLayerColor *layer;
		for( int i=0;i < 5;i++)
        {
            layer = CCLayerColor::layerWithColor(ccc4f(i*20, i*20, i*20,255));
			layer->setContentSize(CCSizeMake(i*100, i*100));
			layer->setPosition(ccp(size.width/2, size.height/2));
			layer->setAnchorPoint(ccp(0.5f, 0.5f));
			layer->setIsRelativeAnchorPoint(true);
			addChild(layer, -1-i);
		}

		// create and initialize a Label
        CCLabelTTF *label = CCLabelTTF::labelWithString("Hello World", "Marker Felt", 64);
        CCMenuItem *item1 = CCMenuItemFont::itemFromString("restart", this, menu_selector(Bug914Layer::restart));

        CCMenu *menu = CCMenu::menuWithItems(item1, NULL);
		menu->alignItemsVertically();
		menu->setPosition(ccp(size.width/2, 100));
		addChild(menu);

		// position the label on the center of the screen
		label->setPosition(ccp( size.width /2 , size.height/2 ));

		// add the label as a child to this Layer
		addChild(label);
        return true;
	}
	return false;
}

void Bug914Layer::ccTouchesMoved(CCSet *touches, CCEvent * event)
{
	CCLog("Number of touches: %d", touches->count());
}

void Bug914Layer::ccTouchesBegan(CCSet *touches, CCEvent * event)
{
	ccTouchesMoved(touches, event);
}

void Bug914Layer::restart(CCObject* sender)
{
    CCDirector::sharedDirector()->replaceScene(Bug914Layer::scene());
}


code:
#ifndef __BUG_914_H__
#define __BUG_914_H__

#include "BugsTest.h"

class Bug914Layer : public BugsTestBaseLayer
{
public:
    static CCScene* scene();
    virtual bool init();

    void ccTouchesMoved(CCSet *touches, CCEvent * event);
    void ccTouchesBegan(CCSet *touches, CCEvent * event);
    void restart(CCObject* sender);

    LAYER_NODE_FUNC(Bug914Layer);
};

#endif // __BUG_914_H__