示例#1
0
//----------------------------------------------------------------------------
void Application::UpdateLogic() {
#ifndef MULTITHREADED
    // Update Input
    UpdateInput();

    // Update time variable

    // Run the game logic
    if (!isPaused) Update();

    // Render frame
    UpdateFrame();

    // Update physics simulation
    UpdatePhysics();

    // Update logic done after physics
    if (!isPaused) UpdateLate();

    // Update sound system
    UpdateSound();

    // Update delta time
    // Calculate FPS

    // Increment current frame variable TODO: removeme
    currentFrame++;
#ifdef _DEBUG
    // Update Debug Console
    UpdateDebug();
#endif
#endif
}
示例#2
0
文件: main.cpp 项目: ming-hai/CubicVR
int main(int argc, char **argv) 
{
	/* Initialize KOS */
	pvr_init(&params);

	printf("bullet test beginning\n");

	/* Get basic stuff initialized */
	glKosInit();


	glShadeModel(GL_SMOOTH);
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glClearDepth(1.0f);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);


	Logger::log("init..\n");
	InitScene();
	myTimer.start();
	Logger::log("go\n");

	mGamepad = new Gamepad();

	while(1) 
	{
		mGamepad->Update();
		if(mGamepad->Button(GAMEPAD_BTN_START))		break;

		
		/* Begin frame */
		glKosBeginFrame();


		UpdatePhysics();

		if (myTimer.getNumUpdates()%120==0)
		{
		 	printf("fps: %.4f\n",myTimer.getNumUpdates()/myTimer.totalSeconds());
		 	printf("fps (immediate): %.4f\n",1.0/myTimer.lastUpdateSeconds());
		}

		// printf("cam: %f,%f,%f\n",myCamera.position.x,myCamera.position.y,myCamera.position.z);
		// printf("target: %f,%f,%f\n",targetObj.controller().position.x,targetObj.controller().position.y,targetObj.controller().position.z);

		//printf("obj: %f,%f,%f\n",myRigidSceneObj.controller().position.x,myRigidSceneObj.controller().position.y,myRigidSceneObj.controller().position.z);

		/* Draw the "scene" */
		draw_gl();

		/* Finish the frame */
		glKosFinishFrame();
	}

	return 0;
}
示例#3
0
uint32 VolumeBrush::EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData)
{
    uint32 dwRet;

	switch(messageID)
	{
		case MID_UPDATE:
		{
			Update();
			break;
		}

		case MID_AFFECTPHYSICS:
		{
			UpdatePhysics((ContainerPhysics*)pData);
			break;
		}

		case MID_PRECREATE:
		{
			dwRet = GameBase::EngineMessageFn(messageID, pData, fData);
			if (fData == PRECREATE_WORLDFILE)
			{
				ReadProp((ObjectCreateStruct*)pData);
			}

			PostPropRead((ObjectCreateStruct*)pData);
			return dwRet;
			break;
		}

		case MID_INITIALUPDATE:
		{
			if (fData != INITIALUPDATE_SAVEGAME)
			{
				InitialUpdate();
			}

			CacheFiles();
			break;
		}

		case MID_SAVEOBJECT:
		{
            Save((HMESSAGEWRITE)pData, (uint32)fData);
		}
		break;

		case MID_LOADOBJECT:
		{
            Load((HMESSAGEREAD)pData, (uint32)fData);
		}
		break;

		default : break;
	}

	return GameBase::EngineMessageFn(messageID, pData, fData);
}
示例#4
0
void CChickenBoid::Update(float dt,SBoidContext &bc)
{
	if(m_physicsControlled)
	{
		UpdatePhysics(dt,bc);

		if(m_bThrown && m_pPhysics)
		{
			pe_status_awake tmp;
			bool bAwake = m_pPhysics->GetStatus(&tmp) != 0;

			if(!bAwake)
			{
				// Falled on ground after being thrown.
				m_bThrown = false;
				m_physicsControlled = false;
			}
		}

		return;
	}

	if(m_dead)
		return;

	m_lastThinkTime += dt;

	if(bc.waterLevel > bc.terrainZ)
		bc.terrainZ = bc.waterLevel;

	if(bc.followPlayer)
	{
		if(m_pos.GetSquaredDistance(bc.playerPos) > MAX_CHICKEN_DISTANCE_FROM_PLAYER*MAX_CHICKEN_DISTANCE_FROM_PLAYER)
		{
			float z = bc.MinHeight + (Boid::Frand()+1)/2.0f*(bc.MaxHeight - bc.MinHeight);
			m_pos = bc.playerPos + Vec3(Boid::Frand()*MAX_CHICKEN_DISTANCE_FROM_PLAYER,Boid::Frand()*MAX_CHICKEN_DISTANCE_FROM_PLAYER,z);
			m_pos.z = bc.engine->GetTerrainElevation(m_pos.x,m_pos.y) + bc.fBoidRadius*0.5f;
			m_speed = bc.MinSpeed;
			m_heading = Vec3(Boid::Frand(),Boid::Frand(),0).GetNormalized();
		}
	}

	Think(dt,bc);

	if(!m_landing)
	{
		// Calc movement with current velocity.
		CalcMovement(dt,bc,true);

		UpdateAnimationSpeed(bc);
		m_accel.Set(0,0,0);
	}
}
示例#5
0
bool Engine::Update()
{ BROFILER_FRAME("MainThread")
	UpdateInput();

	UpdateMessages();

	UpdateLogic();

	UpdateScene();

	UpdatePhysics();

	Draw();

	return true;
}
示例#6
0
文件: Player.cpp 项目: tehcyx/Vox
// Updating
void Player::Update(float dt)
{
	// Update the voxel model
	float animationSpeeds[AnimationSections_NUMSECTIONS] = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f };
	m_pVoxelCharacter->Update(dt, animationSpeeds);
	m_pVoxelCharacter->SetWeaponTrailsOriginMatrix(dt, m_worldMatrix);

	// Update / Create weapon lights and particle effects
	UpdateWeaponLights(dt);
	UpdateWeaponParticleEffects(dt);

	// Update timers
	UpdateTimers(dt);

	// Physics update
	UpdatePhysics(dt);
}
示例#7
0
void MainScene::update(float dt)
{
   UpdateEntity();
   UpdateCamera();
   EntityScheduler::Instance().Update();
   // Update all the debug info
   Notifier::Instance().Notify(NE_UPDATE_DEBUG_INFO,true);
   // Update the physics.
   UpdatePhysics();
   // Clear out any old information
   GraphSensorManager::Instance().ClearChangedSensors();

   Viewport::Instance().Update();
#ifdef TEST_SEARCH_PERFORMANCE
   TestSearchPerformance();
#endif
}
    void Update() final
    {
        const float kFrameTime = GetFrameTime();

        // Update light parameters
        light_angle_ += 0.2f * kFrameTime;
        light_position_.Set(light_distance_*cosf(light_angle_), light_distance_, light_distance_*sinf(light_angle_));

        UpdatePhysics();

        console_->Update(kFrameTime);

        // Camera should be updated after physics
        camera_manager_->Update(kFrameTime);

        // Update matrices
        UpdateProjectionMatrix();
        renderer_->SetViewMatrix(camera_manager_->view_matrix());
        projection_view_matrix_ = renderer_->projection_matrix() * renderer_->view_matrix();

		BindShaderVariables();
    }
示例#9
0
void Application::run(){
	DeltaTime = irrTimer->getTime() - TimeStamp;
	TimeStamp = irrTimer->getTime();

	printf("%f\n", (float)DeltaTime); 
	if(!paused){
		UpdatePhysics(6);
		activeQuad->update(DeltaTime);
	}
	
	updateNetwork(); 

	irrDriver->beginScene(true, true, SColor(255, 20, 0, 0));
	
	irrScene->drawAll();
	
	// debug
	activeQuad->render(irrDriver); 
	
	irrGUI->drawAll();
	irrDriver->endScene();
	irrDevice->run();
}
示例#10
0
//----------------------------------------------------------------------
void CGunTurret::DestroyedGeometry(bool use)
{
	m_destroyed = use;

	CItem::DestroyedGeometry(use);

	if(!m_geometry[eIGS_Destroyed].empty())
	{
		if(use)
		{
			GetEntity()->SetSlotLocalTM(eIGS_Destroyed, GetEntity()->GetSlotLocalTM(eIGS_ThirdPerson, false));
		}

		DrawSlot(eIGS_Aux1,!use);
		SetAspectProfile(eEA_Physics, eIPhys_PhysicalizedRigid);
		UpdatePhysics();
	}

	if(use)
	{
		EnableUpdate(false, eIUS_General);
		Quiet();
	}
}
void DemoEntityManager::RenderFrame ()
{
	dTimeTrackerEvent(__FUNCTION__);

	// Make context current
	if (m_mainWindow->m_suspendVisualUpdates) {
		return;
	}

	dFloat timestep = dGetElapsedSeconds();	
	m_mainWindow->CalculateFPS(timestep);

	// update the the state of all bodies in the scene
	unsigned64 time0 = dGetTimeInMicrosenconds ();
	UpdatePhysics(timestep);
	unsigned64 time1 = dGetTimeInMicrosenconds ();
	m_mainThreadPhysicsTime = dFloat ((time1 - time0) / 1000.0f);

	// Get the interpolated location of each body in the scene
	m_cameraManager->InterpolateMatrices (this, CalculateInteplationParam());

	// Our shading model--Goraud (smooth). 
	glShadeModel (GL_SMOOTH);

	// Culling. 
	glCullFace (GL_BACK);
	glFrontFace (GL_CCW);
	glEnable (GL_CULL_FACE);

	//	glEnable(GL_DITHER);

	// z buffer test
	glEnable(GL_DEPTH_TEST);
	glDepthFunc (GL_LEQUAL);

	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
	glHint(GL_POLYGON_SMOOTH_HINT, GL_FASTEST);

	glClearColor (0.5f, 0.5f, 0.5f, 0.0f );
	//glClear( GL_COLOR_BUFFER_BIT );
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


	// set default lightning
	//	glDisable(GL_BLEND);
	glEnable (GL_LIGHTING);

	// make sure the model view matrix is set to identity before setting world space ligh sources
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	dFloat cubeColor[] = { 1.0f, 1.0f, 1.0f, 1.0 };
	glMaterialParam(GL_FRONT, GL_SPECULAR, cubeColor);
	glMaterialParam(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, cubeColor);
	glMaterialf(GL_FRONT, GL_SHININESS, 50.0);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

	// one light form the Camera eye point
	GLfloat lightDiffuse0[] = { 0.5f, 0.5f, 0.5f, 0.0 };
	GLfloat lightAmbient0[] = { 0.0f, 0.0f, 0.0f, 0.0 };
	dVector camPosition (m_cameraManager->GetCamera()->m_matrix.m_posit);
	GLfloat lightPosition0[] = {camPosition.m_x, camPosition.m_y, camPosition.m_z};

	glLightfv(GL_LIGHT0, GL_POSITION, lightPosition0);
	glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient0);
	glLightfv(GL_LIGHT0, GL_DIFFUSE, lightDiffuse0);
	glLightfv(GL_LIGHT0, GL_SPECULAR, lightDiffuse0);
	glEnable(GL_LIGHT0);


	// set just one directional light
	GLfloat lightDiffuse1[] = { 0.7f, 0.7f, 0.7f, 0.0 };
	GLfloat lightAmbient1[] = { 0.2f, 0.2f, 0.2f, 0.0 };
	GLfloat lightPosition1[] = { -500.0f, 200.0f, 500.0f, 0.0 };

	glLightfv(GL_LIGHT1, GL_POSITION, lightPosition1);
	glLightfv(GL_LIGHT1, GL_AMBIENT, lightAmbient1);
	glLightfv(GL_LIGHT1, GL_DIFFUSE, lightDiffuse1);
	glLightfv(GL_LIGHT1, GL_SPECULAR, lightDiffuse1);
	glEnable(GL_LIGHT1);

	// update Camera
	m_cameraManager->GetCamera()->SetViewMatrix(GetWidth(), GetHeight());

	// render all entities
	if (m_mainWindow->m_hideVisualMeshes) {
		if (m_sky) {
			glPushMatrix();	
			m_sky->Render(timestep, this);
			glPopMatrix();
		}

	} else {
		for (dListNode* node = dList<DemoEntity*>::GetFirst(); node; node = node->GetNext()) {
			DemoEntity* const entity = node->GetInfo();
			glPushMatrix();	
			entity->Render(timestep, this);
			glPopMatrix();
		}
	}

	if (m_tranparentHeap.GetCount()) {
		dMatrix modelView;
		glGetFloat (GL_MODELVIEW_MATRIX, &modelView[0][0]);
		while (m_tranparentHeap.GetCount()) {
			const TransparentMesh& transparentMesh = m_tranparentHeap[0];
			glLoadIdentity();
			glLoadMatrix(&transparentMesh.m_matrix[0][0]);
			transparentMesh.m_mesh->RenderTransparency();
			m_tranparentHeap.Pop();
		}
		glLoadMatrix(&modelView[0][0]);
	}


	m_cameraManager->RenderPickedTarget ();

	if (m_mainWindow->m_showContactPoints) {
		RenderContactPoints (GetNewton());
	}

	if (m_mainWindow->m_showNormalForces) {
		RenderNormalForces (GetNewton());
	}

	if (m_mainWindow->m_showNormalForces) {
//	if (1) {
		// see if there is a vehicle controller and 
		void* const vehListerNode = NewtonWorldGetPreListener(GetNewton(), VEHICLE_PLUGIN_NAME);
		if (vehListerNode) {
			CustomVehicleControllerManager* const manager = (CustomVehicleControllerManager*)NewtonWorldGetListenerUserData(GetNewton(), vehListerNode);
			manager->Debug();
		}

		void* const characterListerNode = NewtonWorldGetPreListener(GetNewton(), PLAYER_PLUGIN_NAME);
		if (characterListerNode) {
			CustomPlayerControllerManager* const manager = (CustomPlayerControllerManager*)NewtonWorldGetListenerUserData(GetNewton(), characterListerNode);
			manager->Debug();
		}
	}



	if (m_mainWindow->m_showAABB) {
		RenderAABB (GetNewton());
	}

	if (m_mainWindow->m_showCenterOfMass) {
		RenderCenterOfMass (GetNewton());
	}

	if (m_mainWindow->m_showJoints) {
		RenderJointsDebugInfo (GetNewton(), 0.5f);
	}


   DEBUG_DRAW_MODE mode = m_solid;
   if (m_mainWindow->m_debugDisplayMode) {
      mode = (m_mainWindow->m_debugDisplayMode == 1) ? m_solid : m_lines;
      DebugRenderWorldCollision (GetNewton(), mode);
   }

	if (m_mainWindow->m_showStatistics) {
		dVector color (1.0f, 1.0f, 1.0f, 0.0f);
		Print (color, 10,  20, "render fps: %7.2f", m_mainWindow->m_fps);
		Print (color, 10,  42, "physics time on main thread: %7.2f ms", GetPhysicsTime() * 1000.0f);
		Print (color, 10,  64, "total memory: %d kbytes", NewtonGetMemoryUsed() / (1024));
		Print (color, 10,  86, "number of bodies: %d", NewtonWorldGetBodyCount(GetNewton()));
		Print (color, 10, 108, "number of threads: %d", NewtonGetThreadsCount(GetNewton()));
		Print (color, 10, 130, "auto sleep: %s", m_mainWindow->m_autoSleepState ? "on" : "off");
	}

	int lineNumber = 130 + 22;

	if (m_renderHood) {

		// set display for 2d render mode

		dFloat width = GetWidth();
		dFloat height = GetHeight();

		glColor3f(1.0, 1.0, 1.0);

		glPushMatrix();
		glMatrixMode(GL_PROJECTION);

		glLoadIdentity();
		gluOrtho2D(0, width, 0, height);
		
			glPushMatrix();
			glMatrixMode(GL_MODELVIEW);
			glLoadIdentity();

			glDisable(GL_LIGHTING);
			glDisable(GL_DEPTH_TEST);
			glEnable(GL_TEXTURE_2D);	

			glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

			// render 2d display
			m_renderHood (this, m_renderHoodContext, lineNumber);

			// restore display mode
			glMatrixMode(GL_PROJECTION);
			glPopMatrix();


		glMatrixMode(GL_MODELVIEW);
		glPopMatrix();
	}


	// draw everything and swap the display buffer
	glFlush();

	// Swap
	SwapBuffers();
}
示例#12
0
void GameBase::UpdateWorldPhysics(){	
	UpdatePhysics();
}
示例#13
0
void CBoidBird::Update( float dt,SBoidContext &bc )
{
	if (m_physicsControlled)
	{
		UpdatePhysics(dt,bc);
		return;
	}
	if (m_dead)
		return;
	
	if (m_heading.IsZero())
		m_heading = Vec3(1,0,0);

	m_lastThinkTime += dt;

	{
		if (bc.followPlayer && !m_spawnFromPt)
		{
			if (m_pos.GetSquaredDistance(bc.playerPos) > MAX_BIRDS_DISTANCE*MAX_BIRDS_DISTANCE)
			{
				float z = bc.MinHeight + (Boid::Frand()+1)/2.0f*(bc.MaxHeight - bc.MinHeight);
				m_pos = bc.playerPos + Vec3(Boid::Frand()*MAX_BIRDS_DISTANCE,Boid::Frand()*MAX_BIRDS_DISTANCE,z );
				m_speed = bc.MinSpeed + ((Boid::Frand()+1)/2.0f) / (bc.MaxSpeed - bc.MinSpeed);
				m_heading = Vec3(Boid::Frand(),Boid::Frand(),0).GetNormalized();
			}
		}

		if(m_status == Bird::TAKEOFF)
		{
			float timePassed = (gEnv->pTimer->GetFrameStartTime() - m_takeOffStartTime).GetSeconds();
			if(m_playingTakeOffAnim &&  timePassed >= m_TakeOffAnimLength)
			{
				m_playingTakeOffAnim = false;
				PlayAnimationId(Bird::ANIM_FLY,true);
			}
			else if( timePassed > TAKEOFF_TIME)
			{
				SetStatus(Bird::FLYING);
			}

		}

		if(m_status == Bird::LANDING)
		{
			Vec3 vDist(m_landingPoint - m_pos);
			float dist2 = vDist.GetLengthSquared2D();
			float dist = sqrt_tpl(dist2 + vDist.z*vDist.z);

			if(dist > 0.02f && m_pos.z > m_landingPoint.z)
			{
				//if(vDist.z < 3 && m_heading)
				vDist /= dist;
				float fInterpSpeed = 2+fabs(m_heading.Dot(vDist))*3.f;
				Interpolate(m_heading,vDist, fInterpSpeed, dt);
				m_heading.NormalizeSafe(); 
			
				if(m_heading.z < vDist.z)
				{
					Interpolate(m_heading.z,vDist.z,3.0f,dt);
					m_heading.NormalizeSafe();
				}

				bool wasLandDeceleratingAlready = m_landDecelerating;
				m_accel.zero();
				m_landDecelerating = dist < bc.landDecelerationHeight;
				if(m_landDecelerating)
				{
					float newspeed= m_startLandSpeed* dist/3.f;
					if(m_speed > newspeed)
						m_speed = newspeed;
 					if(m_speed < 0.2f)
 						m_speed = 0.2f;
					if(!wasLandDeceleratingAlready)
						PlayAnimationId(Bird::ANIM_LANDING_DECELERATING, true);
				}
				else
					m_startLandSpeed = m_speed;
			}
			else
				Landed(bc);

			CalcMovementBird( dt,bc,true );
			UpdatePitch(dt,bc);
			return;

		}

		if (m_status != Bird::ON_GROUND)
		{
			Think(dt,bc);

			// Calc movement with current velocity.
			CalcMovementBird( dt,bc,true );
		}
		else 
		{
			if(bc.walkSpeed > 0 && m_onGroundStatus == Bird::OGS_WALKING)
				ThinkWalk(dt,bc);
			CalcMovementBird( dt,bc,true );
		}

		m_accel.Set(0,0,0);
		UpdatePitch(dt,bc);

		// Check if landing/on ground after think().
		if ( m_status == Bird::LANDING ||(m_dying && m_status != Bird::ON_GROUND))
		{
			float LandEpsilon = 0.5f;

			// Check if landed on water.
			if (m_pos.z-bc.waterLevel < LandEpsilon+0.1f && !m_dying)
			{
				//! From water immidiatly take off.
				//! Gives fishing effect. 
				TakeOff(bc);
			}

		}

		m_actionTime += dt;

		if (m_status == Bird::ON_GROUND )
			UpdateOnGroundAction(dt, bc);
		else
		{
			if(!bc.noLanding && m_actionTime > m_maxActionTime 
				&& !static_cast<CBirdsFlock*>(m_flock)->IsPlayerNearOrigin())
				Land();
		}
	}








}
示例#14
0
文件: Item.cpp 项目: AlwaysGeeky/Vox
// Update
void Item::Update(float dt)
{
	if(m_erase)
	{
		return;
	}

	if(m_pVoxelItem != NULL)
	{
		m_pVoxelItem->Update(dt);
	}

	// Update grid position
	UpdateGridPosition();

	// Update timers
	UpdateTimers(dt);

	// Update player magnet
	UpdatePlayerMagnet(dt);

	// If we don't belong to a chunk
	if(m_pCachedGridChunk == NULL)
	{
		return;
	}

	// Make sure that an owning chunk knows about us
	if(m_pOwningChunk == NULL || m_pOwningChunk->IsInsideChunk(m_position) == false)
	{
		if(m_pOwningChunk != NULL)
		{
			m_pOwningChunk->RemoveItem(this);
		}

		m_pOwningChunk = m_pChunkManager->GetChunkFromPosition(m_position.x, m_position.y, m_position.z);

		if(m_pOwningChunk != NULL)
		{
			m_pOwningChunk->AddItem(this);
		}
		else
		{
			//SetErase(true);
		}

		return;
	}

	// Auto disappear
	if(m_autoDisappear)
	{
		if(m_autoDisappearTimer <= 0.0f)
		{
			SetErase(true);

			return;
		}
	}

	// Update physics
	UpdatePhysics(dt);
}
示例#15
0
void GameBase::UpdateWorldPhysics(){
	PhysicManager::Instance()->UpdatePhysics();
	UpdatePhysics();
}
示例#16
0
DDWORD VolumeBrush::EngineMessageFn(DDWORD messageID, void *pData, DFLOAT fData)
{
    switch(messageID)
    {
    case MID_UPDATE:
    {
        Update();
        break;
    }

    case MID_AFFECTPHYSICS:
    {
        UpdatePhysics((ContainerPhysics*)pData);
        break;
    }

    case MID_PRECREATE:
    {
        // Need to call base class to have the object name read in before
        // we call PostPropRead()

        DDWORD dwRet = B2BaseClass::EngineMessageFn(messageID, pData, fData);

        if ( fData == PRECREATE_WORLDFILE )
        {
            ReadProp((ObjectCreateStruct*)pData);
        }

        ObjectCreateStruct* pStruct = (ObjectCreateStruct*)pData;

        if (pStruct)
        {
            pStruct->m_Flags |= m_dwFlags;
            pStruct->m_ObjectType = OT_CONTAINER;
            _mbscpy((unsigned char*)pStruct->m_Filename, (const unsigned char*)pStruct->m_Name);
            pStruct->m_SkinName[0] = '\0';
            pStruct->m_ContainerCode = (D_WORD)m_eContainerCode;
        }
        return dwRet;
    }
    break;

    case MID_INITIALUPDATE:
    {
//			if (fData != INITIALUPDATE_SAVEGAME)
//			{
        InitialUpdate((int)fData);
//			}

        CacheFiles();
        break;
    }

    case MID_SAVEOBJECT:
        Save((HMESSAGEWRITE)pData, (DDWORD)fData);
        break;

    case MID_LOADOBJECT:
        Load((HMESSAGEREAD)pData, (DDWORD)fData);
        break;

    default :
        break;
    }

    return B2BaseClass::EngineMessageFn(messageID, pData, fData);
}
示例#17
0
void MainScreen::onUpdate(float dt)
{
    (void) dt;
    // Update the core
    mEngine->Update(dt);

    auto& scene = mScene;
    auto& window = mEngine->GetWindow();
    auto& renderer = mEngine->GetRenderer();

    // Update interpolation variables
    for (auto& obj : mScene->GetNodes())
    {
        Transform& trans = obj.second->GetTransformation();
        trans.Update();

        AABB& aabb = obj.second->GetAABB();
        aabb.Update(trans.GetPosition(), trans.GetScale(), trans.GetRotation());
    }

    // Update camera euler angles
    if (window.MouseGrabEnabled())
        mCamera.Look(CameraLookOffset());

    if (mFollowingCharacter)
    {
        // Update character
        mCharacter.Update();

        // Move Camera following character
        auto trans = mCharacter.GetCharacterNode()->GetTransformation().GetInterpolated(1.0f);
        mCamera.SetPos(glm::vec3(trans[3].x, trans[3].y + 4, trans[3].z + 4));
    }
    else
    {
        // Update camera position
        mCamera.Move(CameraMoveDirections());
    }

    // Update the camera matrix
    mCamera.Update();

    // Update light position
    //auto updLight = std::bind(updateLight, renderer, mScene.get(), std::placeholders::_1);
    auto updLight = [this, &renderer, &scene](const glm::vec3& move)
    {
        UpdateLight(renderer, scene.get(), mMovingLightIndex, move);
    };

    float increase = 0.3f;
    if(window.IsKeyPressed(Key::Kp8))
        updLight(glm::vec3(0.0f, increase, 0.0f));
    if(window.IsKeyPressed(Key::Kp4))
        updLight(glm::vec3(-increase, 0.0f, 0.0f));
    if(window.IsKeyPressed(Key::Kp2))
        updLight(glm::vec3(0.0f, -increase, 0.0f));
    if(window.IsKeyPressed(Key::Kp6))
        updLight(glm::vec3(increase, 0.0f, 0.0f));
    if(window.IsKeyPressed(Key::Kp5))
        updLight(glm::vec3(0.0f, 0.0f, -increase));
    if(window.IsKeyPressed(Key::Kp0))
        updLight(glm::vec3(0.0f, 0.0f, increase));

    // Update cubes' rotations
    if (mRotationData.rotating)
    {
        for(auto& p : scene->GetNodes())
        {
            if (p.first.substr(0, 4) == "cube")
                scene->Rotate(p.first, RotationAxis::Y, mRotationData.degreesInc);
        }
    }

    // Update dir light
    increase = 0.3f;
    if (window.IsKeyPressed(Key::Right))
    {
        if (window.IsKeyPressed(Key::LeftShift))
            UpdateDirectionalLight(renderer, glm::vec3(0.0f, 0.0f, increase));
        else
            UpdateDirectionalLight(renderer, glm::vec3(increase, 0.0f, 0.0f));
    }
    if (window.IsKeyPressed(Key::Left))
    {
        if (window.IsKeyPressed(Key::LeftShift))
            UpdateDirectionalLight(renderer, glm::vec3(0.0f, 0.0f, -increase));
        else
            UpdateDirectionalLight(renderer, glm::vec3(-increase, 0.0f, 0.0f));
    }
    if (window.IsKeyPressed(Key::Up))
        UpdateDirectionalLight(renderer, glm::vec3(0.0f, increase, 0.0f));
    if (window.IsKeyPressed(Key::Down))
        UpdateDirectionalLight(renderer, glm::vec3(0.0f, -increase, 0.0f));

    // Update physics
    UpdatePhysics(dt);
}
示例#18
0
/**
 Update all the entities cerrently existing in the stage.
 This function must be called once per frame.
 - Basic steps
   - 1. Call BaseEntity::UpdateBaseEntity( dt ) for each base entity
   - 2. Save positions of copy entities
   - 3. Run physics simulator
   - 4. Remove terminated entities from the active list
   - 5. Call CCopyEntity::Act() for each copy entity except for child entities
   - 6. Update link to the entity tree node if an entity has changed its position in Act()
   TODO: Do 5 & 6 in a single loop to update link for each entity right after is Act().
         Current code does this in separate loops.
 */
void EntityManager::UpdateAllEntities( float dt )
{
	CCopyEntity *pEntity = NULL;
	CCopyEntity *pPrevEntity = NULL;
	CCopyEntity *pTouchedEnt = NULL;

	ONCE( LOG_PRINT( " - updating base entities" ) );

	size_t i, num_base_entities = m_vecpBaseEntity.size();
	for( i=0; i<num_base_entities; i++ )
	{
		m_vecpBaseEntity[i]->UpdateBaseEntity( dt );
	}

	// save the current entity positions
	for( pEntity = m_pEntityInUse.get();
	     pEntity != NULL;
	     pEntity = pEntity->m_pNextRawPtr )
	{
		pEntity->PrevPosition() = pEntity->GetWorldPosition();
	}

	// run physics simulator
	// entity position may be modified in this call
	UpdatePhysics( dt );

	ONCE( LOG_PRINT( " - updated physics" ) );

	// remove terminated entities from the active entity list
	ReleaseTerminatedEntities();

	ONCE( LOG_PRINT( " - removed terminated entities from the active entity list" ) );

	// update active entities
	for( pEntity = this->m_pEntityInUse.get(), pPrevEntity = NULL;
		 pEntity != NULL;
		 pPrevEntity = pEntity, pEntity = pEntity->m_pNextRawPtr )
	{
		// before updating pEntity, check if it has been terminated.
		if( !pEntity->inuse )
			continue;

		// set the results of physics simulation to
		// pose, velocity and angular velocity of the entity
//		if( pEntity->pPhysicsActor && pEntity->GetEntityFlags() & BETYPE_USE_PHYSSIM_RESULTS )
		if( 0 < pEntity->m_vecpPhysicsActor.size() && pEntity->GetEntityFlags() & BETYPE_USE_PHYSSIM_RESULTS )
			pEntity->UpdatePhysics();

		if( pEntity->sState & CESTATE_ATREST )
			continue;

		if( !pEntity->m_pParent || !pEntity->m_pParent->inuse )
		{
			// 'pEntity' has no parent or its parent is already terminated
			pEntity->pBaseEntity->Act( pEntity );
		}

		if( !pEntity->inuse )
			continue; // terminated in its own update routine

		UpdateEntityAfterMoving( pEntity );

		// deal with entities touched during this frame
		for(int i=0; i<pEntity->vecpTouchedEntity.size(); i++)
		{
			pTouchedEnt = pEntity->vecpTouchedEntity[i];
			pEntity->pBaseEntity->Touch( pEntity, pTouchedEnt );

			if( pTouchedEnt )
				pTouchedEnt->pBaseEntity->Touch( pTouchedEnt, pEntity );
		}

		// clear touched entities for the next frame
		pEntity->vecpTouchedEntity.clear();
	}

	ONCE( LOG_PRINT( " - updated active entities" ) );

	// unlink and link the entity in the entity tree if it changed its position
/*
	for( pEntity = m_pEntityInUse.get();
		 pEntity != NULL;
		 pPrevEntity = pEntity, pEntity = pEntity->m_pNextRawPtr )
	{
		if( !pEntity->inuse )
			continue;

		UpdateEntityAfterMoving();
	}
*/
}
示例#19
0
void MainScene::update(float dt)
{
   UpdatePhysics();
   UpdateBody();
}
示例#20
0
//------------------------------------------------------------------------
void CGunTurret::UpdateOrientation(float deltaTime)
{
	FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);

	bool changed = false;
	bool searching = (m_targetId==0 && m_turretparams.searching);
	float speed	= searching ? m_turretparams.search_speed : m_turretparams.turn_speed;

	assert(m_goalYaw >= 0.f && m_goalYaw <= gf_PI2);

	// update turret
	Matrix34 turretTM = GetEntity()->GetSlotLocalTM(eIGS_Aux0, false);
	Ang3 turretAngles(turretTM);

	if(turretAngles.z < 0.0f)
		turretAngles.z+=gf_PI2;

	if(cry_fabsf(m_goalYaw-turretAngles.z) > gf_PI)
	{
		if(m_goalYaw >= gf_PI)
			turretAngles.z += gf_PI2;
		else
			turretAngles.z -= gf_PI2;
	}

	if(m_turretparams.yaw_range < 360.f)
	{
		// reverse, to avoid forbidden range
		if(m_goalYaw > gf_PI && turretAngles.z < gf_PI)
			turretAngles.z += gf_PI2;
		else if(m_goalYaw < gf_PI && turretAngles.z > gf_PI)
			turretAngles.z -= gf_PI2;
	}

	if(cry_fabsf(turretAngles.z-m_goalYaw) > 0.001f)
	{
		Interp(turretAngles.z, m_goalYaw, speed, deltaTime, 0.25f*speed);

		if(m_turretSound == INVALID_SOUNDID && gEnv->IsClient())
			m_turretSound = PlayAction(g_pItemStrings->turret);

		changed = true;
	}
	else if(m_turretSound != INVALID_SOUNDID)
	{
		StopSound(m_turretSound);
		m_turretSound = INVALID_SOUNDID;
	}

	if(changed)
	{
		turretTM.SetRotationXYZ(turretAngles,turretTM.GetTranslation());
		GetEntity()->SetSlotLocalTM(eIGS_Aux0, turretTM);
	}

	// update weapon
	Matrix34 weaponTM = GetEntity()->GetSlotLocalTM(eIGS_ThirdPerson, false);
	Ang3 weaponAngles(weaponTM);

	weaponAngles.z = turretAngles.z;

	if(cry_fabsf(weaponAngles.x-m_goalPitch) > 0.001f)
	{
		Interp(weaponAngles.x, m_goalPitch, speed, deltaTime, 0.25f*speed);

		if(m_cannonSound == INVALID_SOUNDID && gEnv->IsClient())
			m_cannonSound = PlayAction(g_pItemStrings->cannon);

		changed = true;
	}
	else if(m_cannonSound != INVALID_SOUNDID)
	{
		StopSound(m_cannonSound);
		m_cannonSound = INVALID_SOUNDID;
	}

	if(changed)
	{
		weaponTM.SetRotationXYZ(weaponAngles);
		Vec3 w_trans = turretTM.TransformPoint(m_radarHelperPos);
		//Vec3 w_trans = GetSlotHelperPos(eIGS_Aux0,m_radarHelper.c_str(),false);
		weaponTM.SetTranslation(w_trans);

		GetEntity()->SetSlotLocalTM(eIGS_ThirdPerson, weaponTM);

		if(GetEntity()->IsSlotValid(eIGS_Aux1))
		{
			Vec3 b_trans = weaponTM.TransformPoint(m_barrelHelperPos);
			//Vec3 b_trans = GetSlotHelperPos(eIGS_ThirdPerson,m_barrelHelper.c_str(),false);
			weaponTM.SetTranslation(b_trans);
			GetEntity()->SetSlotLocalTM(eIGS_Aux1, weaponTM*m_barrelRotation);
		}

		if(gEnv->IsClient())
		{
			for(TEffectInfoMap::const_iterator it=m_effects.begin(); it!=m_effects.end(); ++it)
			{
				Matrix34 tm(GetSlotHelperRotation(eIGS_ThirdPerson,it->second.helper.c_str(),true), GetSlotHelperPos(eIGS_ThirdPerson,it->second.helper.c_str(),true));
				SetEffectWorldTM(it->first, tm);
			}
		}
	}

	UpdatePhysics();

	if(g_pGameCVars->i_debug_turrets == eGTD_Basic)
	{
		DrawDebug();
		//gEnv->pRenderer->DrawLabel(GetEntity()->GetWorldPos(), 1.4f, "%s yaw: %.2f, goalYaw: %.2f (%.2f), goalPitch: %.2f (%.2f/%.2f)", searching?"[search]":"", RAD2DEG(turretAngles.z), RAD2DEG(m_goalYaw), 0.5f*(m_turretparams.yaw_range), RAD2DEG(m_goalPitch), m_turretparams.min_pitch, m_turretparams.max_pitch);
	}
}