void physicsLoop(GameClass* game, bool& running) { GameTimer timer; while (running) { float msec = timer.GetTimedMS(); game->UpdatePhysics(msec); } }
void LitWavesApp::UpdateMainPassCB(const GameTimer& gt) { XMMATRIX view = XMLoadFloat4x4(&mView); XMMATRIX proj = XMLoadFloat4x4(&mProj); XMMATRIX viewProj = XMMatrixMultiply(view, proj); XMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(view), view); XMMATRIX invProj = XMMatrixInverse(&XMMatrixDeterminant(proj), proj); XMMATRIX invViewProj = XMMatrixInverse(&XMMatrixDeterminant(viewProj), viewProj); XMStoreFloat4x4(&mMainPassCB.View, XMMatrixTranspose(view)); XMStoreFloat4x4(&mMainPassCB.InvView, XMMatrixTranspose(invView)); XMStoreFloat4x4(&mMainPassCB.Proj, XMMatrixTranspose(proj)); XMStoreFloat4x4(&mMainPassCB.InvProj, XMMatrixTranspose(invProj)); XMStoreFloat4x4(&mMainPassCB.ViewProj, XMMatrixTranspose(viewProj)); XMStoreFloat4x4(&mMainPassCB.InvViewProj, XMMatrixTranspose(invViewProj)); mMainPassCB.EyePosW = mEyePos; mMainPassCB.RenderTargetSize = XMFLOAT2((float)mClientWidth, (float)mClientHeight); mMainPassCB.InvRenderTargetSize = XMFLOAT2(1.0f / mClientWidth, 1.0f / mClientHeight); mMainPassCB.NearZ = 1.0f; mMainPassCB.FarZ = 1000.0f; mMainPassCB.TotalTime = gt.TotalTime(); mMainPassCB.DeltaTime = gt.DeltaTime(); mMainPassCB.AmbientLight = { 0.25f, 0.25f, 0.35f, 1.0f }; XMVECTOR lightDir = -MathHelper::SphericalToCartesian(1.0f, mSunTheta, mSunPhi); XMStoreFloat3(&mMainPassCB.Lights[0].Direction, lightDir); mMainPassCB.Lights[0].Strength = { 1.0f, 1.0f, 0.9f }; auto currPassCB = mCurrFrameResource->PassCB.get(); currPassCB->CopyData(0, mMainPassCB); }
void TexWaves::UpdateWaves(const GameTimer& timer) { static float base = 0.0f; if ((timer.TotalTime() - base) >= 0.25f) { base += 0.25f; int i = MathHelper::Rand(4, _waves->RowCount() - 5); int j = MathHelper::Rand(4, _waves->ColumnCount() - 5); float r = MathHelper::RandF(0.2f, 0.5f); _waves->Disturb(i, j, r); } _waves->Update(timer.DeltaTime()); auto currWavesVB = _currFrameResource->WavesVB.get(); for (int i = 0; i < _waves->VertexCount(); i++) { FrameResource::Vertex v; v.Pos = _waves->Position(i); v.Normal = _waves->Normal(i); v.TexC.x = 0.5f + v.Pos.x / _waves->Width(); v.TexC.y = 0.5f + v.Pos.z / _waves->Depth(); currWavesVB->CopyData(i, v); } _wavesRenderItem->Geo->VertexBufferGPU = currWavesVB->Resource(); }
void Engine::Run() { GameTimer gameTimer; gameTimer.Start(); gameTimer.Tick(); SDLEventCallbackHandle quitHandle = g_SDLEventManager.RegisterInterest( std::bind( &Engine::SDLEventProcessing, this, std::placeholders::_1 ) ); SDLEventCallbackHandle inputHandle = g_SDLEventManager.RegisterInterest( std::bind( &InputState::HandleEvent, &g_InputState, std::placeholders::_1 ) ); while ( m_Quit == false ) { gameTimer.Tick(); g_InputState.Update(); g_Input.Update(); g_SDLEventManager.ProcessEvents(); m_SubsystemCollection.Update( gameTimer.GetDeltaAsFloat() ); // Put after subsystems to allow them to consume the escape key if ( g_Input.KeyUpDown( SDL_SCANCODE_ESCAPE ) ) { m_Quit = true; } // Reset profiler frame g_Profiler.GetInstance().ResetFrame(); } g_SDLEventManager.UnregisterInterest( quitHandle ); g_SDLEventManager.UnregisterInterest( inputHandle ); }
void CameraAndDynamicIndexingApp::UpdateMainPassCB(const GameTimer& gt) { XMMATRIX view = mCamera.GetView(); XMMATRIX proj = mCamera.GetProj(); XMMATRIX viewProj = XMMatrixMultiply(view, proj); XMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(view), view); XMMATRIX invProj = XMMatrixInverse(&XMMatrixDeterminant(proj), proj); XMMATRIX invViewProj = XMMatrixInverse(&XMMatrixDeterminant(viewProj), viewProj); XMStoreFloat4x4(&mMainPassCB.View, XMMatrixTranspose(view)); XMStoreFloat4x4(&mMainPassCB.InvView, XMMatrixTranspose(invView)); XMStoreFloat4x4(&mMainPassCB.Proj, XMMatrixTranspose(proj)); XMStoreFloat4x4(&mMainPassCB.InvProj, XMMatrixTranspose(invProj)); XMStoreFloat4x4(&mMainPassCB.ViewProj, XMMatrixTranspose(viewProj)); XMStoreFloat4x4(&mMainPassCB.InvViewProj, XMMatrixTranspose(invViewProj)); mMainPassCB.EyePosW = mCamera.GetPosition3f(); mMainPassCB.RenderTargetSize = XMFLOAT2((float)mClientWidth, (float)mClientHeight); mMainPassCB.InvRenderTargetSize = XMFLOAT2(1.0f / mClientWidth, 1.0f / mClientHeight); mMainPassCB.NearZ = 1.0f; mMainPassCB.FarZ = 1000.0f; mMainPassCB.TotalTime = gt.TotalTime(); mMainPassCB.DeltaTime = gt.DeltaTime(); mMainPassCB.AmbientLight = { 0.25f, 0.25f, 0.35f, 1.0f }; mMainPassCB.Lights[0].Direction = { 0.57735f, -0.57735f, 0.57735f }; mMainPassCB.Lights[0].Strength = { 0.8f, 0.8f, 0.8f }; mMainPassCB.Lights[1].Direction = { -0.57735f, -0.57735f, 0.57735f }; mMainPassCB.Lights[1].Strength = { 0.4f, 0.4f, 0.4f }; mMainPassCB.Lights[2].Direction = { 0.0f, -0.707f, -0.707f }; mMainPassCB.Lights[2].Strength = { 0.2f, 0.2f, 0.2f }; auto currPassCB = mCurrFrameResource->PassCB.get(); currPassCB->CopyData(0, mMainPassCB); }
bool Timer::update(float modifier) { GameTimer* t = ARK2D::getContainer()->getTimer(); m_timer += (t->getDelta() * modifier); if (m_timer >= m_duration) { return true; } return false; }
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) { #ifdef _DEBUG // this is for enabling memory leak detection _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif MSG msg = { 0 }; double tempDT = 10.0; // create window HWND wndHandle = InitWindow(hInstance); //float test = 5; // window is valid if (wndHandle) { // display window ShowWindow(wndHandle, nCmdShow); //Create engine class Engine* engine = new Engine(); engine->Initialize(&wndHandle, &hInstance); GameTimer* time = GameTimer::GetInstance(); //test = AntTweakBar::GetInstance()->GetBar();s //AntTweakBar::GetInstance()->addSlider("test", test); time->Reset(); // enter message loop, loop until the message WM_QUIT is received. while (WM_QUIT != msg.message) { // read messages if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); // this will call the function WndProc below! DispatchMessage(&msg); } else { time->Tick(); double dt = time->DeltaTime(); CalculateFPS(wndHandle, *time); engine->Frame(&dt); // update/render goes here } } // finish the program engine->Release(); delete engine; //delete time; DestroyWindow(wndHandle); } // return how the program finished. return (int) msg.wParam; }
void CameraMovement::update() { GameTimer* timer = ARK2D::getTimer(); Input* in = ARK2D::getInput(); // movement on wasd float d = moveSpeed * timer->getDelta(); if (in->isKeyDown(Input::KEY_W)) { camera->transform.position += camera->direction * d; } if (in->isKeyDown(Input::KEY_S)) { camera->transform.position -= camera->direction * d; } if (in->isKeyDown(Input::KEY_A)) { Vector3<float> right = camera->direction.cross(camera->up).normalise(); camera->transform.position -= right * d; camera->lookAt -= right * d; } if (in->isKeyDown(Input::KEY_D)) { Vector3<float> right = camera->direction.cross(camera->up).normalise(); camera->transform.position += right * d; camera->lookAt += right * d; } // up down if (in->isKeyDown(Input::KEY_SPACE)) { camera->transform.position += camera->up * d; camera->lookAt += camera->up * d; } else if (in->isKeyDown(Input::KEY_V)) { camera->transform.position -= camera->up * d; camera->lookAt -= camera->up * d; } // rotation on arrow keys float r = rotateSpeed * timer->getDelta(); if (in->isKeyDown(Input::KEY_LEFT)) { camera->setHeading(camera->camera_heading + r); } else if (in->isKeyDown(Input::KEY_RIGHT)) { camera->setHeading(camera->camera_heading - r); } if (in->isKeyDown(Input::KEY_UP)) { camera->setPitch(camera->camera_pitch + r); } else if (in->isKeyDown(Input::KEY_DOWN)) { camera->setPitch(camera->camera_pitch - r); } // zoom if (in->isKeyDown(Input::KEY_SHIFT) && in->isKeyDown(Input::KEY_EQUALS)) { camera->fieldOfView -= 1.0f * timer->getDelta(); } else if (in->isKeyDown(Input::KEY_SHIFT) && in->isKeyDown(Input::KEY_HYPHEN)) { camera->fieldOfView += 1.0f * timer->getDelta(); } }
GameTimer* GameTimer::create() { GameTimer *pRet = new GameTimer(); if (pRet) { pRet->autorelease(); return pRet; } else { CC_SAFE_DELETE(pRet); return NULL; } }
void renderGame() { // Clear the color buffer glClear(GL_COLOR_BUFFER_BIT); // Reset transformations glLoadIdentity(); // Set the viewport to the entire window viewport.x = 0; viewport.y = 0; viewport.width = window.width; viewport.height = window.height; glViewport(viewport.x, viewport.y, viewport.width, viewport.height); drawUI(); // Draw game objects ball.draw(); player.draw(); ai.draw(); o1.draw(); o2.draw(); // Draw debug stuff DebugDrawing::getInstance().draw(timer.getGameTime()); // Present glutSwapBuffers(); }
void LitWavesApp::UpdateWaves(const GameTimer& gt) { // Every quarter second, generate a random wave. static float t_base = 0.0f; if((mTimer.TotalTime() - t_base) >= 0.25f) { t_base += 0.25f; int i = MathHelper::Rand(4, mWaves->RowCount() - 5); int j = MathHelper::Rand(4, mWaves->ColumnCount() - 5); float r = MathHelper::RandF(0.2f, 0.5f); mWaves->Disturb(i, j, r); } // Update the wave simulation. mWaves->Update(gt.DeltaTime()); // Update the wave vertex buffer with the new solution. auto currWavesVB = mCurrFrameResource->WavesVB.get(); for(int i = 0; i < mWaves->VertexCount(); ++i) { Vertex v; v.Pos = mWaves->Position(i); v.Normal = mWaves->Normal(i); currWavesVB->CopyData(i, v); } // Set the dynamic VB of the wave renderitem to the current frame VB. mWavesRitem->Geo->VertexBufferGPU = currWavesVB->Resource(); }
void Sun::update(GameTimer& timer) { theta += (float)timer.getDelta() * PI_F / SUN_DAY_TIME; if(theta > 2 * PI_F) theta -= (2 * PI_F); position.x = cos(theta); position.y = sin(theta); }
void TexWaves::AnimateMaterials(const GameTimer& timer) { auto waterMat = _materials["water"].get(); float& tu = waterMat->MatTransform(3, 0); float& tv = waterMat->MatTransform(3, 1); tu += 0.1f * timer.DeltaTime(); tv += 0.02f * timer.DeltaTime(); if (tu >= 1.0f) tu -= 1.0f; if (tv >= 1.0f) tv -= 1.0f; waterMat->MatTransform(3, 0) = tu; waterMat->MatTransform(3, 1) = tv; waterMat->NumFramesDirty = FrameResource::NumFrameResources; }
void PhysicsManager::UpdateChunkRange(Vector3DInt32 &start, Vector3DInt32 &end) { if(start.getX() > end.getX() || start.getY() > end.getY() || start.getZ() > end.getZ()) return; //start needs to be lower than end GameTimer timer; double totalElapsed = 0.f; for(int i = start.getX(); i <= end.getX(); i++) for(int j = start.getY(); j <= end.getY(); j++) for(int k = start.getZ(); k <= end.getZ(); k++) { totalElapsed += timer.getElapsedTimeSec(); if(totalElapsed >= .5f) { totalElapsed = 0; float progress = (float)(i * end.getY() + j) / (float)(end.getX() * end.getY()); graphMan->UpdatePhysicsProgress(progress); } UpdateChunk(Vector3DInt32(i, j, k)); } }
// OpenGL main loop void mainLoop() { SDL_Event e; GameTimer* timer = new GameTimer(); timer->start(); while(!g_quit) { timer->restart(); while(SDL_PollEvent(&e)) g_stateManager->getCurrentState()->handleEvent(e); if (!g_stateManager->hasState()) break; render(); //printf("%d\n", timer->getElapsedTime()); //SDL_SetWindowTitle(g_mainWindow, fps_str); } delete timer; }
void WavesCSApp::AnimateMaterials(const GameTimer& gt) { // Scroll the water material texture coordinates. auto waterMat = mMaterials["water"].get(); float& tu = waterMat->MatTransform(3, 0); float& tv = waterMat->MatTransform(3, 1); tu += 0.1f * gt.DeltaTime(); tv += 0.02f * gt.DeltaTime(); if(tu >= 1.0f) tu -= 1.0f; if(tv >= 1.0f) tv -= 1.0f; waterMat->MatTransform(3, 0) = tu; waterMat->MatTransform(3, 1) = tv; // Material has changed, so need to update cbuffer. waterMat->NumFramesDirty = gNumFrameResources; }
Texture* HeightmapManager::getHeightmap(const unsigned __int64& id, const dvec2& offset, double scale, const vec3& faceNormal) { Texture* texture = mpCache->getTexture(id, true); if (texture != NULL) return texture; GameTimer timer; timer.Reset(); timer.Start(); texture = mpCache->getFreeTexture(id); mpGenerator->setGenerationTarget(texture); mpGenerator->generateHeightmap(offset, scale, faceNormal); timer.Tick(); std::cout << "Generated id: " << id << " in " << (timer.DeltaTime() * 1000.0) << "MS " << " Cache size: " << mpCache->getActiveCount() << " Free count: " << mpCache->getInactiveCount() << std::endl; return texture; }
void TexWaves::UpdateMainPassCB(const GameTimer& timer) { XMMATRIX view = XMLoadFloat4x4(&_view); XMMATRIX proj = XMLoadFloat4x4(&_proj); XMMATRIX viewProj = XMMatrixMultiply(view, proj); XMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(view), view); XMMATRIX invProj = XMMatrixInverse(&XMMatrixDeterminant(proj), proj); XMMATRIX invViewProj = XMMatrixInverse(&XMMatrixDeterminant(viewProj), viewProj); XMStoreFloat4x4(&_mainPassCB.View, XMMatrixTranspose(view)); XMStoreFloat4x4(&_mainPassCB.InvView, XMMatrixTranspose(invView)); XMStoreFloat4x4(&_mainPassCB.Proj, XMMatrixTranspose(proj)); XMStoreFloat4x4(&_mainPassCB.InvProj, XMMatrixTranspose(invProj)); XMStoreFloat4x4(&_mainPassCB.VP, XMMatrixTranspose(viewProj)); XMStoreFloat4x4(&_mainPassCB.InvVP, XMMatrixTranspose(invViewProj)); _mainPassCB.EyePosW = _eyePos; _mainPassCB.RenderTargetSize = XMFLOAT2((float)_clientWidth, (float)_clientHeight); _mainPassCB.InvRenderTargetSize = XMFLOAT2(1.0f / _clientWidth, 1.0f / _clientHeight); _mainPassCB.NearZ = 1.0f; _mainPassCB.FarZ = 1000.0f; _mainPassCB.TotalTime = timer.TotalTime(); _mainPassCB.DeltaTime = timer.DeltaTime(); _mainPassCB.AmbientLight = { 0.25f, 0.25f, 0.35f, 1.0f }; XMVECTOR lightDir = -MathHelper::SphericalToCartesian(1.0f, _sunTheta, _sunPhi); XMStoreFloat3(&_mainPassCB.Lights[0].Direction, lightDir); _mainPassCB.Lights[0].Strength = { 1.0f, 1.0f, 0.9f }; _mainPassCB.Lights[1].Direction = { 0.57735f, -0.57735f, 0.57735f }; _mainPassCB.Lights[1].Strength = { 0.9f, 0.9f, 0.9f }; _mainPassCB.Lights[2].Direction = { -0.57735f, -0.57735f, 0.57735f }; _mainPassCB.Lights[2].Strength = { 0.5f, 0.5f, 0.5f }; auto currPassCB = _currFrameResource->PassCB.get(); currPassCB->CopyData(0, _mainPassCB); }
void CameraAndDynamicIndexingApp::OnKeyboardInput(const GameTimer& gt) { const float dt = gt.DeltaTime(); if(GetAsyncKeyState('W') & 0x8000) mCamera.Walk(10.0f*dt); if(GetAsyncKeyState('S') & 0x8000) mCamera.Walk(-10.0f*dt); if(GetAsyncKeyState('A') & 0x8000) mCamera.Strafe(-10.0f*dt); if(GetAsyncKeyState('D') & 0x8000) mCamera.Strafe(10.0f*dt); mCamera.UpdateViewMatrix(); }
void LitWavesApp::OnKeyboardInput(const GameTimer& gt) { const float dt = gt.DeltaTime(); if(GetAsyncKeyState(VK_LEFT) & 0x8000) mSunTheta -= 1.0f*dt; if(GetAsyncKeyState(VK_RIGHT) & 0x8000) mSunTheta += 1.0f*dt; if(GetAsyncKeyState(VK_UP) & 0x8000) mSunPhi -= 1.0f*dt; if(GetAsyncKeyState(VK_DOWN) & 0x8000) mSunPhi += 1.0f*dt; mSunPhi = MathHelper::Clamp(mSunPhi, 0.1f, XM_PIDIV2); }
void RenderManager::fpsCalc(GameTimer mTimer) { static int frameCnt = 0; static float timeElapsed = 0.0f; frameCnt++; // Compute averages over one second period. if( (mTimer.TotalTime() - timeElapsed) >= 1.0f ) { fps = (int)frameCnt; // fps = frameCnt / 1 mspf = 1000.0f / fps; // Reset for next average. frameCnt = 0; timeElapsed += 1.0f; } }
void DynamicIndexing::OnKeyboardInput(const GameTimer& timer) { const float dt = timer.DeltaTime(); if (GetAsyncKeyState('W') & 0x8000) _camera.Walk(10.0f*dt); if (GetAsyncKeyState('S') & 0x8000) _camera.Walk(-10.0f*dt); if (GetAsyncKeyState('A') & 0x8000) _camera.Strafe(-10.0f*dt); if (GetAsyncKeyState('D') & 0x8000) _camera.Strafe(10.0f*dt); _camera.UpdateViewMatrix(); }
void TexWaves::OnKeyboardInput(const GameTimer& timer) { float dt = timer.DeltaTime(); if (GetAsyncKeyState('1') & 0x8000) _isWireframe = true; else _isWireframe = false; if (GetAsyncKeyState(VK_LEFT) & 0x8000) _sunTheta -= 1.0f * dt; if (GetAsyncKeyState(VK_RIGHT) & 0x8000) _sunTheta += 1.0f * dt; if (GetAsyncKeyState(VK_UP) & 0x8000) _sunPhi -= 1.0f * dt; if (GetAsyncKeyState(VK_RIGHT) & 0x8000) _sunPhi += 1.0f * dt; _sunPhi = MathHelper::Clamp(_sunPhi, 0.1f, XM_PIDIV2); }
void CalculateFPS(HWND& window, GameTimer& time) { // Code computes the average frames per second, and also the // average time it takes to render one frame. These stats // are appended to the window caption bar. static int frameCnt = 0; static float timeElapsed = 0.0f; frameCnt++; //Computes averages over one second period //// // Time Elapsed only grows when the time between it and total time is greater than one. //if the time between them is greater than 1 second, we calculate the fps and time per frame //after that, 1.0 is added to time elapsed. Evening out the time between the two, //the timer does not reset, timElapsed just kinda "catches up on the total time" if ((time.TotalTime() - timeElapsed) >= 1.0f) { float fps = (float)frameCnt; //fps = frameCnt / 1 float mspf = 1000.0f / fps; //This is the miliseconds it takes to render one frame std::wostringstream outs; //Format it nicely to be sent to the window outs.precision(6); outs << L" " << L"FPS: " << fps << L" " << L"Time Per Frame: " << mspf << L" (ms)"; SetWindowText(window, outs.str().c_str()); //update the window bar text //Reset for next average frameCnt = 0; timeElapsed += 1.0f; } }
void CubeDemo::update(const GameTimer & timer) { mCamera->update(timer); mAngle += XM_PI * static_cast<float>(timer.elapsedGameTime()); XMStoreFloat4x4(&mWorldMatrix, XMMatrixRotationY(mAngle)); }
void gameInput() { // Game state if (currState.isKeyDown(KEY_ESC)) { glutLeaveMainLoop(); } else if (currState.isKeyDown(KEY_SPACE)) { Random random; int num = random.getInt(2); if (num == 0) { ball.launch(Vector2(1.0f, random.getFloat(-1.0f, 1.0f))); } else if (num == 1) { ball.launch(Vector2(-1.0f, random.getFloat(-1.0f, 1.0f))); } } else if (currState.isKeyDown(KEY_B) && prevState.isKeyUp(KEY_B)) { // Toggle debug drawing DebugDrawing::getInstance().enabled = !DebugDrawing::getInstance().enabled; } else if (currState.isKeyDown(KEY_P) && prevState.isKeyUp(KEY_P)) { if (paused) { timer.start(); paused = false; } else { keyboard.onPause(); timer.stop(); paused = true; } } else if(currState.isKeyDown(KEY_R) && prevState.isKeyUp(KEY_R)) { if (won) { // reset the string whoWon = ""; // reset the scores of both players playerScore = 0; aiScore = 0; ball.reset(Point2(static_cast<float>(window.centerX), static_cast<float>(window.centerY))); won = false; } } // Player movement if (currState.isKeyDown(KEY_W)) { player.movePaddle(Vector2(0.0f, -1.0f)); } else if (currState.isKeyDown(KEY_S)) { player.movePaddle(Vector2(0.0f, 1.0f)); } }
void updateGame(void) { // Get game time timer.tick(); GameTime gameTime = timer.getGameTime(); // Get input keyboard.getState(currState); gameInput(); if (!paused && !won) { // Update game objects ball.update(gameTime, 0, window.height); player.update(gameTime, 0, window.height); ai.update(gameTime, 0, window.height, ball.position); GLuint halfPoints = static_cast<GLuint>(POINTS_TO_WIN * 0.5f); if (playerScore >= halfPoints || aiScore >= halfPoints) { // Increase obstacle speed as the stakes heighten GLuint higherScore = std::max(playerScore, aiScore); GLuint diff = POINTS_TO_WIN - higherScore; float t = 1.0f / diff; float minSpeed = 200.0f; float maxSpeed = 600.0f; float speed = Math::lerp(minSpeed, maxSpeed, t); o1.update(gameTime, 125.0f, 475.0f, speed); o2.update(gameTime, 125.0f, 475.0f, speed); } // Resolve collisions if(ball.position.distanceToSquared(player.position) <= 50.0f * 50.0f) { player.checkCollisions(ball); } else if(ball.position.distanceToSquared(ai.position) <= 50.0f * 50.0f) { ai.checkCollisions(ball); } else if(ball.position.distanceToSquared(o1.position) <= 50.0f * 50.0f) { o1.checkCollisions(ball); } else if(ball.position.distanceToSquared(o2.position) <= 50.0f * 50.0f) { o2.checkCollisions(ball); } // Scoring checkBall(); // Save input state prevState = currState; // Force game to redisplay glutPostRedisplay(); } }
bool Script::_EvaluateTrigger(trigger_node* trig) { Actor* actor = dynamic_cast<Actor*>(fTarget.Target()); if (actor != NULL && actor->SkipConditions()) return false; #if DEBUG_SCRIPTS printf("SCRIPT: %s%s (%d 0x%x) ? ", trig->flags != 0 ? "!" : "", IDTable::TriggerAt(trig->id).c_str(), trig->id, trig->id); trig->Print(); #endif Core* core = Core::Get(); bool returnValue = false; try { switch (trig->id) { case 0x0002: { /* 0x0002 AttackedBy(O:Object*,I:Style*AStyles) * Returns true only if the active CRE was attacked in the style * specified (not necessarily hit) or had an offensive spell cast * on it by the specified object in the last script round. * The style parameter is non functional - this trigger is triggered * by any attack style. */ object_node* node = FindObjectNode(trig); if (node == NULL) break; node->Print(); ScriptResults* results = fTarget.Target()->LastScriptRoundResults(); if (results != NULL) { Object* object = Object::GetMatchingObjectFromList( results->Attackers(), node); returnValue = object != NULL; } break; } case 0x400A: { //ALIGNMENT(O:OBJECT*,I:ALIGNMENT*Align) (16395 0x400A) Object* object = FindObject(trig); if (object != NULL) returnValue = object->IsAlignment(trig->parameter1); break; } case 0x400B: { //ALLEGIANCE(O:OBJECT*,I:ALLEGIENCE*EA) (16395 0x400b) Object* object = FindObject(trig); if (object != NULL) returnValue = object->IsEnemyAlly(trig->parameter1); break; } case 0x400C: { /*0x400C Class(O:Object*,I:Class*Class)*/ Object* object = FindObject(trig); if (object != NULL) returnValue = object->IsClass(trig->parameter1); break; } case 0x400E: { /* GENERAL(O:OBJECT*,I:GENERAL*GENERAL) (16398 0x400e)*/ Object* object = FindObject(trig); if (object != NULL) returnValue = object->IsGeneral(trig->parameter1); break; } case 0x400F: { /*0x400F Global(S:Name*,S:Area*,I:Value*) Returns true only if the variable with name 1st parameter of type 2nd parameter has value 3rd parameter.*/ std::string variableScope; variableScope.append(trig->string1, 6); std::string variableName; variableName.append(&trig->string1[6]); int32 variableValue = 0; if (variableScope.compare("LOCALS") == 0) { variableValue = fTarget.Target()->GetVariable(variableName.c_str()); } else { // TODO: Check for AREA variables, currently we // treat AREA variables as global variables variableValue = Core::Get()->GetVariable(variableName.c_str()); } returnValue = variableValue == trig->parameter1; break; } case 0x0020: { // HitBy // Returns true on first Script launch, IOW initial area load if (!Processed()) { returnValue = true; break; } //object_node* object = FindObjectNode(trig); //returnValue = Object::CheckIfNodeInList(object, // fTarget->LastScriptRoundResults()->Hitters()); break; } case 0x0022: { /* TimerExpired(I:ID*) */ std::ostringstream stringStream; stringStream << fTarget.Target()->Name() << " " << trig->parameter1; printf("TimerExpired %s\n", stringStream.str().c_str()); GameTimer* timer = GameTimer::Get(stringStream.str().c_str()); if (timer != NULL && timer->Expired()) { returnValue = true; } break; } case 0x002F: { /* 0x002F Heard(O:Object*,I:ID*SHOUTIDS) Returns true only if the active CRE was within 30 feet of the specified object and the specified object shouted the specified number (which does not have to be in SHOUTIDS.ids) in the last script round. NB. If the object is specified as a death variable, the trigger will only return true if the corresponding object shouting also has an Enemy-Ally flag of NEUTRAL. */ Object* object = FindObject(trig); if (object != NULL && core->Distance(fTarget.Target(), object) <= 30 && object->LastScriptRoundResults()->Shouted() == trig->parameter1) { returnValue = true; } break; } case 0x4017: { // Race() Object* object = FindObject(trig); if (object != NULL) returnValue = object->IsRace(trig->parameter1); break; } case 0x4018: { /* 0x4018 Range(O:Object*,I:Range*) Returns true only if the specified object is within distance given (in feet) of the active CRE. */ Object* object = FindObject(trig); if (object != NULL) returnValue = core->Distance(object, fTarget.Target()) <= trig->parameter1; break; } case 0x401C: { /* See(O:Object*) * Returns true only if the active CRE can see * the specified object which must not be hidden or invisible. */ Object* object = FindObject(trig); if (object != NULL) returnValue = core->See(fTarget.Target(), object); break; } case 0x401E: { /* Time(I:Time*Time) * Returns true only if the period of day matches the period * in the 2nd parameter (taken from Time.ids). * Hours are offset by 30 minutes, e.g. Time(1) is true * between 00:30 and 01:29. */ break; } case 0x4023: /* 0x4023 True() */ returnValue = true; break; case 0x4027: { //DELAY(I:DELAY*) (16423 0x4027) // TODO: Implement returnValue = true; break; } case 0x402b: { /* ACTIONLISTEMPTY() (16427 0x402b)*/ returnValue = fTarget.Target()->IsActionListEmpty(); break; } case 0x4034: { /*0x4034 GlobalGT(S:Name*,S:Area*,I:Value*) See Global(S:Name*,S:Area*,I:Value*) except the variable must be greater than the value specified to be true. */ returnValue = core->GetVariable(trig->string1) > trig->parameter1; break; } case 0x4035: { /* 0x4035 GlobalLT(S:Name*,S:Area*,I:Value*) As above except for less than. */ returnValue = core->GetVariable(trig->string1) < trig->parameter1; break; } case 0x0036: { /*0x0036 OnCreation() Returns true if the script is processed for the first time this session, e.g. when a creature is created (for CRE scripts) or when the player enters an area (for ARE scripts).*/ returnValue = !Processed(); break; } case 0x4037: { /* StateCheck(O:Object*,I:State*State) * Returns true only if the specified object * is in the state specified. */ Object* object = FindObject(trig); if (object != NULL) returnValue = object->IsState(trig->parameter1); break; } case 0x4039: { /* NUMBEROFTIMESTALKEDTO(I:NUM*) (16441 0x4039) */ if (actor->NumTimesTalkedTo() == (uint32)trig->parameter1) returnValue = true; break; } case 0x4040: { /* GlobalTimerExpired(S:Name*,S:Area*) (16448 0x4040) */ // TODO: Merge Name and Area before passing them to the // Timer::Get() method (also below) std::string timerName; timerName.append(trig->string2).append(trig->string1); GameTimer* timer = GameTimer::Get(timerName.c_str()); returnValue = timer != NULL && timer->Expired(); break; } case 0x4041: { /* GlobalTimerNotExpired(S:Name*,S:Area*) */ std::string timerName; timerName.append(trig->string2).append(trig->string1); GameTimer* timer = GameTimer::Get(timerName.c_str()); returnValue = timer == NULL || !timer->Expired(); break; } case 0x4043: { // InParty const Actor* actor = dynamic_cast<const Actor*>(FindObject(trig)); if (actor != NULL) returnValue = Game::Get()->Party()->HasActor(actor); break; } case 0x4051: { /* * 0x4051 Dead(S:Name*) * Returns only true if the creature with the specified script name * has its death variable set to 1. Not every form of death sets this, * but most do. So it's an almost complete test for death. * The creature must have existed for this to be true. * Note that SPRITE_IS_DEAD variables are not set if the creature is * killed by a neutral creature. */ /*Script* actorScript = fScripts[trig->string1]; if (actorScript != NULL) { // TODO: More NULL checking const char* deathVariable = actorScript->Target()->CRE()->DeathVariable(); returnValue = fVariables[deathVariable] == 1; }*/ break; } case 0x52: { /* OPENED(O:OBJECT*) (82 0x52) */ object_node* objectNode = FindObjectNode(trig); if (objectNode == NULL) break; // TODO: We assume this is a door, but also // containers can be opened/closed Door* door = dynamic_cast<Door*>(fTarget.Target()); if (door == NULL) break; if (!door->Opened()) break; Object* object = core->GetObject( door->CurrentScriptRoundResults()->fOpenedBy.c_str()); if (object != NULL) returnValue = object->MatchNode(objectNode); break; } case 0x4063: { /*INWEAPONRANGE(O:OBJECT*) (16483 0x4063) */ int range = 40; // TODO: Check weapon range Object* object = FindObject(trig); if (object != NULL) returnValue = core->Distance(object, fTarget.Target()) <= range; break; } #if 0 case 0x4068: { /* TimeGT(I:Time*Time) * Returns true only if the current time is greater than * that specified. Hours are offset by 30 minutes, * e.g. TimeGT(1) is true between 01:30 and 02:29. */ break; } case 0x4069: { //TIMELT(I:TIME*TIME) (16489 0x4069) break; } #endif case 0x0070: { /* 0x0070 Clicked(O:Object*) * Only for trigger regions. * Returns true if the specified object * clicked on the trigger region running this script. */ object_node* objectNode = FindObjectNode(trig); returnValue = fTarget.Target()->LastScriptRoundResults()->Clicker() ->MatchNode(objectNode); //objectNode->Print(); fTarget.Target()->LastScriptRoundResults()->Clicker()->Print(); // TODO: When to set this, other than now ? if (returnValue) fLastTrigger = fTarget; break; } case 0x4074: { /* * 0x4074 Detect(O:Object*) * Returns true if the the specified object * is detected by the active CRE in any way * (hearing or sight). Neither Move Silently * and Hide in Shadows prevent creatures * being detected via Detect(). * Detect ignores Protection from Creature * type effects for static objects. */ Object* object = core->GetObject(fTarget.Target(), FindObjectNode(trig)); if (object != NULL) returnValue = core->See(fTarget.Target(), object); // || core->Hear(fTarget, object); break; } case 0x4076: { /* * 0x4076 OpenState(O:Object*,I:Open*BOOLEAN) * NT Returns true only if the open state of the specified door * matches the state specified in the 2nd parameter. */ object_node* doorObj = FindObjectNode(trig); Door *door = dynamic_cast<Door*>( core->GetObject(doorObj->name)); if (door != NULL) { bool openState = trig->parameter1 == 1; returnValue = door->Opened() == openState; } break; } case 0x407D: { /* ISOVERME(O:Object*) * Only for trigger regions. Returns true only if the specified * object is over the trigger running the script */ object_node* object = FindObjectNode(trig); if (object != NULL) { Object* objectOverRegion = core->GetObject( dynamic_cast<Region*>(fTarget.Target())); if (objectOverRegion != NULL) returnValue = objectOverRegion->MatchNode(object); } break; } case 0x407E: { /* 0x407E AreaCheck(S:ResRef*) * Returns true only if the active CRE * is in the area specified. */ // TODO: We only check the active area returnValue = !strcmp(RoomContainer::Get()->Name(), trig->string1); break; } case 0x4086: { // AREATYPE(I:NUMBER*AREATYPE) (16518 0x4086) // TODO: We only check the active area const uint16 areaType = RoomContainer::Get()->AREA()->Type(); returnValue = areaType & trig->parameter1; break; } case 0x4089: { /*0x4089 OR(I:OrCount*)*/ fOrTriggers = trig->parameter1; returnValue = true; break; } case 0x401b: { /* REPUTATIONLT(O:OBJECT*,I:REPUTATION*) (16411 0x401b) */ Actor* actor = dynamic_cast<Actor*>(FindObject(trig)); if (actor != NULL) { returnValue = actor->CRE()->Reputation() < trig->parameter1; } break; } case 0x4c: { // Entered(O:Object) object_node* node = FindObjectNode(trig); Region* region = dynamic_cast<Region*>(fTarget.Target()); //std::vector<std::string>::const_iterator i; Object* object = Object::GetMatchingObjectFromList( region-> LastScriptRoundResults()-> EnteredActors(), node); if (object != NULL) { fLastTrigger = object; returnValue = true; } break; } default: { printf("SCRIPT: UNIMPLEMENTED TRIGGER!!!\n"); printf("SCRIPT: %s (%d 0x%x)\n", IDTable::TriggerAt(trig->id).c_str(), trig->id, trig->id); trig->Print(); break; } } } catch (...) { printf("SCRIPT: EvaluateTrigger() caught exception"); } if (trig->flags != 0) returnValue = !returnValue; #if DEBUG_SCRIPTS printf("SCRIPT: (%s)\n", returnValue ? "TRUE" : "FALSE"); #endif return returnValue; }
void PinholeCamera::update(const GameTimer & timer) { RayTraceCamera::update(timer); XMFLOAT3 movementAmount = { 0.0f, 0.0f, 0.0f }; if (mKeyboard != nullptr) { if (mKeyboard->isKeyDown(DIK_W)) { movementAmount.y = 1.0f; } if (mKeyboard->isKeyDown(DIK_S)) { movementAmount.y = -1.0f; } if (mKeyboard->isKeyDown(DIK_A)) { movementAmount.x = -1.0f; } if (mKeyboard->isKeyDown(DIK_D)) { movementAmount.x = 1.0f; } if (mKeyboard->isKeyDown(DIK_R)) { movementAmount.z = -1.0f ; } if (mKeyboard->isKeyDown(DIK_F)) { movementAmount.z = 1.0f; } if (mKeyboard->isKeyDown(DIK_Q)) { mViewPlaneDistance -= 10.0f * timer.elapsedGameTime(); } if (mKeyboard->isKeyDown(DIK_E)) { mViewPlaneDistance += 10.0f * timer.elapsedGameTime(); } } float rotationAmount = 0; if ((mMouse != nullptr)) { if ((mMouse->isButtonDown(MouseButtons::MouseButtonsLeft))) { LPDIMOUSESTATE mouseState = mMouse->currentState(); rotationAmount = -mouseState->lX ; //rotationAmount.y = -mouseState->lY * mMouseSensitivity; } } //XMStoreFloat3(&mUp,XMVector3Transform(upVector(), XMMatrixRotationZ(rotationAmount/180.0f * 3.14))); XMVECTOR position = eyeVector(); XMVECTOR movement = XMLoadFloat3(&movementAmount) * mMovementRate * timer.elapsedGameTime(); /*XMVECTOR strafe = right * XMVectorGetX(movement); position += strafe; XMVECTOR forward = XMLoadFloat3(&mDirection) * XMVectorGetY(movement); position += forward;*/ XMStoreFloat3(&mPosition, position + movement); }
Main::Main( bool useKey, bool useMouse, bool enemies, bool collisions, bool rebuildCollisionMeshes) { // Start Ogre root = configRoot(); // Load constants ConstManager::getSingleton(); sceneMgr = root->createSceneManager(ST_GENERIC); window = root->initialise(true, "BlackComrade"); //sceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); // Static Lines class lines = new Lines(sceneMgr); configResources(); // GUI Manager guiMgr = new GuiManager(sceneMgr); // Game Loop gameLoop = new StateUpdate(); // SceneNode Manager sceneNodeMgr = new SceneNodeManager(sceneMgr); // User Input inputState = new InputState(window,true,true,useMouse); gameLoop->addTickable(inputState,"inputState"); // Screen fader fader = new Fader(guiMgr); gameLoop->addTickable(fader,"fader"); // Networking networkingManager = new NetworkingManager(this); // Screenshots screenshot = new Screenshot(inputState,window); gameLoop->addTickable(screenshot,"screenshot"); // Pre-game environment PreGame *preGame = new PreGame(sceneMgr,window,inputState,guiMgr,networkingManager,screenshot); // Sound manager soundMgr = new SoundManager(); collabInfo = preGame->showMenus(); lightAndObjManager = new LightAndObjectsManager(sceneMgr, sceneNodeMgr, gameLoop); // Map MapPieceChoices *mapPieceChoices; std::string mapFileName = ConstManager::getString("map_file_name"); if (mapFileName == "") mapFileName = "examplemap_new.txt"; if (collabInfo->getGameRole() == PILOT) { mapMgr = new MapManager((char*)mapFileName.c_str(), sceneMgr,lightAndObjManager, sceneNodeMgr); mapPieceChoices = mapMgr->getChosenPieces(); networkingManager->replicate(mapPieceChoices); } else { mapPieceChoices = (MapPieceChoices*) networkingManager->getReplica("MapPieceChoices",true); mapMgr = new MapManager((char*)mapFileName.c_str(), mapPieceChoices, sceneMgr, lightAndObjManager, sceneNodeMgr); } if (!useMouse) // || collabInfo->getNetworkRole() == DEVELOPMENTSERVER) inputState->releaseMouse(); if (!useKey) inputState->releaseKeyboard(); // Player info networkingManager->replicate(collabInfo); pilotInfo = (CollaborationInfo*) networkingManager->getReplica("PilotInfo",true); if (collabInfo->getNetworkRole() != DEVELOPMENTSERVER) { engineerInfo = (CollaborationInfo*) networkingManager->getReplica("EngineerInfo",true); navigatorInfo = (CollaborationInfo*) networkingManager->getReplica("NavigatorInfo",true); } else { engineerInfo = new CollaborationInfo("Engineer",CLIENT,ENGINEER); navigatorInfo = new CollaborationInfo("Navigator",CLIENT,NAVIGATOR); engineerInfo->hasCompletedTutorial = true; engineerInfo->isReady = true; navigatorInfo->hasCompletedTutorial = true; navigatorInfo->isReady = true; } // Player stats PlayerStats *myStats = new PlayerStats(collabInfo->getGameRole()); PlayerStats *pilotStats, *engStats, *navStats; collabInfo->setPlayerStats(myStats); networkingManager->replicate(myStats); pilotStats = (PlayerStats*) networkingManager->getReplica("PilotStats",true); pilotInfo->setPlayerStats(pilotStats); if (collabInfo->getNetworkRole() != DEVELOPMENTSERVER) { engStats = (PlayerStats*) networkingManager->getReplica("EngineerStats",true); engineerInfo->setPlayerStats(engStats); navStats = (PlayerStats*) networkingManager->getReplica("NavigatorStats",true); navigatorInfo->setPlayerStats(navStats); } else { engStats = new PlayerStats(ENGINEER); engineerInfo->setPlayerStats(engStats); navStats = new PlayerStats(NAVIGATOR); navigatorInfo->setPlayerStats(navStats); } std::cout << "Your pilot is " << pilotInfo->getNick() << std::endl; std::cout << "Your engineer is " << engineerInfo->getNick() << std::endl; std::cout << "Your navigator is " << navigatorInfo->getNick() << std::endl; // Objective if (collabInfo->getGameRole() == PILOT) { //objective = new Objective(particleSystemEffectManager,collisionMgr); objective = new Objective(particleSystemEffectManager); networkingManager->replicate(objective); } else { objective = (Objective*) networkingManager->getReplica("Objective",true); objective->setParticleSystemEffectManager(particleSystemEffectManager); } objective->setPosition(mapMgr->getObjectivePosition()); gameLoop->addTickable(objective,"objective"); // Collision Manager (takes 99% of our loading time) collisionMgr = new CollisionManager(sceneMgr,mapMgr,objective,preGame->getLoadingScreen(), rebuildCollisionMeshes, sceneNodeMgr); // Damage State if (collabInfo->getGameRole() == PILOT || collabInfo->getNetworkRole() == DEVELOPMENTSERVER) { damageState = new DamageState(pilotInfo,engineerInfo,navigatorInfo); networkingManager->replicate(damageState); } else { damageState = (DamageState*) networkingManager->getReplica("DamageState",true); } damageState->setRepairer(collabInfo); MapTile *startMapTile = mapMgr->getMapTile(&mapMgr->getStartingPosition()); int i = (startMapTile->getConnections())[0]; // Ship State if(collabInfo->getGameRole() == PILOT) { shipState = new ShipState(); networkingManager->replicate(shipState); } else { shipState = (ShipState*) networkingManager->getReplica("ShipState",true); } Vector3 startingPosition = mapMgr->getStartingPosition(); startingPosition.x = startingPosition.x - 215.8; startingPosition.y = 15.5; startingPosition.z = startingPosition.z - 37.5; shipState->setDamageState(damageState); shipState->yaw = (i % 2) ? 0 : PI / 2; //cout << mapMgr->startx << ", " << mapMgr->starty << endl; gameLoop->addTickable(shipState, "shipState"); soundMgr->setShipState(shipState); // Ship Node shipSceneNode = sceneNodeMgr->createNode(shipState); // Effects creator particleSystemEffectManager = new ParticleSystemEffectManager(sceneMgr, mapMgr, shipSceneNode); objective->setParticleSystemEffectManager(particleSystemEffectManager); // Create Engine effects particleSystemEffectManager->createEngineGlow(Vector3(0,0.5,12.0)); particleSystemEffectManager->createEngineGlow(Vector3(0,-0.65,-3.75)); particleSystemEffectManager->createEngineGlow(Vector3(2.5,-0.15,5.75)); particleSystemEffectManager->createEngineGlow(Vector3(-2.5,-0.15,5.75)); // SCALE SHIP!!!! shipScale = ConstManager::getFloat("ship_scale"); shipSceneNode->setScale(shipScale,shipScale,shipScale); soundMgr->setShipNode(shipSceneNode); Entity *shipEntity = sceneNodeMgr->getEntity(shipState); if (collabInfo->getGameRole() == PILOT) { shipEntity->setVisible(false); } // Door Vector3 doorPos = *startMapTile->getSpawn(i); Door *door = new Door(doorPos,(i % 2) ? 0 : PI / 2); sceneNodeMgr->createNode(door); collisionMgr->addColidableMovableObject(sceneNodeMgr->getEntity(door)); gameLoop->addTickable(door, "Door"); // Camera camera = createCamera(shipSceneNode); if(collabInfo->getGameRole() == PILOT) { camera->setPosition(Vector3(0,0,-8)); } else if(collabInfo->getGameRole() == NAVIGATOR) { camera->setPosition(Vector3(0,2.5,9.25)); } else if(collabInfo->getGameRole() == ENGINEER) { camera->setPosition(Vector3(0,-2.5,-8.5)); } // Engineer Controls if(collabInfo->getGameRole() == ENGINEER) { engineerControls = new EngineerControls(inputState,camera); gameLoop->addTickable(engineerControls,"engineerControls"); systemManager = new SystemManager(engineerControls, damageState); networkingManager->replicate(systemManager); } else { if (collabInfo->getNetworkRole() == DEVELOPMENTSERVER) { std::cout << "Making dummy sysmanager\n"; systemManager = new SystemManager(); } else { systemManager = (SystemManager*) networkingManager-> getReplica("SystemManager",true); } } // Pilot Controls if(collabInfo->getGameRole() == PILOT) { collisionMgr->addShipMesh(shipEntity); pilotControls = new PilotControls(inputState,camera); //last 3 terms of flying are the starting position x y z. Note mapMgr->starty = z flying = new Flying( sceneNodeMgr, pilotControls, shipState, damageState, collisionMgr, systemManager, collisions, startingPosition.x, startingPosition.y, startingPosition.z, (i % 2) ? 0 : PI / 2, pilotInfo->getPlayerStats() ); gameLoop->addTickable(pilotControls,"pilotControls"); gameLoop->addTickable(flying,"flying"); } // Navigator Controls if(collabInfo->getGameRole() == NAVIGATOR) { navigatorControls = new NavigatorControls(inputState,camera); gameLoop->addTickable(navigatorControls,"navigatorControls"); } // My controls if (collabInfo->getGameRole() == PILOT) { myControls = pilotControls; } else if (collabInfo->getGameRole() == NAVIGATOR) { myControls = navigatorControls; } else if (collabInfo->getGameRole() == ENGINEER) { myControls = engineerControls; } // Console cons = new Console(sceneMgr); gameLoop->addTickable(cons,"console"); // Minigame manager if (collabInfo->getGameRole() == PILOT) miniGameMgr = new MiniGameManager(cons,inputState,myControls,sceneMgr,collabInfo,navigatorInfo,engineerInfo,this); else if (collabInfo->getGameRole() == NAVIGATOR) miniGameMgr = new MiniGameManager(cons,inputState,myControls,sceneMgr,collabInfo,pilotInfo,engineerInfo,this); else if (collabInfo->getGameRole() == ENGINEER) miniGameMgr = new MiniGameManager(cons,inputState,myControls,sceneMgr,collabInfo,pilotInfo,navigatorInfo,this); gameLoop->addTickable(miniGameMgr,"miniGameManager"); // Tutorial tutorial = new Tutorial(collabInfo,pilotInfo,navigatorInfo,engineerInfo,guiMgr, miniGameMgr,damageState,systemManager,shipState, door,inputState); gameLoop->addTickable(tutorial,"tutorial"); // GameState if(collabInfo->getGameRole() == PILOT) { gameStateMachine = new GameStateMachine(mapMgr,inputState, pilotInfo,engineerInfo,navigatorInfo, tutorial,shipState,damageState,objective); networkingManager->replicate(gameStateMachine); } else { gameStateMachine = (GameStateMachine*) networkingManager-> getReplica("GameStateMachine",true); gameStateMachine->setInputState(inputState); gameStateMachine->setInfos(pilotInfo,navigatorInfo,engineerInfo); } gameLoop->addTickable(gameStateMachine,"gameStateMachine"); gameParameterMap = new GameParameterMap(gameStateMachine); // Print Game State changes printState = new PrintState(gameStateMachine); gameLoop->addTickable(printState,"printState"); // Notifications if (collabInfo->getGameRole() == NAVIGATOR || collabInfo->getNetworkRole() == DEVELOPMENTSERVER) { notificationMgr = new NotificationManager(collabInfo, gameStateMachine, mapMgr, shipState, damageState, systemManager, tutorial, objective); networkingManager->replicate(notificationMgr); } else { notificationMgr = (NotificationManager*) networkingManager-> getReplica("NotificationManager",true); notificationMgr->setCollaborationInfo(collabInfo); notificationMgr->setTutorial(tutorial); } gameLoop->addTickable(notificationMgr,"notifications"); // Pilot Gun State if(collabInfo->getGameRole() == PILOT) { pilotGunState = new GunState(pilotControls,damageState,systemManager,collabInfo); networkingManager->replicate(pilotGunState); } else if(collabInfo->getGameRole() == ENGINEER) { pilotGunState = (GunState*) networkingManager-> getReplica("PilotGunState",true); pilotGunState->setSystemManager(systemManager); std::cout << "Got pilot gun from net" << std::endl; } else { pilotGunState = (GunState*) networkingManager-> getReplica("PilotGunState",true); } gameLoop->addTickable(pilotGunState,"pilotGunState"); // Navigator Gun State if(collabInfo->getGameRole() == NAVIGATOR) { navigatorGunState = new GunState(navigatorControls,damageState,systemManager,collabInfo); networkingManager->replicate(navigatorGunState); gameLoop->addTickable(navigatorGunState,"navigatorGunState"); } else if(collabInfo->getGameRole() == ENGINEER) { navigatorGunState = (GunState*) networkingManager-> getReplica("NavigatorGunState",true); navigatorGunState->setSystemManager(systemManager); std::cout << "Got nav gun from net" << std::endl; gameLoop->addTickable(navigatorGunState,"navigatorGunState"); } else { if (collabInfo->getNetworkRole() != DEVELOPMENTSERVER) { navigatorGunState = (GunState*) networkingManager-> getReplica("NavigatorGunState",true); std::cout << "Got nav gun from net" << std::endl; gameLoop->addTickable(navigatorGunState,"navigatorGunState"); } } // Engineer Gun State if(collabInfo->getGameRole() == ENGINEER) { engineerGunState = new GunState(engineerControls,damageState,systemManager,collabInfo); networkingManager->replicate(engineerGunState); gameLoop->addTickable(engineerGunState,"engineerGunState"); } else { if (collabInfo->getNetworkRole() != DEVELOPMENTSERVER) { engineerGunState = (GunState*) networkingManager-> getReplica("EngineerGunState",true); std::cout << "Got eng gun from net" << std::endl; gameLoop->addTickable(engineerGunState,"engineerGunState"); } } // TODO: starts the enemies pointing towards the ship? // Swarm Manager if (collabInfo->getGameRole() == PILOT) { swarmMgr = new SwarmManager(sceneMgr, sceneNodeMgr, gameParameterMap, mapMgr, shipState,collisionMgr,networkingManager,lines,gameStateMachine,particleSystemEffectManager,soundMgr); } else { swarmMgr = new SwarmManager(sceneMgr, sceneNodeMgr, gameParameterMap, networkingManager,particleSystemEffectManager,soundMgr,collisionMgr); } // Spot Lights pilotSpotLight = new SpotLight(sceneMgr, shipSceneNode, pilotGunState); gameLoop->addTickable(pilotSpotLight, "pilotSpotLight"); if(engineerGunState) { engineerSpotLight = new SpotLight(sceneMgr, shipSceneNode, engineerGunState); gameLoop->addTickable(engineerSpotLight, "engineerSpotLight"); } if(navigatorGunState) { navigatorSpotLight = new SpotLight(sceneMgr, shipSceneNode, navigatorGunState); gameLoop->addTickable(navigatorSpotLight, "navigatorSpotLight"); } // Networking gameLoop->addTickable(networkingManager,"networkingManager"); gameLoop->addTickable(damageState, "damageState"); gameLoop->addTickable(particleSystemEffectManager, "psem"); // Bullet Manager bulletMgr = new BulletManager(shipState,sceneMgr,pilotGunState, engineerGunState,navigatorGunState,collisionMgr,swarmMgr,sceneNodeMgr, damageState,particleSystemEffectManager,objective); gameLoop->addTickable(bulletMgr,"bulletManager"); gameLoop->addTickable(swarmMgr, "swarmMgr"); gameLoop->addTickable(systemManager,"systemManager"); // Audio gameLoop->addTickable(soundMgr,"soundManager"); audioState = new AudioState(pilotGunState,soundMgr,shipSceneNode, notificationMgr,bulletMgr,miniGameMgr, gameStateMachine,objective,damageState); gameLoop->addTickable(audioState,"audioState"); // Game timer GameTimer *timer = new GameTimer(gameStateMachine); gameLoop->addTickable(timer,"timer"); // Game ender gameEnder = new GameEnder(gameStateMachine,guiMgr,this); gameLoop->addTickable(gameEnder,"gameEnder"); // Add the reactor core effects particleSystemEffectManager->makeObjective(); // Wait for the players to be ready std::cout << "Waiting for players...\n"; preGame->waitForPlayers(collabInfo,pilotInfo,engineerInfo,navigatorInfo); // Radar GUI if (collabInfo->getGameRole() == ENGINEER) { bigRadarGui = new RadarGui(guiMgr, shipState, swarmMgr, hud, true, "BigRadar", engineerControls, damageState, cons); gameLoop->addTickable(bigRadarGui,"BigRadar"); smallRadarGui = new RadarGui(guiMgr, shipState, swarmMgr, hud, false, "SmallRadar", engineerControls, damageState, cons); gameLoop->addTickable(smallRadarGui,"SmallRadar"); tutorial->setRadar(bigRadarGui); } gameLoop->addTickable(sceneNodeMgr,"sceneNodeMgr"); // CEGUI Stuff hud = new HUD(guiMgr, shipState,collabInfo->getGameRole(),mapMgr,damageState, cons); tutorial->setHUD(hud); if (collabInfo->getGameRole() == PILOT) tutorial->setFlying(flying); guiStatusUpdater = new GuiStatusUpdater(guiMgr,gameLoop,damageState,myControls, collabInfo->getGameRole(),systemManager,hud, flying,notificationMgr,gameStateMachine,objective, cons, pilotInfo,navigatorInfo,engineerInfo, tutorial); gameLoop->addTickable(guiStatusUpdater,"guiStatusUpdater"); gameLoop->addTickable(lightAndObjManager,"lightAndObjManager"); soundMgr->changeMusic(MS_STEALTH); // Switch to stealth music gameStateMachine->setTutorial(tutorial); cout << "SSN: " << shipSceneNode << endl; // Viewport createViewPort(); // Start Rendering Loop gameLoop->startLoop(); // Hide the console if the game has ended cons->forceHide(); networkingManager->endGame(); // Post-game environment PostGame *postGame = new PostGame(sceneMgr,window,inputState, guiMgr,soundMgr,pilotInfo,navigatorInfo, engineerInfo,gameStateMachine->currentGameState(), damageState,timer->getTime()); std::cout << "Pilot stats:" << "\n"; pilotInfo->getPlayerStats()->print(); std::cout << "Nav stats:" << "\n"; navigatorInfo->getPlayerStats()->print(); std::cout << "Eng stats:" << "\n"; engineerInfo->getPlayerStats()->print(); postGame->showMenus(); networkingManager->stopNetworking(); }