//=============================================================================
// PRIVATE FUNCTIONS
//=============================================================================
static physx::unique_ptr<PxConvexMesh> GenerateConvexFromDXMesh(PxPhysics &iPhysics, ID3DXMesh *iMesh)
{
	//Used to retrieve information from X file
	struct Mesh_FVF {
		D3DXVECTOR3 VertexPos;
		D3DXVECTOR3 Normal;
		D3DXVECTOR2 TexCoord;
	};

	int aNumVerticies = iMesh->GetNumVertices();
	DWORD FVFSize = D3DXGetFVFVertexSize(iMesh->GetFVF());

	//Create pointer for vertices
	PxVec3* verts = new PxVec3[aNumVerticies];

	char *DXMeshPtr;
	iMesh->LockVertexBuffer(D3DLOCK_READONLY, (void**)&DXMeshPtr);
	for(int i = 0; i < aNumVerticies; i++)
	{
		Mesh_FVF *DXMeshFVF = (Mesh_FVF*)DXMeshPtr;
		verts[i] = PxVec3(DXMeshFVF->VertexPos.x, DXMeshFVF->VertexPos.y, DXMeshFVF->VertexPos.z);
		DXMeshPtr += FVFSize;
	}
	iMesh->UnlockVertexBuffer();

	// Create descriptor for convex mesh
	PxConvexMeshDesc convexDesc;
	convexDesc.points.count		= aNumVerticies;
	convexDesc.points.stride	= sizeof(PxVec3);
	convexDesc.points.data		= verts;
	convexDesc.flags			= PxConvexFlag::eCOMPUTE_CONVEX;

	PxTolerancesScale toleranceScale;
	toleranceScale.length = 1.0f;
	toleranceScale.mass = 1000.0f;
	toleranceScale.speed = 9.8f;

	assert(toleranceScale.isValid());

	physx::unique_ptr<PxCooking> cooker = physx::unique_ptr<PxCooking>(
		PxCreateCooking(PX_PHYSICS_VERSION, iPhysics.getFoundation(), PxCookingParams(toleranceScale))
		);

	// Cooking from memory
	MemoryStream buf;
	physx::unique_ptr<PxConvexMesh> convexMesh;
	if(cooker->cookConvexMesh(convexDesc, buf))
	{
		convexMesh = physx::unique_ptr<PxConvexMesh>(iPhysics.createConvexMesh(buf));
	}	

	delete[] verts;

	return convexMesh;
}
		/**
		 * Method is used to initialize physics manager, init PhysX extensions and cooking objects.
		 */
		void PhysicsManager::initializePhysicsManager()
		{
			if(!PxInitExtensions(*physicsSDK))
				Logger::getInstance()->saveLog(Log<string>("Physics Extensions initialization error occurred!"));
			
			PxFoundation& foundation = physicsSDK->getFoundation();
			cooking = PxCreateCooking(PX_PHYSICS_VERSION, &foundation, PxCookingParams());

			if(!cooking)
				Logger::getInstance()->saveLog(Log<string>("Physics Cooking creation error occurred!"));

			defaultFilterShader = filterShader;
			initializeScene();
			addPhysicsMaterial("Default",Vector3D(0.5,0.5,0.0));
			//PxExtensionVisualDebugger::connect(physicsSDK->getPvdConnectionManager(),"localhost",5425, 10000, true);
		}
Example #3
0
bool Apex::InitPhysX()
{
    static PxDefaultErrorCallback gDefaultErrorCallback;
    static PxDefaultAllocator gDefaultAllocatorCallback;

    mFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gDefaultAllocatorCallback, gDefaultErrorCallback);
    if(!mFoundation)
        return false;

    bool recordMemoryAllocations = true;

    mPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *mFoundation,
                PxTolerancesScale(), recordMemoryAllocations);
    if(!mPhysics)
        return false;

    mCooking = PxCreateCooking(PX_PHYSICS_VERSION, *mFoundation, PxCookingParams());
    if (!mCooking)
        return false;

    if (!PxInitExtensions(*mPhysics))
        return false;
    

    //PxSceneDesc sceneDesc(mPhysics->getTolerancesScale());
    //sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f);

    //if(!sceneDesc.cpuDispatcher)
    //{
    //    mCpuDispatcher = PxDefaultCpuDispatcherCreate(mNbThreads);
    //    if(!mCpuDispatcher)
    //        return false;
    //    sceneDesc.cpuDispatcher    = mCpuDispatcher;
    //}

    //if(!sceneDesc.filterShader)
    //{
    //    sceneDesc.filterShader = PxDefaultSimulationFilterShader;
    //}
    //
    ///*#ifdef PX_WINDOWS
    //if(!sceneDesc.gpuDispatcher && mCudaContextManager)
    //{
    //    sceneDesc.gpuDispatcher = mCudaContextManager->getGpuDispatcher();
    //}
    //#*/
    //mProfileZoneManager = &PxProfileZoneManager::createProfileZoneManager(mFoundation);
    //pxtask::CudaContextManagerDesc cudaContextManagerDesc;
    //mCudaContextManager = pxtask::createCudaContextManager(*mFoundation,cudaContextManagerDesc, mProfileZoneManager);
    //sceneDesc.gpuDispatcher = mCudaContextManager->getGpuDispatcher();


    //mScene[mCurrentScene] = mPhysics->createScene(sceneDesc);
    //if (!mScene[mCurrentScene])
    //    return false;
    
    defaultMaterial = mPhysics->createMaterial(0.5f, 0.5f, 0.1f);    //static friction, dynamic friction, restitution
    if(!defaultMaterial)
        return false;

    // Create a plane
    PxRigidStatic* plane = PxCreatePlane(*mPhysics, PxPlane(PxVec3(0,1,0), 700), *defaultMaterial);
    if (!plane)
        return false;

    //mScene[mCurrentScene]->addActor(*plane);

    // Create a heightfield
    PhysXHeightfield* heightfield = new PhysXHeightfield();
    //heightfield->InitHeightfield(mPhysics, mScene[mCurrentScene], "terrain5.raw");

    // check if PvdConnection manager is available on this platform
    if(mPhysics->getPvdConnectionManager() == NULL)
	{
        return true;
	}

    // setup connection parameters
    const char*     pvd_host_ip = "127.0.0.1";  // IP of the PC which is running PVD
    int             port        = 5425;         // TCP port to connect to, where PVD is listening
    unsigned int    timeout     = 100;          // timeout in milliseconds to wait for PVD to respond,
                                                // consoles and remote PCs need a higher timeout.
    PxVisualDebuggerConnectionFlags connectionFlags = PxVisualDebuggerExt::getAllConnectionFlags();

    // and now try to connect
    pvdConnection = PxVisualDebuggerExt::createConnection(mPhysics->getPvdConnectionManager(),
        pvd_host_ip, port, timeout, connectionFlags);

    mPhysics->getVisualDebugger()->setVisualDebuggerFlag(PxVisualDebuggerFlags::eTRANSMIT_CONTACTS, true);

    return true;
}
Example #4
0
void GameWorld::init()
{
	gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback);
	if (!gFoundation) {
		printf("PxCreateFoundation failed!");
	}
	gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true);
	if (!PxInitExtensions(*gPhysics)) {
		printf("init error pxinit\n");
	}
	gCooking = PxCreateCooking(PX_PHYSICS_VERSION, *gFoundation, PxCookingParams(gPhysics->getTolerancesScale()));
	if (!gCooking) {
		printf("PxCreateCooking failed!\n");
	}
	PxSceneDesc sceneDesc(gPhysics->getTolerancesScale());
	sceneDesc.gravity = PxVec3(0.0f, -98.0f, 0.0f);
	gDispatcher = PxDefaultCpuDispatcherCreate(2);
	sceneDesc.cpuDispatcher = gDispatcher;
	sceneDesc.filterShader = PxDefaultSimulationFilterShader;
	gScene = gPhysics->createScene(sceneDesc);
	gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f);
	PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 0, 1, 400), *gMaterial);
	gScene->addActor(*groundPlane);
	groundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 0, -1, 400), *gMaterial);
	gScene->addActor(*groundPlane);
	groundPlane = PxCreatePlane(*gPhysics, PxPlane(1, 0, 0, 280), *gMaterial);
	gScene->addActor(*groundPlane);
	groundPlane = PxCreatePlane(*gPhysics, PxPlane(-1, 0, 0, 280), *gMaterial);
	gScene->addActor(*groundPlane);
	groundPlane = PxCreatePlane(*gPhysics, PxPlane(0, -1, 0, 600), *gMaterial);
	gScene->addActor(*groundPlane);
	groundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, -1), *gMaterial);
	gScene->addActor(*groundPlane);
	gGround.loadFromObj(GROUND_FILE);
	gGround.cookingMesh(*gPhysics, *gCooking);
	gGround.createActor(*gMaterial, *gPhysics);
	gScene->addActor(*(gGround.actor));

	//包围盒
	box.loadFromObj(BOX_FILE);

	//初始化飞球
	pxFlyBall = new PxFlyBall(Color4f(1.0, 200 / 255.0, 0), 5.0);
	Material mtl;
	PerlinImage perlinYellow = createPerlinLightYelloImage(40, 40, 6, 1.8);
	PerlinTexture(perlinYellow, mtl.kd_texid);
	mtl.ka = Color4f(1, 1, 1, 1);
	mtl.kd = Color4f(1, 1, 1, 1);
	mtl.ks = Color4f(1, 1, 1, 1);
	pxFlyBall->mtl = mtl;
	pxFlyBall->createPxBall(*gPhysics, PxTransform(PxVec3(rand() % 500 - 250, 100, rand() % 700 - 350)), *gMaterial);
	pxFlyBall->pxActor->setAngularDamping(0.5);
	perlinYellow.clear();
	gScene->addActor(*(pxFlyBall->pxActor));

	//初始化白球
	pxControlBall = new PxControlBall(Color4f(1.0, 1.0, 1.0), 5.0);
	PerlinImage perlinGray = createPerlinGrayImage(40, 40, 6, 1.8);
	PerlinTexture(perlinGray, mtl.kd_texid);
	mtl.ka = Color4f(1, 1, 1, 1);
	mtl.kd = Color4f(1, 1, 1, 1);
	mtl.ks = Color4f(0, 0, 0, 0);
	pxControlBall->mtl = mtl;
	pxControlBall->createPxBall(*gPhysics, PxTransform(PxVec3(0, 50, 0)), *gMaterial);
	pxControlBall->pxActor->setAngularDamping(0.5);
	perlinGray.clear();
	gScene->addActor(*(pxControlBall->pxActor));
	
	GLfloat light1PosType[] = { -5.0,1.0,5.0,0.0 };
	GLfloat whiteColor[] = { 1.0,1.0,1.0,1.0 };
	GLfloat darkColor[] = { 0.4,0.4,0.4,1 };
	GLfloat specColor[] = { 1,1,1,1 };
	GLfloat lightColor[] = { 1,1,1,1 };
	GLfloat globalAmbient[] = { 0.2,0.2,0.2,1.0 };
	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, globalAmbient);
	glLightfv(GL_LIGHT1, GL_AMBIENT, darkColor);
	glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor);
	glLightfv(GL_LIGHT1, GL_SPECULAR, specColor);
	glLightfv(GL_LIGHT1, GL_POSITION, light1PosType);
}
void Gameplay::entityInit(Object * p)
{
    // load config
    _config = new TiXmlDocument( "./cfg/config.xml" );
    _config->LoadFile();

    // read pitch shift option    
    TiXmlElement* xmlSound = Gameplay::iGameplay->getConfigElement( "sound" ); assert( xmlSound );
    int pitchShift;
    xmlSound->Attribute( "pitchShift", &pitchShift );
    _pitchShiftIsEnabled = ( pitchShift != 0 );   

	// read cheats option    
    TiXmlElement* details = Gameplay::iGameplay->getConfigElement( "details" ); assert( details );
    int cheats;
    details->Attribute( "cheats", &cheats );
    _cheatsEnabled = ( cheats != 0 );  

	// read free jumping mode  
    int freemode;
    details->Attribute( "freemode", &freemode );
    _freeModeIsEnabled = ( freemode != 0 ); 

	// read meters / feet mode  
    int units;
    details->Attribute( "units", &units );
    _feetModeIsEnabled = ( units != 0 ); 

    // setup random number generation
    getCore()->getRandToolkit()->setSeed( GetTickCount() );


    // retrieve interfaces
    queryInterface( "Engine", &iEngine ); assert( iEngine );
    queryInterface( "Gui", &iGui ); assert( iGui );
    queryInterface( "Language", &iLanguage ); assert( iLanguage );
    queryInterface( "Input", &iInput ); assert( iInput );
    queryInterface( "Audio", &iAudio ); assert( iAudio );
    if( !iAudio || !iInput || !iLanguage || !iGui || !iEngine )
    {
        throw Exception( "One or more core modules are not found, so gameplay will Crash Right Now!" );
    }

    // check language module
    if( wcscmp( iLanguage->getVersionString(), ::version.getVersionString() ) != 0 )
    {
        // incompatible module? - show no localization data
        iLanguage->reset();
    }

	getCore()->logMessage("Version: %ls (Clean)", ::version.getVersionString());

    // create input device
    _inputDevice = iInput->createInputDevice();
    createActionMap();

    // create physics resources
	foundation = PxCreateFoundation(PX_PHYSICS_VERSION, gDefaultAllocatorCallback, gDefaultErrorCallback);
    gPhysicsSDK = PxCreatePhysics(PX_PHYSICS_VERSION, *foundation, PxTolerancesScale() );
	pxCooking = PxCreateCooking(PX_PHYSICS_VERSION, *foundation, PxCookingParams(PxTolerancesScale()));
	PxInitExtensions(*gPhysicsSDK);

	//PHYSX3
    //NxGetPhysicsSDK()->setParameter( NX_VISUALIZATION_SCALE, 100.0f );
    //NxGetPhysicsSDK()->setParameter( NX_VISUALIZE_ACTOR_AXES, 1 );
    //NxGetPhysicsSDK()->setParameter( NX_VISUALIZE_COLLISION_SHAPES, 1 );
    //NxGetPhysicsSDK()->setParameter( NX_VISUALIZE_COLLISION_STATIC, 1 );
    //NxGetPhysicsSDK()->setParameter( NX_VISUALIZE_COLLISION_DYNAMIC,1 );

    // generate user community events from XML documents
    generateUserCommunityEvents();

    // open index
    TiXmlDocument* index = new TiXmlDocument( "./usr/index.xml" );
    index->LoadFile();

    // enumerate career nodes
    TiXmlNode* child = index->FirstChild();
    if( child ) do 
    {
        if( child->Type() == TiXmlNode::ELEMENT && strcmp( child->Value(), "career" ) == 0 )
        {
            _careers.push_back( new Career( static_cast<TiXmlElement*>( child ) ) );
        }
        child = child->NextSibling();
    }
    while( child != NULL );

    // close index document
    delete index;

    // create career for LICENSED_CHAR
    #ifdef GAMEPLAY_EDITION_ATARI
        createLicensedCareer();
    #endif

    // determine afterfx configuration
    TiXmlElement* video = getConfigElement( "video" ); assert( video );
    int afterfx = 0;
    video->Attribute( "afterfx", &afterfx );

    // create render target
    if( afterfx &&
        iEngine->isPfxSupported( engine::pfxBloom ) &&
        iEngine->isPfxSupported( engine::pfxMotionBlur ) )
    {
        _renderTarget = new AfterFxRT();
    }
    else
    {
        _renderTarget = new SimpleRT();
    }

    // play menu music
    playSoundtrack( "./res/sounds/music/dirty_moleculas_execution.ogg" );

    // evaluation protection
    #ifdef GAMEPLAY_EVALUATION_TIME
        SYSTEMTIME evaluationTime = GAMEPLAY_EVALUATION_TIME;
        SYSTEMTIME latestFileTime;
        if( getLatestFileTimeB( &latestFileTime ) )
        {
            if( isGreaterTime( &latestFileTime, &evaluationTime ) )
            {
                pushActivity( new Messagebox( Gameplay::iLanguage->getUnicodeString( 765 ) ) );
            }
            else
            {
                // startup
                _preloaded = new Preloaded();
                pushActivity( _preloaded );
            }
        }
    #else
        // determine if licence is required to play game
        bool licenceIsRequired = false;
        #ifndef GAMEPLAY_EDITION_ND
            #ifndef GAMEPLAY_EDITION_ATARI
                #ifndef GAMEPLAY_EDITION_POLISH
                    licenceIsRequired = false;
                #endif
            #endif
        #endif

        // startup        
        _preloaded = new Preloaded();
        pushActivity( _preloaded );
    #endif   
}