コード例 #1
0
ファイル: apex.cpp プロジェクト: schulchr/Olympus
void Apex::LoadDynamicTriangleMesh(int numVerts, PxVec3* verts, ObjectInfo info)
{
	PxRigidDynamic* meshActor = mPhysics->createRigidDynamic(PxTransform::createIdentity());
	PxShape* meshShape, *convexShape;
	if(meshActor)
	{
		//meshActor->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, true);

		PxTriangleMeshDesc meshDesc;
		meshDesc.points.count           = numVerts;
		meshDesc.points.stride          = sizeof(PxVec3);
		meshDesc.points.data            = verts;

		//meshDesc.triangles.count        = numInds/3.;
		//meshDesc.triangles.stride       = 3*sizeof(int);
		//meshDesc.triangles.data         = inds;

		PxToolkit::MemoryOutputStream writeBuffer;
		bool status = mCooking->cookTriangleMesh(meshDesc, writeBuffer);
		if(!status)
			return;

		PxToolkit::MemoryInputData readBuffer(writeBuffer.getData(), writeBuffer.getSize());

		PxTriangleMeshGeometry triGeom;
		triGeom.triangleMesh = mPhysics->createTriangleMesh(readBuffer);
		//triGeom.scale = PxMeshScale(PxVec3(info.sx,info.sy,info.sz),physx::PxQuat::createIdentity());
		
		meshShape = meshActor->createShape(triGeom, *defaultMaterial);
		//meshShape->setLocalPose(PxTransform(PxVec3(info.x,info.y,info.z)));
		meshShape->setFlag(PxShapeFlag::eUSE_SWEPT_BOUNDS, true);

		PxConvexMeshDesc convexDesc;
		convexDesc.points.count     = numVerts;
		convexDesc.points.stride    = sizeof(PxVec3);
		convexDesc.points.data      = verts;
		convexDesc.flags            = PxConvexFlag::eCOMPUTE_CONVEX;

		if(!convexDesc.isValid())
			return;
		PxToolkit::MemoryOutputStream buf;
		if(!mCooking->cookConvexMesh(convexDesc, buf))
			return;
		PxToolkit::MemoryInputData input(buf.getData(), buf.getSize());
		PxConvexMesh* convexMesh = mPhysics->createConvexMesh(input);
		PxConvexMeshGeometry convexGeom = PxConvexMeshGeometry(convexMesh);
		convexShape = meshActor->createShape(convexGeom, *defaultMaterial);
		//convexShape->setLocalPose(PxTransform(PxVec3(info.x,info.y,info.z)));
		//convexShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false);

		
		convexShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, true);
		meshShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false);
		meshActor->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, false);

		meshActor->setGlobalPose(PxTransform(PxVec3(info.x,info.y,info.z), PxQuat(info.ry, PxVec3(0.0f,1.0f,0.0f))));
		mScene[mCurrentScene]->addActor(*meshActor);
		dynamicActors.push_back(meshActor);
	}
}
コード例 #2
0
ファイル: LabScaleImpacts.cpp プロジェクト: nmovshov/ARSS_win
void labscale::CreateRegolithContainer()
{
    // Geometry variables
    PxReal box_d = labscale::reg_box.diameter;
    PxReal box_h = labscale::reg_box.fillHeight*2;
    PxReal wall_dh = box_d/20;

    // We'll make the regolith container with a kinematic actor
    PxRigidDynamic* theBox = gPhysX.mPhysics->createRigidDynamic(PxTransform(PxVec3(0,0.05*wall_dh,0)));
    if (!theBox)
        ncc__error("Actor creation failed!");
    theBox->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, true);

    // Define sides
    PxBoxGeometry box_bottom(box_d/2,wall_dh/2,box_d/2);
    PxBoxGeometry box_side(wall_dh/2,box_h/2,box_d/2);
    PxMaterial* defmat=gPhysX.mDefaultMaterial;

    // Attach the sides, making front wall invisible
    theBox->createShape(box_bottom,*defmat,PxTransform(PxVec3(0,wall_dh/2,0))); // the bottom
    theBox->createShape(box_side,*defmat,PxTransform(PxVec3(-box_d/2,box_h/2,0),PxQuat(0,PxVec3(0,1,0)))); // left wall
    theBox->createShape(box_side,*defmat,PxTransform(PxVec3( box_d/2,box_h/2,0),PxQuat(0,PxVec3(0,1,0)))); // right wall
    theBox->createShape(box_side,*defmat,PxTransform(PxVec3(0,box_h/2,-box_d/2),PxQuat(PxPi/2,PxVec3(0,1,0)))); // back wall
    PxShape* fwall =  theBox->createShape(box_side,*defmat,PxTransform(PxVec3(0,box_h/2, box_d/2),PxQuat(PxPi/2,PxVec3(0,1,0)))); // front wall
    fwall->setName("~fwall");

    // Name, color, and register the container
    theBox->setName("the_box");
    ColorActor(theBox, ncc::rgb::rRed);
    gPhysX.mScene->addActor(*theBox);
    labscale::VIPs.container = theBox;

}
コード例 #3
0
PxRigidDynamic* Vehicle::createVehicleActor(const PxVehicleChassisData& chassisData,
	PxMaterial** wheelMaterials, PxConvexMesh** wheelConvexMeshes, const PxU32 numWheels,
	PxMaterial** chassisMaterials, PxConvexMesh** chassisConvexMeshes, const PxU32 numChassisMeshes, PxPhysics& physics, PxVec3 initPos)
{
	//We need a rigid body actor for the vehicle.
	//Don't forget to add the actor to the scene after setting up the associated vehicle.
	PxRigidDynamic* vehActor = physics.createRigidDynamic(PxTransform(initPos));
	vehActor->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_CCD, true);

	//Wheel and chassis simulation filter data.
	PxFilterData wheelSimFilterData;
	wheelSimFilterData.word0 = COLLISION_FLAG_WHEEL;
	wheelSimFilterData.word1 = COLLISION_FLAG_WHEEL_AGAINST;
	PxFilterData chassisSimFilterData;
	chassisSimFilterData.word0 = COLLISION_FLAG_CHASSIS;
	chassisSimFilterData.word1 = COLLISION_FLAG_CHASSIS_AGAINST;

	//Wheel and chassis query filter data.
	//Optional: cars don't drive on other cars.
	PxFilterData wheelQryFilterData;
	wheelQryFilterData.word0 = FilterGroup::eWHEEL;
	setupNonDrivableSurface(wheelQryFilterData);
	PxFilterData chassisQryFilterData;
	chassisQryFilterData.word0 = FilterGroup::eVEHICLE;

	setupNonDrivableSurface(chassisQryFilterData);

	//Add all the wheel shapes to the actor.
	for (PxU32 i = 0; i < numWheels; i++)
	{
		PxConvexMeshGeometry geom(wheelConvexMeshes[i]);
		PxShape* wheelShape = vehActor->createShape(geom, *wheelMaterials[i]);
		wheelShape->setQueryFilterData(wheelQryFilterData);
		wheelShape->setSimulationFilterData(wheelSimFilterData);
		wheelShape->setLocalPose(PxTransform(PxIdentity));
	}

	//Add the chassis shapes to the actor.
	for (PxU32 i = 0; i < numChassisMeshes; i++)
	{
		PxShape* chassisShape = vehActor->createShape
			(PxConvexMeshGeometry(chassisConvexMeshes[i]), *chassisMaterials[i]);
		chassisShape->setQueryFilterData(chassisQryFilterData);
		chassisShape->setSimulationFilterData(chassisSimFilterData);
		chassisShape->setLocalPose(PxTransform(PxIdentity));
	}

	vehActor->setMass(chassisData.mMass);
	vehActor->setMassSpaceInertiaTensor(chassisData.mMOI);
	vehActor->setCMassLocalPose(PxTransform(chassisData.mCMOffset, PxQuat(PxIdentity)));

	return vehActor;
}
コード例 #4
0
ファイル: Physics.cpp プロジェクト: bananu7/Engine
CPhysicsEntity* CPhysics::CreateBall(float radius, CVector3 const& position)
{
	PxTransform Transform (PxVec3 (position.X, position.Y, position.Z));
	PxRigidDynamic* aSphereActor = m_SDK->createRigidDynamic(Transform);
	PxShape* aSphereShape = aSphereActor->createShape(PxSphereGeometry(radius), *m_Material);
	float SphereDensity = 0.0f;
	PxRigidBodyExt::updateMassAndInertia(*aSphereActor, SphereDensity);
	m_Scene->addActor(*aSphereActor);
	return new CPhysicsEntity(aSphereActor);
}
コード例 #5
0
ファイル: Actors.cpp プロジェクト: hkeeble/Pinball
	void ShapeActor::Create()
	{
		void* s = NULL;

		if(m_aType == DynamicActor)
		{
			PxRigidDynamic* ptr = StaticCast(s, PxRigidDynamic*); // Receive Correctly Cast Pointer
			ptr = Physics::PxGetPhysics()->createRigidDynamic(m_pose);
			m_shape = ptr->createShape(m_geometry.any(), *m_material, IDENTITY_TRANS);
			PxRigidBodyExt::setMassAndUpdateInertia(*ptr, m_density);
			m_actor.dynamicActor = ptr;
		}
コード例 #6
0
void PhysicsSystemPhysX::update(const Time& deltaTime)
{	
	// Step the simulation forward
	mScene->simulate(deltaTime.seconds());

	if (mScene->fetchResults())
	{

		// Now let's push back the transforms into the World
		ComponentManager* colliderBoxManager = getWorld()->getComponentManager<CColliderBox>();
		ComponentManager* transformManager = getWorld()->getComponentManager<CTransform>();
		for (std::size_t i = 0; i < colliderBoxManager->size(); ++i)
		{
			Entity E = colliderBoxManager->getInstanceEntity(i);
			CColliderBox* box = (CColliderBox*)colliderBoxManager->getInstance(i);
			CTransform* transform = (CTransform*)transformManager->getComponentFromEntity(E);

			// Create
			if (box->userData == nullptr)
			{
				PxMaterial* boxMaterial = mPhysics->createMaterial(0.5f, 0.5f, 0.1f);

				PxRigidDynamic* boxActor = mPhysics->createRigidDynamic(PxTransform(transform->position.x, transform->position.y, transform->position.z));
				boxActor->createShape(PxBoxGeometry(10.f, 10.f, 10.f), *boxMaterial);
				PxRigidBodyExt::updateMassAndInertia(*boxActor, 30);
				//boxActor->setLinearVelocity(PxVec3(0, -50, 0));

				mScene->addActor(*boxActor);
				box->userData = boxActor;
			}
			// Update
			else
			{
				PxRigidDynamic* boxActor = (PxRigidDynamic*)box->userData;
				PxTransform pxTransform = boxActor->getGlobalPose();

				transform->position.x = pxTransform.p.x;
				transform->position.y = pxTransform.p.y;
				transform->position.z = pxTransform.p.z;

				transform->rotation.x = pxTransform.q.x;
				transform->rotation.y = pxTransform.q.y;
				transform->rotation.z = pxTransform.q.z;
				transform->rotation.w = pxTransform.q.w;
			}
		}

		syncActors();
	}
}
コード例 #7
0
ファイル: SampleParticles.cpp プロジェクト: akurt5/AIEShit
PxRigidDynamic* SampleParticles::Raygun::createRayCapsule(bool enableCollision, PxFilterData filterData)
{
	PxRigidDynamic* actor = mSample->getPhysics().createRigidDynamic(PxTransform::createIdentity());
	mSample->runtimeAssert(actor, "PxPhysics::createRigidDynamic returned NULL\n");
	PxShape* shape = actor->createShape(PxCapsuleGeometry(0.1f, 150.0f), mSample->getDefaultMaterial());
	mSample->runtimeAssert(shape, "PxRigidDynamic::createShape returned NULL\n");
	shape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, false);
	shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, enableCollision);
	shape->setSimulationFilterData(filterData);
	actor->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, true);
	actor->setMass(1.0f);
	actor->setMassSpaceInertiaTensor(PxVec3(1.0f));
	mSample->getActiveScene().addActor(*actor);	
	return actor;
}
コード例 #8
0
ファイル: SampleSubmarine.cpp プロジェクト: thomhughes/Awe
void SampleSubmarine::explode(PxRigidActor* actor, const PxVec3& explosionPos, const PxReal explosionStrength)
{
	size_t numRenderActors = mRenderActors.size();
	for(PxU32 i = 0; i < numRenderActors; i++)
	{
		if(&(mRenderActors[i]->getPhysicsShape()->getActor()) == actor)
		{
			PxShape* shape = mRenderActors[i]->getPhysicsShape();
			PxTransform pose = PxShapeExt::getGlobalPose(*shape);
			
			PxGeometryHolder geom = shape->getGeometry();

			// create new actor from shape (to split compound)
			PxRigidDynamic* newActor = mPhysics->createRigidDynamic(pose);
			if(!newActor) fatalError("createRigidDynamic failed!");

			PxShape* newShape = newActor->createShape(geom.any(), *mMaterial);
			newShape->userData = mRenderActors[i];
			mRenderActors[i]->setPhysicsShape(newShape);
			
			newActor->setActorFlag(PxActorFlag::eVISUALIZATION, true);
			newActor->setLinearDamping(10.5f);
			newActor->setAngularDamping(0.5f);
			PxRigidBodyExt::updateMassAndInertia(*newActor, 1.0f);
			mScene->addActor(*newActor);
			mPhysicsActors.push_back(newActor);
			
			PxVec3 explosion = pose.p - explosionPos;
			PxReal len = explosion.normalize();
			explosion *= (explosionStrength / len);
			newActor->setLinearVelocity(explosion);
			newActor->setAngularVelocity(PxVec3(1,2,3));

		}
	}

	removeActor(actor);
}
コード例 #9
0
void FBXActor::createCollisionShapes(PhysicsDemoScene *a_app)
{
	float density = 300;

	//pole
	PxBoxGeometry box = PxBoxGeometry(0.1f,4,0.1f);
	PxTransform transform(*((PxMat44*)(&m_world)));	//cast from glm to PhysX matrices

	PxRigidDynamic* dynamicActor = PxCreateDynamic(*a_app->g_Physics, transform, box, *a_app->g_PhysicsMaterial, density);

	dynamicActor->userData = this;	//set the user data to point at this FBXActor class

	//offset
	int nShapes = dynamicActor->getNbShapes();
	PxShape* shapes;
	dynamicActor->getShapes(&shapes, nShapes);

	PxTransform relativePose = PxTransform(PxVec3(0.0f,4.0f,0.0f));
	shapes->setLocalPose(relativePose);

	//head
	box = PxBoxGeometry(0.8f,0.5f,0.3f);
	relativePose = PxTransform(PxVec3(0.0f,2.0f,0.0f));
	PxShape* shape = dynamicActor->createShape(box, *a_app->g_PhysicsMaterial);
	if (shape)
	{
		shape->setLocalPose(relativePose);
	}

	PxRigidBodyExt::updateMassAndInertia(*dynamicActor, (PxReal)density);

	//add to scene
	a_app->g_PhysicsScene->addActor(*dynamicActor);
	a_app->g_PhysXActors.push_back(dynamicActor);

}
コード例 #10
0
ファイル: Class.cpp プロジェクト: Dimiondark/testxo
bool CTank::CreateTankActor( CPhysX * pPhysX )
{
	if( !LoadData( "InitShader.lua" ) )
		return false;

// 	CParamTank* pParamTank = new CParamTank;
// 
// 	if( !CLua::LoadParamTank( "", &pParamTank ) )
// 	{
// 
// 	}

	if( GameObject * pBody = GetDetail( BODY ) )
	{
		if ( pBody->CreateTriangleMesh( pPhysX ) )
		{			
			pBody->Update( 0.f );
			
			PxTriangleMesh* triangleMesh = pBody->GetTriangleMesh();
			D3DXVECTOR3     Position     = pBody->GetPosition();
			//D3DXComputeBoundingBox(Vertices,  g_pMesh->GetNumVertices(),  FVFVertexSize, &pMin, &pMax);
			//PxRigidDynamic* pRigDynAct   = pPhysX->GetPhysics()->createRigidDynamic( PxTransform( physx::PxVec3( Position.x, Position.y, Position.z ) ) );
// 			PxRigidDynamic* pRigDynAct   = PxCreateDynamic( *pPhysX->GetPhysics(), PxTransform( physx::PxVec3( Position.x, Position.y, Position.z ) ), PxBoxGeometry( 14.f, 4.6f, 6.f ), *pMaterial, 1.f );
// 
// 			if( pRigDynAct && pMaterial && triangleMesh )
// 			{
// 				//pRigDynAct->createShape( PxTriangleMeshGeometry( triangleMesh ), *pMaterial );
// 				
// 				pRigDynAct->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, false);
// 				pRigDynAct->setActorFlag( PxActorFlag::eVISUALIZATION, true );
// 				pRigDynAct->setAngularDamping( 0.5f );
// 				//pRigDynAct->setMass( 10000.f );
// 				PxRigidBodyExt::updateMassAndInertia( *pRigDynAct, 10.f );
// 				
// 				if( pMaterial )
// 					pPhysX->PushMaterial( pMaterial );
// 				
// 				pPhysX->AddActorScene( pRigDynAct );
// 				m_pActor = pRigDynAct;
// 
// 				return true;
// 			}

			const int    nWheels     = 12;
			PxF32        chassisMass = 1500.f;
			const PxF32  wheelMass   = 50.f;			
			PxF32		 fShift      = -0.85f;
			PxVec3 wheelCentreOffsets[ nWheels ];

			for( int i = 0; i < nWheels/2; ++i )
			{
				wheelCentreOffsets[ i*2   ] = PxVec3( -1.2f, -0.5f,  2.1f + i * fShift );
				wheelCentreOffsets[ i*2+1 ] = PxVec3(  1.2f, -0.5f,  2.1f + i * fShift );				
			}

			// размеры корпуса
			const PxVec3 chassisDims( 2.4f, 1.f, 6.f );// = computeChassisAABBDimensions(chassisConvexMesh);

			// Начало координат находится в центре шасси сетки
			// Установить центр масс будет ниже этой точки
			const PxVec3 chassisCMOffset = PxVec3( 0.f, -chassisDims.y * 0.5f - 0.65f, 0.f );

			PxVehicleWheelsSimData* wheelsSimData = PxVehicleWheelsSimData::allocate( nWheels );
			PxVehicleWheelsSimData& wheelsData = *wheelsSimData;
			PxVehicleDriveSimData4W driveData;
			
			PxVec3 chassisMOI( (chassisDims.y*chassisDims.y + chassisDims.z * chassisDims.z) * chassisMass / 12.f,
							   (chassisDims.x*chassisDims.x + chassisDims.z * chassisDims.z) * chassisMass / 12.f,
							   (chassisDims.x*chassisDims.x + chassisDims.y * chassisDims.y) * chassisMass / 12.f);

			// структура шасси
			PxVehicleChassisData chassisData;
			
			chassisData.mMass	  = chassisMass;		// Масса транспортного средства жесткой актер тела
			chassisData.mMOI	  = chassisMOI;			// Момент инерции автомобиля жесткая актер тела.
			chassisData.mCMOffset = chassisCMOffset;	// Центр масс смещение автомобиля жесткая актер тела.

			// Немного настройки здесь.Автомобиль будет иметь более отзывчивым поворот, если мы сведем
			// у-компоненты шасси момента инерции.
			chassisMOI.y *= 0.8f;

			const PxF32 massRear  = 0.5f * chassisMass * ( chassisDims.z - 3 * chassisCMOffset.z ) / chassisDims.z;
			const PxF32 massFront = massRear;

			//Extract the wheel radius and width from the wheel convex meshes
			PxF32 wheelWidths[ nWheels ] = {0.f};
			PxF32 wheelRadii[ nWheels ]  = {0.f};
			for( PxU32 i = 0; i < nWheels; ++i )
			{
				 wheelWidths[ i ] = 0.5f;
				 wheelRadii [ i ] = 0.32f;
			}

			// Теперь вычислим колеса массы и инерции компонентов вокруг оси оси			
			PxF32 wheelMOIs[ nWheels ];
			for( PxU32 i = 0; i < nWheels; ++i )
			{
				wheelMOIs[ i ] = 0.5f * wheelMass * wheelRadii[ i ] * wheelRadii[ i ];
			}

			// Давайте создадим структуру данных колеса теперь с радиусом, массы и МВД
			PxVehicleWheelData wheels[ nWheels ];
			for(PxU32 i = 0; i < nWheels; ++i )
			{
				wheels[ i ].mRadius				= wheelRadii[ i ];		// Радиус блок, который включает в себя колеса металл плюс резиновые шины
				wheels[ i ].mMass				= wheelMass;			// Масса колеса плюс шины
				wheels[ i ].mMOI				= wheelMOIs[ i ];		// Момент инерции колеса
				wheels[ i ].mWidth				= wheelWidths[ i ];		// Максимальная ширина блок, который включает в себя колеса плюс шин
				//wheels[ i ].mMaxHandBrakeTorque = 0.f;					// Отключение стояночного тормоза от передних колес и позволяют для задних колес
				//wheels[ i ].mMaxSteer			= 0.f;					// Включить рулевого управления для передних колес и отключить для передних колес
				//wheels[ i ].mDampingRate		= 1.f;				// Скорость затухания описывает скорость, с которой свободно вращающееся колесо теряет скорость вращения
			}

			//Let's set up the tire data structures now.
			//Put slicks on the front tires and wets on the rear tires.
			PxVehicleTireData tires[ nWheels ];

			for(PxU32 i = 0; i < nWheels; ++i )
			{				
				tires[ i ].mType = 1;			// тип сцепления шин с поверхностью
			}

			// Структура данных подвески
			PxVehicleSuspensionData susps[ nWheels ];

			for( PxU32 i = 0; i < nWheels; i++ )
			{
				susps[ i ].mMaxCompression	 = 0.03f;				// Максимальное сжатие пружинной подвески
				susps[ i ].mMaxDroop		 = 0.03f;				// Максимальное удлинение пружинной подвески
				susps[ i ].mSpringStrength	 = 20000.f;	// пружинная сила подвески блока
				susps[ i ].mSpringDamperRate = 500.f;
				susps[ i ].mSprungMass		 = chassisMass / nWheels;	// Масса транспортного средства, которая поддерживается пружинная подвеска, указанных в кг.
			}
			
			PxVec3 suspTravelDirections[ nWheels ];
			PxVec3 wheelCentreCMOffsets[ nWheels ];
			PxVec3 suspForceAppCMOffsets[ nWheels ];
			PxVec3 tireForceAppCMOffsets[ nWheels ];

			for( PxU32 i = 0 ; i < nWheels; ++i )
			{
				wheelCentreCMOffsets [ i ] = wheelCentreOffsets[ i ] - chassisCMOffset;
				suspForceAppCMOffsets[ i ] = PxVec3( wheelCentreCMOffsets[ i ].x, -0.3f, wheelCentreCMOffsets[ i ].z );
				tireForceAppCMOffsets[ i ] = PxVec3( wheelCentreCMOffsets[ i ].x, -0.3f, wheelCentreCMOffsets[ i ].z );
				suspTravelDirections [ i ] = PxVec3( 0, -1, 0 );	// направление подвески
			}

			// Теперь добавьте колеса, шины и подвеска данных
			for( PxU32 i = 0; i < nWheels; ++i )
			{
				wheelsData.setWheelData( i, wheels[ i ] );								// установить данные колеса
				wheelsData.setTireData( i, tires[ i ] );								// Установите шину данных колеса
				wheelsData.setSuspensionData( i, susps[ i ] );							// Установите подвеску данные колеса
				wheelsData.setSuspTravelDirection( i, suspTravelDirections[ i ] );		// Установить направление движения подвески колес
				wheelsData.setWheelCentreOffset( i, wheelCentreCMOffsets[ i ] );		// Установить смещение от центра жесткой тело массой в центре колеса
				wheelsData.setSuspForceAppPointOffset( i, suspForceAppCMOffsets[ i ] );	// Установить приложение точкой подвески силу подвески колес
				wheelsData.setTireForceAppPointOffset( i, tireForceAppCMOffsets[ i ] );	// Установить приложение точку шин силу шинах колес
			}

			//Diff
			PxVehicleDifferential4WData diff;
			diff.mType = PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD;
			driveData.setDiffData( diff );

			//Engine
			PxVehicleEngineData engine;
			engine.mPeakTorque								= 300.f;	// максимальная скорость вращения двигателя
			engine.mMaxOmega								= 400.f;	// Максимальный крутящий момент доступен обратиться к двигателю
			engine.mDampingRateFullThrottle					= 0.15f;	// скорость затухания двигатель при полностью открытой дроссельной заслонке	
			engine.mDampingRateZeroThrottleClutchEngaged	= 8.f;		// скорость затухания двигатель при нулевой газ при включении сцепления
			engine.mDampingRateZeroThrottleClutchDisengaged	= 0.35f;	// Краткие скорость затухания двигатель при нулевой газ при выключенном сцеплении (на нейтральной передаче)

			driveData.setEngineData( engine );

			//Gears
			PxVehicleGearsData gears;
			gears.mSwitchTime = 0.5f;
			driveData.setGearsData( gears );

			// Прочность сцепления
			PxVehicleClutchData clutch;
			clutch.mStrength = PxVehicleGearsData::eMAX_NUM_GEAR_RATIOS;
			driveData.setClutchData( clutch );

			//Ackermann steer accuracy
			PxVehicleAckermannGeometryData ackermann;
			ackermann.mAccuracy		  = 0.1f;
			ackermann.mAxleSeparation = wheelCentreOffsets[ 0 ].z - wheelCentreOffsets[ nWheels - 1 ].z;	// Расстояние между центром передней оси и центром задней оси
			ackermann.mFrontWidth	  = wheelCentreOffsets[ 0 ].x - wheelCentreOffsets[ 1		    ].x;	// Расстояние между центральной точке два передних колеса
			ackermann.mRearWidth	  = wheelCentreOffsets[ nWheels - 2 ].x - wheelCentreOffsets[ nWheels - 1 ].x;	// Расстояние между центральной точке два задних колеса
			driveData.setAckermannGeometryData(ackermann);			
			
			PxTriangleMesh * pTriangleMesh = 0;
			D3DXVECTOR3      vPosition;

			if( GameObject * pRoller = GetDetail( WHEEL_LEFT_1ST ) )
			{
				if( pRoller->CreateTriangleMesh( pPhysX ) )
				{
					pRoller->Update( 0.f );					
					pTriangleMesh = pRoller->GetTriangleMesh();
					Position      = pRoller->GetPosition();
				}
			}

			// Нам нужно добавить колеса столкновения форм, их местный позы, материал для колес, и моделирование фильтра для колес
			PxTriangleMeshGeometry WheelGeom( pTriangleMesh );
			
			PxGeometry* wheelGeometries[ nWheels ] = {0};
			PxTransform wheelLocalPoses[ nWheels ];

			for( PxU32 i = 0; i < nWheels; ++i )
			{
				wheelGeometries[ i ] = &WheelGeom;
				wheelLocalPoses[ i ] = PxTransform::createIdentity();
			}
			
			PxMaterial* pMaterial = pPhysX->GetPhysics()->createMaterial( 0.5f, 0.5f, 0.1f );    //коэффициенты трения скольжения и покоя(Dynamic friction,Static friction), коэффициент упругости
			const PxMaterial& wheelMaterial	= *pMaterial;
			PxFilterData wheelCollFilterData;

			wheelCollFilterData.word0 = COLLISION_FLAG_WHEEL;
			wheelCollFilterData.word1 = COLLISION_FLAG_WHEEL_AGAINST;

			// Нам нужно добавить шасси столкновения форм, их местный позы, материала для шасси и моделирования фильтр для шасси.
			//PxBoxGeometry chassisConvexGeom( 1.5f, 0.3f, 4.f );
			PxBoxGeometry chassisConvexGeom( chassisDims.x/2, chassisDims.y/2, chassisDims.z/2 );

			const PxGeometry* chassisGeoms	    = &chassisConvexGeom;
			const PxTransform chassisLocalPoses = PxTransform::createIdentity();
			const PxMaterial& chassisMaterial	= *pMaterial;

			PxFilterData chassisCollFilterData;
			chassisCollFilterData.word0 = COLLISION_FLAG_CHASSIS;
			chassisCollFilterData.word1 = COLLISION_FLAG_CHASSIS_AGAINST;

			// Создание фильтра запроса данных для автомобилей, чтобы машины не пытайтесь ездить на себя.
			PxFilterData vehQryFilterData;			
			SampleVehicleSetupVehicleShapeQueryFilterData( &vehQryFilterData );

			PxRigidDynamic* vehActor = pPhysX->GetPhysics()->createRigidDynamic( PxTransform::createIdentity() );

			//Add all the wheel shapes to the actor.
			for( PxU32 i = 0; i < nWheels; ++i )
			{
				PxShape* wheelShape=vehActor->createShape( *wheelGeometries[ i ], wheelMaterial );
				wheelShape->setQueryFilterData( vehQryFilterData );
				wheelShape->setSimulationFilterData( wheelCollFilterData );
				wheelShape->setLocalPose( wheelLocalPoses[ i ] );
				wheelShape->setFlag( PxShapeFlag::eSIMULATION_SHAPE, true );
			}

			//Add the chassis shapes to the actor			
			PxShape* chassisShape = vehActor->createShape( *chassisGeoms, chassisMaterial );
			chassisShape->setQueryFilterData( vehQryFilterData );
			chassisShape->setSimulationFilterData( chassisCollFilterData );
			chassisShape->setLocalPose( PxTransform( physx::PxVec3( 0, 0, 0 ) ) );
			

			vehActor->setMass( chassisData.mMass );
			vehActor->setMassSpaceInertiaTensor( chassisData.mMOI );
			vehActor->setCMassLocalPose( PxTransform( chassisData.mCMOffset, PxQuat::createIdentity() ) );
			vehActor->setGlobalPose( PxTransform( physx::PxVec3( 0, 8, 0 ), PxQuat::createIdentity() ) );

			PxVehicleDriveTank* pTank = PxVehicleDriveTank::allocate( nWheels );
 			
 			pTank->setup( pPhysX->GetPhysics(), vehActor, *wheelsSimData, driveData, nWheels );			
			pPhysX->AddActorScene( vehActor );
			m_pActor = vehActor;
			pPhysX->AddTank( pTank );

			//Free the sim data because we don't need that any more.
			wheelsSimData->free();
			//pTank->setDriveModel( PxVehicleDriveTank::eDRIVE_MODEL_SPECIAL );
			pTank->setToRestState();			
			pTank->mDriveDynData.setUseAutoGears( true );

			return true;
		}
	}

	return false;
}
コード例 #11
0
ファイル: physXRigidManager.cpp プロジェクト: david-leal/nau
void
PhysXRigidManager::addDynamicBody(const std::string & scene, physx::PxScene * world, physx::PxCooking * mCooking, nau::physics::IPhysics::BoundingVolume shape, physx::PxMaterial * material) {
	PxPhysics *gPhysics = &(world->getPhysics());
	PxRigidDynamic * dynamic;

	rigidBodies[scene].scalingFactor = getScalingFactor(rigidBodies[scene].info.extInfo.transform);
	PxMeshScale scale = PxMeshScale(rigidBodies[scene].scalingFactor);
	PxMat44 aux(rigidBodies[scene].info.extInfo.transform);
	PxVec3 pos(aux.getPosition());
	aux *= (1.0f / rigidBodies[scene].scalingFactor);
	PxMat44 mat(
		PxVec3(aux.column0.x, aux.column0.y, aux.column0.z),
		PxVec3(aux.column1.x, aux.column1.y, aux.column1.z),
		PxVec3(aux.column2.x, aux.column2.y, aux.column2.z),
		pos
	);

	//PxTransform trans = PxTransform(PxMat44(rigidBodies[scene].extInfo.transform));
	PxTransform trans = PxTransform(mat);

	switch (shape.sceneShape)
	{
	case nau::physics::IPhysics::BOX:
	{
		dynamic = gPhysics->createRigidDynamic(trans);
		dynamic->createShape(
			PxBoxGeometry(
				shape.max[0] * rigidBodies[scene].scalingFactor,
				shape.max[1] * rigidBodies[scene].scalingFactor,
				shape.max[2] * rigidBodies[scene].scalingFactor),
			*material);
	}
	break;
	case nau::physics::IPhysics::SPHERE:
	{
		dynamic = gPhysics->createRigidDynamic(trans);
		dynamic->createShape(PxSphereGeometry(shape.max[0] * rigidBodies[scene].scalingFactor), *material);
	}
	break;
	case nau::physics::IPhysics::CAPSULE:
	{
		dynamic = gPhysics->createRigidDynamic(trans);
		dynamic->createShape(
			PxCapsuleGeometry(
				shape.max[0] * rigidBodies[scene].scalingFactor,
				shape.max[1] * rigidBodies[scene].scalingFactor),
			*material);
	}
	break;
	default:
	{
		dynamic = gPhysics->createRigidDynamic(trans);
		PxConvexMesh * convexMesh = gPhysics->createConvexMesh(*getTriangleMeshGeo(world, mCooking, rigidBodies[scene].info.extInfo, false));
		dynamic->createShape(PxConvexMeshGeometry(convexMesh, scale), *material);
	}
	break;
	}

	dynamic->userData = static_cast<void*> (new std::string(scene));
	rigidBodies[scene].rollingFriction = -1.0f;
	rigidBodies[scene].rollingFrictionTimeStamp = 1;
	world->addActor(*dynamic);
	rigidBodies[scene].info.actor = dynamic;
}
コード例 #12
0
ファイル: physXWorld.cpp プロジェクト: david-leal/nau
void
PhsXWorld::_addRigid(float mass, float friction, float restitution, std::shared_ptr<nau::scene::IScene> &aScene, std::string name, nau::math::vec3 aVec) {

    PxPhysics *gPhysics = &(m_pDynamicsWorld->getPhysics());

    if (mass == 0.0f) {
        PxRigidStatic* staticActor;
        if (name.compare("plane") == 0) {
            staticActor = PxCreatePlane(*gPhysics,
                                        PxPlane(0.0f, 1.0f, 0.0f, 0.0f),
                                        *(gPhysics->createMaterial(friction, friction, restitution))
                                       );

        }
        else {
            /*if (name.compare("box") == 0) {
            	staticActor = PxCreateStatic(*gPhysics,
            		PxTransform(PxMat44(const_cast<float*> (aScene->getTransform().getMatrix()))),
            		PxBoxGeometry(1.0f,1.0f,1.0f),
            		*(gPhysics->createMaterial(1.0f, 1.0f, 0.6f))
            	);
            }
            else {*/
            staticActor = gPhysics->createRigidStatic(PxTransform(PxMat44(const_cast<float*> (aScene->getTransform().getMatrix()))));
            PxTriangleMeshGeometry triGeom;
            triGeom.triangleMesh = gPhysics->createTriangleMesh(getTriangleMeshGeo(m_pDynamicsWorld, aScene));
            staticActor->createShape(triGeom, *(gPhysics->createMaterial(friction, friction, restitution)));
            //}
        }
        staticActor->userData = aScene.get();
        m_pDynamicsWorld->addActor(*staticActor);
    }
    else {
        PxRigidDynamic* dynamic;
        //if (name.compare("ball") == 0) {
        //	dynamic = PxCreateDynamic(*gPhysics,
        //		PxTransform(PxMat44(const_cast<float*> (aScene->getTransform().getMatrix()))),
        //		PxSphereGeometry(1),
        //		*(gPhysics->createMaterial(0.5f, 0.5f, 0.6f)),
        //		10.0f
        //	);
        //	//dynamic->setLinearVelocity(PxVec3(0, -50, -100));
        //}
        //else {
        PxTransform trans = PxTransform(PxMat44(const_cast<float*> (aScene->getTransform().getMatrix())));
        dynamic = gPhysics->createRigidDynamic(trans);
        PxConvexMesh * convexMesh = gPhysics->createConvexMesh(getTriangleMeshGeo(m_pDynamicsWorld, aScene, false));
        PxConvexMeshGeometry convGeom(convexMesh);
        //PxConvexMeshGeometry convGeom(convexMesh, PxMeshScale(0.5f));
        //convGeom.convexMesh = gPhysics->createConvexMesh(getTriangleMeshGeo(m_pDynamicsWorld, aScene, false));

        //PxShape *shape = dynamic->createShape(convGeom, *(gPhysics->createMaterial(0.5f, 0.5f, 0.6f)), PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE);
        PxShape *shape = dynamic->createShape(convGeom, *(gPhysics->createMaterial(friction, friction, restitution)));
        //shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, true);
        //dynamic->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, false);
        //}
        dynamic->userData = aScene.get();
        //dynamic->setAngularDamping(0.5f);
        //dynamic->setLinearVelocity(velocity);

        m_pDynamicsWorld->addActor(*dynamic);
    }
}