
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 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.
*/

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

#include "../stdafx.h"
#include "Physics_ModifiedWorld.h"
#include "Physics_FourChannelHeightField.h"
#include "Physics_ModifiedCompound.h"

ModifiedWorld::ModifiedWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration)
: btDiscreteDynamicsWorld(dispatcher,pairCache,constraintSolver,collisionConfiguration)
{
	m_DebugCenter = btVector3(0.0f,0.0f,0.0f);
	m_DebugRadius = 10.0f;
	m_DebugDrawMin = btVector3(-10.0f,-10.0f,-10.0f);
	m_DebugDrawMax = btVector3(10.0f,10.0f,10.0f);
}

ModifiedWorld::~ModifiedWorld() {
	
}

void ModifiedWorld::synchronizeMotionStates() {
	// Do nothing to save a lot of performance when they are not used
}

class DebugDrawcallback : public btTriangleCallback, public btInternalTriangleIndexCallback
{
	btIDebugDraw*	m_debugDrawer;
	btVector3	m_color;
	btTransform	m_worldTrans;
public:
	DebugDrawcallback(btIDebugDraw*	debugDrawer,const btTransform& worldTrans,const btVector3& color) :
	  m_debugDrawer(debugDrawer),
		  m_color(color),
		  m_worldTrans(worldTrans)
	  {
	  }
	
	  virtual void internalProcessTriangleIndex(btVector3* triangle,int partId,int  triangleIndex)
	  {
		  processTriangle(triangle,partId,triangleIndex);
	  }
	
	  virtual void processTriangle(btVector3* triangle,int partId, int triangleIndex)
	  {
		  (void)partId;
		  (void)triangleIndex;
		
		  btVector3 wv0,wv1,wv2;
		  wv0 = m_worldTrans*triangle[0];
		  wv1 = m_worldTrans*triangle[1];
		  wv2 = m_worldTrans*triangle[2];
		  btVector3 center = (wv0+wv1+wv2)*btScalar(1./3.);
		
		  m_debugDrawer->drawLine(wv0,wv1,m_color);
		  m_debugDrawer->drawLine(wv1,wv2,m_color);
		  m_debugDrawer->drawLine(wv2,wv0,m_color);
	  }
};

void ModifiedWorld::debugDrawWorld(void) {
	if (getDebugDrawer() && getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawContactPoints) {
		int numManifolds = getDispatcher()->getNumManifolds();
		for (int i=0;i<numManifolds;i++) {
			btPersistentManifold* contactManifold = getDispatcher()->getManifoldByIndexInternal(i);
			//btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0());
			//btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1());
			int numContacts = contactManifold->getNumContacts();
			for (int j=0;j<numContacts;j++) {
				btManifoldPoint& cp = contactManifold->getContactPoint(j);
				getDebugDrawer()->drawContactPoint(cp.m_positionWorldOnB,cp.m_normalWorldOnB,cp.getDistance(),cp.getLifeTime(),btVector3(1,1,1));
			}
		}
	}
	if (getDebugDrawer() && (getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe))) {
		int i;
		for (  i=0;i<m_collisionObjects.size();i++) {
			btCollisionObject* colObj = m_collisionObjects[i];
			if ((colObj->getCollisionFlags() & btCollisionObject::CF_DISABLE_VISUALIZE_OBJECT)==0) {
				btVector3 minAabb,maxAabb;
				colObj->getCollisionShape()->getAabb(colObj->getWorldTransform(), minAabb,maxAabb);
				btVector3 contactThreshold(gContactBreakingThreshold,gContactBreakingThreshold,gContactBreakingThreshold);
				minAabb -= contactThreshold;
				maxAabb += contactThreshold;
				btVector3 minAabb2,maxAabb2;
				if(colObj->getInternalType()==btCollisionObject::CO_RIGID_BODY)
				{
					colObj->getCollisionShape()->getAabb(colObj->getInterpolationWorldTransform(),minAabb2,maxAabb2);
					minAabb2 -= contactThreshold;
					maxAabb2 += contactThreshold;
					minAabb.setMin(minAabb2);
					maxAabb.setMax(maxAabb2);
				}
				if (!(minAabb.getX() > m_DebugDrawMax.getX() || maxAabb.getX() < m_DebugDrawMin.getX()
				   || minAabb.getY() > m_DebugDrawMax.getY() || maxAabb.getY() < m_DebugDrawMin.getY()
				   || minAabb.getZ() > m_DebugDrawMax.getZ() || maxAabb.getZ() < m_DebugDrawMin.getZ())) {
					btVector3 color(btScalar(0.0f),btScalar(0.0f),btScalar(0.0f));
					switch(colObj->getActivationState()) {
					case ACTIVE_TAG:
						color = btVector3(0.0f,1.0f,0.0f); break;
					case ISLAND_SLEEPING:
						color =  btVector3(0.0f,0.0f,1.0f);break;
					case WANTS_DEACTIVATION:
						color = btVector3(0.0f,1.0f,1.0f);break;
					case DISABLE_DEACTIVATION:
						color = btVector3(1.0f,1.0f,0.0f);break;
					case DISABLE_SIMULATION:
						color = btVector3(1.0f,0.0f,0.0f);break;
					default:
						color = btVector3(1.0f,1.0f,1.0f);
					};
					if (getDebugDrawer() && (getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawWireframe)) {
						debugDrawObject(colObj->getWorldTransform(),colObj->getCollisionShape(),color);
					}
					/* Disabled because the DrawAabb flag causes Bullet to send draw calls during a collision algorithm
					if (m_debugDrawer && (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawAabb) && ((colObj->getCollisionShape())->isInfinite() == false)) {
						m_debugDrawer->drawAabb(minAabb,maxAabb,color);
					}
					*/
				}
			}
		}
	}
	
	bool drawConstraints = false;
	if (getDebugDrawer())
	{
		int mode = getDebugDrawer()->getDebugMode();
		if(mode  & (btIDebugDraw::DBG_DrawConstraints | btIDebugDraw::DBG_DrawConstraintLimits))
		{
			drawConstraints = true;
		}
	}
	if(drawConstraints)
	{
		for(int i = getNumConstraints()-1; i>=0 ;i--)
		{
			btTypedConstraint* constraint = getConstraint(i);
			debugDrawConstraint(constraint);
		}
	}
	if (getDebugDrawer() && (getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawAabb))) {
		int i;
		if (getDebugDrawer() && getDebugDrawer()->getDebugMode())
		{
			for (i=0;i<m_actions.size();i++)
			{
				m_actions[i]->debugDraw(m_debugDrawer);
			}
		}
	}
}

void ModifiedWorld::debugDrawObject(const btTransform& worldTransform, const btCollisionShape* shape, const btVector3& color) {
	// Draw a small simplex at the center of the object
	getDebugDrawer()->drawTransform(worldTransform,1);
	
	if (shape->getShapeType() == COMPOUND_SHAPE_PROXYTYPE) {
		const ModifiedCompound* compoundShape = static_cast<const ModifiedCompound*>(shape);
		for (int i=compoundShape->getNumChildShapes()-1;i>=0;i--)
		{
			btTransform childTrans = compoundShape->getChildTransform(i);
			const btCollisionShape* colShape = compoundShape->getChildShape(i);
			debugDrawObject(worldTransform*childTrans,colShape,color);
		}
	} else {
		// For polyhedral shapes
		if (shape->isPolyhedral()) {
			btPolyhedralConvexShape* polyshape = (btPolyhedralConvexShape*) shape;
			int i;
			if (polyshape->getConvexPolyhedron())
			{
				const btConvexPolyhedron* poly = polyshape->getConvexPolyhedron();
				for (i=0;i<poly->m_faces.size();i++)
				{
					int numVerts = poly->m_faces[i].m_indices.size();
					if (numVerts)
					{
						int lastV = poly->m_faces[i].m_indices[numVerts-1];
						for (int v=0;v<poly->m_faces[i].m_indices.size();v++)
						{
							int curVert = poly->m_faces[i].m_indices[v];
							getDebugDrawer()->drawLine(worldTransform*poly->m_vertices[lastV],worldTransform*poly->m_vertices[curVert],color);
							lastV = curVert;
						}
					}
				}
				
			} else {
				for (i=0;i<polyshape->getNumEdges();i++)
				{
					btVector3 a,b;
					polyshape->getEdge(i,a,b);
					btVector3 wa = worldTransform * a;
					btVector3 wb = worldTransform * b;
					getDebugDrawer()->drawLine(wa,wb,color);
				}
			}
		}
		else
		{
			switch (shape->getShapeType())
			{
			case BOX_SHAPE_PROXYTYPE:
				{
					const btBoxShape* boxShape = static_cast<const btBoxShape*>(shape);
					btVector3 halfExtents = boxShape->getHalfExtentsWithMargin();
					getDebugDrawer()->drawBox(-halfExtents,halfExtents,worldTransform,color);
					break;
				}
			case SPHERE_SHAPE_PROXYTYPE:
				{
					const btSphereShape* sphereShape = static_cast<const btSphereShape*>(shape);
					btScalar radius = sphereShape->getMargin();//radius doesn't include the margin, so draw with margin
					getDebugDrawer()->drawSphere(radius, worldTransform, color);
					break;
				}
			case MULTI_SPHERE_SHAPE_PROXYTYPE:
				{
					const btMultiSphereShape* multiSphereShape = static_cast<const btMultiSphereShape*>(shape);
					btTransform childTransform;
					childTransform.setIdentity();
					for (int i = multiSphereShape->getSphereCount()-1; i>=0;i--)
					{
						childTransform.setOrigin(multiSphereShape->getSpherePosition(i));
						getDebugDrawer()->drawSphere(multiSphereShape->getSphereRadius(i), worldTransform*childTransform, color);
					}
					break;
				}
			case CAPSULE_SHAPE_PROXYTYPE:
				{
					const btCapsuleShape* capsuleShape = static_cast<const btCapsuleShape*>(shape);
					btScalar radius = capsuleShape->getRadius();
					btScalar halfHeight = capsuleShape->getHalfHeight();
					int upAxis = capsuleShape->getUpAxis();
					getDebugDrawer()->drawCapsule(radius, halfHeight, upAxis, worldTransform, color);
					break;
				}
			case CONE_SHAPE_PROXYTYPE:
				{
					const btConeShape* coneShape = static_cast<const btConeShape*>(shape);
					btScalar radius = coneShape->getRadius();//+coneShape->getMargin();
					btScalar height = coneShape->getHeight();//+coneShape->getMargin();
					int upAxis= coneShape->getConeUpIndex();
					getDebugDrawer()->drawCone(radius, height, upAxis, worldTransform, color);
					break;
				}
			case CYLINDER_SHAPE_PROXYTYPE:
				{
					const btCylinderShape* cylinder = static_cast<const btCylinderShape*>(shape);
					int upAxis = cylinder->getUpAxis();
					btScalar radius = cylinder->getRadius();
					btScalar halfHeight = cylinder->getHalfExtentsWithMargin()[upAxis];
					getDebugDrawer()->drawCylinder(radius, halfHeight, upAxis, worldTransform, color);
					break;
				}
			case STATIC_PLANE_PROXYTYPE:
				{
					const btStaticPlaneShape* staticPlaneShape = static_cast<const btStaticPlaneShape*>(shape);
					btScalar planeConst = staticPlaneShape->getPlaneConstant();
					const btVector3& planeNormal = staticPlaneShape->getPlaneNormal();
					getDebugDrawer()->drawPlane(planeNormal, planeConst, worldTransform, color);
					break;
				}
			default:
				{
					if (shape->isConcave()) {
						btConcaveShape* concaveMesh = (btConcaveShape*) shape;
						DebugDrawcallback drawCallback(getDebugDrawer(),worldTransform,color);
						
						// Convert debug volume from world space to object space
						btVector3 Center_Local = (m_DebugCenter - worldTransform.getOrigin()) * worldTransform.getBasis().transpose();
						btVector3 DrawMin = btVector3(Center_Local.getX() - m_DebugRadius, Center_Local.getY() - m_DebugRadius, Center_Local.getZ() - m_DebugRadius);
						btVector3 DrawMax = btVector3(Center_Local.getX() + m_DebugRadius, Center_Local.getY() + m_DebugRadius, Center_Local.getZ() + m_DebugRadius);
						
						// Draw the triangles
						concaveMesh->processAllTriangles(&drawCallback, DrawMin, DrawMax);
					}
					if (shape->getShapeType() == CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE) {
						btConvexTriangleMeshShape* convexMesh = (btConvexTriangleMeshShape*) shape;
						DebugDrawcallback drawCallback(getDebugDrawer(),worldTransform,color);
						convexMesh->getMeshInterface()->InternalProcessAllTriangles(&drawCallback,m_DebugDrawMin,m_DebugDrawMax);
					}
				}
			}
		}
	}
}

void ModifiedWorld::rayTestHeightField(const btTransform& rayFromTrans,const btTransform& rayToTrans, btCollisionObject* collisionObject, const btCollisionShape* collisionShape, const btTransform& colObjWorldTransform, RayResultCallback& resultCallback) {
	btSphereShape pointShape(btScalar(0.0));
	pointShape.setMargin(0.0f);
	const btConvexShape* castShape = &pointShape;
	if (collisionShape->isConcave()) {
		if (collisionShape->getShapeType() != TRIANGLE_MESH_SHAPE_PROXYTYPE) {
			FourChannelHeightField* concaveShape = (FourChannelHeightField*)collisionShape;

			btTransform worldTocollisionObject = colObjWorldTransform.inverse();

			btVector3 rayFromLocal = worldTocollisionObject * rayFromTrans.getOrigin();
			btVector3 rayToLocal = worldTocollisionObject * rayToTrans.getOrigin();

			struct BridgeTriangleRaycastCallback : public btTriangleRaycastCallback {
				btCollisionWorld::RayResultCallback* m_resultCallback;
				btCollisionObject*	m_collisionObject;
				btConcaveShape*	m_triangleMesh;

				btTransform m_colObjWorldTransform;

				BridgeTriangleRaycastCallback( const btVector3& from,const btVector3& to,
					btCollisionWorld::RayResultCallback* resultCallback, btCollisionObject* collisionObject,btConcaveShape*	triangleMesh, const btTransform& colObjWorldTransform):
				
				btTriangleRaycastCallback(from,to, resultCallback->m_flags),
					m_resultCallback(resultCallback),
					m_collisionObject(collisionObject),
					m_triangleMesh(triangleMesh),
					m_colObjWorldTransform(colObjWorldTransform)
				{
				}

				virtual btScalar reportHit(const btVector3& hitNormalLocal, btScalar hitFraction, int partId, int triangleIndex )
				{
					btCollisionWorld::LocalShapeInfo	shapeInfo;
					shapeInfo.m_shapePart = partId;
					shapeInfo.m_triangleIndex = triangleIndex;

					btVector3 hitNormalWorld = m_colObjWorldTransform.getBasis() * hitNormalLocal;

					btCollisionWorld::LocalRayResult rayResult
						(m_collisionObject,
						&shapeInfo,
						hitNormalWorld,
						hitFraction);

					bool	normalInWorldSpace = true;
					return m_resultCallback->addSingleResult(rayResult,normalInWorldSpace);
				}

			};

			BridgeTriangleRaycastCallback	rcb(rayFromLocal,rayToLocal,&resultCallback,collisionObject,concaveShape, colObjWorldTransform);
			rcb.m_hitFraction = resultCallback.m_closestHitFraction;

			concaveShape->processTrianglesAlongLine(&rcb,rayFromLocal,rayToLocal);
		}
	}
}
