text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2013 Erwin Coumans  http://bulletphysics.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 BT_COMPOUND_COMPOUND_COLLISION_ALGORITHM_H
#define BT_COMPOUND_COMPOUND_COLLISION_ALGORITHM_H

#include "btCompoundCollisionAlgorithm.h"

#include "BulletCollision/CollisionDispatch/btActivatingCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btDispatcher.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"

#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
class btDispatcher;
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "BulletCollision/CollisionDispatch/btHashedSimplePairCache.h"
class btDispatcher;
class btCollisionObject;

class btCollisionShape;

/// btCompoundCompoundCollisionAlgorithm  supports collision between two btCompoundCollisionShape shapes
class btCompoundCompoundCollisionAlgorithm  : public btCompoundCollisionAlgorithm
{

	class btHashedSimplePairCache*	m_childCollisionAlgorithmCache;
	btSimplePairArray m_removePairs;

	int	m_compoundShapeRevision0;//to keep track of changes, so that childAlgorithm array can be updated
	int	m_compoundShapeRevision1;

	void	removeChildAlgorithms();

//	void	preallocateChildAlgorithms(const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap);

public:

	btCompoundCompoundCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped);

	virtual ~btCompoundCompoundCollisionAlgorithm();

	virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	btScalar	calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray);

	struct CreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
		{
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCompoundCollisionAlgorithm));
			return new(mem) btCompoundCompoundCollisionAlgorithm(ci,body0Wrap,body1Wrap,false);
		}
	};

	struct SwappedCreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
		{
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCompoundCollisionAlgorithm));
			return new(mem) btCompoundCompoundCollisionAlgorithm(ci,body0Wrap,body1Wrap,true);
		}
	};

};

#endif //BT_COMPOUND_COMPOUND_COLLISION_ALGORITHM_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2013 Erwin Coumans  http://bulletphysics.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.
*/

/**
 * @mainpage Bullet Documentation
 *
 * @section intro_sec Introduction
 * Bullet is a Collision Detection and Rigid Body Dynamics Library. The Library is Open Source and free for commercial use, under the ZLib license ( http://opensource.org/licenses/zlib-license.php ).
 *
 * The main documentation is Bullet_User_Manual.pdf, included in the source code distribution.
 * There is the Physics Forum for feedback and general Collision Detection and Physics discussions.
 * Please visit http://www.bulletphysics.org
 *
 * @section install_sec Installation
 *
 * @subsection step1 Step 1: Download
 * You can download the Bullet Physics Library from the github repository: https://github.com/bulletphysics/bullet3/releases
 *
 * @subsection step2 Step 2: Building
 * Bullet has multiple build systems, including premake, cmake and autotools. Premake and cmake support all platforms.
 * Premake is included in the Bullet/build folder for Windows, Mac OSX and Linux.
 * Under Windows you can click on Bullet/build/vs2010.bat to create Microsoft Visual Studio projects.
 * On Mac OSX and Linux you can open a terminal and generate Makefile, codeblocks or Xcode4 projects:
 * cd Bullet/build
 * ./premake4_osx gmake or ./premake4_linux gmake or ./premake4_linux64 gmake or (for Mac) ./premake4_osx xcode4
 * cd Bullet/build/gmake
 * make
 *
 * An alternative to premake is cmake. You can download cmake from http://www.cmake.org
 * cmake can autogenerate projectfiles for Microsoft Visual Studio, Apple Xcode, KDevelop and Unix Makefiles.
 * The easiest is to run the CMake cmake-gui graphical user interface and choose the options and generate projectfiles.
 * You can also use cmake in the command-line. Here are some examples for various platforms:
 * cmake . -G "Visual Studio 9 2008"
 * cmake . -G Xcode
 * cmake . -G "Unix Makefiles"
 * Although cmake is recommended, you can also use autotools for UNIX: ./autogen.sh ./configure to create a Makefile and then run make.
 *
 * @subsection step3 Step 3: Testing demos
 * Try to run and experiment with BasicDemo executable as a starting point.
 * Bullet can be used in several ways, as Full Rigid Body simulation, as Collision Detector Library or Low Level / Snippets like the GJK Closest Point calculation.
 * The Dependencies can be seen in this documentation under Directories
 *
 * @subsection step4 Step 4: Integrating in your application, full Rigid Body and Soft Body simulation
 * Check out BasicDemo how to create a btDynamicsWorld, btRigidBody and btCollisionShape, Stepping the simulation and synchronizing your graphics object transform.
 * Check out SoftDemo how to use soft body dynamics, using btSoftRigidDynamicsWorld.
 * @subsection step5 Step 5 : Integrate the Collision Detection Library (without Dynamics and other Extras)
 * Bullet Collision Detection can also be used without the Dynamics/Extras.
 * Check out btCollisionWorld and btCollisionObject, and the CollisionInterfaceDemo.
 * @subsection step6 Step 6 : Use Snippets like the GJK Closest Point calculation.
 * Bullet has been designed in a modular way keeping dependencies to a minimum. The ConvexHullDistance demo demonstrates direct use of btGjkPairDetector.
 *
 * @section copyright Copyright
 * For up-to-data information and copyright and contributors list check out the Bullet_User_Manual.pdf
 *
 */

#ifndef BT_COLLISION_WORLD_H
#define BT_COLLISION_WORLD_H

class btCollisionShape;
class btConvexShape;
class btBroadphaseInterface;
class btSerializer;

#include "LinearMath/btVector3.h"
#include "LinearMath/btTransform.h"
#include "btCollisionObject.h"
#include "btCollisionDispatcher.h"
#include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h"
#include "LinearMath/btAlignedObjectArray.h"

/// CollisionWorld is interface and container for the collision detection
class btCollisionWorld
{
protected:
	btAlignedObjectArray<btCollisionObject*> m_collisionObjects;
	btDispatcher*                            m_dispatcher1;
	btDispatcherInfo                         m_dispatchInfo;
	btBroadphaseInterface*                   m_broadphasePairCache;
	btIDebugDraw*                            m_debugDrawer;

	/// m_forceUpdateAllAabbs can be set to false as an optimization to only
	/// update active object AABBs. it is true by default, because it is
	/// error-prone (setting the position of static objects wouldn't update their
	/// AABB)
	bool m_forceUpdateAllAabbs;

	void serializeCollisionObjects(btSerializer* serializer);

public:
	/// this constructor doesn't own the dispatcher and paircache/broadphase
	btCollisionWorld(btDispatcher* dispatcher, btBroadphaseInterface* broadphasePairCache, btCollisionConfiguration* collisionConfiguration);

	virtual ~btCollisionWorld();

	void                         setBroadphase(btBroadphaseInterface* pairCache) { m_broadphasePairCache = pairCache; }
	const btBroadphaseInterface* getBroadphase() const { return m_broadphasePairCache; }
	btBroadphaseInterface*       getBroadphase() { return m_broadphasePairCache; }
	btOverlappingPairCache*      getPairCache() { return m_broadphasePairCache->getOverlappingPairCache(); }
	btDispatcher*                getDispatcher() { return m_dispatcher1; }
	const btDispatcher*          getDispatcher() const { return m_dispatcher1; }
	void                         updateSingleAabb(btCollisionObject* colObj);
	virtual void                 updateAabbs();

	/// the computeOverlappingPairs is usually already called by
	/// performDiscreteCollisionDetection (or stepSimulation). it can be useful to
	/// use if you perform ray tests without collision detection/simulation
	virtual void computeOverlappingPairs();

	virtual void          setDebugDrawer(btIDebugDraw* debugDrawer) { m_debugDrawer = debugDrawer; }
	virtual btIDebugDraw* getDebugDrawer() { return m_debugDrawer; }
	virtual void          debugDrawWorld();
	virtual void          debugDrawObject(const btTransform& worldTransform, const btCollisionShape* shape, const btVector3& color);

	/// LocalShapeInfo gives extra information for complex shapes. Currently,
	/// only btTriangleMeshShape is available, so it just contains triangleIndex
	/// and subpart
	struct LocalShapeInfo
	{
		int m_shapePart;
		int m_triangleIndex;

		//const btCollisionShape*	m_shapeTemp;
		//const btTransform* m_shapeLocalTransform;
	};

	struct LocalRayResult
	{
		LocalRayResult(
		    const btCollisionObject* collisionObject,
		    LocalShapeInfo*          localShapeInfo,
		    const btVector3&         hitNormalLocal,
		    btScalar                 hitFraction)
		    : m_collisionObject(collisionObject),
		      m_localShapeInfo(localShapeInfo),
		      m_hitNormalLocal(hitNormalLocal),
		      m_hitFraction(hitFraction)
		{
		}

		const btCollisionObject* m_collisionObject;
		LocalShapeInfo*          m_localShapeInfo;
		btVector3                m_hitNormalLocal;
		btScalar                 m_hitFraction;
	};

	/// RayResultCallback is used to report new raycast results
	struct RayResultCallback
	{
		btScalar                 m_closestHitFraction;
		const btCollisionObject* m_collisionObject;
		int                      m_collisionFilterGroup;
		int                      m_collisionFilterMask;

		//@BP Mod - Custom flags, currently used to enable backface culling on
		//tri-meshes, see btRaycastCallback.h. Apply any of the EFlags defined there
		//on m_flags here to invoke.
		unsigned int m_flags;

		virtual ~RayResultCallback() {}
		bool hasHit() const { return (m_collisionObject != 0); }

		RayResultCallback()
		    : m_closestHitFraction(btScalar(1.)),
		      m_collisionObject(0),
		      m_collisionFilterGroup(btBroadphaseProxy::DefaultFilter),
		      m_collisionFilterMask(btBroadphaseProxy::AllFilter),
		      //@BP Mod
		      m_flags(0)
		{
		}

		virtual bool needsCollision(btBroadphaseProxy* proxy0) const
		{
			bool collides = (proxy0->m_collisionFilterGroup & m_collisionFilterMask) != 0;
			collides = collides && (m_collisionFilterGroup & proxy0->m_collisionFilterMask);
			return collides;
		}

		virtual btScalar addSingleResult(LocalRayResult& rayResult, bool normalInWorldSpace) = 0;
	};

	struct ClosestRayResultCallback : public RayResultCallback
	{
		ClosestRayResultCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld)
		    : m_rayFromWorld(rayFromWorld),
		      m_rayToWorld(rayToWorld)
		{
		}

		/// used to calculate hitPointWorld from hitFraction
		btVector3 m_rayFromWorld;

		btVector3 m_rayToWorld;
		btVector3 m_hitNormalWorld;
		btVector3 m_hitPointWorld;

		virtual btScalar addSingleResult(LocalRayResult& rayResult, bool normalInWorldSpace)
		{
			// caller already does the filter on the m_closestHitFraction
			btAssert(rayResult.m_hitFraction <= m_closestHitFraction);

			m_closestHitFraction = rayResult.m_hitFraction;
			m_collisionObject    = rayResult.m_collisionObject;
			if (normalInWorldSpace)
			{
				m_hitNormalWorld = rayResult.m_hitNormalLocal;
			}
			else
			{
				// need to transform normal into worldspace
				m_hitNormalWorld = m_collisionObject->getWorldTransform().getBasis() * rayResult.m_hitNormalLocal;
			}
			m_hitPointWorld.setInterpolate3(m_rayFromWorld, m_rayToWorld, rayResult.m_hitFraction);
			return rayResult.m_hitFraction;
		}
	};

	struct AllHitsRayResultCallback : public RayResultCallback
	{
		AllHitsRayResultCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld)
		    : m_rayFromWorld(rayFromWorld),
		      m_rayToWorld(rayToWorld)
		{
		}

		btAlignedObjectArray<const btCollisionObject*> m_collisionObjects;

		/// used to calculate hitPointWorld from hitFraction
		btVector3 m_rayFromWorld;

		btVector3                       m_rayToWorld;
		btAlignedObjectArray<btVector3> m_hitNormalWorld;
		btAlignedObjectArray<btVector3> m_hitPointWorld;
		btAlignedObjectArray<btScalar>  m_hitFractions;

		virtual btScalar addSingleResult(LocalRayResult& rayResult, bool normalInWorldSpace)
		{
			m_collisionObject = rayResult.m_collisionObject;
			m_collisionObjects.push_back(rayResult.m_collisionObject);
			btVector3 hitNormalWorld;
			if (normalInWorldSpace)
			{
				hitNormalWorld = rayResult.m_hitNormalLocal;
			}
			else
			{
				// need to transform normal into worldspace
				hitNormalWorld = m_collisionObject->getWorldTransform().getBasis() * rayResult.m_hitNormalLocal;
			}
			m_hitNormalWorld.push_back(hitNormalWorld);
			btVector3 hitPointWorld;
			hitPointWorld.setInterpolate3(m_rayFromWorld, m_rayToWorld, rayResult.m_hitFraction);
			m_hitPointWorld.push_back(hitPointWorld);
			m_hitFractions.push_back(rayResult.m_hitFraction);
			return m_closestHitFraction;
		}
	};

	struct LocalConvexResult
	{
		LocalConvexResult(
		    const btCollisionObject* hitCollisionObject,
		    LocalShapeInfo*          localShapeInfo,
		    const btVector3&         hitNormalLocal,
		    const btVector3&         hitPointLocal,
		    btScalar                 hitFraction)
		    : m_hitCollisionObject(hitCollisionObject),
		      m_localShapeInfo(localShapeInfo),
		      m_hitNormalLocal(hitNormalLocal),
		      m_hitPointLocal(hitPointLocal),
		      m_hitFraction(hitFraction)
		{
		}

		const btCollisionObject* m_hitCollisionObject;
		LocalShapeInfo*          m_localShapeInfo;
		btVector3                m_hitNormalLocal;
		btVector3                m_hitPointLocal;
		btScalar                 m_hitFraction;
	};

	/// RayResultCallback is used to report new raycast results
	struct ConvexResultCallback
	{
		btScalar m_closestHitFraction;
		int      m_collisionFilterGroup;
		int      m_collisionFilterMask;

		ConvexResultCallback()
		    : m_closestHitFraction(btScalar(1.)),
		      m_collisionFilterGroup(btBroadphaseProxy::DefaultFilter),
		      m_collisionFilterMask(btBroadphaseProxy::AllFilter)
		{
		}

		virtual ~ConvexResultCallback() {}
		bool hasHit() const { return (m_closestHitFraction < btScalar(1.)); }

		virtual bool needsCollision(btBroadphaseProxy* proxy0) const
		{
			bool collides = (proxy0->m_collisionFilterGroup & m_collisionFilterMask) != 0;
			collides = collides && (m_collisionFilterGroup & proxy0->m_collisionFilterMask);
			return collides;
		}

		virtual btScalar addSingleResult(LocalConvexResult& convexResult, bool normalInWorldSpace) = 0;
	};

	struct ClosestConvexResultCallback : public ConvexResultCallback
	{
		ClosestConvexResultCallback(const btVector3& convexFromWorld, const btVector3& convexToWorld)
		    : m_convexFromWorld(convexFromWorld),
		      m_convexToWorld(convexToWorld),
		      m_hitCollisionObject(0)
		{
		}

		/// used to calculate hitPointWorld from hitFraction
		btVector3 m_convexFromWorld;

		btVector3                m_convexToWorld;
		btVector3                m_hitNormalWorld;
		btVector3                m_hitPointWorld;
		const btCollisionObject* m_hitCollisionObject;

		virtual btScalar addSingleResult(LocalConvexResult& convexResult, bool normalInWorldSpace)
		{
			// caller already does the filter on the m_closestHitFraction
			btAssert(convexResult.m_hitFraction <= m_closestHitFraction);

			m_closestHitFraction = convexResult.m_hitFraction;
			m_hitCollisionObject = convexResult.m_hitCollisionObject;
			if (normalInWorldSpace)
			{
				m_hitNormalWorld = convexResult.m_hitNormalLocal;
			}
			else
			{
				// need to transform normal into worldspace
				m_hitNormalWorld = m_hitCollisionObject->getWorldTransform().getBasis() * convexResult.m_hitNormalLocal;
			}
			m_hitPointWorld = convexResult.m_hitPointLocal;
			return convexResult.m_hitFraction;
		}
	};

	/// ContactResultCallback is used to report contact points
	struct ContactResultCallback
	{
		int      m_collisionFilterGroup;
		int      m_collisionFilterMask;
		btScalar m_closestDistanceThreshold;

		ContactResultCallback()
		    : m_collisionFilterGroup(btBroadphaseProxy::DefaultFilter),
		      m_collisionFilterMask(btBroadphaseProxy::AllFilter),
		      m_closestDistanceThreshold(0)
		{
		}

		virtual ~ContactResultCallback() {}

		virtual bool needsCollision(btBroadphaseProxy* proxy0) const
		{
			bool collides = (proxy0->m_collisionFilterGroup & m_collisionFilterMask) != 0;
			collides = collides && (m_collisionFilterGroup & proxy0->m_collisionFilterMask);
			return collides;
		}

		virtual btScalar addSingleResult(
		    btManifoldPoint&                cp,
		    const btCollisionObjectWrapper* colObj0Wrap,
		    int                             partId0,
		    int                             index0,
		    const btCollisionObjectWrapper* colObj1Wrap,
		    int                             partId1,
		    int                             index1) = 0;
	};

	int getNumCollisionObjects() const { return int(m_collisionObjects.size()); }

	/// rayTest performs a raycast on all objects in the btCollisionWorld, and
	/// calls the resultCallback. This allows for several queries: first hit, all
	/// hits, any hit, dependent on the value returned by the callback.
	virtual void rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, RayResultCallback& resultCallback) const;

	/// convexTest performs a swept convex cast on all objects in the
	/// btCollisionWorld, and calls the resultCallback. This allows for several
	/// queries: first hit, all hits, any hit, dependent on the value return by
	/// the callback.
	void convexSweepTest(
	    const btConvexShape*  castShape,
	    const btTransform&    from,
	    const btTransform&    to,
	    ConvexResultCallback& resultCallback,
	    btScalar              allowedCcdPenetration = btScalar(0.)) const;

	/// contactTest performs a discrete collision test between colObj against all
	/// objects in the btCollisionWorld, and calls the resultCallback. it reports
	/// one or more contact points for every overlapping object (including the one
	/// with deepest penetration)
	void contactTest(btCollisionObject* colObj, ContactResultCallback& resultCallback);

	/// contactTest performs a discrete collision test between two collision
	/// objects and calls the resultCallback if overlap if detected. it reports
	/// one or more contact points (including the one with deepest penetration)
	void contactPairTest(btCollisionObject* colObjA, btCollisionObject* colObjB, ContactResultCallback& resultCallback);

	/// rayTestSingle performs a raycast call and calls the resultCallback. It is
	/// used internally by rayTest. In a future implementation, we consider moving
	/// the ray test as a virtual method in btCollisionShape. This allows more
	/// customization.
	static void rayTestSingle(
	    const btTransform&      rayFromTrans,
	    const btTransform&      rayToTrans,
	    btCollisionObject*      collisionObject,
	    const btCollisionShape* collisionShape,
	    const btTransform&      colObjWorldTransform,
	    RayResultCallback&      resultCallback);

	static void rayTestSingleInternal(
	    const btTransform&              rayFromTrans,
	    const btTransform&              rayToTrans,
	    const btCollisionObjectWrapper* collisionObjectWrap,
	    RayResultCallback&              resultCallback);

	/// objectQuerySingle performs a collision detection query and calls the
	/// resultCallback. It is used internally by rayTest.
	static void objectQuerySingle(
	    const btConvexShape*    castShape,
	    const btTransform&      rayFromTrans,
	    const btTransform&      rayToTrans,
	    btCollisionObject*      collisionObject,
	    const btCollisionShape* collisionShape,
	    const btTransform&      colObjWorldTransform,
	    ConvexResultCallback&   resultCallback,
	    btScalar                allowedPenetration);

	static void objectQuerySingleInternal(
	    const btConvexShape*            castShape,
	    const btTransform&              convexFromTrans,
	    const btTransform&              convexToTrans,
	    const btCollisionObjectWrapper* colObjWrap,
	    ConvexResultCallback&           resultCallback,
	    btScalar                        allowedPenetration);

	virtual void addCollisionObject(
	    btCollisionObject* collisionObject,
	    int                collisionFilterGroup = btBroadphaseProxy::DefaultFilter,
	    int                collisionFilterMask  = btBroadphaseProxy::AllFilter);

	btCollisionObjectArray&       getCollisionObjectArray() { return m_collisionObjects; }
	const btCollisionObjectArray& getCollisionObjectArray() const { return m_collisionObjects; }
	virtual void                  removeCollisionObject(btCollisionObject* collisionObject);
	virtual void                  performDiscreteCollisionDetection();
	btDispatcherInfo&             getDispatchInfo() { return m_dispatchInfo; }
	const btDispatcherInfo&       getDispatchInfo() const { return m_dispatchInfo; }
	bool                          getForceUpdateAllAabbs() const { return m_forceUpdateAllAabbs; }
	void                          setForceUpdateAllAabbs(bool forceUpdateAllAabbs) { m_forceUpdateAllAabbs = forceUpdateAllAabbs; }

	/// Preliminary serialization test for Bullet 2.76. Loading those files
	/// requires a separate parser (Bullet/Demos/SerializeDemo)
	virtual void serialize(btSerializer* serializer);
};

#endif //BT_COLLISION_WORLD_H

repo_name: JoshParnell/libphx

repo_language: C

mime_type: text/x-c++


text:
/*
 * Box-Box collision detection re-distributed under the ZLib license with permission from Russell L. Smith
 * Original version is from Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith.
 * All rights reserved.  Email: russ@q12.org   Web: www.q12.org

Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_BOX_BOX_DETECTOR_H
#define BT_BOX_BOX_DETECTOR_H

class btBoxShape;
#include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h"

/// btBoxBoxDetector wraps the ODE box-box collision detector
/// re-distributed under the Zlib license with permission from Russell L. Smith
struct btBoxBoxDetector : public btDiscreteCollisionDetectorInterface
{
	const btBoxShape* m_box1;
	const btBoxShape* m_box2;

public:

	btBoxBoxDetector(const btBoxShape* box1,const btBoxShape* box2);

	virtual ~btBoxBoxDetector() {};

	virtual void	getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw,bool swapResults=false);

};

#endif //BT_BOX_BOX_DETECTOR_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_HASHED_SIMPLE_PAIR_CACHE_H
#define BT_HASHED_SIMPLE_PAIR_CACHE_H

#include "LinearMath/btAlignedObjectArray.h"

const int BT_SIMPLE_NULL_PAIR=0xffffffff;

struct btSimplePair
{
	btSimplePair(int indexA,int indexB)
		:m_indexA(indexA),
		m_indexB(indexB),
		m_userPointer(0)
	{
	}

	int m_indexA;
	int m_indexB;
	union
	{
		void*	m_userPointer;
		int		m_userValue;
	};
};

typedef btAlignedObjectArray<btSimplePair>	btSimplePairArray;

extern int gOverlappingSimplePairs;
extern int gRemoveSimplePairs;
extern int gAddedSimplePairs;
extern int gFindSimplePairs;

class btHashedSimplePairCache
{
	btSimplePairArray	m_overlappingPairArray;

protected:

	btAlignedObjectArray<int>	m_hashTable;
	btAlignedObjectArray<int>	m_next;

public:
	btHashedSimplePairCache();
	virtual ~btHashedSimplePairCache();

	void removeAllPairs();

	virtual void*	removeOverlappingPair(int indexA,int indexB);

	// Add a pair and return the new pair. If the pair already exists,
	// no new pair is created and the old one is returned.
	virtual btSimplePair* 	addOverlappingPair(int indexA,int indexB)
	{
		gAddedSimplePairs++;

		return internalAddPair(indexA,indexB);
	}

	virtual btSimplePair*	getOverlappingPairArrayPtr()
	{
		return &m_overlappingPairArray[0];
	}

	const btSimplePair*	getOverlappingPairArrayPtr() const
	{
		return &m_overlappingPairArray[0];
	}

	btSimplePairArray&	getOverlappingPairArray()
	{
		return m_overlappingPairArray;
	}

	const btSimplePairArray&	getOverlappingPairArray() const
	{
		return m_overlappingPairArray;
	}

	btSimplePair* findPair(int indexA,int indexB);

	int GetCount() const { return m_overlappingPairArray.size(); }

	int	getNumOverlappingPairs() const
	{
		return m_overlappingPairArray.size();
	}
private:

	btSimplePair* 	internalAddPair(int indexA, int indexB);

	void	growTables();

	SIMD_FORCE_INLINE bool equalsPair(const btSimplePair& pair, int indexA, int indexB)
	{
		return pair.m_indexA == indexA && pair.m_indexB == indexB;
	}

	SIMD_FORCE_INLINE unsigned int getHash(unsigned int indexA, unsigned int indexB)
	{
		unsigned int key = indexA | (indexB << 16);
		// Thomas Wang's hash

		key += ~(key << 15);
		key ^=  (key >> 10);
		key +=  (key << 3);
		key ^=  (key >> 6);
		key += ~(key << 11);
		key ^=  (key >> 16);
		return key;
	}

	SIMD_FORCE_INLINE btSimplePair* internalFindPair(int proxyIdA , int proxyIdB, int hash)
	{

		int index = m_hashTable[hash];

		while( index != BT_SIMPLE_NULL_PAIR && equalsPair(m_overlappingPairArray[index], proxyIdA, proxyIdB) == false)
		{
			index = m_next[index];
		}

		if ( index == BT_SIMPLE_NULL_PAIR )
		{
			return NULL;
		}

		btAssert(index < m_overlappingPairArray.size());

		return &m_overlappingPairArray[index];
	}

};

#endif //BT_HASHED_SIMPLE_PAIR_CACHE_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_COLLISION_CREATE_FUNC
#define BT_COLLISION_CREATE_FUNC

#include "LinearMath/btAlignedObjectArray.h"
class btCollisionAlgorithm;
class btCollisionObject;
struct btCollisionObjectWrapper;
struct btCollisionAlgorithmConstructionInfo;

///Used by the btCollisionDispatcher to register and create instances for btCollisionAlgorithm
struct btCollisionAlgorithmCreateFunc
{
	bool m_swapped;

	btCollisionAlgorithmCreateFunc()
		:m_swapped(false)
	{
	}
	virtual ~btCollisionAlgorithmCreateFunc(){};

	virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& , const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
	{

		(void)body0Wrap;
		(void)body1Wrap;
		return 0;
	}
};
#endif //BT_COLLISION_CREATE_FUNC


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_COLLISION_DISPATCHER_MT_H
#define BT_COLLISION_DISPATCHER_MT_H

#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
#include "LinearMath/btThreads.h"

class btCollisionDispatcherMt : public btCollisionDispatcher
{
public:
    btCollisionDispatcherMt( btCollisionConfiguration* config, int grainSize = 40 );

    virtual btPersistentManifold* getNewManifold( const btCollisionObject* body0, const btCollisionObject* body1 ) BT_OVERRIDE;
    virtual void releaseManifold( btPersistentManifold* manifold ) BT_OVERRIDE;

    virtual void dispatchAllCollisionPairs( btOverlappingPairCache* pairCache, const btDispatcherInfo& info, btDispatcher* dispatcher ) BT_OVERRIDE;

protected:
    bool m_batchUpdating;
    int m_grainSize;
};

#endif //BT_COLLISION_DISPATCHER_MT_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_EMPTY_ALGORITH
#define BT_EMPTY_ALGORITH
#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"
#include "btCollisionCreateFunc.h"
#include "btCollisionDispatcher.h"

#define ATTRIBUTE_ALIGNED(a)

///EmptyAlgorithm is a stub for unsupported collision pairs.
///The dispatcher can dispatch a persistent btEmptyAlgorithm to avoid a search every frame.
class btEmptyAlgorithm : public btCollisionAlgorithm
{

public:

	btEmptyAlgorithm(const btCollisionAlgorithmConstructionInfo& ci);

	virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray)
	{
	}

	struct CreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
        virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
        {
			(void)body0Wrap;
			(void)body1Wrap;
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btEmptyAlgorithm));
			return new(mem) btEmptyAlgorithm(ci);
		}
	};

} ATTRIBUTE_ALIGNED(16);

#endif //BT_EMPTY_ALGORITH


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_SPHERE_TRIANGLE_DETECTOR_H
#define BT_SPHERE_TRIANGLE_DETECTOR_H

#include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h"

class btSphereShape;
class btTriangleShape;

/// sphere-triangle to match the btDiscreteCollisionDetectorInterface
struct SphereTriangleDetector : public btDiscreteCollisionDetectorInterface
{
	virtual void	getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw,bool swapResults=false);

	SphereTriangleDetector(btSphereShape* sphere,btTriangleShape* triangle, btScalar contactBreakingThreshold);

	virtual ~SphereTriangleDetector() {};

	bool collide(const btVector3& sphereCenter,btVector3 &point, btVector3& resultNormal, btScalar& depth, btScalar &timeOfImpact, btScalar	contactBreakingThreshold);

private:

	bool pointInTriangle(const btVector3 vertices[], const btVector3 &normal, btVector3 *p );
	bool facecontains(const btVector3 &p,const btVector3* vertices,btVector3& normal);

	btSphereShape* m_sphere;
	btTriangleShape* m_triangle;
	btScalar	m_contactBreakingThreshold;

};
#endif //BT_SPHERE_TRIANGLE_DETECTOR_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_BOX_BOX__COLLISION_ALGORITHM_H
#define BT_BOX_BOX__COLLISION_ALGORITHM_H

#include "btActivatingCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/BroadphaseCollision/btDispatcher.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"

class btPersistentManifold;

///box-box collision detection
class btBoxBoxCollisionAlgorithm : public btActivatingCollisionAlgorithm
{
	bool	m_ownManifold;
	btPersistentManifold*	m_manifoldPtr;

public:
	btBoxBoxCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci)
		: btActivatingCollisionAlgorithm(ci) {}

	virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	btBoxBoxCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap);

	virtual ~btBoxBoxCollisionAlgorithm();

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray)
	{
		if (m_manifoldPtr && m_ownManifold)
		{
			manifoldArray.push_back(m_manifoldPtr);
		}
	}

	struct CreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
		{
			int bbsize = sizeof(btBoxBoxCollisionAlgorithm);
			void* ptr = ci.m_dispatcher1->allocateCollisionAlgorithm(bbsize);
			return new(ptr) btBoxBoxCollisionAlgorithm(0,ci,body0Wrap,body1Wrap);
		}
	};

};

#endif //BT_BOX_BOX__COLLISION_ALGORITHM_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_DEFAULT_COLLISION_CONFIGURATION
#define BT_DEFAULT_COLLISION_CONFIGURATION

#include "btCollisionConfiguration.h"
class btVoronoiSimplexSolver;
class btConvexPenetrationDepthSolver;

struct btDefaultCollisionConstructionInfo
{
	btPoolAllocator* m_persistentManifoldPool;
	btPoolAllocator* m_collisionAlgorithmPool;
	int              m_defaultMaxPersistentManifoldPoolSize;
	int              m_defaultMaxCollisionAlgorithmPoolSize;
	int              m_customCollisionAlgorithmMaxElementSize;
	int              m_useEpaPenetrationAlgorithm;

	btDefaultCollisionConstructionInfo()
	    : m_persistentManifoldPool(0),
	      m_collisionAlgorithmPool(0),
	      m_defaultMaxPersistentManifoldPoolSize(4096),
	      m_defaultMaxCollisionAlgorithmPoolSize(4096),
	      m_customCollisionAlgorithmMaxElementSize(0),
	      m_useEpaPenetrationAlgorithm(true)
	{
	}
};

/// btCollisionConfiguration allows to configure Bullet collision detection
/// stack allocator, pool memory allocators
//@todo: describe the meaning
class btDefaultCollisionConfiguration : public btCollisionConfiguration
{
protected:
	int m_persistentManifoldPoolSize;

	btPoolAllocator* m_persistentManifoldPool;
	bool             m_ownsPersistentManifoldPool;

	btPoolAllocator* m_collisionAlgorithmPool;
	bool             m_ownsCollisionAlgorithmPool;

	/// default penetration depth solver
	btConvexPenetrationDepthSolver* m_pdSolver;

	/// default CreationFunctions, filling the m_doubleDispatch table
	btCollisionAlgorithmCreateFunc* m_convexConvexCreateFunc;
	btCollisionAlgorithmCreateFunc* m_convexConcaveCreateFunc;
	btCollisionAlgorithmCreateFunc* m_swappedConvexConcaveCreateFunc;
	btCollisionAlgorithmCreateFunc* m_compoundCreateFunc;
	btCollisionAlgorithmCreateFunc* m_compoundCompoundCreateFunc;

	btCollisionAlgorithmCreateFunc* m_swappedCompoundCreateFunc;
	btCollisionAlgorithmCreateFunc* m_emptyCreateFunc;
	btCollisionAlgorithmCreateFunc* m_sphereSphereCF;
	btCollisionAlgorithmCreateFunc* m_sphereBoxCF;
	btCollisionAlgorithmCreateFunc* m_boxSphereCF;

	btCollisionAlgorithmCreateFunc* m_boxBoxCF;
	btCollisionAlgorithmCreateFunc* m_sphereTriangleCF;
	btCollisionAlgorithmCreateFunc* m_triangleSphereCF;
	btCollisionAlgorithmCreateFunc* m_planeConvexCF;
	btCollisionAlgorithmCreateFunc* m_convexPlaneCF;

public:
	btDefaultCollisionConfiguration(const btDefaultCollisionConstructionInfo& constructionInfo = btDefaultCollisionConstructionInfo());

	virtual ~btDefaultCollisionConfiguration();

	// memory pools
	virtual btPoolAllocator* getPersistentManifoldPool() { return m_persistentManifoldPool; }
	virtual btPoolAllocator* getCollisionAlgorithmPool() { return m_collisionAlgorithmPool; }

	virtual btCollisionAlgorithmCreateFunc* getCollisionAlgorithmCreateFunc(int proxyType0, int proxyType1);
	virtual btCollisionAlgorithmCreateFunc* getClosestPointsAlgorithmCreateFunc(int proxyType0, int proxyType1);

	/// Use this method to allow to generate multiple contact points between at
	/// once, between two objects using the generic convex-convex algorithm. By
	/// default, this feature is disabled for best performance.
	/// @param numPerturbationIterations controls the number of collision queries.
	/// Set it to zero to disable the feature.
	/// @param minimumPointsPerturbationThreshold is the minimum number of points
	/// in the contact cache, above which the feature is disabled. 3 is a good
	/// value for both params, if you want to enable the feature. This is because
	/// the default contact cache contains a maximum of 4 points, and one
	/// collision query at the unperturbed orientation is performed first. See
	/// Bullet/Demos/CollisionDemo for an example how this feature gathers multiple points.
	//@todo we could add a per-object setting of those parameters, for
	//level-of-detail collision detection.
	void setConvexConvexMultipointIterations(int numPerturbationIterations = 3, int minimumPointsPerturbationThreshold = 3);

	void setPlaneConvexMultipointIterations(int numPerturbationIterations = 3, int minimumPointsPerturbationThreshold = 3);
};

#endif //BT_DEFAULT_COLLISION_CONFIGURATION


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_COLLISION_CONFIGURATION
#define BT_COLLISION_CONFIGURATION

struct btCollisionAlgorithmCreateFunc;

class btPoolAllocator;

///btCollisionConfiguration allows to configure Bullet collision detection
///stack allocator size, default collision algorithms and persistent manifold pool size
///@todo: describe the meaning
class	btCollisionConfiguration
{

public:

	virtual ~btCollisionConfiguration()
	{
	}

	///memory pools
	virtual btPoolAllocator* getPersistentManifoldPool() = 0;

	virtual btPoolAllocator* getCollisionAlgorithmPool() = 0;

	virtual btCollisionAlgorithmCreateFunc* getCollisionAlgorithmCreateFunc(int proxyType0,int proxyType1) =0;

	virtual btCollisionAlgorithmCreateFunc* getClosestPointsAlgorithmCreateFunc(int proxyType0, int proxyType1) = 0;

};

#endif //BT_COLLISION_CONFIGURATION


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_SPHERE_TRIANGLE_COLLISION_ALGORITHM_H
#define BT_SPHERE_TRIANGLE_COLLISION_ALGORITHM_H

#include "btActivatingCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
class btPersistentManifold;
#include "btCollisionDispatcher.h"

/// btSphereSphereCollisionAlgorithm  provides sphere-sphere collision detection.
/// Other features are frame-coherency (persistent data) and collision response.
/// Also provides the most basic sample for custom/user btCollisionAlgorithm
class btSphereTriangleCollisionAlgorithm : public btActivatingCollisionAlgorithm
{
	bool	m_ownManifold;
	btPersistentManifold*	m_manifoldPtr;
	bool	m_swapped;

public:
	btSphereTriangleCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool swapped);

	btSphereTriangleCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci)
		: btActivatingCollisionAlgorithm(ci) {}

	virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray)
	{
		if (m_manifoldPtr && m_ownManifold)
		{
			manifoldArray.push_back(m_manifoldPtr);
		}
	}

	virtual ~btSphereTriangleCollisionAlgorithm();

	struct CreateFunc :public 	btCollisionAlgorithmCreateFunc
	{

		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
		{

			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSphereTriangleCollisionAlgorithm));

			return new(mem) btSphereTriangleCollisionAlgorithm(ci.m_manifold,ci,body0Wrap,body1Wrap,m_swapped);
		}
	};

};

#endif //BT_SPHERE_TRIANGLE_COLLISION_ALGORITHM_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2014 Erwin Coumans  http://bulletphysics.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 BT_COLLISION_WORLD_IMPORTER_H
#define BT_COLLISION_WORLD_IMPORTER_H

#include "LinearMath/btTransform.h"
#include "LinearMath/btVector3.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "LinearMath/btHashMap.h"

class btCollisionShape;
class btCollisionObject;
struct btBulletSerializedArrays;

struct ConstraintInput;
class btCollisionWorld;
struct btCollisionShapeData;
class btTriangleIndexVertexArray;
class btStridingMeshInterface;
struct btStridingMeshInterfaceData;
class btGImpactMeshShape;
class btOptimizedBvh;
struct btTriangleInfoMap;
class btBvhTriangleMeshShape;
class btPoint2PointConstraint;
class btHingeConstraint;
class btConeTwistConstraint;
class btGeneric6DofConstraint;
class btGeneric6DofSpringConstraint;
class btSliderConstraint;
class btGearConstraint;
struct btContactSolverInfo;

class btCollisionWorldImporter
{
protected:
	btCollisionWorld* m_collisionWorld;

	int m_verboseMode;

	btAlignedObjectArray<btCollisionShape*>  m_allocatedCollisionShapes;
	btAlignedObjectArray<btCollisionObject*> m_allocatedRigidBodies;

	btAlignedObjectArray<btOptimizedBvh*>	 m_allocatedBvhs;
	btAlignedObjectArray<btTriangleInfoMap*> m_allocatedTriangleInfoMaps;
	btAlignedObjectArray<btTriangleIndexVertexArray*> m_allocatedTriangleIndexArrays;
	btAlignedObjectArray<btStridingMeshInterfaceData*> m_allocatedbtStridingMeshInterfaceDatas;
	btAlignedObjectArray<btCollisionObject*> m_allocatedCollisionObjects;

	btAlignedObjectArray<char*>				m_allocatedNames;

	btAlignedObjectArray<int*>				m_indexArrays;
	btAlignedObjectArray<short int*>		m_shortIndexArrays;
	btAlignedObjectArray<unsigned char*>	m_charIndexArrays;

	btAlignedObjectArray<btVector3FloatData*>	m_floatVertexArrays;
	btAlignedObjectArray<btVector3DoubleData*>	m_doubleVertexArrays;

	btHashMap<btHashPtr,btOptimizedBvh*>	m_bvhMap;
	btHashMap<btHashPtr,btTriangleInfoMap*>	m_timMap;

	btHashMap<btHashString,btCollisionShape*>	m_nameShapeMap;
	btHashMap<btHashString,btCollisionObject*>	m_nameColObjMap;

	btHashMap<btHashPtr,const char*>	m_objectNameMap;

	btHashMap<btHashPtr,btCollisionShape*>	m_shapeMap;
	btHashMap<btHashPtr,btCollisionObject*>	m_bodyMap;

	//methods

	char*	duplicateName(const char* name);

	btCollisionShape* convertCollisionShape(  btCollisionShapeData* shapeData  );

public:

	btCollisionWorldImporter(btCollisionWorld* world);

	virtual ~btCollisionWorldImporter();

    bool	convertAllObjects( btBulletSerializedArrays* arrays);

		///delete all memory collision shapes, rigid bodies, constraints etc. allocated during the load.
	///make sure you don't use the dynamics world containing objects after you call this method
	virtual void deleteAllData();

	void	setVerboseMode(int verboseMode)
	{
		m_verboseMode = verboseMode;
	}

	int getVerboseMode() const
	{
		return m_verboseMode;
	}

		// query for data
	int	getNumCollisionShapes() const;
	btCollisionShape* getCollisionShapeByIndex(int index);
	int getNumRigidBodies() const;
	btCollisionObject* getRigidBodyByIndex(int index) const;

	int getNumBvhs() const;
	btOptimizedBvh*  getBvhByIndex(int index) const;
	int getNumTriangleInfoMaps() const;
	btTriangleInfoMap* getTriangleInfoMapByIndex(int index) const;

	// queris involving named objects
	btCollisionShape* getCollisionShapeByName(const char* name);
	btCollisionObject* getCollisionObjectByName(const char* name);

	const char*	getNameForPointer(const void* ptr) const;

	///those virtuals are called by load and can be overridden by the user

	//bodies

	virtual btCollisionObject*  createCollisionObject(	const btTransform& startTransform,	btCollisionShape* shape,const char* bodyName);

	///shapes

	virtual btCollisionShape* createPlaneShape(const btVector3& planeNormal,btScalar planeConstant);
	virtual btCollisionShape* createBoxShape(const btVector3& halfExtents);
	virtual btCollisionShape* createSphereShape(btScalar radius);
	virtual btCollisionShape* createCapsuleShapeX(btScalar radius, btScalar height);
	virtual btCollisionShape* createCapsuleShapeY(btScalar radius, btScalar height);
	virtual btCollisionShape* createCapsuleShapeZ(btScalar radius, btScalar height);

	virtual btCollisionShape* createCylinderShapeX(btScalar radius,btScalar height);
	virtual btCollisionShape* createCylinderShapeY(btScalar radius,btScalar height);
	virtual btCollisionShape* createCylinderShapeZ(btScalar radius,btScalar height);
	virtual btCollisionShape* createConeShapeX(btScalar radius,btScalar height);
	virtual btCollisionShape* createConeShapeY(btScalar radius,btScalar height);
	virtual btCollisionShape* createConeShapeZ(btScalar radius,btScalar height);
	virtual class btTriangleIndexVertexArray*	createTriangleMeshContainer();
	virtual	btBvhTriangleMeshShape* createBvhTriangleMeshShape(btStridingMeshInterface* trimesh, btOptimizedBvh* bvh);
	virtual btCollisionShape* createConvexTriangleMeshShape(btStridingMeshInterface* trimesh);
#ifdef SUPPORT_GIMPACT_SHAPE_IMPORT
	virtual btGImpactMeshShape* createGimpactShape(btStridingMeshInterface* trimesh);
#endif //SUPPORT_GIMPACT_SHAPE_IMPORT
	virtual btStridingMeshInterfaceData* createStridingMeshInterfaceData(btStridingMeshInterfaceData* interfaceData);

	virtual class btConvexHullShape* createConvexHullShape();
	virtual class btCompoundShape* createCompoundShape();
	virtual class btScaledBvhTriangleMeshShape* createScaledTrangleMeshShape(btBvhTriangleMeshShape* meshShape,const btVector3& localScalingbtBvhTriangleMeshShape);

	virtual class btMultiSphereShape* createMultiSphereShape(const btVector3* positions,const btScalar* radi,int numSpheres);

	virtual btTriangleIndexVertexArray* createMeshInterface(btStridingMeshInterfaceData& meshData);

	///acceleration and connectivity structures
	virtual btOptimizedBvh*	createOptimizedBvh();
	virtual btTriangleInfoMap* createTriangleInfoMap();

};

#endif //BT_WORLD_IMPORTER_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_SIMULATION_ISLAND_MANAGER_H
#define BT_SIMULATION_ISLAND_MANAGER_H

#include "BulletCollision/CollisionDispatch/btUnionFind.h"
#include "btCollisionCreateFunc.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "btCollisionObject.h"

class btCollisionObject;
class btCollisionWorld;
class btDispatcher;
class btPersistentManifold;

///SimulationIslandManager creates and handles simulation islands, using btUnionFind
class btSimulationIslandManager
{
	btUnionFind m_unionFind;

	btAlignedObjectArray<btPersistentManifold*>  m_islandmanifold;
	btAlignedObjectArray<btCollisionObject* >  m_islandBodies;

	bool m_splitIslands;

public:
	btSimulationIslandManager();
	virtual ~btSimulationIslandManager();

	void initUnionFind(int n);

	btUnionFind& getUnionFind() { return m_unionFind;}

	virtual	void	updateActivationState(btCollisionWorld* colWorld,btDispatcher* dispatcher);
	virtual	void	storeIslandActivationState(btCollisionWorld* world);

	void	findUnions(btDispatcher* dispatcher,btCollisionWorld* colWorld);

	struct	IslandCallback
	{
		virtual ~IslandCallback() {};

		virtual	void	processIsland(btCollisionObject** bodies,int numBodies,class btPersistentManifold**	manifolds,int numManifolds, int islandId) = 0;
	};

	void	buildAndProcessIslands(btDispatcher* dispatcher,btCollisionWorld* collisionWorld, IslandCallback* callback);

	void buildIslands(btDispatcher* dispatcher,btCollisionWorld* colWorld);

	bool getSplitIslands()
	{
		return m_splitIslands;
	}
	void setSplitIslands(bool doSplitIslands)
	{
		m_splitIslands = doSplitIslands;
	}

};

#endif //BT_SIMULATION_ISLAND_MANAGER_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_SPHERE_SPHERE_COLLISION_ALGORITHM_H
#define BT_SPHERE_SPHERE_COLLISION_ALGORITHM_H

#include "btActivatingCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
#include "btCollisionDispatcher.h"

class btPersistentManifold;

/// btSphereSphereCollisionAlgorithm  provides sphere-sphere collision detection.
/// Other features are frame-coherency (persistent data) and collision response.
/// Also provides the most basic sample for custom/user btCollisionAlgorithm
class btSphereSphereCollisionAlgorithm : public btActivatingCollisionAlgorithm
{
	bool	m_ownManifold;
	btPersistentManifold*	m_manifoldPtr;

public:
	btSphereSphereCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* col0Wrap,const btCollisionObjectWrapper* col1Wrap);

	btSphereSphereCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci)
		: btActivatingCollisionAlgorithm(ci) {}

	virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray)
	{
		if (m_manifoldPtr && m_ownManifold)
		{
			manifoldArray.push_back(m_manifoldPtr);
		}
	}

	virtual ~btSphereSphereCollisionAlgorithm();

	struct CreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* col0Wrap,const btCollisionObjectWrapper* col1Wrap)
		{
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSphereSphereCollisionAlgorithm));
			return new(mem) btSphereSphereCollisionAlgorithm(0,ci,col0Wrap,col1Wrap);
		}
	};

};

#endif //BT_SPHERE_SPHERE_COLLISION_ALGORITHM_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2008 Erwin Coumans  http://bulletphysics.com

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#ifndef BT_GHOST_OBJECT_H
#define BT_GHOST_OBJECT_H

#include "btCollisionObject.h"
#include "BulletCollision/BroadphaseCollision/btOverlappingPairCallback.h"
#include "LinearMath/btAlignedAllocator.h"
#include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h"
#include "btCollisionWorld.h"

class btConvexShape;
class btDispatcher;

/// The btGhostObject can keep track of all objects that are overlapping. By
/// default, this overlap is based on the AABB. This is useful for creating a
/// character controller, collision sensors/triggers, explosions etc. We plan on
/// adding rayTest and other queries for the btGhostObject.
ATTRIBUTE_ALIGNED16(class) btGhostObject : public btCollisionObject
{
protected:
	btAlignedObjectArray<btCollisionObject*> m_overlappingObjects;

public:
	btGhostObject();
	virtual ~btGhostObject();

	void convexSweepTest(
	    const btConvexShape*                    castShape,
	    const btTransform&                      convexFromWorld,
	    const btTransform&                      convexToWorld,
	    btCollisionWorld::ConvexResultCallback& resultCallback,
	    btScalar                                allowedCcdPenetration = 0.f) const;

	void rayTest(
	    const btVector3&                     rayFromWorld,
	    const btVector3&                     rayToWorld,
	    btCollisionWorld::RayResultCallback& resultCallback) const;

	/// this method is mainly for expert/internal use only.
	virtual void addOverlappingObjectInternal(btBroadphaseProxy * otherProxy, btBroadphaseProxy* thisProxy = 0);
	/// this method is mainly for expert/internal use only.
	virtual void removeOverlappingObjectInternal(btBroadphaseProxy * otherProxy, btDispatcher * dispatcher, btBroadphaseProxy* thisProxy = 0);

	int                                            getNumOverlappingObjects() const { return m_overlappingObjects.size(); }
	btCollisionObject*                             getOverlappingObject(int index) { return m_overlappingObjects[index]; }
	const btCollisionObject*                       getOverlappingObject(int index) const { return m_overlappingObjects[index]; }
	btAlignedObjectArray<btCollisionObject*>&      getOverlappingPairs() { return m_overlappingObjects; }
	const btAlignedObjectArray<btCollisionObject*> getOverlappingPairs() const { return m_overlappingObjects; }

	static const btGhostObject* upcast(const btCollisionObject* colObj)
	{
		if (colObj->getInternalType() == CO_GHOST_OBJECT)
		{
			return (const btGhostObject*) colObj;
		}
		return 0;
	}
	static btGhostObject* upcast(btCollisionObject * colObj)
	{
		if (colObj->getInternalType() == CO_GHOST_OBJECT)
		{
			return (btGhostObject*) colObj;
		}
		return 0;
	}
};

class btPairCachingGhostObject : public btGhostObject
{
	btHashedOverlappingPairCache* m_hashPairCache;

public:
	btPairCachingGhostObject();
	virtual ~btPairCachingGhostObject();

	/// this method is mainly for expert/internal use only.
	virtual void addOverlappingObjectInternal(btBroadphaseProxy* otherProxy, btBroadphaseProxy* thisProxy = 0);
	/// this method is mainly for expert/internal use only.
	virtual void removeOverlappingObjectInternal(btBroadphaseProxy* otherProxy, btDispatcher* dispatcher, btBroadphaseProxy* thisProxy = 0);

	btHashedOverlappingPairCache* getOverlappingPairCache() { return m_hashPairCache; }
};

/// The btGhostPairCallback interfaces and forwards adding and removal of
/// overlapping pairs from the btBroadphaseInterface to btGhostObject.
class btGhostPairCallback : public btOverlappingPairCallback
{
public:
	btGhostPairCallback() { }
	virtual ~btGhostPairCallback() { }

	virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1)
	{
		btCollisionObject* colObj0 = (btCollisionObject*) proxy0->m_clientObject;
		btCollisionObject* colObj1 = (btCollisionObject*) proxy1->m_clientObject;
		btGhostObject*     ghost0  = btGhostObject::upcast(colObj0);
		btGhostObject*     ghost1  = btGhostObject::upcast(colObj1);
		if (ghost0) { ghost0->addOverlappingObjectInternal(proxy1, proxy0); }
		if (ghost1) { ghost1->addOverlappingObjectInternal(proxy0, proxy1); }
		return 0;
	}

	virtual void* removeOverlappingPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1, btDispatcher* dispatcher)
	{
		btCollisionObject* colObj0 = (btCollisionObject*) proxy0->m_clientObject;
		btCollisionObject* colObj1 = (btCollisionObject*) proxy1->m_clientObject;
		btGhostObject*     ghost0  = btGhostObject::upcast(colObj0);
		btGhostObject*     ghost1  = btGhostObject::upcast(colObj1);
		if (ghost0) { ghost0->removeOverlappingObjectInternal(proxy1, dispatcher, proxy0); }
		if (ghost1) { ghost1->removeOverlappingObjectInternal(proxy0, dispatcher, proxy1); }
		return 0;
	}

	virtual void removeOverlappingPairsContainingProxy(btBroadphaseProxy* /*proxy0*/, btDispatcher* /*dispatcher*/)
	{
		btAssert(0);
		// need to keep track of all ghost objects and call them here
		//m_hashPairCache->removeOverlappingPairsContainingProxy(proxy0,dispatcher);
	}
};

#endif


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_COMPOUND_COLLISION_ALGORITHM_H
#define BT_COMPOUND_COLLISION_ALGORITHM_H

#include "btActivatingCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btDispatcher.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"

#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
class btDispatcher;
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "btCollisionCreateFunc.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "BulletCollision/BroadphaseCollision/btDbvt.h"
class btDispatcher;
class btCollisionObject;

class btCollisionShape;
typedef bool (*btShapePairCallback)(const btCollisionShape* pShape0, const btCollisionShape* pShape1);
extern btShapePairCallback gCompoundChildShapePairCallback;

/// btCompoundCollisionAlgorithm  supports collision between CompoundCollisionShapes and other collision shapes
class btCompoundCollisionAlgorithm  : public btActivatingCollisionAlgorithm
{
	btNodeStack stack2;
	btManifoldArray manifoldArray;

protected:
	btAlignedObjectArray<btCollisionAlgorithm*> m_childCollisionAlgorithms;
	bool m_isSwapped;

	class btPersistentManifold*	m_sharedManifold;
	bool					m_ownsManifold;

	int	m_compoundShapeRevision;//to keep track of changes, so that childAlgorithm array can be updated

	void	removeChildAlgorithms();

	void	preallocateChildAlgorithms(const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap);

public:

	btCompoundCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped);

	virtual ~btCompoundCollisionAlgorithm();

	btCollisionAlgorithm* getChildAlgorithm (int n) const
	{
		return m_childCollisionAlgorithms[n];
	}

	virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	btScalar	calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray)
	{
		int i;
		for (i=0;i<m_childCollisionAlgorithms.size();i++)
		{
			if (m_childCollisionAlgorithms[i])
				m_childCollisionAlgorithms[i]->getAllContactManifolds(manifoldArray);
		}
	}

	struct CreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
		{
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCollisionAlgorithm));
			return new(mem) btCompoundCollisionAlgorithm(ci,body0Wrap,body1Wrap,false);
		}
	};

	struct SwappedCreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
		{
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCollisionAlgorithm));
			return new(mem) btCompoundCollisionAlgorithm(ci,body0Wrap,body1Wrap,true);
		}
	};

};

#endif //BT_COMPOUND_COLLISION_ALGORITHM_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2008 Erwin Coumans  http://bulletphysics.com

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#ifndef __BT_ACTIVATING_COLLISION_ALGORITHM_H
#define __BT_ACTIVATING_COLLISION_ALGORITHM_H

#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"

///This class is not enabled yet (work-in-progress) to more aggressively activate objects.
class btActivatingCollisionAlgorithm : public btCollisionAlgorithm
{
//	btCollisionObject* m_colObj0;
//	btCollisionObject* m_colObj1;

protected:

	btActivatingCollisionAlgorithm (const btCollisionAlgorithmConstructionInfo& ci);

	btActivatingCollisionAlgorithm (const btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap);

public:
	virtual ~btActivatingCollisionAlgorithm();

};
#endif //__BT_ACTIVATING_COLLISION_ALGORITHM_H


text:
#ifndef BT_COLLISION_OBJECT_WRAPPER_H
#define BT_COLLISION_OBJECT_WRAPPER_H

///btCollisionObjectWrapperis an internal data structure.
///Most users can ignore this and use btCollisionObject and btCollisionShape instead
class btCollisionShape;
class btCollisionObject;
class btTransform;
#include "LinearMath/btScalar.h" // for SIMD_FORCE_INLINE definition

#define BT_DECLARE_STACK_ONLY_OBJECT \
private:                             \
	void* operator new(size_t size);   \
	void  operator delete(void*);

struct btCollisionObjectWrapper;
struct btCollisionObjectWrapper
{
	BT_DECLARE_STACK_ONLY_OBJECT

private:
	btCollisionObjectWrapper(const btCollisionObjectWrapper&); // not implemented. Not allowed.
	btCollisionObjectWrapper* operator=(const btCollisionObjectWrapper&);

public:
	const btCollisionObjectWrapper* m_parent;
	const btCollisionShape*         m_shape;
	const btCollisionObject*        m_collisionObject;
	const btTransform&              m_worldTransform;
	int                             m_partId;
	int                             m_index;

	btCollisionObjectWrapper(
	    const btCollisionObjectWrapper* parent,
	    const btCollisionShape*         shape,
	    const btCollisionObject*        collisionObject,
	    const btTransform&              worldTransform,
	    int                             partId,
	    int                             index)
	    : m_parent(parent),
	      m_shape(shape),
	      m_collisionObject(collisionObject),
	      m_worldTransform(worldTransform),
	      m_partId(partId),
	      m_index(index)
	{
	}

	SIMD_FORCE_INLINE const btTransform& getWorldTransform() const { return m_worldTransform; }
	SIMD_FORCE_INLINE const btCollisionObject* getCollisionObject() const { return m_collisionObject; }
	SIMD_FORCE_INLINE const btCollisionShape* getCollisionShape() const { return m_shape; }
};

#endif //BT_COLLISION_OBJECT_WRAPPER_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_BOX_2D_BOX_2D__COLLISION_ALGORITHM_H
#define BT_BOX_2D_BOX_2D__COLLISION_ALGORITHM_H

#include "BulletCollision/CollisionDispatch/btActivatingCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/BroadphaseCollision/btDispatcher.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"

class btPersistentManifold;

///box-box collision detection
class btBox2dBox2dCollisionAlgorithm : public btActivatingCollisionAlgorithm
{
	bool	m_ownManifold;
	btPersistentManifold*	m_manifoldPtr;

public:
	btBox2dBox2dCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci)
		: btActivatingCollisionAlgorithm(ci) {}

	virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	btBox2dBox2dCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap);

	virtual ~btBox2dBox2dCollisionAlgorithm();

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray)
	{
		if (m_manifoldPtr && m_ownManifold)
		{
			manifoldArray.push_back(m_manifoldPtr);
		}
	}

	struct CreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
		{
			int bbsize = sizeof(btBox2dBox2dCollisionAlgorithm);
			void* ptr = ci.m_dispatcher1->allocateCollisionAlgorithm(bbsize);
			return new(ptr) btBox2dBox2dCollisionAlgorithm(0,ci,body0Wrap,body1Wrap);
		}
	};

};

#endif //BT_BOX_2D_BOX_2D__COLLISION_ALGORITHM_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

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 BT_MANIFOLD_RESULT_H
#define BT_MANIFOLD_RESULT_H

class btCollisionObject;
struct btCollisionObjectWrapper;

#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
class btManifoldPoint;

#include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h"

#include "LinearMath/btTransform.h"
#include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h"
#include "BulletCollision/CollisionDispatch/btCollisionObject.h"

typedef bool (*ContactAddedCallback)(btManifoldPoint& cp,	const btCollisionObjectWrapper* colObj0Wrap,int partId0,int index0,const btCollisionObjectWrapper* colObj1Wrap,int partId1,int index1);
extern ContactAddedCallback		gContactAddedCallback;

//#define DEBUG_PART_INDEX 1

///btManifoldResult is a helper class to manage  contact results.
class btManifoldResult : public btDiscreteCollisionDetectorInterface::Result
{
protected:

	btPersistentManifold* m_manifoldPtr;

	const btCollisionObjectWrapper* m_body0Wrap;
	const btCollisionObjectWrapper* m_body1Wrap;
	int	m_partId0;
	int m_partId1;
	int m_index0;
	int m_index1;

public:

	btManifoldResult()
		:
#ifdef DEBUG_PART_INDEX

	m_partId0(-1),
	m_partId1(-1),
	m_index0(-1),
	m_index1(-1)
#endif //DEBUG_PART_INDEX
		m_closestPointDistanceThreshold(0)
	{
	}

	btManifoldResult(const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap);

	virtual ~btManifoldResult() {};

	void	setPersistentManifold(btPersistentManifold* manifoldPtr)
	{
		m_manifoldPtr = manifoldPtr;
	}

	const btPersistentManifold*	getPersistentManifold() const
	{
		return m_manifoldPtr;
	}
	btPersistentManifold*	getPersistentManifold()
	{
		return m_manifoldPtr;
	}

	virtual void setShapeIdentifiersA(int partId0,int index0)
	{
		m_partId0=partId0;
		m_index0=index0;
	}

	virtual void setShapeIdentifiersB(	int partId1,int index1)
	{
		m_partId1=partId1;
		m_index1=index1;
	}

	virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth);

	SIMD_FORCE_INLINE	void refreshContactPoints()
	{
		btAssert(m_manifoldPtr);
		if (!m_manifoldPtr->getNumContacts())
			return;

		bool isSwapped = m_manifoldPtr->getBody0() != m_body0Wrap->getCollisionObject();

		if (isSwapped)
		{
			m_manifoldPtr->refreshContactPoints(m_body1Wrap->getCollisionObject()->getWorldTransform(),m_body0Wrap->getCollisionObject()->getWorldTransform());
		} else
		{
			m_manifoldPtr->refreshContactPoints(m_body0Wrap->getCollisionObject()->getWorldTransform(),m_body1Wrap->getCollisionObject()->getWorldTransform());
		}
	}

	const btCollisionObjectWrapper* getBody0Wrap() const
	{
		return m_body0Wrap;
	}
	const btCollisionObjectWrapper* getBody1Wrap() const
	{
		return m_body1Wrap;
	}

	void setBody0Wrap(const btCollisionObjectWrapper* obj0Wrap)
	{
		m_body0Wrap = obj0Wrap;
	}

	void setBody1Wrap(const btCollisionObjectWrapper* obj1Wrap)
	{
		m_body1Wrap = obj1Wrap;
	}

	const btCollisionObject* getBody0Internal() const
	{
		return m_body0Wrap->getCollisionObject();
	}

	const btCollisionObject* getBody1Internal() const
	{
		return m_body1Wrap->getCollisionObject();
	}

	btScalar	m_closestPointDistanceThreshold;

	/// in the future we can let the user override the methods to combine restitution and friction
	static btScalar	calculateCombinedRestitution(const btCollisionObject* body0,const btCollisionObject* body1);
	static btScalar	calculateCombinedFriction(const btCollisionObject* body0,const btCollisionObject* body1);
	static btScalar calculateCombinedRollingFriction(const btCollisionObject* body0,const btCollisionObject* body1);
    static btScalar calculateCombinedSpinningFriction(const btCollisionObject* body0,const btCollisionObject* body1);
    static btScalar calculateCombinedContactDamping(const btCollisionObject* body0,const btCollisionObject* body1);
	static btScalar calculateCombinedContactStiffness(const btCollisionObject* body0,const btCollisionObject* body1);
};

#endif //BT_MANIFOLD_RESULT_H


text:
#ifndef BT_INTERNAL_EDGE_UTILITY_H
#define BT_INTERNAL_EDGE_UTILITY_H

#include "LinearMath/btHashMap.h"
#include "LinearMath/btVector3.h"

#include "BulletCollision/CollisionShapes/btTriangleInfoMap.h"

///The btInternalEdgeUtility helps to avoid or reduce artifacts due to wrong collision normals caused by internal edges.
///See also http://code.google.com/p/bullet/issues/detail?id=27

class btBvhTriangleMeshShape;
class btCollisionObject;
struct btCollisionObjectWrapper;
class btManifoldPoint;
class btIDebugDraw;

enum btInternalEdgeAdjustFlags
{
	BT_TRIANGLE_CONVEX_BACKFACE_MODE = 1,
	BT_TRIANGLE_CONCAVE_DOUBLE_SIDED = 2, //double sided options are experimental, single sided is recommended
	BT_TRIANGLE_CONVEX_DOUBLE_SIDED = 4
};

///Call btGenerateInternalEdgeInfo to create triangle info, store in the shape 'userInfo'
void	btGenerateInternalEdgeInfo (btBvhTriangleMeshShape*trimeshShape, btTriangleInfoMap* triangleInfoMap);

///Call the btFixMeshNormal to adjust the collision normal, using the triangle info map (generated using btGenerateInternalEdgeInfo)
///If this info map is missing, or the triangle is not store in this map, nothing will be done
void	btAdjustInternalEdgeContacts(btManifoldPoint& cp, const btCollisionObjectWrapper* trimeshColObj0Wrap,const btCollisionObjectWrapper* otherColObj1Wrap, int partId0, int index0, int normalAdjustFlags = 0);

///Enable the BT_INTERNAL_EDGE_DEBUG_DRAW define and call btSetDebugDrawer, to get visual info to see if the internal edge utility works properly.
///If the utility doesn't work properly, you might have to adjust the threshold values in btTriangleInfoMap
//#define BT_INTERNAL_EDGE_DEBUG_DRAW

#ifdef BT_INTERNAL_EDGE_DEBUG_DRAW
void	btSetDebugDrawer(btIDebugDraw* debugDrawer);
#endif //BT_INTERNAL_EDGE_DEBUG_DRAW

#endif //BT_INTERNAL_EDGE_UTILITY_H