Example #1
0
/**
*  @brief
*    Constructor
*/
BodyEllipsoid::BodyEllipsoid(PLPhysics::World &cWorld, const Vector3 &vRadius) :
	PLPhysics::BodyEllipsoid(cWorld, static_cast<World&>(cWorld).CreateBodyImpl(), vRadius)
{
	// Deactivate the physics simulation if required
	const bool bSimulationActive = cWorld.IsSimulationActive();
	if (bSimulationActive)
		cWorld.SetSimulationActive(false);

	// Get the Newton physics world
	Newton::NewtonWorld *pNewtonWorld = static_cast<World&>(cWorld).GetNewtonWorld();

	// Create collision primitive
	Newton::NewtonCollision *pCollision = NewtonCreateSphere(pNewtonWorld, m_vRadius.x, m_vRadius.y, m_vRadius.z, 0, nullptr);

	// Create the rigid body
	// [TODO] Remove this as soon as there's an up-to-date Linux version of Newton Game Dynamics available!
	#if (NEWTON_MAJOR_VERSION == 2) && (NEWTON_MINOR_VERSION >= 28)
		Newton::NewtonBody *pNewtonBody = NewtonCreateBody(pNewtonWorld, pCollision, Matrix4x4::Identity);
	#else
		Newton::NewtonBody *pNewtonBody = NewtonCreateBody(pNewtonWorld, pCollision);
	#endif
	NewtonReleaseCollision(pNewtonWorld, pCollision);

	// Calculate the collision volume
	const float fCollisionVolume = static_cast<float>((4/3)*Math::Pi*m_vRadius.x*m_vRadius.y*m_vRadius.z);

	// Initialize the Newton physics body
	static_cast<BodyImpl&>(GetBodyImpl()).InitializeNewtonBody(*this, *pNewtonBody, fCollisionVolume);

	// Reactivate the physics simulation if required
	if (bSimulationActive)
		cWorld.SetSimulationActive(bSimulationActive);
}
	Roket_PhysicsBody::Roket_PhysicsBody(NewtonCollision* collision, NewtonWorld* physworld, ePhysicsType type, int materialid)
	{
		body = NewtonCreateBody(physworld,collision);
		NewtonReleaseCollision(physworld,collision);
		NewtonBodySetUserData(body,this);
		NewtonBodySetTransformCallback(body,physics::TransformCallback);
		NewtonBodySetForceAndTorqueCallback(body,physics::ApplyForceAndTorqueCallback);
		affectedByGravity = true;
		objectExists = true;

		// apply initial force
		/*float omega[3];
		omega[0] = 10.0f;
		omega[1] = 10.0f;
		omega[2] = 10.0f;
		NewtonBodySetOmega (body, &omega[0]);*/

		/*
		float force[3];
		force[0] = 0.0f;
		force[1] = -9.8f;
		force[2] = 0.0f;
		NewtonBodyAddForce( body, &force[0] );
		*/

		world = physworld;
	}
Example #3
0
NewtonBody*	CPhysics::CreateRigidBody(NewtonWorld *world,  CObject3D *object, NewtonCollision *collision, float mass)
{
	object->UpdateMatrix();
	float matrix[16];
	object->matrixModel.FlattenToArray(matrix);
	Vector3 angles = object->rotation * ToRad;

	NewtonBody *body = NewtonCreateBody(world, collision, matrix);
	

	if (mass > 0)
	{
		float inertia[3], origin[3];
		NewtonConvexCollisionCalculateInertialMatrix (collision, &inertia[0], &origin[0]);	
		NewtonBodySetMassMatrix(body, mass, mass * inertia[0], mass * inertia[1], mass * inertia[2]);
		NewtonBodySetCentreOfMass(body, &origin[0]);
	}	

	NewtonBodySetUserData(body, object);
	NewtonBodySetTransformCallback(body, CPhysics::TransformCallback);
	NewtonBodySetDestructorCallback(body, CPhysics::DestroyBodyCallback);

	NewtonReleaseCollision(world, collision);
	
	return body;
}
Example #4
0
void CCamera::Initialiser(NewtonWorld *nWorld,CVector3 taille)
{
	// On initialise le vecteur de dimensions
   m_vTailleCollisionCam.x = taille.x;
   m_vTailleCollisionCam.y = taille.y;
   m_vTailleCollisionCam.z = taille.z;


   CMatrix matrice; // On créé une matrice
   matrice.setIdentite();

   // On définit la matrice de manière à ce que l'objet soit placé aux positions
   // spécifiées en utilisant la dernière colonne de la matrice
   matrice.m_Mat[3][0] = 0;
   matrice.m_Mat [3][1] = 0;
   matrice.m_Mat [3][2] = 0;

   // On initialise la boîte de collision
   NewtonCollision * collision = NULL;
   // On créé la boite de collision aux dimensions de l'objet
   collision = NewtonCreateBox (nWorld, m_vTailleCollisionCam.x, m_vTailleCollisionCam.y, m_vTailleCollisionCam.z, NULL);
   // On initialise le corps avec la boite de collision
   m_pBody = NewtonCreateBody (nWorld, collision);

   if (m_pBody == NULL)
      std::cerr << "Impossible d'initialiser le corps.";
   // On détruit la boite de collision, on n'en a plus besoin
   NewtonReleaseCollision (nWorld, collision);

   // Enfin, on affecte notre matrice (qui représente donc sa position dans l'espace)
   // à notre corps grâce à la fonction NewtonBodySetMatrix
   NewtonBodySetMatrix (m_pBody, &matrice.m_Mat [0][0]);
}
Example #5
0
NewtonBody* Body::create(NewtonCollision* collision, float mass, int freezeState, const Vec4f& damping)
{
	Vec4f minBox, maxBox;
	Vec4f origin, inertia;

	m_body = NewtonCreateBody(newton::world, collision, this->m_matrix[0]);

	NewtonBodySetUserData(m_body, this);
	NewtonBodySetMatrix(m_body, this->m_matrix[0]);
	NewtonConvexCollisionCalculateInertialMatrix(collision, &inertia[0], &origin[0]);

	if (mass < 0.0f)
		mass = NewtonConvexCollisionCalculateVolume(collision) * 0.5f;

	if (mass != 0.0f)
		NewtonBodySetMassMatrix(m_body, mass, mass * inertia.x, mass * inertia.y, mass * inertia.z);

	NewtonBodySetCentreOfMass(m_body, &origin[0]);

	NewtonBodySetForceAndTorqueCallback(m_body, Body::__applyForceAndTorqueCallback);
	NewtonBodySetTransformCallback(m_body, Body::__setTransformCallback);
	NewtonBodySetDestructorCallback(m_body, Body::__destroyBodyCallback);

	NewtonBodySetFreezeState(m_body, freezeState);
	NewtonBodySetLinearDamping(m_body, damping.w);
	NewtonBodySetAngularDamping(m_body, &damping[0]);

	return m_body;
}
void CollisionDetection::createConvexHull( Entity *entity, bool enemy )
{
    size_t vertex_count;
	size_t index_count;
	Ogre::Vector3 *vertices;
	unsigned long *indices;

    GetMeshInformation(   entity->getMesh(), vertex_count, vertices, index_count, indices,
                          Vector3( 0.0, 0.0, 0.0 ),//entity->getParentNode()->getPosition(),
                          Ogre::Quaternion::IDENTITY, //entity->getParentNode()->getOrientation()
                          Ogre::Vector3(1,1,1));//entity->getParentNode()->_getDerivedScale() );//Ogre::Vector3(1,1,1));

    dFloat *vertexCloud = new dFloat[vertex_count*3];
    for( int i = 0; i < vertex_count; i++ )
    {
        vertexCloud[i*3] = vertices[i].x;
        vertexCloud[i*3+1] = vertices[i].y;
        vertexCloud[i*3+2] = vertices[i].z;
    }
    shapeID++;
    NewtonCollision *newCol = NewtonCreateConvexHull (newtonWorld, vertex_count, vertexCloud, 12, 0.0, shapeID, NULL);
    if(enemy)
    {
        enemyEnt = newCol;
    }
    else
    {
        NewtonBody* rigidBodyBox = NewtonCreateBody (newtonWorld, newCol);
        //PROBLEM with the line as this comand should work, but terminates the app;Possibly a c++ issue
        //NewtonReleaseCollision( newtonWorld, enemyCol);
        collisionsMap.insert(pair<Entity*,NewtonCollision*>(entity,newCol));
        bodysMap.insert(pair<Entity*,NewtonBody*>(entity,rigidBodyBox));
    }
}
static void AddShatterEntity (DemoEntityManager* const scene, DemoMesh* const visualMesh, NewtonCollision* const collision, const ShatterEffect& shatterEffect, dVector location)
{
	dQuaternion rotation;
	SimpleShatterEffectEntity* const entity = new SimpleShatterEffectEntity (visualMesh, shatterEffect);
	entity->SetMatrix(*scene, rotation, location);
	entity->InterpolateMatrix (*scene, 1.0f);
	scene->Append(entity);

	dVector origin;
	dVector inertia;
	NewtonConvexCollisionCalculateInertialMatrix (collision, &inertia[0], &origin[0]);	

float mass = 10.0f;
int materialId = 0;

	dFloat Ixx = mass * inertia[0];
	dFloat Iyy = mass * inertia[1];
	dFloat Izz = mass * inertia[2];

	//create the rigid body
	dMatrix matrix (GetIdentityMatrix());
	matrix.m_posit = location;

	NewtonWorld* const world = scene->GetNewton();
	NewtonBody* const rigidBody = NewtonCreateBody (world, collision, &matrix[0][0]);


	entity->m_myBody = rigidBody;
	entity->m_myweight = dAbs (mass * DEMO_GRAVITY);

	// set the correct center of gravity for this body
	NewtonBodySetCentreOfMass (rigidBody, &origin[0]);

	// set the mass matrix
	NewtonBodySetMassMatrix (rigidBody, mass, Ixx, Iyy, Izz);

	// activate 
	//	NewtonBodyCoriolisForcesMode (blockBoxBody, 1);

	// save the pointer to the graphic object with the body.
	NewtonBodySetUserData (rigidBody, entity);

	// assign the wood id
	NewtonBodySetMaterialGroupID (rigidBody, materialId);

	//  set continue collision mode
	//	NewtonBodySetContinuousCollisionMode (rigidBody, continueCollisionMode);

	// set a destructor for this rigid body
	NewtonBodySetDestructorCallback (rigidBody, PhysicsBodyDestructor);

	// set the transform call back function
	NewtonBodySetTransformCallback (rigidBody, DemoEntity::SetTransformCallback);

	// set the force and torque call back function
	NewtonBodySetForceAndTorqueCallback (rigidBody, PhysicsApplyGravityForce);
}
Example #8
0
/*
=============
CMod_PhysicsEndBSPCollisionTree
=============
*/
void CMod_PhysicsEndBSPCollisionTree() {
	dVector worldMin, worldMax;
	
	NewtonTreeCollisionEndBuild (g_collision, 1);
	
	dMatrix worldMatrix (GetIdentityMatrix());
	g_rigidBody = NewtonCreateBody (g_world, g_collision);
	NewtonReleaseCollision (g_world, g_collision);
	
	NewtonBodySetMatrix (g_rigidBody, &worldMatrix[0][0]);
	
	NewtonCollisionCalculateAABB (g_collision, &worldMatrix[0][0], &worldMin[0], &worldMax[0]);
	NewtonSetWorldSize (g_world, &worldMin[0], &worldMax[0]);
}
Example #9
0
/**
*  @brief
*    Constructor
*/
BodyTerrain::BodyTerrain(PLPhysics::World &cWorld, uint32 nWidth, uint32 nHeight,
						 const float fTerrain[], const Vector3 &vBoxMin, const Vector3 &vBoxMax, const Vector3 &vScale) :
	PLPhysics::BodyTerrain(cWorld, static_cast<World&>(cWorld).CreateBodyImpl()),
	m_nWidth(nWidth),
	m_nHeight(nHeight),
	m_pfTerrain(fTerrain),
	m_vBoxMin(vBoxMin),
	m_vBoxMax(vBoxMax),
	m_vScale(vScale)
{
	// Deactivate the physics simulation if required
	const bool bSimulationActive = cWorld.IsSimulationActive();
	if (bSimulationActive)
		cWorld.SetSimulationActive(false);

	// Get the Newton physics world
	NewtonWorld *pNewtonWorld = static_cast<World&>(cWorld).GetNewtonWorld();

	// Create collision primitive
	NewtonCollision *pCollision = NewtonCreateUserMeshCollision(pNewtonWorld, m_vBoxMin, m_vBoxMax, this, MeshCollisionCollideCallback, UserMeshCollisionRayHitCallback, nullptr, nullptr, nullptr, 0);

	// Create the rigid body
	// [TODO] Remove this as soon as there's an up-to-date Linux version of Newton Game Dynamics available!
	#if (NEWTON_MAJOR_VERSION == 2) && (NEWTON_MINOR_VERSION >= 28)
		Newton::NewtonBody *pNewtonBody = NewtonCreateBody(pNewtonWorld, pCollision, Matrix4x4::Identity);
	#else
		Newton::NewtonBody *pNewtonBody = NewtonCreateBody(pNewtonWorld, pCollision);
	#endif
	NewtonReleaseCollision(pNewtonWorld, pCollision);

	// Initialize the Newton physics body
	static_cast<BodyImpl&>(GetBodyImpl()).InitializeNewtonBody(*this, *pNewtonBody, 0.0f);

	// Reactivate the physics simulation if required
	if (bSimulationActive)
		cWorld.SetSimulationActive(bSimulationActive);
}
Example #10
0
/*
=============
CMod_PhysicsAddEntity
=============
*/
void CMod_PhysicsAddEntity(sharedEntity_t * gEnt) {
	NewtonCollision* collision = NULL;
	NewtonBody* body = NULL;

	std::map<int, bspCmodel>::iterator it = bspModels.find (gEnt->s.modelindex);
	if ( it == bspModels.end() ) {
		return;
	}
	
	vec3_t inertia, com;
	dMatrix matrix (GetIdentityMatrix());
	bspCmodel* bmodel = &it->second;
	
	collision = NewtonCreateConvexHull (g_world, bmodel->vertices.size(), &bmodel->vertices[0].m_x, sizeof (dVector), 0.0f, &matrix[0][0]);
	body = NewtonCreateBody (g_world, collision);
	NewtonConvexCollisionCalculateVolume (collision);
	NewtonReleaseCollision (g_world, collision);
	
	bmodel->rigidBody = body;

	NewtonBodySetMaterialGroupID (body, defaultMaterialGroup);
	NewtonBodySetUserData (body, (void*)gEnt);
	NewtonBodySetDestructorCallback (body, PhysicsEntityDie);
	NewtonBodySetContinuousCollisionMode (body, 0);
	NewtonBodySetForceAndTorqueCallback (body, PhysicsEntityThink);
	NewtonBodySetTransformCallback (body, PhysicsEntitySetTransform);
	
	NewtonConvexCollisionCalculateInertialMatrix (collision, &inertia[0], &com[0]);
	NewtonBodySetCentreOfMass (body, &com[0]);
	
	VectorScale (inertia, 10.0f, inertia); // The inertia needs to be scaled by the mass.
	
	NewtonBodySetMassMatrix (body, 10.f, inertia[0], inertia[1], inertia[2]);
	
	matrix.m_posit.m_x = gEnt->s.origin[0] * UNITS_PER_METRE;
	matrix.m_posit.m_y = gEnt->s.origin[1] * UNITS_PER_METRE;
	matrix.m_posit.m_z = gEnt->s.origin[2] * UNITS_PER_METRE;
	NewtonBodySetMatrix (body, &matrix[0][0]);
	
	gEnt->s.pos.trType = TR_INTERPOLATE;
	VectorCopy (gEnt->s.origin, gEnt->s.pos.trBase);
	VectorCopy (gEnt->s.origin, gEnt->r.currentOrigin);
	
	gEnt->s.apos.trType = TR_INTERPOLATE;
	VectorCopy (gEnt->s.angles, gEnt->s.apos.trBase);
	VectorCopy (gEnt->s.angles, gEnt->r.currentAngles);
}
Example #11
0
void Newtonnode::initConvexHull(NewtonWorld *pWorld,const ion::video::Mesh& srcmesh,const float mass,
								const float Ixx,const float Iyy,const float Izz)
{
	if (pWorld==0) {
		ion::base::log("Newtonnode::initConvexHull()",ion::base::Error) << "No NewtonWorld pointer given\n";
		return;
	}

	if (!srcmesh.isValid()) {
		ion::base::log("Newtonnode::initConvexHull()",ion::base::Error) << "Source mesh is invalid\n";
		return;
	}

	if (!srcmesh.vertexstream().isMapped()) {
		ion::base::log("Newtonnode::initConvexHull()",ion::base::Error) << "source mesh \"" << srcmesh.objIdentifier() << " is not mapped!\n";
		return;
	}




	if ((m_pNewtonCollision!=0) && (m_pNewtonworld!=0))
		NewtonReleaseCollision(m_pNewtonworld,m_pNewtonCollision);

	float *pPoints;
	{
		pPoints=new float[3*srcmesh.vertexstream().capacity()];
		for (ion_uint32 v=0;v<srcmesh.vertexstream().capacity();++v) {
			const ion::math::Vector3f &rV=srcmesh.vertexstream().position(v);
			pPoints[v*3+0]=rV.x();
			pPoints[v*3+1]=rV.y();
			pPoints[v*3+2]=rV.z();
		}
	}

	m_pNewtonworld=pWorld;
	m_pNewtonCollision=NewtonCreateConvexHull(m_pNewtonworld,srcmesh.vertexstream().capacity(),pPoints,12,0);
	m_pBody=NewtonCreateBody(m_pNewtonworld,m_pNewtonCollision);
	NewtonBodySetUserData(m_pBody,this);
	NewtonBodySetMassMatrix(m_pBody,mass,Ixx,Iyy,Izz);
	NewtonReleaseCollision(m_pNewtonworld,m_pNewtonCollision);

	NewtonBodySetTransformCallback (m_pBody, physicsSetTransform);
	NewtonBodySetForceAndTorqueCallback (m_pBody, physicsApplyForceAndTorque);

	delete [] pPoints;
}
Example #12
0
Body::Body( World* W, OgreNewt::Collision* col, int bodytype ) 
{
	m_world = W;
	m_collision = col;
	m_type = bodytype;
	m_node = NULL;
	m_matid = NULL;
	
	m_userdata = NULL;

	m_forcecallback = NULL;
	m_transformcallback = NULL;

	m_body = NewtonCreateBody( m_world->getNewtonWorld(), col->getNewtonCollision() ); 

	NewtonBodySetUserData( m_body, this );
	NewtonBodySetDestructorCallback( m_body, newtonDestructor );
}
Example #13
0
NewtonBody* CreateRigidBody (NewtonWorld* world, Entity* ent, NewtonCollision* collision, dFloat mass)
{
	dVector minBox;
	dVector maxBox;
	dVector origin;
	dVector inertia;
	NewtonBody* body;
 
	// Now with the collision Shape we can crate a rigid body
	body = NewtonCreateBody (world, collision);
 
	// bodies can have a destructor. 
	// this is a function callback that can be used to destroy any local data stored 
	// and that need to be destroyed before the body is destroyed. 
	NewtonBodySetDestructorCallback (body, DestroyBodyCallback);
 
	// save the entity as the user data for this body
	nEWTONbODySetUserData (body, ent);
 
	// we need to set physics properties to this body
	dMatrix matrix (ent->m_curRotation, ent->m_curPosition);
	NewtonBodySetMatrix (body, &matrix[0][0]);
 
	// we need to set the proper center of mass and inertia matrix for this body
	// the inertia matrix calculated by this function does not include the mass.
	// therefore it needs to be multiplied by the mass of the body before it is used.
	NewtonConvexCollisionCalculateInertialMatrix (collision, &inertia[0], &origin[0]);	
 
	// set the body mass matrix
	NewtonBodySetMassMatrix (body, mass, mass * inertia.m_x, mass * inertia.m_y, mass * inertia.m_z);
 
	// set the body origin
	NewtonBodySetCentreOfMass (body, &origin[0]);
 
	// set the function callback to apply the external forces and torque to the body
	// the most common force is Gravity
	NewtonBodySetForceAndTorqueCallback (body, ApplyForceAndTorqueCallback);
 
	// set the function callback to set the transformation state of the graphic entity associated with this body 
	// each time the body change position and orientation in the physics world
	NewtonBodySetTransformCallback (body, SetTransformCallback);
 
	return body;
}
Example #14
0
void Car::initPhysics() {

    NewtonWorld * nWorld = this->controller->getWorld();
    NewtonCollision* collision;
    float mass = 900.0f;

    vector3df v1 = this->carNode->getBoundingBox().MinEdge;
    vector3df v2 = this->carNode->getBoundingBox().MaxEdge;

    dVector minBox(v1.X, v1.Y, v1.Z);
    dVector maxBox(v2.X, v2.Y, v2.Z);

    dVector size(maxBox - minBox);
    dVector origin((maxBox + minBox).Scale(0.5f));

    size.m_w = 1.0f;
    origin.m_w = 1.0f;

    dMatrix offset(GetIdentityMatrix());
    offset.m_posit = origin;

    collision = NewtonCreateBox(nWorld, size.m_x, size.m_y, size.m_z, 0, &offset[0][0]);

    dVector inertia;

    matrix4 m = this->carNode->getRelativeTransformation();
    NewtonConvexHullModifierSetMatrix(collision, m.pointer());
    NewtonBody * body = NewtonCreateBody(nWorld, collision, m.pointer());
    NewtonBodySetUserData(body, this);
    NewtonConvexCollisionCalculateInertialMatrix(collision, &inertia[0], &origin[0]);
    NewtonBodySetMassMatrix(body, mass, mass * inertia.m_x, mass * inertia.m_y, mass * inertia.m_z);
    NewtonBodySetCentreOfMass(body, &origin[0]);
    NewtonBodySetForceAndTorqueCallback(body, applyCarMoveForce);
    NewtonBodySetTransformCallback(body, applyCarTransform);
    int matId = NewtonMaterialGetDefaultGroupID(nWorld);
    NewtonMaterialSetCollisionCallback(nWorld, matId, matId, this, 0, applyCarCollisionForce);

    NewtonReleaseCollision(nWorld, collision);
    this->setCarBodyAndGravity(body, dVector(0,-10,0,0));
    this->setLocalCoordinates(this->createChassisMatrix());
}
Example #15
0
void Newtonnode::initCube(NewtonWorld *pWorld,const float xlength,const float ylength,const float zlength)
{
	if (pWorld==0) {
		ion::base::log("Newtonnode::initCube()",ion::base::Error) << "No NewtonWorld pointer given\n";
		return;
	}


	if ((m_pNewtonCollision!=0) && (m_pNewtonworld!=0))
		NewtonReleaseCollision(m_pNewtonworld,m_pNewtonCollision);

	m_pNewtonworld=pWorld;
	m_pNewtonCollision=NewtonCreateBox(m_pNewtonworld,xlength,ylength,zlength,0);
	m_pBody=NewtonCreateBody(m_pNewtonworld,m_pNewtonCollision);
	NewtonBodySetUserData(m_pBody,this);
	NewtonBodySetMassMatrix(m_pBody, 1.0f, 1.0f, 1.0f, 1.0f);
	NewtonReleaseCollision(m_pNewtonworld,m_pNewtonCollision);

	NewtonBodySetTransformCallback (m_pBody, physicsSetTransform);
	NewtonBodySetForceAndTorqueCallback (m_pBody, physicsApplyForceAndTorque);
}
Example #16
0
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
bool
PhysicsActor::attachBody(pCollisionShape_type _collision)
{
    // valid Newton collision primitives include the following:
    //   Null, Box, Sphere (ovoid), Cone, Capsule, Cylinder, ChamferCylinder,
    //   ConvexHull (not impl yet), CompoundCollision (not impl),
    //   TreeCollision (not impl yet), UserMesh (heightfield)



    m_pActor = NewtonCreateBody(dynamic_cast<PhysicsZone*>(m_pZone.get())->getZonePtr(), dynamic_cast<CollisionShape*>(_collision.get())->getShapePtr());
    NewtonReleaseCollision(dynamic_cast<PhysicsZone*>(m_pZone.get())->getZonePtr(), dynamic_cast<CollisionShape*>(_collision.get())->getShapePtr());

    // set the transform call back function
    NewtonBodySetTransformCallback(m_pActor, TransformCallback);
    NewtonBodySetForceAndTorqueCallback(m_pActor, ApplyForceAndTorqueCallback);
    NewtonBodySetAutoactiveCallback(m_pActor, ActivationStateCallback);

    //NewtonBodySetFreezeTreshold(m_pActor, 

    NewtonBodySetUserData(m_pActor, this);

    return true;
}
NewtonBody* dRigidbodyNodeInfo::CreateNewtonBody (NewtonWorld* const world, dScene* const scene, dScene::dTreeNode* const myNode) const
{
    // find the collision and crate a rigid body
    _ASSERTE (IsType (dRigidbodyNodeInfo::GetRttiType()));

    // attach the parent node as user data
    dScene::dTreeNode* parentNode = scene->FindParentByType(myNode, dSceneNodeInfo::GetRttiType());
    dSceneNodeInfo* sceneInfo = (dSceneNodeInfo*) scene->GetInfoFromNode(parentNode);

    dScene::dTreeNode* shapeNode = scene->FindChildByType (myNode, dCollisionNodeInfo::GetRttiType());
    _ASSERTE (shapeNode);
    dCollisionNodeInfo* collInfo = (dCollisionNodeInfo*) scene->GetInfoFromNode(shapeNode);

    dMatrix matrix (sceneInfo->CalculateOrthoMatrix());

    NewtonCollision* collision = collInfo->CreateNewtonCollision (world, scene, shapeNode);
    NewtonBody* body = NewtonCreateBody(world, collision, &matrix[0][0]);
    NewtonReleaseCollision(world, collision);

//	NewtonBodySetMatrix(body, &matrix[0][0]);

    NewtonBodySetUserData(body, parentNode);

    NewtonBodySetCentreOfMass(body, &m_centerOfMass[0]);
    NewtonBodySetMassMatrix(body, m_massMatrix.m_w, m_massMatrix.m_x, m_massMatrix.m_y, m_massMatrix.m_z);
    NewtonBodySetVelocity(body, &m_velocity[0]);
    NewtonBodySetOmega(body, &m_omega[0]);

    //dVector internalDamp(rigidBody->GetI);
    //NewtonBodySetLinearDamping(body, internalDamp);
    //dVariable* bodyType = rigidBody->FindVariable("rigidBodyType");
    //if (!bodyType || !strcmp (bodyType->GetString(), "default gravity")) {
    //	NewtonBodySetTransformCallback(body, DemoEntity::SetTransformCallback);
    //}
    return body;
}
static void CreateDebriPiece (const NewtonBody* sourceBody, NewtonMesh* mesh, dFloat volume)
{
	dFloat Ixx;
	dFloat Iyy;
	dFloat Izz;
	dFloat mass;
	dFloat shapeVolume;
	NewtonWorld* world;
	NewtonBody* rigidBody;
	NewtonCollision* collision;
	OGLMesh* meshInstance;
	SceneManager* system;
	RenderPrimitive* primitive;
	dVector inertia;
	dVector origin;
	dVector veloc;
	dVector omega;
	dMatrix matrix;

	world = NewtonBodyGetWorld (sourceBody);

	NewtonBodyGetMatrix (sourceBody, &matrix[0][0]);

	NewtonBodyGetMassMatrix (sourceBody, &mass, &Ixx, &Iyy, &Izz);

	// make a visual object
	meshInstance = new OGLMesh();

	meshInstance->BuildFromMesh (mesh);

	// create a visual geometry
	primitive = new RenderPrimitive (matrix, meshInstance);
	meshInstance->Release();

	// save the graphics system
	system = (SceneManager*) NewtonWorldGetUserData(world);
	system->AddModel (primitive);

	collision = NewtonCreateConvexHullFromMesh (world, mesh, 0.1f, DEBRI_ID);

	// calculate the moment of inertia and the relative center of mass of the solid
	shapeVolume = NewtonConvexCollisionCalculateVolume (collision);
	NewtonConvexCollisionCalculateInertialMatrix (collision, &inertia[0], &origin[0]);	

	mass = mass * shapeVolume / volume;
	Ixx = mass * inertia[0];
	Iyy = mass * inertia[1];
	Izz = mass * inertia[2];

	//create the rigid body
	rigidBody = NewtonCreateBody (world, collision);

	// set the correct center of gravity for this body
	NewtonBodySetCentreOfMass (rigidBody, &origin[0]);

	// set the mass matrix
	NewtonBodySetMassMatrix (rigidBody, mass, Ixx, Iyy, Izz);

	// save the pointer to the graphic object with the body.
	NewtonBodySetUserData (rigidBody, primitive);

	// assign the wood id
//	NewtonBodySetMaterialGroupID (rigidBody, NewtonBodyGetMaterialGroupID(source));

	// set continue collision mode
	NewtonBodySetContinuousCollisionMode (rigidBody, 1);

	// set a destructor for this rigid body
	NewtonBodySetDestructorCallback (rigidBody, PhysicsBodyDestructor);

	// set the transform call back function
	NewtonBodySetTransformCallback (rigidBody, PhysicsSetTransform);

	// set the force and torque call back function
	NewtonBodySetForceAndTorqueCallback (rigidBody, PhysicsApplyGravityForce);

	// set the matrix for both the rigid body and the graphic body
	NewtonBodySetMatrix (rigidBody, &matrix[0][0]);
	PhysicsSetTransform (rigidBody, &matrix[0][0], 0);

	NewtonBodyGetVelocity(sourceBody, &veloc[0]);
	NewtonBodyGetOmega(sourceBody, &omega[0]);
	veloc += omega * matrix.RotateVector(origin);

// for now so that I can see the body
veloc = dVector (0, 0, 0, 0);
//	omega = dVector (0, 0, 0, 0);

	NewtonBodySetVelocity(rigidBody, &veloc[0]);
	NewtonBodySetOmega(rigidBody, &omega[0]);

	NewtonReleaseCollision(world, collision);

}
Example #19
0
void AddDoubleSwingDoors (NewtonWorld* nWorld)
{
	dFloat mass;
	dFloat Ixx;
	dFloat Iyy;
	dFloat Izz;
	NewtonBody* link0;
	NewtonBody* link1;
	CustomHinge* joint;
	BoxPrimitive* visualObject;
	NewtonCollision* collision;

	dVector size (2.0f, 5.0f, 0.5f);

	// calculate a acurate momenet of inertia
	mass = 5.0f;
	Ixx = 0.7f * mass * (size.m_y * size.m_y + size.m_z * size.m_z) / 12.0f;
	Iyy = 0.7f * mass * (size.m_x * size.m_x + size.m_z * size.m_z) / 12.0f;
	Izz = 0.7f * mass * (size.m_x * size.m_x + size.m_y * size.m_y) / 12.0f;

	// create 100 tack of 10 boxes each
	dMatrix location (GetIdentityMatrix());
	location.m_posit.m_x = -2.0f; 
	location.m_posit.m_y =  3.0f; 
	location.m_posit.m_z = -2.0f; 

	// create a collision primitive to be shared by all links
	collision = NewtonCreateBox (nWorld, size.m_x, size.m_y, size.m_z, NULL); 

	// make first wing
	{
		// create the a graphic character (use a visualObject as our body
		visualObject = new BoxPrimitive (location, size);

		//create the rigid body
		link1 = NewtonCreateBody (nWorld, collision);

		// Set Material Id for this object
		NewtonBodySetMaterialGroupID (link1, woodID);

		// save the pointer to the graphic object with the body.
		NewtonBodySetUserData (link1, visualObject);

		// set a destrutor for this rigid body
		NewtonBodySetDestructorCallback (link1, PhysicsBodyDestructor);

		// set the tranform call back function
		NewtonBodySetTransformCallback (link1, PhysicsSetTransform);

		// set the force and torque call back funtion
		NewtonBodySetForceAndTorqueCallback (link1,PhysicsApplyGravityForce);

		// set the mass matrix
		NewtonBodySetMassMatrix (link1, mass, Ixx, Iyy, Izz);

		// set the matrix for tboth the rigid nody and the graphic body
		NewtonBodySetMatrix (link1, &location[0][0]);
		PhysicsSetTransform (link1, &location[0][0]);

		dVector pivot (location.m_posit);
		dVector pin (location.m_up);
		pivot.m_x += size.m_x * 0.5f;

		// connect these two bodies by a ball and sockect joint
		joint = new CustomHinge (pivot, pin, link1, NULL);

		joint->EnableLimits (true);
		joint->SetLimis (-30.0f * 3.1416f/180.0f, 30.0f * 3.1416f/180.0f); 
	}


	// make second wing
	{

		location.m_posit.m_x -= size.m_x;

		// create the a graphic character (use a visualObject as our body
		visualObject = new BoxPrimitive (location, size);

		//create the rigid body
		link0 = NewtonCreateBody (nWorld, collision);

		// Set Material Id for this object
		NewtonBodySetMaterialGroupID (link0, woodID);

		// save the pointer to the graphic object with the body.
		NewtonBodySetUserData (link0, visualObject);

		// set a destrutor for this rigid body
		NewtonBodySetDestructorCallback (link0, PhysicsBodyDestructor);

		// set the tranform call back function
		NewtonBodySetTransformCallback (link0, PhysicsSetTransform);

		// set the force and torque call back funtion
		NewtonBodySetForceAndTorqueCallback (link0,PhysicsApplyGravityForce);

		// set the mass matrix
		NewtonBodySetMassMatrix (link0, mass, Ixx, Iyy, Izz);

		// set the matrix for tboth the rigid nody and the graphic body
		NewtonBodySetMatrix (link0, &location[0][0]);
		PhysicsSetTransform (link0, &location[0][0]);

		dVector pivot (location.m_posit);
		dVector pin (location.m_up);
		pivot.m_x += size.m_x * 0.5f;

		// connect these two bodies by a ball and sockect joint
		//joint = NewtonConstraintCreateHinge (nWorld, &pivot.m_x, &pin.m_x, link0, link1);
		joint = new CustomHinge (pivot, pin, link0, link1);

		joint->EnableLimits (true);
		joint->SetLimis (-30.0f * 3.1416f/180.0f, 30.0f * 3.1416f/180.0f); 
	}

	// release the collision geometry when not need it
	NewtonReleaseCollision (nWorld, collision);
}
Example #20
0
void AddRollingBeats (NewtonWorld* nWorld)
{
	dFloat mass;
	dFloat Ixx;
	dFloat Iyy;
	dFloat Izz;
	NewtonBody* bar;
	NewtonCollision* collision;

	dMatrix location (GetIdentityMatrix());
	location.m_posit.m_x =  5.0f; 
	location.m_posit.m_y =  2.0f; 
	location.m_posit.m_z = -2.0f; 
	dVector size (10.0f, 0.25f, 0.25f);

	bar = NULL;
	// /////////////////////////////////////////////////////////////////////////////////////             
	//
	// create a bar and attach it to the world with a hinge with limits
	//
	// ////////////////////////////////////////////////////////////////////////////////////
	{
		CustomHinge* joint;
		RenderPrimitive* visualObject;

		// create the a graphic character (use a visualObject as our body
		visualObject = new CylinderPrimitive (location, size.m_y, size.m_x);

		// create a collision primitive to be shared by all links
		collision = NewtonCreateCylinder (nWorld, size.m_y, size.m_x, NULL); 

		// craete the bar body
		bar = NewtonCreateBody(nWorld, collision);
		NewtonReleaseCollision (nWorld, collision);

		// attach graphic object to the rigid body
		NewtonBodySetUserData(bar, visualObject);

		// set a destructor function
		NewtonBodySetDestructorCallback (bar, PhysicsBodyDestructor);

		// set the tranform call back function
		NewtonBodySetTransformCallback (bar, PhysicsSetTransform);

		// set the force and torque call back funtion
		NewtonBodySetForceAndTorqueCallback (bar,PhysicsApplyGravityForce);


		// calculate a acurate momenet of inertia
		mass = 5.0f;
		Ixx = 0.7f * mass * (size.m_y * size.m_y + size.m_z * size.m_z) / 12.0f;
		Iyy = 0.7f * mass * (size.m_x * size.m_x + size.m_z * size.m_z) / 12.0f;
		Izz = 0.7f * mass * (size.m_x * size.m_x + size.m_y * size.m_y) / 12.0f;

		// set the mass matrix
		NewtonBodySetMassMatrix (bar, mass, Ixx, Iyy, Izz);

		// set the matrix for both the rigid nody and the graphic body
		NewtonBodySetMatrix (bar, &location[0][0]);
		PhysicsSetTransform (bar, &location[0][0]);

		dVector pin (0.0f, 1.0f, 0.0f);
		dVector pivot (location.m_posit);
		pivot.m_x -= size.m_x * 0.5f;
  
		// connect these two bodies by a ball and sockect joint
		//joint = NewtonConstraintCreateHinge (nWorld, &pivot.m_x, &pin.m_x, link0, link1);
		joint = new CustomHinge (pivot, pin, bar, NULL);

		// no limits
		//joint->EnableLimits (true);
		//joint->SetAngleLimis (-30.0f * 3.1416f/180.0f, 30.0f * 3.1416f/180.0f); 
	}


	{
		// ////////////////////////////////////////////////////////////////////////////////////
		//
		// add a sliding visualObject with limits
		//
		NewtonBody* beat;
		CustomSlider* joint;
		RenderPrimitive* visualObject;
		dMatrix beatLocation (location);
		dVector beatSize (0.5f, 2.0f, 2.0f);

		beatLocation.m_posit.m_x += size.m_x * 0.25f;

		// create the a graphic character (use a visualObject as our body
		visualObject = new BoxPrimitive (beatLocation, beatSize);

		// create a collision primitive to be shared by all links
		collision = NewtonCreateBox (nWorld, beatSize.m_x, beatSize.m_y, beatSize.m_z, NULL); 

		beat = NewtonCreateBody(nWorld, collision);
		NewtonReleaseCollision (nWorld, collision);

			// attach graphic object to the rigid body
		NewtonBodySetUserData(beat, visualObject);

		// set a destyuctor function
		NewtonBodySetDestructorCallback (beat, PhysicsBodyDestructor);

		// set the tranform call back function
		NewtonBodySetTransformCallback (beat, PhysicsSetTransform);

		// set the force and torque call back funtion
		NewtonBodySetForceAndTorqueCallback (beat,PhysicsApplyGravityForce);


		// calculate a acurate momenet of inertia
		mass = 5.0f;
		Ixx = 0.7f * mass * (beatSize.m_y * beatSize.m_y + beatSize.m_z * beatSize.m_z) / 12.0f;
		Iyy = 0.7f * mass * (beatSize.m_x * beatSize.m_x + beatSize.m_z * beatSize.m_z) / 12.0f;
		Izz = 0.7f * mass * (beatSize.m_x * beatSize.m_x + beatSize.m_y * beatSize.m_y) / 12.0f;

		// set the mass matrix
		NewtonBodySetMassMatrix (beat, mass, Ixx, Iyy, Izz);

		// set the matrix for both the rigid nody and the graphic body
		NewtonBodySetMatrix (beat, &beatLocation[0][0]);
		PhysicsSetTransform (beat, &beatLocation[0][0]);

		// set the pivot relative for the first bar
		dVector pivot (beatLocation.m_posit); 
		dVector pin (beatLocation.m_front);
		joint = new CustomSlider (pivot, pin, beat, bar);

		// claculate the minimum and maximum limit for this joints
		dFloat minLimits = ((location.m_posit.m_x - beatLocation.m_posit.m_x) - size.m_x * 0.5f);
		dFloat maxLimits = ((location.m_posit.m_x - beatLocation.m_posit.m_x) + size.m_x * 0.5f);

		joint->EnableLimits(true);
		joint->SetLimis (minLimits, maxLimits); 
	}


	{
		// ////////////////////////////////////////////////////////////////////////////////////
		//
		// add a corkscrew visualObject with limits
		//
		// ////////////////////////////////////////////////////////////////////////////////////
		NewtonBody* beat;
		CustomCorkScrew* joint;
		RenderPrimitive* visualObject;
		dMatrix beatLocation (location);
		dVector beatSize (0.5f, 1.25f, 1.25f);

		beatLocation.m_posit.m_x -= size.m_x * 0.25f;

		// create the a graphic character (use a visualObject as our body
		//visualObject = new BoxPrimitive (beatLocation, beatSize);
		visualObject = new ChamferCylinderPrimitive (beatLocation, beatSize.m_y, beatSize.m_x);

		// create a collision primitive to be shared by all links
		collision = NewtonCreateChamferCylinder (nWorld, beatSize.m_y, beatSize.m_x, NULL); 

		beat = NewtonCreateBody(nWorld, collision);
		NewtonReleaseCollision (nWorld, collision);

			// attach graphic object to the rigid body
		NewtonBodySetUserData(beat, visualObject);

		// set a destyuctor function
		NewtonBodySetDestructorCallback (beat, PhysicsBodyDestructor);

		// set the tranform call back function
		NewtonBodySetTransformCallback (beat, PhysicsSetTransform);

		// set the force and torque call back funtion
		NewtonBodySetForceAndTorqueCallback (beat,PhysicsApplyGravityForce);


		// calculate a acurate momenet of inertia
		mass = 5.0f;
		Ixx = 0.7f * mass * (beatSize.m_y * beatSize.m_y + beatSize.m_z * beatSize.m_z) / 12.0f;
		Iyy = 0.7f * mass * (beatSize.m_x * beatSize.m_x + beatSize.m_z * beatSize.m_z) / 12.0f;
		Izz = 0.7f * mass * (beatSize.m_x * beatSize.m_x + beatSize.m_y * beatSize.m_y) / 12.0f;

		// set the mass matrix
		NewtonBodySetMassMatrix (beat, mass, Ixx, Iyy, Izz);

		// set the matrix for both the rigid nody and the graphic body
		NewtonBodySetMatrix (beat, &beatLocation[0][0]);
		PhysicsSetTransform (beat, &beatLocation[0][0]);

		// set the pivot relative for the first bar
		dVector pivot (beatLocation.m_posit); 
		dVector pin (beatLocation.m_front);
		joint = new CustomCorkScrew (pivot, pin, beat, bar);

		// claculate the minimum and maximum limit for this joints
		dFloat minLimits = ((location.m_posit.m_x - beatLocation.m_posit.m_x) - size.m_x * 0.5f);
		dFloat maxLimits = ((location.m_posit.m_x - beatLocation.m_posit.m_x) + size.m_x * 0.5f);

		joint->EnableLimits(true);
		joint->SetLimis (minLimits, maxLimits); 
	}


	{
		// ////////////////////////////////////////////////////////////////////////////////////
		//
		// add a universal joint visualObject with limits
		//
		// ////////////////////////////////////////////////////////////////////////////////////
		NewtonBody* beat;
		CustomUniversal* joint;
		RenderPrimitive* visualObject;
		dMatrix beatLocation (location);
		dVector beatSize (0.5f, 1.25f, 1.25f);

		beatLocation.m_posit.m_x -= size.m_x * 0.5f;

		// create the a graphic character (use a visualObject as our body
		//visualObject = new BoxPrimitive (beatLocation, beatSize);
		visualObject = new ChamferCylinderPrimitive (beatLocation, beatSize.m_y, beatSize.m_x);

		// create a collision primitive to be shared by all links
		collision = NewtonCreateChamferCylinder (nWorld, beatSize.m_y, beatSize.m_x, NULL); 

		beat = NewtonCreateBody(nWorld, collision);
		NewtonReleaseCollision (nWorld, collision);

			// attach graphic object to the rigid body
		NewtonBodySetUserData(beat, visualObject);

		// set a destyuctor function
		NewtonBodySetDestructorCallback (beat, PhysicsBodyDestructor);

		// set the tranform call back function
		NewtonBodySetTransformCallback (beat, PhysicsSetTransform);

		// set the force and torque call back funtion
		NewtonBodySetForceAndTorqueCallback (beat,PhysicsApplyGravityForce);


		// calculate a acurate momenet of inertia
		mass = 5.0f;
		Ixx = 0.7f * mass * (beatSize.m_y * beatSize.m_y + beatSize.m_z * beatSize.m_z) / 12.0f;
		Iyy = 0.7f * mass * (beatSize.m_x * beatSize.m_x + beatSize.m_z * beatSize.m_z) / 12.0f;
		Izz = 0.7f * mass * (beatSize.m_x * beatSize.m_x + beatSize.m_y * beatSize.m_y) / 12.0f;

		// set the mass matrix
		NewtonBodySetMassMatrix (beat, mass, Ixx, Iyy, Izz);

		// set the matrix for both the rigid nody and the graphic body
		NewtonBodySetMatrix (beat, &beatLocation[0][0]);
		PhysicsSetTransform (beat, &beatLocation[0][0]);

		// set the pivot relative for the first bar
		dVector pivot (beatLocation.m_posit); 
		dVector pin0 (beatLocation.m_front);
		dVector pin1 (beatLocation.m_up);
		// tell this joint to destroiy its local private data when destroyed
		joint = new CustomUniversal (pivot, pin0, pin1, beat, bar);
	}


	{
		// ////////////////////////////////////////////////////////////////////////////////////
		//
		// add a universal joint visualObject with limits
		//
		// ////////////////////////////////////////////////////////////////////////////////////
		NewtonBody* beat;
		CustomUniversal* joint;
		RenderPrimitive* visualObject;
		dMatrix beatLocation (location);
		dVector beatSize (0.5f, 1.25f, 1.25f);

		beatLocation.m_posit.m_x = size.m_x;

		// create the a graphic character (use a visualObject as our body
		//visualObject = new BoxPrimitive (beatLocation, beatSize);
		visualObject = new ChamferCylinderPrimitive (beatLocation, beatSize.m_y, beatSize.m_x);

		// create a collision primitive to be shared by all links
		collision = NewtonCreateChamferCylinder (nWorld, beatSize.m_y, beatSize.m_x, NULL); 

		beat = NewtonCreateBody(nWorld, collision);
		NewtonReleaseCollision (nWorld, collision);

			// attach graphic object to the rigid body
		NewtonBodySetUserData(beat, visualObject);

		// set a destyuctor function
		NewtonBodySetDestructorCallback (beat, PhysicsBodyDestructor);

		// set the tranform call back function
		NewtonBodySetTransformCallback (beat, PhysicsSetTransform);

		// set the force and torque call back funtion
		NewtonBodySetForceAndTorqueCallback (beat,PhysicsApplyGravityForce);


		// calculate a acurate momenet of inertia
		mass = 5.0f;
		Ixx = 0.7f * mass * (beatSize.m_y * beatSize.m_y + beatSize.m_z * beatSize.m_z) / 12.0f;
		Iyy = 0.7f * mass * (beatSize.m_x * beatSize.m_x + beatSize.m_z * beatSize.m_z) / 12.0f;
		Izz = 0.7f * mass * (beatSize.m_x * beatSize.m_x + beatSize.m_y * beatSize.m_y) / 12.0f;

		// set the mass matrix
		NewtonBodySetMassMatrix (beat, mass, Ixx, Iyy, Izz);

		// set the matrix for both the rigid nody and the graphic body
		NewtonBodySetMatrix (beat, &beatLocation[0][0]);
		PhysicsSetTransform (beat, &beatLocation[0][0]);

		// set the pivot relative for the first bar
		dVector pivot (beatLocation.m_posit); 
		dVector pin0 (beatLocation.m_front.Scale(-1.0f));
		dVector pin1 (beatLocation.m_up);
		// tell this joint to destroiy its local private data when destroyed
		joint = new CustomUniversal (pivot, pin0, pin1, beat, bar);
	}

}
Example #21
0
// create physics scene
void InitScene()
{
	BoxPrimitive* box;
	BoxPrimitive* floor;
	NewtonBody* boxBody;
	NewtonBody* floorBody; 
	NewtonCollision* collision;

	// create the newton world
	nWorld = NewtonCreate (PhysicsAlloc, PhysicsFree);

	// set the linear solver model for faster speed 
	NewtonSetSolverModel (nWorld, 8);

	// set the adpative friction model for faster speed 
	NewtonSetFrictionModel (nWorld, 1);


	// Set the termination function
	atexit(CleanUp); 

	// create the the floor graphic objects
	dVector size (100.0f, 2.0f, 100.0f);
	dMatrix location (GetIdentityMatrix());
	location.m_posit.m_y = -5.0f; 
	
	// create a box for floor 
	floor = new BoxPrimitive (location, size, g_floorTexture);


	// create the the floor collision, and body with default values
	collision = NewtonCreateBox (nWorld, size.m_x, size.m_y, size.m_z, NULL); 
	floorBody = NewtonCreateBody (nWorld, collision);
	NewtonReleaseCollision (nWorld, collision);


	// set the transformation for this rigid body
	NewtonBodySetMatrix (floorBody, &location[0][0]);

	// save the pointer to the graphic object with the body.
	NewtonBodySetUserData (floorBody, floor);

	// set a destrutor for this rigid body
	NewtonBodySetDestructorCallback (floorBody, PhysicsBodyDestructor);

	// set the initial size
	size = dVector(0.5f, 0.5f, 0.5f);

	// create the collision 
	collision = NewtonCreateBox (nWorld, size.m_x, size.m_y, size.m_z, NULL); 


	// create 100 stacks of 10 boxes each
	location.m_posit.m_x = -10.0f; 
	for (int k = 0; k < 10; k ++) { 
		location.m_posit.m_z =  0.0f; 
		for (int j = 0; j < 10; j ++) { 
			location.m_posit.m_y =  2.0f; 

			for (int i = 0; i < 10; i ++) {

				// create a graphic box
				box = new BoxPrimitive (location, size);

				//create the rigid body
				boxBody = NewtonCreateBody (nWorld, collision);

				// save the pointer to the graphic object with the body.
				NewtonBodySetUserData (boxBody, box);

				// set a destrutor for this rigid body
				NewtonBodySetDestructorCallback (boxBody, PhysicsBodyDestructor);

				// set the tranform call back function
				NewtonBodySetTransformCallback (boxBody, PhysicsSetTransform);

				// set the force and torque call back funtion
				NewtonBodySetForceAndTorqueCallback (boxBody, PhysicsApplyForceAndTorque);

				// set the mass matrix
				//NewtonBodySetMassMatrix (boxBody, 1.0f, 1.0f / 6.0f, 1.0f / 6.0f, 1.0f  / 6.0f);
				NewtonBodySetMassMatrix (boxBody, 1.0f, 1.0f, 1.0f, 1.0f);

				// set the matrix for tboth the rigid nody and the graphic body
				NewtonBodySetMatrix (boxBody, &location[0][0]);
				PhysicsSetTransform (boxBody, &location[0][0]);

				location.m_posit.m_y += size.m_y * 2.0f;
			}
			location.m_posit.m_z -= size.m_z * 4.0f; 	
		}
		location.m_posit.m_x += size.m_x * 4.0f; 
	}

	// release the collsion geometry when not need it
	NewtonReleaseCollision (nWorld, collision);

}
Example #22
0
// create a rope of boxes
void AddRope (NewtonWorld* nWorld)
{
	int i;
	dFloat mass;
	dFloat Ixx;
	dFloat Iyy;
	dFloat Izz;
	NewtonBody* link0;
	NewtonBody* link1;
	NewtonCustomJoint* joint;
	
	NewtonCollision* collision;
	RenderPrimitive* visualObject;


	dVector size (2.0f, 0.25f, 0.25f);

	// calculate a acurate momenet of inertia
	mass = 2.0f;
	Ixx = 0.7f * mass * (size.m_y * size.m_y + size.m_z * size.m_z) / 12.0f;
	Iyy = 0.7f * mass * (size.m_x * size.m_x + size.m_z * size.m_z) / 12.0f;
	Izz = 0.7f * mass * (size.m_x * size.m_x + size.m_y * size.m_y) / 12.0f;


	// create 100 tack of 10 boxes each
	//dMatrix location (GetIdentityMatrix());
	dMatrix location (dgRollMatrix(3.1426f * 0.5f));
	location.m_posit.m_y = 11.5f; 
	location.m_posit.m_z = -5.0f; 

	// create a collision primitive to be shared by all links
	collision = NewtonCreateCapsule (nWorld, size.m_y, size.m_x, NULL);
	link0 = NULL;

	// create a lon vertical rope with limits
	for (i = 0; i < 7; i ++) {
		// create the a graphic character (use a visualObject as our body
		visualObject = new CapsulePrimitive (location, size.m_y, size.m_x);

		//create the rigid body
		link1 = NewtonCreateBody (nWorld, collision);


		// add some damping to each link
		NewtonBodySetLinearDamping (link1, 0.2f);
		dVector angularDamp (0.2f, 0.2f, 0.2f);
		NewtonBodySetAngularDamping (link1, &angularDamp.m_x);

		// Set Material Id for this object
		NewtonBodySetMaterialGroupID (link1, woodID);

		// save the pointer to the graphic object with the body.
		NewtonBodySetUserData (link1, visualObject);

		// set a destrutor for this rigid body
		NewtonBodySetDestructorCallback (link1, PhysicsBodyDestructor);

		// set the tranform call back function
		NewtonBodySetTransformCallback (link1, PhysicsSetTransform);

		// set the force and torque call back funtion
		NewtonBodySetForceAndTorqueCallback (link1,PhysicsApplyGravityForce);

		// set the mass matrix
		NewtonBodySetMassMatrix (link1, mass, Ixx, Iyy, Izz);

		// set the matrix for tboth the rigid nody and the graphic body
		NewtonBodySetMatrix (link1, &location[0][0]);
		PhysicsSetTransform (link1, &location[0][0]);

		dVector pivot (location.m_posit);
		pivot.m_y += (size.m_x - size.m_y) * 0.5f;

		dFloat coneAngle = 2.0 * 3.1416f / 180.0f;
		dFloat twistAngle = 2.0 * 3.1416f / 180.0f;
		dVector pin (location.m_front.Scale (-1.0f));

		joint = new CustomConeLimitedBallAndSocket(twistAngle, coneAngle, pin, pivot, link1, link0);

		link0 = link1;
		location.m_posit.m_y -= (size.m_x - size.m_y);
	}


	// vrete a short horizontal rope with limits
	location = GetIdentityMatrix();
	location.m_posit.m_y = 2.5f; 
	location.m_posit.m_z = -7.0f; 
	link0 = NULL;
	for (i = 0; i < 3; i ++) {
		// create the a graphic character (use a visualObject as our body
		visualObject = new CapsulePrimitive (location, size.m_y, size.m_x);

		//create the rigid body
		link1 = NewtonCreateBody (nWorld, collision);

		// add some damping to each link
		NewtonBodySetLinearDamping (link1, 0.2f);
		dVector angularDamp (0.2f, 0.2f, 0.2f);
		NewtonBodySetAngularDamping (link1, &angularDamp.m_x);

		// Set Material Id for this object
		NewtonBodySetMaterialGroupID (link1, woodID);

		// save the pointer to the graphic object with the body.
		NewtonBodySetUserData (link1, visualObject);

		// make sure it is active
		NewtonWorldUnfreezeBody (nWorld, link1);
		//NewtonBodySetAutoFreeze (link1, 0);

		// set a destrutor for this rigid body
		NewtonBodySetDestructorCallback (link1, PhysicsBodyDestructor);

		// set the tranform call back function
		NewtonBodySetTransformCallback (link1, PhysicsSetTransform);

		// set the force and torque call back funtion
		NewtonBodySetForceAndTorqueCallback (link1,PhysicsApplyGravityForce);

		// set the mass matrix
		NewtonBodySetMassMatrix (link1, mass, Ixx, Iyy, Izz);

		// set the matrix for tboth the rigid nody and the graphic body
		NewtonBodySetMatrix (link1, &location[0][0]);
		PhysicsSetTransform (link1, &location[0][0]);

		dVector pivot (location.m_posit);
		pivot.m_x += (size.m_x - size.m_y) * 0.5f;

		dFloat coneAngle = 10.0 * 3.1416f / 180.0f;
		dFloat twistAngle = 10.0 * 3.1416f / 180.0f;
		dVector pin (location.m_front.Scale (-1.0f));
		joint = new CustomConeLimitedBallAndSocket(twistAngle, coneAngle, pin, pivot, link1, link0);

		link0 = link1;
		location.m_posit.m_x -= (size.m_x - size.m_y);
	}

	// release the collision geometry when not need it
	NewtonReleaseCollision (nWorld, collision);
}
static void BuildFloorAndSceneRoot (SceneManager& system)
{
	NewtonWorld* world;
	RenderPrimitive* floor;
	NewtonBody* floorBody;
	NewtonCollision* floorCollision;
	OGLMesh* meshInstance;

	world = system.m_world;
	// /////////////////////////////////////////////////////////////////////
	//
	// create the sky box,
	system.AddModel (new SkyBox ());


	// create the the floor graphic objects
	dVector floorSize (100.0f, 2.0f, 100.0f);
	dMatrix location (GetIdentityMatrix());
	location.m_posit.m_y = -5.0f; 

	// create a box for floor 
	floorCollision = NewtonCreateBox (world, floorSize.m_x, floorSize.m_y, floorSize.m_z, 0, NULL); 

	//	meshInstance = OGLMesh::MakeBox (world, size.m_x, size.m_y, size.m_z, "GrassAndDirt.tga");
	meshInstance = new OGLMesh (floorCollision, "GrassAndDirt.tga", "metal_30.tga", "metal_30.tga");
	floor = new RenderPrimitive (location, meshInstance);
	system.AddModel (floor);
	meshInstance->Release();

	// create the the floor collision, and body with default values
	floorBody = NewtonCreateBody (world, floorCollision);
	NewtonReleaseCollision (world, floorCollision);


	// set the transformation for this rigid body
	NewtonBodySetMatrix (floorBody, &location[0][0]);

	// save the pointer to the graphic object with the body.
	NewtonBodySetUserData (floorBody, floor);

	// set a destructor for this rigid body
	NewtonBodySetDestructorCallback (floorBody, PhysicsBodyDestructor);


	// get the default material ID
	int defaultID;
	defaultID = NewtonMaterialGetDefaultGroupID (world);

	// set default material properties
	NewtonMaterialSetDefaultSoftness (world, defaultID, defaultID, 0.05f);
	NewtonMaterialSetDefaultElasticity (world, defaultID, defaultID, 0.4f);
	NewtonMaterialSetDefaultCollidable (world, defaultID, defaultID, 1);
	NewtonMaterialSetDefaultFriction (world, defaultID, defaultID, 1.0f, 0.5f);
	NewtonMaterialSetCollisionCallback (world, defaultID, defaultID, NULL, NULL, GenericContactProcess); 

	//	NewtonMaterialSetSurfaceThickness(world, materialID, materialID, 0.1f);
	NewtonMaterialSetSurfaceThickness(world, defaultID, defaultID, 0.0f);

	// set the island update callback
	NewtonSetIslandUpdateEvent (world, PhysicsIslandUpdate);

	// save the callback
	SetDemoCallbacks (system);

	InitEyePoint (dVector (1.0f, 0.0f, 0.0f), dVector (-40.0f, 10.0f, 0.0f));
}
Example #24
0
Terrain::Terrain(const ion::base::String& identifier,NewtonWorld *pNewtonworld,ion::scene::Renderer& rRenderer,
		ion::base::Streamable& heightmap,const ion_uint32 width,const ion_uint32 depth,const ion_uint32 patchwidth,
		const ion_uint32 patchdepth,const ion::math::Vector3f& offset,const ion::math::Vector3f& size):
m_pNewtonworld(pNewtonworld),Node(identifier)
{
	ion_uint32 numpatchesX=(width-1)/(patchwidth-1),numpatchesZ=(depth-1)/(patchdepth-1);
	ion_uint16 *pHeightbuffer=new ion_uint16[(width+1)*(depth+1)];

	{
		ion_uint16 *pHLine=pHeightbuffer;
		for (ion_uint32 z=0;z<depth;++z) {
			heightmap.read(pHLine,width*sizeof(ion_uint16));

			// Copy the first height to the one extra height for correct normal vector calculations
			pHLine[width]=pHLine[0];

			pHLine+=(width+1);
		}
		// Copy the first line to the one extra line for correct normal vector calculations
		memcpy(pHeightbuffer+(width+1)*depth,pHeightbuffer,(width+1)*sizeof(ion_uint16));
	}

	const ion::math::Vector3f psize(
		size.x()/((float)numpatchesX),
		size.y(),
		size.z()/((float)numpatchesZ)
		);

	ion::math::Vector3f poffset(
		offset.x()/*-psize.x()*0.5f*/,
		offset.y(),
		offset.z()/*-psize.z()*0.5f*/
		);

	ion::base::Localfile serializefile;
	bool fileok=serializefile.open(serializefilename,"rb");
	if (fileok) {
		ion::base::log("Terrain::Terrain()",ion::base::Message) << "Using previously serialized terrain data\n";
		serializefile.open(serializefilename,"rb");
		m_pTreeCollision=NewtonCreateTreeCollisionFromSerialization(pNewtonworld,0,TerrainDeserialize,&serializefile);
		serializefile.close();
	} else {
		ion::base::log("Terrain::Terrain()",ion::base::Message) << "Calculating terrain data\n";
		m_pTreeCollision=NewtonCreateTreeCollision(pNewtonworld,0);
		NewtonTreeCollisionBeginBuild(m_pTreeCollision);
		{
			for (ion_uint32 z=0;z<(depth-1);++z) {
				/*float zz1=offset.z()+((float)z)/((float)(depth-1))*zsize;
				float zz2=offset.z()+((float)(z+1))/((float)(depth-1))*zsize;*/

				float zz1=offset.z()+( ((float)z)/((float)(patchdepth-1)) )*psize.z();
				float zz2=offset.z()+( ((float)(z+1))/((float)(patchdepth-1)) )*psize.z();

				unsigned int zT=(z/patchdepth)&1;
				for (ion_uint32 x=0;x<(width-1);++x) {
					float xx1=offset.x()+( ((float)x)/((float)(patchwidth-1)) )*psize.x();
					float xx2=offset.x()+( ((float)(x+1))/((float)(patchwidth-1)) )*psize.x();
					/*float xx1=offset.x()+((float)x)/((float)(width-1))*xsize;
					float xx2=offset.x()+((float)(x+1))/((float)(width-1))*xsize;*/

					float yy11=offset.y()+((float)(pHeightbuffer[x+z*(width+1)]))/65535.0f*size.y();
					float yy21=offset.y()+((float)(pHeightbuffer[x+1+z*(width+1)]))/65535.0f*size.y();
					float yy12=offset.y()+((float)(pHeightbuffer[x+(z+1)*(width+1)]))/65535.0f*size.y();
					float yy22=offset.y()+((float)(pHeightbuffer[x+1+(z+1)*(width+1)]))/65535.0f*size.y();

					float tri1[]={
						xx1,yy11,zz1,
						xx1,yy12,zz2,
						xx2,yy21,zz1
					};

					float tri2[]={
						xx2,yy21,zz1,
						xx1,yy12,zz2,
						xx2,yy22,zz2
					};

					unsigned int xT=(x/patchwidth)&1;

					unsigned int matID=((xT&zT)==1) ? 0 : (xT|zT);

					NewtonTreeCollisionAddFace(m_pTreeCollision,3,tri1,12,0);
					NewtonTreeCollisionAddFace(m_pTreeCollision,3,tri2,12,0);
				}
			}
		}
		NewtonTreeCollisionEndBuild(m_pTreeCollision,0);

		serializefile.open(serializefilename,"wb");
		NewtonTreeCollisionSerialize(m_pTreeCollision,TerrainSerialize,&serializefile);
		serializefile.close();
	}

	NewtonBody *pTerrainBody=NewtonCreateBody(m_pNewtonworld,m_pTreeCollision);
	NewtonReleaseCollision(m_pNewtonworld,m_pTreeCollision);
	NewtonBodySetMatrix(pTerrainBody,ion::math::Matrix4f::identitymatrix());

	for (ion_uint32 z=0;z<numpatchesZ;++z) {

		/*if (z==0) {
			heightmap.read(pHeightbuffer,sizeof(ion_uint16)*width*patchdepth);
		} else {
			memcpy(pHeightbuffer,pHeightbuffer+width*(patchdepth-1),width*sizeof(ion_uint16));
			heightmap.read(pHeightbuffer+width,sizeof(ion_uint16)*width*(patchdepth-1));
		}*/

		poffset.x()=offset.x()/*-psize.x()*0.5f*/;

		for (ion_uint32 x=0;x<numpatchesX;++x) {
			ion_uint16 *pH=pHeightbuffer+x*(patchwidth-1)+z*(width+1)*(patchdepth-1);
			TerrainPatch *pPatch=new TerrainPatch("tpatch",rRenderer,pH,patchwidth,width+1,patchdepth,
				(z==(numpatchesZ-1)),poffset,psize);

			poffset.x()+=psize.x();
			m_Patches.push_back(pPatch);
			addChild(*pPatch);
		}

		poffset.z()+=psize.z();
	}

	delete [] pHeightbuffer;
}
int CustomMultiBodyVehicle::AddSingleSuspensionTire (
    void* userData,
    const dVector& localPosition,
    dFloat mass,
    dFloat radius,
    dFloat width,
    dFloat suspensionLength,
    dFloat springConst,
    dFloat springDamper)
{
    dFloat Ixx;
    dFloat Iyy;
    dFloat Izz;
    dMatrix carMatrix;
    NewtonBody* tire;
    NewtonWorld* world;
    NewtonCollision *collision;

    world = NewtonBodyGetWorld(GetBody0());

    // create the tire RogidBody
    collision = NewtonCreateChamferCylinder(world, radius, width, 0, NULL);

    //create the rigid body
    tire = NewtonCreateBody (world, collision);

    // release the collision
    NewtonReleaseCollision (world, collision);

    // save the user data
    NewtonBodySetUserData (tire, userData);

    // set the material group id for vehicle
    NewtonBodySetMaterialGroupID (tire, 0);
//	NewtonBodySetMaterialGroupID (tire, woodID);

    // set the force and torque call back function
    NewtonBodySetForceAndTorqueCallback (tire, NewtonBodyGetForceAndTorqueCallback (GetBody0()));

    // body part do not collision
    NewtonBodySetJointRecursiveCollision (tire, 0);

    // calculate the moment of inertia and the relative center of mass of the solid
    dVector origin;
    dVector inertia;
    NewtonConvexCollisionCalculateInertialMatrix (collision, &inertia[0], &origin[0]);
    Ixx = mass * inertia[0];
    Iyy = mass * inertia[1];
    Izz = mass * inertia[2];

    // set the mass matrix
    NewtonBodySetMassMatrix (tire, mass, Ixx, Iyy, Izz);

    // calculate the tire local base pose matrix
    dMatrix tireMatrix;
    tireMatrix.m_front = m_localFrame.m_right;
    tireMatrix.m_up = m_localFrame.m_up;
    tireMatrix.m_right = tireMatrix.m_front * tireMatrix.m_up;
    tireMatrix.m_posit = localPosition;
    NewtonBodyGetMatrix(GetBody0(), &carMatrix[0][0]);
    tireMatrix = tireMatrix * carMatrix;

    // set the matrix for both the rigid body and the graphic body
    NewtonBodySetMatrix (tire, &tireMatrix[0][0]);

    // add a single tire
    m_tires[m_tiresCount] = new CustomMultiBodyVehicleTire (GetBody0(), tire, suspensionLength, springConst, springDamper, radius);
    m_tiresCount ++;

    return m_tiresCount - 1;
}
Example #26
0
Car::Car(const ion::base::String& identifier,NewtonWorld *pWorld,const ion::video::Mesh& srcmesh,const float mass,
		 const float Ixx,const float Iyy,const float Izz):Node(identifier),m_pNewtonChassisCollision(0),m_pBody(0),
		 m_pNewtonworld(pWorld),m_pNewtonJoint(0)
{
	if (pWorld==0) {
		ion::base::log("Car::Car()",ion::base::Error) << "No NewtonWorld pointer given\n";
		return;
	}

	if (!srcmesh.isValid()) {
		ion::base::log("Car::Car()",ion::base::Error) << "Source mesh is invalid\n";
		return;
	}

	if (!srcmesh.vertexstream().isMapped()) {
		ion::base::log("Car::Car()",ion::base::Error) << "source mesh \"" << srcmesh.objIdentifier() << " is not mapped!\n";
		return;
	}


	if ((m_pNewtonChassisCollision!=0) && (m_pNewtonworld!=0))
		NewtonReleaseCollision(m_pNewtonworld,m_pNewtonChassisCollision);

	float *pPoints;
	{
		pPoints=new float[3*srcmesh.vertexstream().capacity()];
		for (ion_uint32 v=0;v<srcmesh.vertexstream().capacity();++v) {
			const ion::math::Vector3f &rV=srcmesh.vertexstream().position(v);
			pPoints[v*3+0]=rV.x();
			pPoints[v*3+1]=rV.y();
			pPoints[v*3+2]=rV.z();
		}
	}

	ion::math::Matrix4f c;

	m_pNewtonworld=pWorld;
	m_pNewtonChassisCollision=NewtonCreateConvexHull(m_pNewtonworld,srcmesh.vertexstream().capacity(),pPoints,12,c);
	m_pBody=NewtonCreateBody(m_pNewtonworld,m_pNewtonChassisCollision);
	NewtonBodySetUserData(m_pBody,this);

	ion::math::Vector3f origin,inertia;

	// calculate the moment of inertia and the relative center of mass of the solid
	NewtonConvexCollisionCalculateInertialMatrix (m_pNewtonChassisCollision, &inertia[0], &origin[0]);	

	float ixx = mass * inertia[0];
	float iyy = mass * inertia[1];
	float izz = mass * inertia[2];

	// set the mass matrix
	NewtonBodySetMassMatrix (m_pBody, mass, ixx, iyy, izz);

	origin.y()=-1;
	NewtonBodySetCentreOfMass (m_pBody, &origin[0]);

	NewtonBodySetMatrix(m_pBody,localTransform().matrix());

	NewtonReleaseCollision(m_pNewtonworld,m_pNewtonChassisCollision);

	NewtonBodySetTransformCallback (m_pBody, physicsSetTransform);
	NewtonBodySetForceAndTorqueCallback (m_pBody, physicsApplyForceAndTorque);

	float updir[3]={0,1,0};

	m_pNewtonJoint=NewtonConstraintCreateVehicle(m_pNewtonworld,&updir[0],m_pBody);
	NewtonVehicleSetTireCallback(m_pNewtonJoint,tireUpdate);

	delete [] pPoints;
}
Example #27
0
bool Physics::buildStaticGeometry( osg::Group* p_root, const std::string& levelFile )
{
    NewtonCollision* p_collision = NULL;

    // check if a serialization file exists, if so then load it. otherwise build the static geometry on the fly.
    assert( levelFile.length() && "internal error: missing levelFile name!" );
    std::string file = cleanPath( levelFile );
    std::vector< std::string > path;
    explode( file, "/", &path );
    file = yaf3d::Application::get()->getMediaPath() + YAF3DPHYSICS_MEDIA_FOLDER + path[ path.size() - 1 ] + YAF3DPHYSICS_SERIALIZE_POSTFIX;
    std::ifstream serializationfile;
    serializationfile.open( file.c_str(), std::ios_base::binary | std::ios_base::in );
    if ( !serializationfile )
    {
        log_warning << "Physics: no serialization file for physics static geometry exists, building on-the-fly ..." << std::endl;

        p_collision = NewtonCreateTreeCollision( _p_world, levelCollisionCallback );
        NewtonTreeCollisionBeginBuild( p_collision );

        // build the collision faces
        //--------------------------
        // start timer
        osg::Timer_t start_tick = osg::Timer::instance()->tick();
        //! iterate through all geometries and create their collision faces
        PhysicsVisitor physVisitor( osg::NodeVisitor::TRAVERSE_ALL_CHILDREN, p_collision );
        p_root->accept( physVisitor );
        // stop timer and give out the time messure
        osg::Timer_t end_tick = osg::Timer::instance()->tick();
        log_debug << "Physics: elapsed time for building physics collision faces = "<< osg::Timer::instance()->delta_s( start_tick, end_tick ) << std::endl;
        log_debug << "Physics:  total num of evaluated primitives: " << physVisitor.getNumPrimitives() << std::endl;
        log_debug << "Physics:  total num of vertices: " << physVisitor.getNumVertices() << std::endl;

        //--------------------------
        // finalize tree building with optimization off ( because the meshes are already optimized by
        //  osg _and_ Newton has currently problems with optimization )
        NewtonTreeCollisionEndBuild( p_collision, 0 /* 1 */);
    }
    else
    {
        log_debug << "Physics: loading serialization file for physics static geometry: '" << file << "' ..." << std::endl;

        // start timer
        osg::Timer_t start_tick = osg::Timer::instance()->tick();

        p_collision = NewtonCreateTreeCollisionFromSerialization( _p_world, NULL, deserializationCallback, &serializationfile );
        assert( p_collision && "internal error, something went wrong during physics deserialization!" );

        // stop timer and give out the time messure
        osg::Timer_t end_tick = osg::Timer::instance()->tick();
        log_debug << "Physics: elapsed time for deserializing physics collision faces = "<< osg::Timer::instance()->delta_s( start_tick, end_tick ) << std::endl;

        serializationfile.close();
    }

    _p_body = NewtonCreateBody( _p_world, p_collision );

    // release collision object
    NewtonReleaseCollision( _p_world, p_collision );

    // set Material Id for this object
    NewtonBodySetMaterialGroupID( _p_body, getMaterialId( "level" ) );

    osg::Matrixf mat;
    mat.identity();
    NewtonBodySetMatrix( _p_body, mat.ptr() );

    // calculate the world bbox and world size
    float  bmin[ 4 ], bmax[ 4 ];
    NewtonCollisionCalculateAABB( p_collision, mat.ptr(), bmin, bmax );
    bmin[ 0 ] -= 10.0f;
    bmin[ 1 ] -= 10.0f;
    bmin[ 2 ] -= 10.0f;
    bmin[ 3 ] = 1.0f;
    bmax[ 0 ] += 10.0f;
    bmax[ 1 ] += 10.0f;
    bmax[ 2 ] += 10.0f;
    bmax[ 3 ] = 1.0f;
    NewtonSetWorldSize( _p_world, bmin, bmax );

    return true;
}
	void SimulationLister(DemoEntityManager* const scene, DemoEntityManager::dListNode* const mynode, dFloat timeStep)
	{
		m_delay --;
		if (m_delay > 0) {
			return;
		}

		// see if the net force on the body comes fr a high impact collision
		dFloat maxInternalForce = 0.0f;
		for (NewtonJoint* joint = NewtonBodyGetFirstContactJoint(m_myBody); joint; joint = NewtonBodyGetNextContactJoint(m_myBody, joint)) {
			for (void* contact = NewtonContactJointGetFirstContact (joint); contact; contact = NewtonContactJointGetNextContact (joint, contact)) {
				//dVector point;
				//dVector normal;	
				dVector contactForce;
				NewtonMaterial* const material = NewtonContactGetMaterial (contact);
				//NewtonMaterialGetContactPositionAndNormal (material, &point.m_x, &normal.m_x);
				NewtonMaterialGetContactForce(material, m_myBody, &contactForce[0]);
				dFloat forceMag = contactForce % contactForce;
				if (forceMag > maxInternalForce) {
					maxInternalForce = forceMag;
				}
			}
		}

		

		// if the force is bigger than 4 Gravities, It is considered a collision force
		dFloat maxForce = BREAK_FORCE_IN_GRAVITIES * m_myweight;

		if (maxInternalForce > (maxForce * maxForce)) {
			NewtonWorld* const world = NewtonBodyGetWorld(m_myBody);

			dFloat Ixx; 
			dFloat Iyy; 
			dFloat Izz; 
			dFloat mass; 
			NewtonBodyGetMassMatrix(m_myBody, &mass, &Ixx, &Iyy, &Izz);

			dVector com;
			dVector veloc;
			dVector omega;
			dMatrix bodyMatrix;

			NewtonBodyGetVelocity(m_myBody, &veloc[0]);
			NewtonBodyGetOmega(m_myBody, &omega[0]);
			NewtonBodyGetCentreOfMass(m_myBody, &com[0]);
			NewtonBodyGetMatrix(m_myBody, &bodyMatrix[0][0]);
			com = bodyMatrix.TransformVector (com);

			dMatrix matrix (GetCurrentMatrix());
			dQuaternion rotation (matrix);
			for (ShatterEffect::dListNode* node = m_effect.GetFirst(); node; node = node->GetNext()) {
				ShatterAtom& atom = node->GetInfo();

				DemoEntity* const entity = new DemoEntity (NULL);
				entity->SetMesh (atom.m_mesh);
				entity->SetMatrix(*scene, rotation, matrix.m_posit);
				entity->InterpolateMatrix (*scene, 1.0f);
				scene->Append(entity);

				int materialId = 0;

				dFloat debriMass = mass * atom.m_massFraction;
				dFloat Ixx = debriMass * atom.m_momentOfInirtia.m_x;
				dFloat Iyy = debriMass * atom.m_momentOfInirtia.m_y;
				dFloat Izz = debriMass * atom.m_momentOfInirtia.m_z;

				//create the rigid body
				NewtonBody* const rigidBody = NewtonCreateBody (world, atom.m_collision, &matrix[0][0]);

				// set the correct center of gravity for this body
				NewtonBodySetCentreOfMass (rigidBody, &atom.m_centerOfMass[0]);

				// calculate the center of mas of the debris
				dVector center (matrix.TransformVector(atom.m_centerOfMass));

				// calculate debris initial velocity
				dVector v (veloc + omega * (center - com));

				// set initial velocity
				NewtonBodySetVelocity(rigidBody, &v[0]);
				NewtonBodySetOmega(rigidBody, &omega[0]);

				// set the  debrie center of mass
				NewtonBodySetCentreOfMass (rigidBody, &atom.m_centerOfMass[0]);


				// set the mass matrix
				NewtonBodySetMassMatrix (rigidBody, debriMass, Ixx, Iyy, Izz);

				// activate 
				//	NewtonBodyCoriolisForcesMode (blockBoxBody, 1);

				// save the pointer to the graphic object with the body.
				NewtonBodySetUserData (rigidBody, entity);

				// assign the wood id
				NewtonBodySetMaterialGroupID (rigidBody, materialId);

				//  set continue collision mode
				//	NewtonBodySetContinuousCollisionMode (rigidBody, continueCollisionMode);

				// set a destructor for this rigid body
				NewtonBodySetDestructorCallback (rigidBody, PhysicsBodyDestructor);

				// set the transform call back function
				NewtonBodySetTransformCallback (rigidBody, DemoEntity::SetTransformCallback);

				// set the force and torque call back function
				NewtonBodySetForceAndTorqueCallback (rigidBody, PhysicsApplyGravityForce);
			}

			NewtonDestroyBody(world, m_myBody);
			scene->RemoveEntity	(mynode);
		}
	};
void CollisionDetection::addStaticTreeCollisionMesh( Entity *entity, string name)
{
    bool meshCreated = false;
    NewtonCollision *treeCollision;

    std::stringstream out;
    out << name;

    string fileString = ConstManager::getString("cmesh_file_path");
    fileString += out.str();
    fileString.append(".cmesh");
    cout << fileString<<endl;
    char *fileName = (char*) fileString.c_str();

    if( !gernerateMeshes )
    {
        FILE* meshFile;
        meshFile = fopen(fileName,"r");
        if (meshFile!=NULL)
        {
            treeCollision = NewtonCreateCollisionFromSerialization (newtonWorld, myDeserializeCollisionCallbackFunction, meshFile);
            fclose (meshFile);
            meshCreated = true;
        }
        else
        {
            cout << "Colision detection could not read file.\nAttempting to create mesh from scratch" << endl;
        }
    }

    if( !meshCreated )
    {
        treeCollision = NewtonCreateTreeCollision (newtonWorld, 0);
        NewtonTreeCollisionBeginBuild(treeCollision);

        size_t vertex_count;
        size_t index_count;
        Ogre::Vector3 *vertices;
        unsigned long *indices;

        GetMeshInformation(   entity->getMesh(), vertex_count, vertices, index_count, indices,
                              entity->getParentNode()->getPosition(),
                              entity->getParentNode()->getOrientation(),
                              entity->getParentNode()->_getDerivedScale());

    /*                               Ogre::Vector3(),
                                  Ogre::Quaternion::IDENTITY,
                                  Ogre::Vector3(1,1,1)); */
        dFloat vArray[9];
        int i0, i1, i2;
        for (int i = 0; i < static_cast<int>(index_count); i += 3)
        {
            i0 = indices[i];
            i1 = indices[i+1];
            i2 = indices[i+2];

            vArray[0] = vertices[i0].x;
            vArray[1] = vertices[i0].y;
            vArray[2] = vertices[i0].z;

            vArray[3] = vertices[i1].x;
            vArray[4] = vertices[i1].y;
            vArray[5] = vertices[i1].z;

            vArray[6] = vertices[i2].x;
            vArray[7] = vertices[i2].y;
            vArray[8] = vertices[i2].z;

             NewtonTreeCollisionAddFace(treeCollision, 3, vArray,
                        sizeof(dFloat)*3, i);
        }

        NewtonTreeCollisionEndBuild(treeCollision, 1);

        FILE* meshFile;
        meshFile = fopen(fileName,"w");
        if (meshFile!=NULL)
        {
            NewtonCollisionSerialize(newtonWorld, treeCollision, mySerializeCollisionCallbackFunction, meshFile);
            fclose (meshFile);
        }
        else
        {
            cout << "Colision detection could not write cmesh file." << endl;
        }
    }

    NewtonBody* rigidTree = NewtonCreateBody (newtonWorld, treeCollision);
    NewtonReleaseCollision (newtonWorld, treeCollision);

    NewtonBodySetMatrix (rigidTree, &idmatrix[0]);

    dFloat boxP0[3];
    dFloat boxP1[3];

    //possibly need this if we rely on newton
    //NewtonCollisionCalculateAABB (treeCollision, &idmatrix[0], &boxP0[0], &boxP1[0]);

    collisionsMap.insert(pair<Entity*,NewtonCollision*>(entity,treeCollision));
    bodysMap.insert(pair<Entity*,NewtonBody*>(entity,rigidTree));
}