//-----------------------------------------------------------------------------
//  Constructor
//-----------------------------------------------------------------------------
CPhysicEngine::CPhysicEngine (void)
{
    // Creacion e inicializacion del objeto principal de PhysX
    int nVersion = NX_PHYSICS_SDK_VERSION;
    NxSDKCreateError errorCode;
    m_pPhysicsSDK = NxCreatePhysicsSDK (NX_PHYSICS_SDK_VERSION, Globals::g_pUserAllocator, this, NxPhysicsSDKDesc(), &errorCode);
    if (!m_pPhysicsSDK)  return;

#ifdef _DEBUG
    m_pPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect ("localhost", 5425);
#endif

    // Set the physics parameters
    m_pPhysicsSDK->setParameter (NX_SKIN_WIDTH, 0.001f);

    // Set the debug visualization parameters
    m_pPhysicsSDK->setParameter (NX_VISUALIZATION_SCALE, 1);
    m_pPhysicsSDK->setParameter (NX_VISUALIZE_COLLISION_SHAPES, 1);
    m_pPhysicsSDK->setParameter (NX_VISUALIZE_ACTOR_AXES, 1);

    // Inicializacion del motor de cooking para procesamiento de triangleMeshes
    NxInitCooking();

    // Creacion del gestor de controllers
    m_pControllerMgr = NxCreateControllerManager ( Globals::g_pUserAllocator );
}
Example #2
0
DXApp::DXApp(void)
{
    _p_physdk = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, NULL);
    _p_D3D = Direct3DCreate9(D3D_SDK_VERSION);
    _max_particle_count = 400; //TODO: undo hardcoded
    width = 1024;
    height = 768;
    fFoward = 0;
    fStrafe = 0;
    Cam.location = NxVec3(-1000.0f, 500.0f,0.0f);
    Cam.ViewDir = NxVec3(0.7f, -0.3f, 0.0f);
    ShadowMapSize = 1024;
    bPaused = false;
    bTest = false;
    _screen_buffer = NULL;
    _blur_buffer = NULL;
    _particle_Mesh = NULL;
    _particle_count = 0;
    bBlurVel = true;
    _particle_color = c_particle_color;
    _particle_scale = c_particle_scale;
    _particle_size = c_particle_size;
    _particle_list = new SimParticle[_max_particle_count];//(NxActor*[])malloc(_particle_list_length);
    _particle_draw_list = new DrawParticle[_max_particle_count];//(DrawParticle[])malloc(_particle_draw_list_length);
    memset(_particle_draw_list, 0, _particle_draw_list_length);
    memset(_particle_list, 0, _particle_list_length);
}
Example #3
0
void InitNx()
{
    // Create the physics SDK
    gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION);
    if (!gPhysicsSDK)  return;

	// Set the physics parameters
	gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.01);

	// Set the debug visualization parameters
	gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
//	gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LIMITS, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LOCAL_AXES, 1);

    // Create the scene
    NxSceneDesc sceneDesc;
    sceneDesc.gravity               = gDefaultGravity;
	sceneDesc.simType				= NX_SIMULATION_HW;
    gScene = gPhysicsSDK->createScene(sceneDesc);	
 if(!gScene){ 
		sceneDesc.simType				= NX_SIMULATION_SW; 
		gScene = gPhysicsSDK->createScene(sceneDesc);  
		if(!gScene) return;
	}

	// Create the default material
	NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); 
	defaultMaterial->setRestitution(0.5);
	defaultMaterial->setStaticFriction(0.5);
	defaultMaterial->setDynamicFriction(0.5);

	// Create the objects in the scene
	CreateGroundPlane();

	capsule1 = CreateCapsule(NxVec3(0,5,0), 1, 0.5, 10);
	capsule1->raiseBodyFlag(NX_BF_KINEMATIC);
	capsule2 = CreateCapsule(NxVec3(0,3,0), 1, 0.5, 10);
//	capsule2->setLinearDamping(0.1);
    capsule2->raiseBodyFlag(NX_BF_DISABLE_GRAVITY);

	NxVec3 globalAnchor = NxVec3(0,5,0);
	NxVec3 globalAxis = NxVec3(0,1,0);
	d6Joint = CreateD6Joint(capsule1, capsule2, globalAnchor, globalAxis);

	gSelectedActor = capsule2;
	gForceStrength = 50000;
	gCameraSpeed = 10;

	// Initialize HUD
	InitializeHUD();
	InitializeSpecialHUD();

	// Get the current time
	getElapsedTime();

	// Start the first frame of the simulation
	if (gScene)  StartPhysics();
}
Example #4
0
	bool PhysicsManager::initialize() {
		mIsInitialized = false;
		mIsSceneCreated = false;
		mIsRunningSim = false;

		mUserAllocator = new UserAllocator;

		NxPhysicsSDKDesc desc;
		desc.setToDefault();
		
		NxSDKCreateError errorCode = NXCE_NO_ERROR;

		//&mErrorStream
		mSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION,mUserAllocator,NULL,desc); //, NULL, new ErrorStream(), desc, &errorCode
		if(mSDK == NULL)
		{
			//printf("\nSDK create error (%d - %s).\nUnable to initialize the PhysX SDK, exiting the sample.\n\n", errorCode, getNxSDKCreateError(errorCode));
			return false;
		}

		mSDK->getFoundationSDK().getRemoteDebugger()->connect("127.0.0.1");
		mSDK->setParameter(NX_SKIN_WIDTH, 0.05f);

		mIsInitialized = true;
		
		return true;

	}
Example #5
0
bool plSimulationMgr::InitSimulation()
{
    fSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, &gErrorStream);
    if (!fSDK) {
        fLog->AddLine("Phailed to init PhysX SDK");
        return false; // client will handle this and ask user to install
    }

    fLog = plStatusLogMgr::GetInstance().CreateStatusLog(40, "Simulation.log", plStatusLog::kFilledBackground | plStatusLog::kAlignToTop);
    fLog->AddLine("Initialized PhysX SDK");

    if (!NxInitCooking(nullptr, &gErrorStream)) {
        fLog->AddLine("Phailed to init NxCooking");
        fSDK->release();
        fSDK = nullptr;
        return false;
    }

#ifndef PLASMA_EXTERNAL_RELEASE
    // If this is an internal build, enable the PhysX debugger
    fSDK->getFoundationSDK().getRemoteDebugger()->connect("localhost", 5425);
#endif

    return true;
}
Example #6
0
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
PhysicsProcessor::PhysicsProcessor()
{
    NxPhysicsSDKDesc desc;
    NxSDKCreateError errorCode = NXCE_NO_ERROR;

    NxPhysicsSDK* pPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, NULL, desc, &errorCode);
    if( pPhysicsSDK == NULL )
    {
        throw std::exception("Exception: Cannot create PhysX SDK Pointer.");
    }
    this->m_pPhysicsSDK = pPhysicsSDK;

    this->m_pPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.025f);

    NxSceneDesc sceneDesc;
    sceneDesc.gravity = NxVec3(0.0f, -9.81f, 0.0f);

    NxScene* pScene = this->m_pPhysicsSDK->createScene(sceneDesc);
    if( pScene == NULL )
    {
        throw std::exception("Exception: Cannot create PhysX Scene Pointer.");
    }
    this->m_pScene = pScene;

    PhysicsActorFactory* pFactory = &PhysicsActorFactory::instance();

    pFactory->setScene(this->m_pScene);

    NxMaterial * defaultMaterial = this->m_pScene->getMaterialFromIndex(0); 
	defaultMaterial->setRestitution(0.0f);
	defaultMaterial->setStaticFriction(0.5f);
	defaultMaterial->setDynamicFriction(0.5f);
}
Example #7
0
void InitNx()
{
	// Create a memory allocator
    gAllocator = new UserAllocator;

    // Create the physics SDK
    gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator, &gErrorStream);
    if (0 == gPhysicsSDK) return;

	//This should be update for compatible with GPU and PPU!!!
	// Check for hardware availability
	NxHWVersion hwCheck = gPhysicsSDK->getHWVersion();
	if (hwCheck == NX_HW_VERSION_NONE) 
	{
		printf("Unable to find any NVIDIA PhysX hardware, this sample requires hardware physics to run. Please make sure that you have correctly installed the latest version of the NVIDIA PhysX SDK.\n");
		gPhysicsSDK->release();
		gPhysicsSDK = 0;
		NX_DELETE_SINGLE(gAllocator);
		exit(1);
	}

	// Set the physics parameters
	gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.05);

	// Set the debug visualization parameters
	gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_FNORMALS, 1);

	CreateScenario();
}
Example #8
0
void GameState::createPhysicScene()
{
	UserAllocator *gAllocator = new UserAllocator;
	mPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator);

	//LoThreadCom<GameState>::startLoading(Delegate<GameState>(this, &GameState::loadPhyScene));

	loadPhyScene();
	NxRemoteDebugger* rd = mPhysicsSDK->getFoundationSDK().getRemoteDebugger();
	rd->connect("localhost");

	//创建汽车 
	car = new Vehicle("car01", mSceneMgr, mWindow, mPhysicScene, mSceneMgr->getSceneNode("R1PS")->getPosition() + Ogre::Vector3(0, 1, 0),
		mStdQuaternion);

	car2 = new Vehicle("car02", mSceneMgr, mWindow, mPhysicScene, mSceneMgr->getSceneNode("R1PS")->getPosition() + Ogre::Vector3(0, 1, 0) + mStdQuaternion.xAxis()*2,
		mStdQuaternion);
	
	car3 = new Vehicle("car03", mSceneMgr, mWindow, mPhysicScene, mSceneMgr->getSceneNode("R1PS")->getPosition() + Ogre::Vector3(0, 1, 0) + mStdQuaternion.xAxis()*4,
		mStdQuaternion);

	car4 = new Vehicle("car04", mSceneMgr, mWindow, mPhysicScene, mSceneMgr->getSceneNode("R1PS")->getPosition() + Ogre::Vector3(0, 1, 0) - mStdQuaternion.xAxis()*2,
		mStdQuaternion);

	mSceneMgr->setAmbientLight(Ogre::ColourValue(0.8f, 0.8f, 0.8f));

	mCamera->detachFromParent();
	car4->getCameraNode()->attachObject(mCamera);
	mCamera->setAutoTracking(true, car4->getCarNode());
}
Example #9
0
void NovodexPhysicSystem::init(float gx, float gy, float gz) 
{
	m_physicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION);

	assert(m_physicsSDK);

	NxSceneDesc sceneDesc;

	sceneDesc.gravity = NxVec3(gx, gy, gz);

	m_scene = m_physicsSDK->createScene(sceneDesc);

	assert(m_scene);

/*	NxSceneQueryDesc sceneQueryDesc;
	sceneQueryDesc.executeMode = NX_SQE_ASYNCHRONOUS;
	sceneQueryDesc.report = &gQueryReport;
	m_SceneQueryObject = m_scene->createSceneQuery(sceneQueryDesc);
*/

	//NxMaterial* defaultMaterial = m_scene->getMaterialFromIndex(0);
	//defaultMaterial->setRestitution(0.2f);
	//defaultMaterial->setStaticFriction(0.5f);
	//defaultMaterial->setDynamicFriction(0.5f);
}
Example #10
0
void PhysStart ( void )
{
	gAllocator = new UserAllocator;
    gPhysicsSDK = NxCreatePhysicsSDK ( NX_PHYSICS_SDK_VERSION,gAllocator );

    if ( !gPhysicsSDK )
		return;

	gPhysicsSDK->setParameter ( NX_MIN_SEPARATION_FOR_PENALTY, -0.05f );

	gPhysicsSDK->setParameter ( NX_VISUALIZATION_SCALE,        1 );
	gPhysicsSDK->setParameter ( NX_VISUALIZE_COLLISION_SHAPES, 1 );
	gPhysicsSDK->setParameter ( NX_VISUALIZE_ACTOR_AXES,       1 );
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_FNORMALS, 1);

    NxSceneDesc			sceneDesc;
    sceneDesc.gravity               = gDefaultGravity;
    sceneDesc.broadPhase            = NX_BROADPHASE_COHERENT;
    sceneDesc.collisionDetection    = true;
	sceneDesc.userContactReport		= carContactReport;
    gScene = gPhysicsSDK->createScene ( sceneDesc );

	NxMaterial* defaultMaterial = gScene->getMaterialFromIndex ( 0 );
	defaultMaterial->setRestitution     ( 0.0f );
	defaultMaterial->setStaticFriction  ( 0.5f );
	defaultMaterial->setDynamicFriction ( 0.5f );

	gPhysicsSDK->setActorGroupPairFlags(0, 0, NX_NOTIFY_ON_TOUCH);
}
Example #11
0
void InitNx()
{
	// Create a memory allocator
    gAllocator = new UserAllocator;

    // Create the physics SDK
	gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator);
	if (!gPhysicsSDK)  return;

	// Set the physics parameters
	gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.01);

	// Set the debug visualization parameters
	gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);
	//gPhysicsSDK->setParameter(NX_VISUALIZE_CLOTH_COLLISIONS, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_CLOTH_SLEEP, 1);

	// Check available hardware
	NxHWVersion hwCheck = gPhysicsSDK->getHWVersion();
	if (hwCheck == NX_HW_VERSION_NONE) 
	{
		gHardwareCloth = false;
	}
	else 
		gHardwareCloth = true;

	// Create the scenes
    NxSceneDesc sceneDesc;
    sceneDesc.gravity = gDefaultGravity;
    sceneDesc.simType = NX_SIMULATION_HW;
    gScene = gPhysicsSDK->createScene(sceneDesc);	
	if(!gScene){ 
		sceneDesc.simType = NX_SIMULATION_SW; 
		gScene = gPhysicsSDK->createScene(sceneDesc);  
		if(!gScene) return;
	}

	// Create the default material
	NxMaterialDesc       m; 
	m.restitution        = 0.5;
	m.staticFriction     = 0.2;
	m.dynamicFriction    = 0.2;
	NxMaterial* mat = gScene->getMaterialFromIndex(0);
	mat->loadFromDesc(m); 

    SetupTearingScene();

	if (gScene->getNbActors() > 0)
		gSelectedActor = *gScene->getActors();
	else
		gSelectedActor = NULL;

	// Initialize HUD
    InitializeHUD();
	InitializeSpecialHUD();
}
Example #12
0
void InitNx()
{
	// Create a memory allocator
    gAllocator = new UserAllocator;

    // Create the physics SDK
    gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator);
    if (!gPhysicsSDK)  return;

	// Set the physics parameters
	gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.01);

	// Set the debug visualization parameters
	gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 2);
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LIMITS, 1);

    // Create the scene
    NxSceneDesc sceneDesc;
    sceneDesc.gravity               = gDefaultGravity;
    sceneDesc.simType				= NX_SIMULATION_HW;
    gScene = gPhysicsSDK->createScene(sceneDesc);	
 if(!gScene){ 
		sceneDesc.simType				= NX_SIMULATION_SW; 
		gScene = gPhysicsSDK->createScene(sceneDesc);  
		if(!gScene) return;
	}

	// Create the default material
	NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); 
	defaultMaterial->setRestitution(0.5);
	defaultMaterial->setStaticFriction(0.5);
	defaultMaterial->setDynamicFriction(0.5);

	// Create the objects in the scene
	CreateGroundPlane();

	mainBox = CreateMainObject();

	gSelectedActor = mainBox;
	gCameraPos = NxVec3(0,15,-50);
	gCameraSpeed = 20;
    gForceStrength = 50000000;

	// Initialize HUD
	InitializeHUD();

	// Get the current time
	getElapsedTime();

	// Start the first frame of the simulation
	if (gScene)  StartPhysics();
}
Example #13
0
bool PxWorld::restartSDK( bool destroyOnly, PxWorld *clientWorld, PxWorld *serverWorld )
{
   // If either the client or the server still exist
   // then we cannot reset the SDK.
   if ( clientWorld || serverWorld )
      return false;

   // Destroy the existing SDK.
   if ( gPhysicsSDK )
   {
      PxTSStatic::freeMeshCache();

      NXU::releasePersistentMemory();
      gPhysicsSDK->release();
      gPhysicsSDK = NULL;

      SAFE_DELETE( gPxConsoleStream );
   }

   // If we're not supposed to restart... return.
   if ( destroyOnly )
      return true;

   gPxConsoleStream = new PxConsoleStream();

   NxPhysicsSDKDesc sdkDesc;
   sdkDesc.flags |= NX_SDKF_NO_HARDWARE;

   NxSDKCreateError error;
   gPhysicsSDK = NxCreatePhysicsSDK(   NX_PHYSICS_SDK_VERSION, 
                                       NULL,
                                       gPxConsoleStream,
                                       sdkDesc,
                                       &error );
   if ( !gPhysicsSDK )
   {
      Con::errorf( "PhysX failed to initialize!  Error code: %d", error );
      Platform::messageBox(   Con::getVariable( "$appName" ),
                              avar("PhysX could not be started!\r\n"
                              "Please be sure you have the latest version of PhysX installed.\r\n"
                              "Error Code: %d", error),
                              MBOk, MIStop );
      Platform::forceShutdown( -1 );
   }

   // Set the default skin width for all actors.
   gPhysicsSDK->setParameter( NX_SKIN_WIDTH, 0.01f );

   return true;
}
static bool InitNx()
{
	if (!gAllocator)
		gAllocator = new UserAllocator;

	// Initialize PhysicsSDK
	NxPhysicsSDKDesc desc;
	NxSDKCreateError errorCode = NXCE_NO_ERROR;
	gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator, NULL, desc, &errorCode);
	if(gPhysicsSDK == NULL) 
	{
		printf("\nSDK create error (%d - %s).\nUnable to initialize the PhysX SDK, exiting the sample.\n\n", errorCode, getNxSDKCreateError(errorCode));
		return false;
	}
#if SAMPLES_USE_VRD
	// The settings for the VRD host and port are found in SampleCommonCode/SamplesVRDSettings.h
	if (gPhysicsSDK->getFoundationSDK().getRemoteDebugger() && !gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->isConnected())
		gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect(SAMPLES_VRD_HOST, SAMPLES_VRD_PORT, SAMPLES_VRD_EVENTMASK);
#endif

	gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.025f);

	// Create two scenes
	for(NxU32 i=0;i<2;i++)
	{
		NxSceneDesc sceneDesc;
		sceneDesc.gravity				= gDefaultGravity;

		gScenes[i] = gPhysicsSDK->createScene(sceneDesc);
		if(gScenes[i] == NULL) 
		{
			printf("\nError: Unable to create one of the two PhysX scenes, exiting the sample.\n\n");
			return false;
		}

		// Create ground plane
		NxPlaneShapeDesc PlaneDesc;
		NxActorDesc ActorDesc;
		ActorDesc.shapes.pushBack(&PlaneDesc);
		gScenes[i]->createActor(ActorDesc);

		//materials are no longer shared between scenes so they have to be set up for both:
		NxMaterial * defaultMaterial = gScenes[i]->getMaterialFromIndex(0); 
		defaultMaterial->setRestitution(0.0f);
		defaultMaterial->setStaticFriction(0.5f);
		defaultMaterial->setDynamicFriction(0.5f);
	}
	return true;
}
Example #15
0
// Core dump globals
NxPhysicsSDK* CreatePhysics()
{
    NxPhysicsSDK* pSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator);
	if (!pSDK)  return NULL;

	// Set the physics parameters
	pSDK->setParameter(NX_SKIN_WIDTH, 0.01);

	// Set the debug visualization parameters
	pSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
	pSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
	pSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);
	pSDK->setParameter(NX_VISUALIZE_COLLISION_FNORMALS, 1);
	return pSDK;
}
Example #16
0
void InitNx()
{
	// Create a memory allocator
	gAllocator = new UserAllocator;

	// Create the physics SDK
	gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator);
	if (!gPhysicsSDK)  return;

	// Set the physics parameters
	gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.01);

	// Set the debug visualization parameters
	gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
	//gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
	//gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);
	//gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_FNORMALS, 1);

	// Create the scene
	NxSceneDesc sceneDesc;
	sceneDesc.simType				= NX_SIMULATION_SW;
	sceneDesc.gravity               = gDefaultGravity;
	gScene = gPhysicsSDK->createScene(sceneDesc);	

	// Create the default material
	NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); 
	defaultMaterial->setRestitution(0.5);
	defaultMaterial->setStaticFriction(0.5);
	defaultMaterial->setDynamicFriction(0.5);

	groundPlane	= CreateGroundPlane();
	//groundPlane->getShapes()[0]->setFlag(NX_SF_FLUID_DRAIN,true);

	// Create drain actors
	CreateDrainActors();

	fluidEmitter = CreateFluidEmitter(0.35, 0.35);

	// Initialize HUD
	InitializeHUD();

	// Get the current time
	getElapsedTime();

	// Start the first frame of the simulation
	if (gScene)  StartPhysics();
}
		//-----------------------------------------------------------------------
		bool PhysXBridge::initNx(Real gravityY)
		{
			if (!mPhysicsSDK)
			{
				// Initialize PhysicsSDK
				NxPhysicsSDKDesc desc;
				NxSDKCreateError errorCode = NXCE_NO_ERROR;
				mPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, 0, new PhysXLogging(), desc, &errorCode);
				if(!mPhysicsSDK) 
				{
					EXCEPT(Exception::ERR_INTERNAL_ERROR, "PU: Cannot initialise the PhysX SDK.", "PhysXBridge::initNx");
				}

				mPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.05f);
			}

			// Create a scene
			if (!mScene)
			{
				NxSceneDesc sceneDesc;
				sceneDesc.gravity = NxVec3(0.0f, gravityY, 0.0f);
				mScene = mPhysicsSDK->createScene(sceneDesc);
				if(!mScene)
				{
					EXCEPT(Exception::ERR_INTERNAL_ERROR, "PU: Cannot create a PhysX Scene.", "PhysXBridge::initNx");
				}

				// Set the contact report
				mScene->setUserContactReport(&mPhysXContactReport);

				// Set default material
				NxMaterial* defaultMaterial = mScene->getMaterialFromIndex(0);
				defaultMaterial->setRestitution(0.0f);
				defaultMaterial->setStaticFriction(0.5f);
				defaultMaterial->setDynamicFriction(0.5f);

				// Create ground plane
				createPlane();
			}

			// Create a controller
			ControllerManager& controllerManager = ControllerManager::getSingleton(); 
			ControllerValueRealPtr physXBridgeUpdateValue(PU_NEW PhysXBridgeUpdateValue(this));
			mTimeController = controllerManager.createFrameTimePassthroughController(physXBridgeUpdateValue);

			return true;
		}
Example #18
0
//-------------------------------------------------------------------------------------------------
bool sdPhysicsSystem::Initialize()
{
	if (m_bInitialized)
	{
		NIASSERT(0);

		Destroy();
		m_bInitialized = false;
	}

	// 创建内存分配器
	m_pkAllocator = NiNew sdPhysXAllocator;
	NIASSERT(m_pkAllocator);

	// 创建调试输出数据流
	m_pkOutputStream = NiNew sdPhysXOutputStream;
	NIASSERT(m_pkOutputStream);

	// 创建PhysX,初始化参数
	NxSDKCreateError kErrorCode;
	NxPhysicsSDKDesc kDesc;
	m_pkPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, m_pkOutputStream, kDesc, &kErrorCode);
	NIASSERT(m_pkPhysicsSDK);

	m_pkPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.1f);
	m_pkPhysicsSDK->setParameter(NX_BOUNCE_THRESHOLD, -0.5f);
	m_pkPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1.f);
	m_pkPhysicsSDK->setParameter(NX_VISUALIZE_BODY_AXES, 0.2f);
	m_pkPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1.f);
	m_pkPhysicsSDK->setParameter(NX_VISUALIZE_CLOTH_MESH, 1.f);
//	m_pkPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_FNORMALS, 1.f);
//	m_pkPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXESS, 1.f);

	// 创建Cook库
	//m_pkCooking = NxGetCookingLib(NX_PHYSICS_SDK_VERSION);
	//NIASSERT(m_pkCooking);
	//m_pkCooking->NxInitCooking();

	//
	m_pkUserTriggerReport = NiNew sdPhysXTriggerReport;
	NIASSERT(m_pkUserTriggerReport);

	return m_bInitialized = true;
}
 virtual ReadResult readObject(const std::string& file, const osgDB::ReaderWriter::Options* options) const
 {
     std::string ext = osgDB::getLowerCaseFileExtension( file );
     if ( !acceptsExtension(ext) ) return ReadResult::FILE_NOT_HANDLED;
     
     NxPhysicsSDKDesc desc;
     NxSDKCreateError errorCode = NXCE_NO_ERROR;
     NxPhysicsSDK* physicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, new ErrorStream, desc, &errorCode);
     if ( !physicsSDK ) 
     {
         OSG_WARN << "[PhysXInterface] Unable to initialize the PhysX SDK, error code: " << errorCode << std::endl;
         return NULL;
     }
     osgPhysics::setPhysxInstance( physicsSDK );
     
     osg::ref_ptr<osgPhysics::PhysXInterface> interface = new osgPhysics::PhysXInterface;
     interface->setPhysicsData( physicsSDK );
     return interface.get();
 }
Example #20
0
void InitNx()
{
    // Create the physics SDK
    gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION);
    if (!gPhysicsSDK)  return;

	// Set the debug visualization parameters for forcefield visualization
	gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_FORCE_FIELDS, 1.0f);

    // Create the scene
    NxSceneDesc sceneDesc;
 	sceneDesc.simType = NX_SIMULATION_HW;
    sceneDesc.gravity = gDefaultGravity;
    gScene = gPhysicsSDK->createScene(sceneDesc);	
	if(!gScene)
	{ 
		sceneDesc.simType = NX_SIMULATION_SW; 
		gScene = gPhysicsSDK->createScene(sceneDesc);  
		if(!gScene) return;
	}

	// Create the objects in the scene
	groundPlane = CreateGroundPlane();
	box1 = CreateBox(NxVec3(5,3.5,0));

	// Create a Custome kernel and a Linear kernel
	CreateFFCustomKernel();
	CreateFFLinearKernel();

	//Create the forcefield in the scene
	gForceField = CreateForcefield();

	// Initialize HUD
	InitializeHUD();

	// Get the current time
	getElapsedTime();

	// Start the first frame of the simulation
	if (gScene)  StartPhysics();
}
Example #21
0
//
//	ESciVis::InitPhysX
//
void ESciVis::InitPhysX( void )
{
	LOG_INIT("PhysX");
	
	// Create the physics SDK
    nx = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION);
    if (!nx)  return;

	// Set the physics parameters
	nx->setParameter(NX_SKIN_WIDTH, 0.01f);

	// Set the debug visualization parameters
	nx->setParameter(NX_VISUALIZATION_SCALE, 1);
	nx->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
	nx->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);

    // Create the scene
    NxSceneDesc sceneDesc;
    sceneDesc.gravity               = NxVec3(0,0,0);
	sceneDesc.simType				= NX_SIMULATION_SW;
    nx_scene = nx->createScene(sceneDesc);	
	
	if(!nx_scene) { 
		sceneDesc.simType				= NX_SIMULATION_SW; 
		nx_scene = nx->createScene(sceneDesc);  
		if(!nx_scene) return;
	}
	
	//	coocking lib :
	nx_cook	=	NxGetCookingLib(NX_PHYSICS_SDK_VERSION);
	if (!nx_cook) {
		RUNTIME_ERROR("NxGetCookingLib() failed");
	}
	nx_cook->NxInitCooking();
	

	// Create the default material
	NxMaterial* defaultMaterial = nx_scene->getMaterialFromIndex(0); 
	defaultMaterial->setRestitution(0.5);
	defaultMaterial->setStaticFriction(0.5);
	defaultMaterial->setDynamicFriction(0.5);
}
Example #22
0
bool PhysX::InitNx()
{

	// Initialize PhysicsSDK
	NxPhysicsSDKDesc desc;
	NxSDKCreateError errorCode = NXCE_NO_ERROR;
	m_pPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, NULL, desc, &errorCode);
	if(m_pPhysicsSDK == NULL) 
	{
		printf("Unable to initialize the PhysX SDK, exiting the sample.\n");
		return false;
	}

	m_pPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.03f);

	// Create a scene
	NxSceneDesc sceneDesc;
	sceneDesc.gravity				= NxVec3(0.0f, -9.81f, 0.0f);
	m_pScene = m_pPhysicsSDK->createScene(sceneDesc);
	if(m_pScene == NULL) 
	{
		printf("Unable to create a PhysX scene, exiting the sample.\n");
		return false;
	}

	// Set default material
	NxMaterial* defaultMaterial = m_pScene->getMaterialFromIndex(0);
	defaultMaterial->setRestitution(0.0f);
	defaultMaterial->setStaticFriction(0.5f);
	defaultMaterial->setDynamicFriction(0.5f);

	// Create ground plane
	NxPlaneShapeDesc planeDesc;
	NxActorDesc actorDesc;
	actorDesc.shapes.pushBack(&planeDesc);
	m_pScene->createActor(actorDesc);

	return true;
}
Example #23
0
bool plSimulationMgr::InitSimulation()
{
    fSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, &gErrorStream);
    if (!fSDK)
        return false; // client will handle this and ask user to install

    fLog = plStatusLogMgr::GetInstance().CreateStatusLog(40, "Simulation.log", plStatusLog::kFilledBackground | plStatusLog::kAlignToTop);
    fLog->AddLine("Initialized simulation mgr");

#ifndef PLASMA_EXTERNAL_RELEASE
    // If this is an internal build, enable the PhysX debugger
    fSDK->getFoundationSDK().getRemoteDebugger()->connect("localhost", 5425);
#endif

    if ( !plPXConvert::Validate() )
    {
#ifndef PLASMA_EXTERNAL_RELEASE
        hsMessageBox("Ageia's PhysX or Plasma offsets have changed, need to rewrite conversion code.","PhysX Error",MB_OK);
#endif
        return false; // client will handle this and ask user to install
    }

    return true;
}
Example #24
0
bool InitNx()
{
	// Initialize PhysicsSDK
	NxPhysicsSDKDesc desc;
	NxSDKCreateError errorCode = NXCE_NO_ERROR;
	gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, 0, 0, desc, &errorCode);
	if(gPhysicsSDK == NULL) 
	{
		printf("\nSDK create error (%d - %s).\nUnable to initialize the PhysX SDK, exiting the sample.\n\n", errorCode, getNxSDKCreateError(errorCode));
		return false;
	}

	gPhysicsSDK->setParameter(NX_SKIN_WIDTH, gSkinWidth);
	gPhysicsSDK->setParameter(NX_DEFAULT_SLEEP_ENERGY, 0.01f);

	// Create a scene
	NxSceneDesc sceneDesc;
	sceneDesc.gravity				= NxVec3(0.0f, -9.81f, 0.0f);
	sceneDesc.userNotify = &g_SleepCallBack; //用户自定义事件
	sceneDesc.userContactReport		= &gMyContactReport;
	gScene = gPhysicsSDK->createScene(sceneDesc);
	if(gScene == NULL) 
	{
		printf("\nError: Unable to create a PhysX scene, exiting the sample.\n\n");
		return false;
	}
	gScene->setTiming();
	// Set default material
	NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0);
	defaultMaterial->setRestitution(0.0f);
	defaultMaterial->setStaticFriction(0.5f);
	defaultMaterial->setDynamicFriction(0.5f);

	CreatePhysicsTerrain();
	return true;
}
Example #25
0
void InitNx()
{
    // Create the physics SDK
	gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, &gErrorStream);
    if (!gPhysicsSDK)  return;

	// Set the physics parameters
	gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.05);

	// Set the debug visualization parameters
	gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
//	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_AXES, 1);
//	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_FNORMALS, 1);

	gPhysicsSDK->setParameter(NX_VISUALIZE_CONTACT_POINT, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_CONTACT_NORMAL, 1);

    // Create the scene
    NxSceneDesc sceneDesc;
    sceneDesc.gravity               = gDefaultGravity;
	sceneDesc.simType				= NX_SIMULATION_HW;
    gScene = gPhysicsSDK->createScene(sceneDesc);	
 if(!gScene){ 
		sceneDesc.simType				= NX_SIMULATION_SW; 
		gScene = gPhysicsSDK->createScene(sceneDesc);  
		if(!gScene) return;
	}

	NxU32 set = 0;

#ifdef WIN32
	set = SetCurrentDirectory(&fname[0]);
	if (!set) set = SetCurrentDirectory(&fname1[0]);
	if (!set)
	{
		char basePath[256];
		GetModuleFileName(NULL, basePath, 256);
		char* pTmp = strrchr(basePath, '\\');
		basePath[pTmp-basePath+1] = 0;
		SetCurrentDirectory(basePath);//for running from start menu

		set = SetCurrentDirectory(&fname2[0]);
	}
	if (!set) set = SetCurrentDirectory(&fname3[0]);
#elif LINUX
	set = chdir(&fname[0]);
	if (set != 0) set = chdir(&fname2[0]);
	if (set != 0) set = chdir(&fname3[0]);
#endif

	// Create the default material
	NxMaterialDesc defaultMaterial;
	defaultMaterial.restitution = 0;
	defaultMaterial.staticFriction = 0.5;
	defaultMaterial.dynamicFriction	= 0.5;
	NxMaterial* m = gScene->getMaterialFromIndex(0);
	m->loadFromDesc(defaultMaterial);


	char buffer[512];
	FindMediaFile("Course.pml", buffer);
	nxmlLoadScene(buffer, gPhysicsSDK, gScene);

	// Switch from Max Coordinate System to
	// Training Program Coordinate System
	NxMat34 mat;
    NxMat33 orient;
	orient.setColumn(0, NxVec3(-1,0,0));
	orient.setColumn(1, NxVec3(0,0,1));
	orient.setColumn(2, NxVec3(0,1,0));
	mat.M = orient;
	SwitchCoordinateSystem(gScene, mat);

	// Reset wheel material
	wsm = NULL;

	// Create the trike actor
	trike = CreateTrike(NxVec3(0,3,0));
	trike->wakeUp(1e30);

    AddUserDataToActors(gScene);

	gSelectedActor = trike;

	// Initialize HUD
	InitializeHUD();
	InitializeSpecialHUD();

	// Get the current time
	getElapsedTime();

	// Start the first frame of the simulation
	if (gScene)  StartPhysics();
}
Example #26
0
	Data(bool useHardware, bool useHardwareOnly, bool useMultithreading, PhysicsParams *params)
	:	sdk(0),
		scene(0),
		crashed(false),

		statsNumActors(0),
		statsNumDynamicActors(0),
		statsNumDynamicActorsInAwakeGroups(0),
		statsMaxDynamicActorsInAwakeGroups(0),
		statsSimulationTime(0),
		statsSimulationWaitTime(0),
		statsSimulationStartWaitTime(0),
		startSimulationTime(0),

		statsContacts(0),
		ccd(false),
		ccdMaxThickness(0.5f),

		runningInHardware(false),
		physicslib_fluid_containment_actor(0),
		physicslib_fluid_containment_shape(0),
		physicslib_fluid_containment_sphere_actor(0),
		physicslib_fluid_containment_sphere_shape(0)
	{
		if (params == NULL)
		{
			params = &physics_defaultParams;
			::Logger::getInstance()->debug("PhysicsLib - No physics params given, using defaults.");
		}

		if (params->scriptRunner == NULL)
		{
			::Logger::getInstance()->warning("PhysicsLib - No script runner given, collision groups, etc. will be initialized to default values.");
		}

		NxPhysicsSDKDesc sdkDesc;
		if(!useHardware)
			sdkDesc.flags |= NX_SDKF_NO_HARDWARE;

		sdk = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, 0, getLogger(), sdkDesc);
		//sdk = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION);

		// HACK: ...
		physxSDK = sdk;

		if(sdk)
		{
			if(sdk->getHWVersion() == NX_HW_VERSION_NONE)
				useHardware = false;

			if (params->ccd)
			{
				sdk->setParameter(NX_CONTINUOUS_CD, true);
				sdk->setParameter(NX_CCD_EPSILON, 0.001f);
			}
			this->ccd = params->ccd;
			this->ccdMaxThickness = params->ccdMaxThickness;

			NxSceneDesc sceneDesc;
			sceneDesc.gravity = NxVec3(params->gravity.x, params->gravity.y, params->gravity.z);	
			sceneDesc.userContactReport = &contactReport;
			//sceneDesc.userNotify = &userNotify;

			if(useHardware)
			{
				sceneDesc.simType = NX_SIMULATION_HW;
				if (useHardwareOnly)
				{
					sceneDesc.flags |= NX_SF_RESTRICTED_SCENE;
				}
			}
			else
			{
				sceneDesc.simType = NX_SIMULATION_SW;
			}

			if (!useMultithreading)
			{
				// Disable threading
				sceneDesc.flags = 0;
			}

			runningInHardware = useHardware;

			sceneDesc.flags |= NX_SF_ENABLE_ACTIVETRANSFORMS;
			scene = sdk->createScene(sceneDesc);
			if(scene)
			{
				NxMaterial *defaultMaterial = scene->getMaterialFromIndex(0);
				defaultMaterial->setStaticFriction(params->defaultStaticFriction);
				defaultMaterial->setDynamicFriction(params->defaultDynamicFriction);
				defaultMaterial->setRestitution(params->defaultRestitution);

#ifdef PROJECT_CLAW_PROTO
				// Create material for cops (larger friction, no restitution)
				NxMaterialDesc materialDesc;
				materialDesc.restitution = 0.0f;   
				materialDesc.restitutionCombineMode = NX_CM_MIN;
				materialDesc.staticFriction = 10.0f;
				materialDesc.dynamicFriction = 10.0f;
				unitMaterial = scene->createMaterial(materialDesc);
#endif

				sdk->setParameter(NX_VISUALIZATION_SCALE, 1.f);

#ifndef PROJECT_SHADOWGROUNDS
				sdk->setParameter(NX_SKIN_WIDTH, 0.01f);
#endif

				// NEW: the new scriptable collision/contact group initialization
				int contactFlags1 = NX_NOTIFY_ON_START_TOUCH | NX_NOTIFY_ON_TOUCH | NX_NOTIFY_FORCES;
#ifdef PHYSICS_FEEDBACK
				int contactFlags2 = NX_NOTIFY_ON_START_TOUCH | NX_NOTIFY_ON_TOUCH | NX_NOTIFY_FORCES;
#else
				int contactFlags2 = NX_NOTIFY_ON_START_TOUCH | NX_NOTIFY_FORCES;
#endif
				if (params->scriptRunner != NULL)
				{
					bool ok = params->scriptRunner->runPhysicsLibScript("physics_init", "set_contacts");
					if (!ok)
						::Logger::getInstance()->error("PhysicsLib - Failed to run physics_init:set_contacts script (script/sub may not be loaded or did not return expected value).");
				}

				for (int i = 0; i < PHYSICS_MAX_COLLISIONGROUPS; i++)
				{
					for (int j = 0; j < PHYSICS_MAX_COLLISIONGROUPS; j++)
					{
						if (physicslib_group_cont[i][j] != physicslib_group_cont[j][i])
						{
							::Logger::getInstance()->error("PhysicsLib - Improperly mirrored physics contacts data (group1 -> group2 does not have same flag as group2 -> group1).");
							::Logger::getInstance()->debug("contacts data group numbers follow:");
							::Logger::getInstance()->debug(int2str(i));
							::Logger::getInstance()->debug(int2str(j));
						}
						if (physicslib_group_cont[i][j] == PHYSICSLIB_GROUP_CONTACT_FLAGS1)
							scene->setActorGroupPairFlags(i, j, contactFlags1);
						else if (physicslib_group_cont[i][j] == PHYSICSLIB_GROUP_CONTACT_FLAGS2)
							scene->setActorGroupPairFlags(i, j, contactFlags2);
					}
				}

				if (params->scriptRunner != NULL)
				{
					bool ok = params->scriptRunner->runPhysicsLibScript("physics_init", "set_collisions");
					if (!ok)
						::Logger::getInstance()->error("PhysicsLib - Failed to run physics_init:set_collision script (script/sub may not be loaded or did not return expected value).");
				}

				for (int i = 0; i < PHYSICS_MAX_COLLISIONGROUPS; i++)
				{
					for (int j = 0; j < PHYSICS_MAX_COLLISIONGROUPS; j++)
					{
						if (physicslib_group_coll[i][j] != physicslib_group_coll[j][i])
						{
							::Logger::getInstance()->error("PhysicsLib - Improperly mirrored physics collision data (group1 -> group2 does not have same flag as group2 -> group1).");
							::Logger::getInstance()->debug("collision data group numbers follow:");
							::Logger::getInstance()->debug(int2str(i));
							::Logger::getInstance()->debug(int2str(j));
						}
						scene->setGroupCollisionFlag(i, j, physicslib_group_coll[i][j]);
					}
				}

// OLD SCHEISSE...
/*
				// Contact groups
				{
					int contactFlags1 = NX_NOTIFY_ON_START_TOUCH | NX_NOTIFY_ON_TOUCH | NX_NOTIFY_FORCES;
#ifdef PHYSICS_FEEDBACK
					int contactFlags2 = NX_NOTIFY_ON_START_TOUCH | NX_NOTIFY_ON_TOUCH | NX_NOTIFY_FORCES;
#else
					int contactFlags2 = NX_NOTIFY_ON_START_TOUCH | NX_NOTIFY_FORCES;
#endif
					//int contactFlags3 = NX_NOTIFY_ON_START_TOUCH | NX_NOTIFY_FORCES;

					scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_STATIC, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, contactFlags2);
					scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_STATIC, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, contactFlags2);
					scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_STATIC, PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, contactFlags1);
					scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, contactFlags2);
					scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, contactFlags2);
					//scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, contactFlags2);
scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, contactFlags1);
					scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, PHYSICS_COLLISIONGROUP_UNITS, contactFlags2);
scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_STATIC, PHYSICS_COLLISIONGROUP_UNITS, contactFlags2);
scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_STATIC, contactFlags1);
					//scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, PHYSICS_COLLISIONGROUP_UNITS, contactFlags3);
				}

				// Collision groups
				{
					// claw
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_CLAW, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_NOCOLLISION, false);
scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_CLAW, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, false);

					// Model particles
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false);

					// Doors
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_DOORS, PHYSICS_COLLISIONGROUP_DOORS, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_DOORS, PHYSICS_COLLISIONGROUP_STATIC, false);

					// Units and model particles
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_UNITS, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_UNITS, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, false);

					// Fluids
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false);

					// Fluids w/ detailed collision
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS_DETAILED, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS_DETAILED, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS_DETAILED, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS_DETAILED, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false);

					// Fluid containment
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_STATIC, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_UNITS, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_DOORS, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_FLUIDS_DETAILED, false);

					// No collision
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_STATIC, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_UNITS, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_DOORS, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, false);
					scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_NOCOLLISION, false);
				}
*/
			}
		}
	}
Example #27
0
int main(int argc, char **argv)
{
    //init and PVD
    bool initialized = false;
    NxPhysicsSDK *physicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION);
    if (!physicsSDK)
        return 0;
    else
        physicsSDK->getFoundationSDK().getRemoteDebugger()->connect("localhost", 5425);
    physicsSDK->setParameter(NX_CONTINUOUS_CD, true);

    initialized = true;

    //create a scene
    bool sceneInit = false;
    NxSceneDesc sceneDesc;
    sceneDesc.gravity.set(0, -9.81f, 0);
    gScene = physicsSDK->createScene(sceneDesc);

    if (gScene != NULL)
        sceneInit = true;

    //create a plane
    {
        NxActorDesc actorDesc;
        NxPlaneShapeDesc planeDesc;
        //planeDesc.normal = NxVec3(0, 0, 1);
        //planeDesc.d = -10.0f;

        actorDesc.shapes.pushBack(&planeDesc);
        gScene->createActor(actorDesc);
    }

    //create material
    NxMaterial *defaultMaterial = gScene->getMaterialFromIndex(0);
    defaultMaterial->setRestitution(0.3f);
    defaultMaterial->setStaticFriction(0.5f);
    defaultMaterial->setDynamicFriction(0.5f);



    //create a box
    {
        NxActorDesc actorDesc;
        NxBodyDesc bodyDesc;
        bodyDesc.angularDamping = 0.5;
        bodyDesc.linearVelocity = NxVec3(1, 0, 0);
        actorDesc.body = &bodyDesc;

        NxBoxShapeDesc boxDesc;
        boxDesc.dimensions = NxVec3(2.0f, 3.0f, 4.0f);
        actorDesc.shapes.pushBack(&boxDesc);
        actorDesc.density = 10.0f;
        actorDesc.globalPose.t = NxVec3(10.0f, 10.0f, 10.0f);
        gScene->createActor(actorDesc)->userData = NULL;
    }

    //create a cloth
    {
        // Create the objects in the scene
        NxActor* sphere1 = CreateSphere(NxVec3(-1, 0, -0.5), 1, 10);
        NxActor* box1 = CreateBox(NxVec3(1, 0, -1), NxVec3(1, 1, 1), 10);
        NxActor* box2 = CreateBox(NxVec3(0, 6.5, 0), NxVec3(5, 0.5, 0.5), 10);
        NxActor* box3 = CreateBox(NxVec3(0, 6.5, -7), NxVec3(5, 0.5, 0.5), 10);

        box2->setLinearDamping(5);
        box3->setLinearDamping(5);
        NxD6JointDesc d6Desc;
        d6Desc.actor[0] = NULL;
        d6Desc.actor[1] = box2;
        NxVec3 globalAnchor(0, 7, 0);
        d6Desc.localAnchor[0] = globalAnchor;
        box2->getGlobalPose().multiplyByInverseRT(globalAnchor, d6Desc.localAnchor[1]);
        box2->raiseBodyFlag(NX_BF_DISABLE_GRAVITY);

        box3->getGlobalPose().multiplyByInverseRT(globalAnchor, d6Desc.localAnchor[1]);
        box3->raiseBodyFlag(NX_BF_DISABLE_GRAVITY);

        d6Desc.localAxis[0] = NxVec3(1, 0, 0);
        d6Desc.localNormal[0] = NxVec3(0, 1, 0);
        d6Desc.localAxis[1] = NxVec3(1, 0, 0);
        d6Desc.localNormal[1] = NxVec3(0, 1, 0);

        d6Desc.twistMotion = NX_D6JOINT_MOTION_LOCKED;
        d6Desc.swing1Motion = NX_D6JOINT_MOTION_LOCKED;
        d6Desc.swing2Motion = NX_D6JOINT_MOTION_LOCKED;
        d6Desc.xMotion = NX_D6JOINT_MOTION_FREE;
        d6Desc.yMotion = NX_D6JOINT_MOTION_FREE;
        d6Desc.zMotion = NX_D6JOINT_MOTION_FREE;

        NxJoint* d6Joint = gScene->createJoint(d6Desc);

        NxClothDesc clothDesc;
        clothDesc.globalPose.t = NxVec3(4, 7, 0);
        clothDesc.thickness = 0.2;
        //clothDesc.density = 1;
        clothDesc.bendingStiffness = 0.5;
        clothDesc.stretchingStiffness = 1;
        //clothDesc.dampingCoefficient = 0.5;
        clothDesc.friction = 0.5;
        //clothDesc.collisionResponseCoefficient = 1;
        //clothDesc.attachmentResponseCoefficient = 1;
        //clothDesc.solverIterations = 5;
        //clothDesc.flags |= NX_CLF_STATIC;
        //clothDesc.flags |= NX_CLF_DISABLE_COLLISION;
        //clothDesc.flags |= NX_CLF_VISUALIZATION;
        //clothDesc.flags |= NX_CLF_GRAVITY;
        clothDesc.flags |= NX_CLF_BENDING;
        //clothDesc.flags |= NX_CLF_BENDING_ORTHO;
        clothDesc.flags |= NX_CLF_DAMPING;
        //clothDesc.flags |= NX_CLF_COMDAMPING;
        clothDesc.flags |= NX_CLF_COLLISION_TWOWAY;

        clothDesc.flags &= ~NX_CLF_HARDWARE;
        clothDesc.flags |= NX_CLF_FLUID_COLLISION;
        clothDesc.selfCollisionThickness = 10.0f;


        NxReal w = 8;
        NxReal h = 7;
        NxReal d = 0.05;
        NxClothMeshDesc meshDesc;
        bool mInitDone = false;

        int numX = (int)(w / d) + 1;
        int numY = (int)(h / d) + 1;


        meshDesc.numVertices = (numX + 1) * (numY + 1);
        meshDesc.numTriangles = numX*numY * 2;
        meshDesc.pointStrideBytes = sizeof(NxVec3);
        meshDesc.triangleStrideBytes = 3 * sizeof(NxU32);
        meshDesc.vertexMassStrideBytes = sizeof(NxReal);
        meshDesc.vertexFlagStrideBytes = sizeof(NxU32);
        meshDesc.points = (NxVec3*)malloc(sizeof(NxVec3)*meshDesc.numVertices);
        meshDesc.triangles = (NxU32*)malloc(sizeof(NxU32)*meshDesc.numTriangles * 3);
        meshDesc.vertexMasses = 0;
        meshDesc.vertexFlags = 0;
        meshDesc.flags = 0;

        int i, j;
        NxVec3 *p = (NxVec3*)meshDesc.points;
        for (i = 0; i <= numY; i++) {
            for (j = 0; j <= numX; j++) {
                p->set(-d*j, 0.0f, -d*i);
                p++;
            }
        }

        NxU32 *id = (NxU32*)meshDesc.triangles;
        for (i = 0; i < numY; i++) {
            for (j = 0; j < numX; j++) {
                NxU32 i0 = i * (numX + 1) + j;
                NxU32 i1 = i0 + 1;
                NxU32 i2 = i0 + (numX + 1);
                NxU32 i3 = i2 + 1;
                if ((j + i) % 2) {
                    *id++ = i0;
                    *id++ = i2;
                    *id++ = i1;
                    *id++ = i1;
                    *id++ = i2;
                    *id++ = i3;
                }
                else {
                    *id++ = i0;
                    *id++ = i2;
                    *id++ = i3;
                    *id++ = i0;
                    *id++ = i3;
                    *id++ = i1;
                }
            }
        }
        // if we want tearing we must tell the cooker
        // this way it will generate some space for particles that will be generated during tearing
        if (meshDesc.flags & NX_CLF_TEARABLE)
            meshDesc.flags |= NX_CLOTH_MESH_TEARABLE;


        //cooking
        static NxCookingInterface *gCooking = 0;
        gCooking = NxGetCookingLib(NX_PHYSICS_SDK_VERSION);
        gCooking->NxInitCooking();

        gCooking->NxCookClothMesh(meshDesc, UserStream("e:\\cooked.bin", false));

        //Meshdata Buffers
        NxMeshData mReceiveBuffers;
        // here we setup the buffers through which the SDK returns the dynamic cloth data
        // we reserve more memory for vertices than the initial mesh takes
        // because tearing creates new vertices
        // the SDK only tears cloth as long as there is room in these buffers
        NxU32 numVertices = meshDesc.numVertices;
        NxU32 numTriangles = meshDesc.numTriangles;

        NxU32 maxVertices = 2 * numVertices;
        mReceiveBuffers.verticesPosBegin = (NxVec3*)malloc(sizeof(NxVec3)*maxVertices);
        mReceiveBuffers.verticesNormalBegin = (NxVec3*)malloc(sizeof(NxVec3)*maxVertices);
        mReceiveBuffers.verticesPosByteStride = sizeof(NxVec3);
        mReceiveBuffers.verticesNormalByteStride = sizeof(NxVec3);
        mReceiveBuffers.maxVertices = maxVertices;
        mReceiveBuffers.numVerticesPtr = (NxU32*)malloc(sizeof(NxU32));

        // the number of triangles is constant, even if the cloth is torn
        NxU32 maxIndices = 3 * numTriangles;
        mReceiveBuffers.indicesBegin = (NxU32*)malloc(sizeof(NxU32)*maxIndices);
        mReceiveBuffers.indicesByteStride = sizeof(NxU32);
        mReceiveBuffers.maxIndices = maxIndices;
        mReceiveBuffers.numIndicesPtr = (NxU32*)malloc(sizeof(NxU32));

        // the parent index information would be needed if we used textured cloth
        NxU32 maxParentIndices = maxVertices;
        mReceiveBuffers.parentIndicesBegin = (NxU32*)malloc(sizeof(NxU32)*maxParentIndices);
        mReceiveBuffers.parentIndicesByteStride = sizeof(NxU32);
        mReceiveBuffers.maxParentIndices = maxParentIndices;
        mReceiveBuffers.numParentIndicesPtr = (NxU32*)malloc(sizeof(NxU32));

        // init the buffers in case we want to draw the mesh
        // before the SDK as filled in the correct values
        *mReceiveBuffers.numVerticesPtr = 0;
        *mReceiveBuffers.numIndicesPtr = 0;



        clothDesc.clothMesh = physicsSDK->createClothMesh(UserStream("e:\\cooked.bin", true));
        clothDesc.meshData = mReceiveBuffers;

        NxCloth *mCloth;
        mCloth = gScene->createCloth(clothDesc);
        mCloth->attachToShape(*box2->getShapes(), NX_CLOTH_ATTACHMENT_TWOWAY);
        mCloth->attachToShape(*box3->getShapes(), NX_CLOTH_ATTACHMENT_TWOWAY);
    }

    //create fluid 1
    {
        //fluid = CreateFluid(NxVec3(0, 12, -3.5), 15, 0.1, gScene);
    }
    //create fluid 2
    {
        //Create a set of initial particles
        ParticleSDK*	initParticles = new ParticleSDK[max_particles];
        unsigned initParticlesNum = 0;

        //Create particle filled sphere in buffer.
        NxVec3 fluidPos(0, 2, 0);
        NxVec3 offsetPos(0, 12, -3.5);
        float distance = 0.1f;
        //#ifdef __PPCGEKKO__
        //	unsigned sideNum = 12;
        //#else
        unsigned sideNum = 16;
        //#endif

        //Setup structure to pass initial particles.
        NxParticleData initParticleData;
        initParticlesNum = 0;
        initParticleData.numParticlesPtr = &initParticlesNum;
        initParticleData.bufferPos = &initParticles[0].position.x;
        initParticleData.bufferPosByteStride = sizeof(ParticleSDK);
        initParticleData.bufferVel = &initParticles[0].velocity.x;
        initParticleData.bufferVelByteStride = sizeof(ParticleSDK);

        CreateParticleSphere(initParticleData, max_particles, false, offsetPos, NxVec3(0, 0, 0), 0.0f, distance, sideNum);

        //Setup fluid descriptor
        NxFluidDesc fluidDesc;
        fluidDesc.maxParticles = max_particles;
        fluidDesc.kernelRadiusMultiplier = 2.0f;
        fluidDesc.restParticlesPerMeter = 10.0f;
        fluidDesc.motionLimitMultiplier = 3.0f;
        fluidDesc.packetSizeMultiplier = 8;
        fluidDesc.collisionDistanceMultiplier = 0.1;
        fluidDesc.stiffness = 50.0f;
        fluidDesc.viscosity = 40.0f;
        fluidDesc.restDensity = 1000.0f;
        fluidDesc.damping = 0.0f;
        fluidDesc.restitutionForStaticShapes = 0.0f;
        fluidDesc.dynamicFrictionForStaticShapes = 0.05f;
        fluidDesc.simulationMethod = NX_F_SPH;
        fluidDesc.flags &= ~NX_FF_HARDWARE;

        //Add initial particles to fluid creation.
        fluidDesc.initialParticleData = initParticleData;

        //Create user fluid.
        //- create NxFluid in NxScene
        //- setup the buffers to read from data from the SDK
        //- set NxFluid::userData field to MyFluid instance
        bool trackUserData = false;
        bool provideCollisionNormals = false;
        MyFluid* fluid = new MyFluid(gScene, fluidDesc, trackUserData, provideCollisionNormals, NxVec3(0.4f, 0.5f, 0.9f), 0.03f);
        assert(fluid);
        gMyFluids.pushBack(fluid);
    }
    //simulate
    for (int i = 0; i < 3000; i++)
    {
        gScene->simulate(1.0f / 60.f);
        gScene->flushStream();
        //GetPhysicsResults
        gScene->fetchResults(NX_RIGID_BODY_FINISHED, true);

        // update fluid status
        if (i == 400)
        {
            MyFluid* fluid = gMyFluids[0];
            const ParticleSDK* particles = fluid->getParticles();
            unsigned particlesNum = fluid->getParticlesNum();
            if (!gUpdates)
            {
                gUpdates = new ParticleUpdateSDK[max_particles];
            }
            for (unsigned i = 0; i < particlesNum; i++)
            {
                ParticleUpdateSDK& update = gUpdates[i];
                NxVec3& force = update.force;
                force.set(0, 0, 0);
                NxU32& flags = update.flags;
                if (i >= particlesNum/2)
                {
                    flags = 0;
                    flags |= NX_FP_DELETE;
                }
                else
                {
                    flags = 0;
                }

            }
            //在这里更改粒子的属性
            NxParticleUpdateData updateData;
            updateData.bufferFlag = &gUpdates[0].flags;
            updateData.bufferFlagByteStride = sizeof(ParticleUpdateSDK);
            fluid->getNxFluid()->updateParticles(updateData);
        }
    }


    //release
    if (physicsSDK != NULL)
    {
        if (gScene != NULL)
            physicsSDK->releaseScene(*gScene);
        gScene = NULL;
        NxReleasePhysicsSDK(physicsSDK);
        physicsSDK = NULL;
    }
    return 1;
}
//----------------------------------------------------------------------------
// Init data
//----------------------------------------------------------------------------
bool CPhysicsManager::Init ()
{

	m_bIsOk = true;

	m_pMyAllocator = new CPhysicUserAllocator;
	assert(m_pMyAllocator);
	m_bIsOk = (m_pMyAllocator != NULL);
	if (m_bIsOk)
	{
		LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Inicializando la libreria PhysX");
		// Initialize PhysicsSDK
		NxPhysicsSDKDesc desc;
		NxSDKCreateError errorCode = NXCE_NO_ERROR;
		m_pPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, m_pMyAllocator, NULL, desc, &errorCode);


		/*Precompilation Directives*/
		#if defined( _DEBUG )
		#define USE_DEBUGGER
		#ifdef USE_DEBUGGER
		m_pPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect("127.0.0.1");
		#endif
		#endif
		

		m_bIsOk = (m_pPhysicsSDK != NULL);
		if (m_bIsOk)
		{
			LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Creado el PhysXSDK");
			LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: -------PhsX Settings---");
			LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: El valor del SkinWidth es: %f", 
				m_InitParams.m_fSkinWidth);


			//TODO por XML m_pPhysicsSDK->setParameter(NX_SKIN_WIDTH, m_InitParams.m_fSkinWidth);
			m_pPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.1f);

			//CODI PER PRINTAR INFO DELS JOINTS
			m_pPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);
			m_pPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LIMITS, 1);
			m_pPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LOCAL_AXES, 1);
			m_pPhysicsSDK->setParameter(NX_CONTINUOUS_CD, 1);

			// Create a scene
			LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: El valor de la gravedad es: %f",
				m_InitParams.m_fGravity);
			NxSceneDesc sceneDesc;
			//TODO por XML sceneDesc.gravity = NxVec3(0.0f, m_InitParams.m_fGravity, 0.0f);
			sceneDesc.gravity = NxVec3(0.0f, -9.8f, 0.0f);
			m_pScene = m_pPhysicsSDK->createScene(sceneDesc);
			
			m_bIsOk = (m_pScene != NULL);
			if (m_bIsOk)
			{
				LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Solo hay un material, con los siguientes params");
				LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: DefaultMaterial->Restitution %f:",
					m_InitParams.m_Restitution_DefMat);
				LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: DefaultMaterial->StaticFriction %f:",
					m_InitParams.m_StaticFriction_DefMat);
				LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: DefaultMaterial->DynamicFriction %f:",
					m_InitParams.m_DynamicFriction_DefMat);
				LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: ----END PhsX Settings---");
				// Set default material
				NxMaterial* defaultMaterial = m_pScene->getMaterialFromIndex(0);
				defaultMaterial->setRestitution(m_InitParams.m_Restitution_DefMat);
				defaultMaterial->setStaticFriction(m_InitParams.m_StaticFriction_DefMat);
				defaultMaterial->setDynamicFriction(m_InitParams.m_DynamicFriction_DefMat);

				//Collision Flags
				//m_pScene->setGroupCollisionFlag(ECG_ARMA,ECG_ESCENARI,true);


				 //Create a controllerManager
				m_pControllerManager = NxCreateControllerManager(m_pMyAllocator);
				m_bIsOk = (m_pControllerManager != NULL);
				if (m_bIsOk)
				{
				LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Creado el controlador de caracteres");
				m_pCookingMesh = new CPhysicCookingMesh();
				assert(m_pCookingMesh);
				m_bIsOk = m_pCookingMesh->Init(m_pPhysicsSDK, m_pMyAllocator);
				if (m_bIsOk) {
				LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Creado el CookingMesh");
				}

				} //m_bIsOk m_pControllerManager?*/

			}//isOk m_pScene?

		}//isOk m_pPhysicsSDK ?

	}//isOk m_pMyAllocator ?

	if (!m_bIsOk)
	{
		std::string msg_error = "PhysicsManager::Init-> Error en la inicializacion de PhysX";
		LOGGER->AddNewLog(ELL_ERROR, msg_error.c_str());
		Release();
		throw CException(__FILE__, __LINE__, msg_error);
	}

	return m_bIsOk;
}
Example #29
0
void InitNx()
{
	// Create a memory allocator
    gAllocator = new UserAllocator;

    // Create the physics SDK
    gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator);
    if (!gPhysicsSDK)  return;

	// Set the physics parameters
	gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.01);

	// Set the debug visualization parameters
	gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LIMITS, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LOCAL_AXES, 1);

    // Create the scene
    NxSceneDesc sceneDesc;
    sceneDesc.gravity               = gDefaultGravity;
    sceneDesc.simType				= NX_SIMULATION_HW;
    gScene = gPhysicsSDK->createScene(sceneDesc);	
 if(!gScene){ 
		sceneDesc.simType				= NX_SIMULATION_SW; 
		gScene = gPhysicsSDK->createScene(sceneDesc);  
		if(!gScene) return;
	}

	// Create the default material
	NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); 
	defaultMaterial->setRestitution(0.5);
	defaultMaterial->setStaticFriction(0.5);
	defaultMaterial->setDynamicFriction(0.5);

	// Create the objects in the scene
	CreateGroundPlane();

	// Slider Joint
	capsule1 = CreateCapsule(NxVec3(0,5,0), 1, 0.5, 10);
	capsule1->raiseBodyFlag(NX_BF_KINEMATIC);
	capsule2 = CreateCapsule(NxVec3(0,3,0), 1, 0.5, 10);
    capsule2->raiseBodyFlag(NX_BF_DISABLE_GRAVITY);

	NxVec3 globalAnchor = gJointStartPos;
	NxVec3 globalAxis = NxVec3(0,1,0);
	d6Joint = CreateD6Joint(capsule1, capsule2, globalAnchor, globalAxis);

	ball = CreateFollowBall(gBallStartPos,0.25,1);
	ball->raiseBodyFlag(NX_BF_KINEMATIC);

	NxMat33 orient = ball->getGlobalOrientation();
	NxMat33 controlOrient;
	controlOrient.setRow(0, orient.getRow(2));
	controlOrient.setRow(1, orient.getRow(0));
	controlOrient.setRow(2, orient.getRow(1));
	ball->setGlobalOrientation(controlOrient);

	gSelectedActor = ball;
	gForceStrength = 1500;
	gCameraSpeed = 10;

	box = CreateBox(NxVec3(3,0,0), NxVec3(0.5,1,0.5), 20);
	sphere = CreateSphere(NxVec3(0,0,3), 1, 10);
	capsule = CreateCapsule(NxVec3(-3,0,0), 2, 0.5, 10);
	pyramid = CreatePyramid(NxVec3(0,0,-3), NxVec3(0.75,1.5,0.75), 10);

	box->setLinearDamping(0.5);
	sphere->setLinearDamping(0.5);
	capsule->setLinearDamping(0.5);
	pyramid->setLinearDamping(0.5);

	AddUserDataToActors(gScene);

	// Initialize HUD
	InitializeHUD();

	// Get the current time
	getElapsedTime();

	// Start the first frame of the simulation
	if (gScene)  StartPhysics();
}
Example #30
0
/***********************************************************
	init function
***********************************************************/
void PhysXEngine::Init()
{
	// Create the physics SDK
    gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION);
    if (!gPhysicsSDK)  
		return;

	if (gPhysicsSDK->getFoundationSDK().getRemoteDebugger())
		gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect("localhost", 5425);


	// Set the physics parameters
	gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.01f);

	// Set the debug visualization parameters
	gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);

    // Create the scene
    NxSceneDesc sceneDesc;
 	sceneDesc.simType				= NX_SIMULATION_SW;
    sceneDesc.gravity               = NxVec3(0,-9.8f,0);
    gScene = gPhysicsSDK->createScene(sceneDesc);	
	if(!gScene)
	{ 
		sceneDesc.simType			= NX_SIMULATION_SW; 
		gScene = gPhysicsSDK->createScene(sceneDesc);  
		if(!gScene) 
			return;
	}


	// Create the default material
	NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); 
	defaultMaterial->setRestitution(0.5);
	defaultMaterial->setStaticFriction(0.5);
	defaultMaterial->setDynamicFriction(0.5);


	// add a cube and a plane
	//CreatePlane(NxVec3(0, 0, 0), NxVec3(0, 1, 0));

	CreateBox(NxVec3(0, 4, 0), 3.0f, 3.0f, 3.0f, 10, false);
	CreateBox(NxVec3(7, 10, 7), 2.0f, 3.0f, 2.0f, 10, true);
	CreateBox(NxVec3(20, 1, 20), 30.0f, 1.0f, 30.0f, 10, false);

	// init time
	_lasttime = SynchronizedTimeHandler::getInstance()->GetCurrentTimeDouble();


	// init character controllers
	gManager = NxCreateControllerManager(gAllocator);


	//float TimeStep = 1.0f / 60.0f;
	gScene->setTiming();


	// Start the first frame of the simulation
	if (gScene)  
		StartPhysics();

}