Пример #1
0
int test_ui(int argc, char **argv){
	bool quit=false;
	Input inputs;
	Timer::Update();

	Window *awin = static_cast<Window*>(UI::Add(new Window(0,0,200,400,"A Window")));
	Tabs *tabcont = static_cast<Tabs*>(awin->AddChild(new Tabs(5,25,180,300,"Tabs")));
	Tab *tab1 = static_cast<Tab*>(tabcont->AddChild(new Tab("Tab1")));
	Tab *tab2 = static_cast<Tab*>(tabcont->AddChild(new Tab("Tab2")));

	tab1->AddChild(new Picture(50,100,50,50,"Resources/Graphics/corvet.png"));
	tab1->AddChild(new Checkbox(10,120,true,"Hello"));
	tab1->AddChild(new Button(100,300,50,20,"A button"));
	tab1->AddChild(new Button(100,340,50,20,"A button2"));
	
	tab2->AddChild(new Slider(5,20,100,20,"Slider"));
	tab2->AddChild(new Textbox(5,50,100,1,"Hello","Textbox"));
	tab2->AddChild(new Label(5,80,"Hello"));
	
	while( !quit ) {
		quit = inputs.Update();
		
		Timer::Update();

		Video::Erase();

		UI::Draw();
		Video::Update();
		Timer::Delay();
	}
	return 0;
}
Пример #2
0
void WolfEngine::MainLoop()
{
    int quit = 0;
    SDL_Event eventHandler;
    Uint32 curFrameTime = 0;
    Uint32 lastFrameTime = 0;
    Input input;

	//glEnable(GL_CULL_FACE);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    while (!quit)
    {
        curFrameTime = SDL_GetTicks();
        
        Time::frameTimeS = (float)(curFrameTime - lastFrameTime) / 1000;
        
        // Clear the screen
		glClearColor ( 0.392, 0.584, 0.929, 1.0 );
		glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

        input.Update(&eventHandler);
        
        if (eventHandler.type == SDL_WINDOWEVENT_RESIZED)
        {
            scene->camera->width = eventHandler.window.data1;
            scene->camera->height = eventHandler.window.data2;
        }
        
        if (eventHandler.type == SDL_QUIT)
        {
            quit = 1;
        }
        
        scene->Update();
        
        //Update the gameObjects
        scene->UpdateObjects();

		scene->camera->UpdateMatrices();
        
        //Render the SpriteRenderers
        scene->RenderObjects();
        
        //Late update
        scene->LateUpdateObjects();

        lastFrameTime = curFrameTime;

		SDL_GL_SwapWindow(window);
        
        if (maxFPS != -1 && SDL_GetTicks() - curFrameTime < 1000 / maxFPS)
            SDL_Delay((1000 / maxFPS) - (SDL_GetTicks() - curFrameTime));
    }
	Quit();
}
Пример #3
0
/**\brief Simple Game loop.*/
void Test::GameLoop( void ){
	bool quit=false;
	Input inputs;
	Timer::Update();
	while( !quit ) {
		quit = inputs.Update();
		
		int logicLoops = Timer::Update();
		while(logicLoops--) {
				// Update cycle
		}

		Video::Erase();
		Video::Update();
		UI::Draw();
		Timer::Delay();
	}
}
Пример #4
0
// Game Loop 
void Game::GameLoop( )
{
	Graphics graphics;
	Input input;
	SDL_Event sdlEvent;
	m_Player = Player( graphics, 280.f, 252.f );
	m_Level = Level( "Level1", Vector2( 100, 100 ), graphics );

	float lastUpdateTime = SDL_GetTicks( );	

	while( true )
	{
		// Update input
		input.Update( );

		// SDL Events
		if ( SDL_PollEvent( &sdlEvent ) )
		{
			// Key is down
			if ( sdlEvent.type == SDL_KEYDOWN )
			{				
				// is it repeating
				if ( sdlEvent.key.repeat == 0 )
				{
					input.KeyDownEvent( sdlEvent );
				}
			}
			// Key is released
			else if ( sdlEvent.type == SDL_KEYUP )
			{
				input.KeyUpEvent( sdlEvent );
			}
			// User quits
			else if ( sdlEvent.type == SDL_QUIT )
			{
				return;
			}
		}

		// Quit if escape is pressed
		if ( input.WasKeyPressed( SDL_SCANCODE_ESCAPE ) )
		{
			return;
		}

		// Player character 
		if ( input.IsKeyHeld( SDL_SCANCODE_LEFT ) || input.IsKeyHeld( SDL_SCANCODE_A ) )
		{
			m_Player.MovePlayer( Direction::LEFT );
		}
		else if ( input.IsKeyHeld( SDL_SCANCODE_RIGHT ) || input.IsKeyHeld( SDL_SCANCODE_D ) )
		{
			m_Player.MovePlayer( Direction::RIGHT );
		}
		else
		{
			m_Player.StopMoving( );
		}

		// Jump
		if ( input.WasKeyPressed( SDL_SCANCODE_SPACE ) )
		{
			m_Player.Jump( );
		}

		// Debug
		bDrawDebug = ( input.IsKeyHeld( SDL_SCANCODE_5 ) ) ? true : false;

		const float CURRENT_TIME_IN_MS = SDL_GetTicks( );
		float elapsedTimeInMS = CURRENT_TIME_IN_MS - lastUpdateTime;
		lastUpdateTime = CURRENT_TIME_IN_MS;

		Tick( std::fmin( elapsedTimeInMS, GameStats::MAX_FRAME_TIME ) ); 
		Draw( graphics );
	}

	SDL_Quit( );
}
Пример #5
0
/*
=======
WinMain
=======
*/
int WINAPI WinMain ( HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int nCmdShow ) {
	HWND hwnd;
    MSG  msg;	

	/* Initialise and create window */
	hwnd = CreateOurWindow( "Mirrors and Shadows", S_WIDTH, S_HEIGHT, 0, false, hInstance );	
	if( hwnd == NULL ) return true;

	/* Initialise OpenGL and other settings */
	Init( hwnd );

	/* Create the OpenGLApplication */
	OpenGLApplication theApplication( mInput, mCamera );
	theApplication.Init();

	/* Main Loop */
	while( true ) {							
		if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) {
		    if( msg.message == WM_QUIT ) {
				break;
			}
			TranslateMessage( &msg );							
			DispatchMessage( &msg );
		/* Render Scene */
		} else {
			/* Update Input and Camera */
			mInput.Update();
			mCamera.Update();

			/* Switch to WireFrame */
			if( mInput.mKeys[ VK_SPACE ] ) {
				glPolygonMode( GL_FRONT, GL_LINE );
			} else {
				glPolygonMode( GL_FRONT, GL_FILL );
			}

			/* Display Controls */
			if( mInput.mKeys[ VK_CONTROL ] ) {
				theApplication.mDisplayControls = true;
			} else {
				theApplication.mDisplayControls = false;
			}

			/* Start OpenGl - clear buffers & load identity matrix */
			glClearStencil( 0 );
			glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT ); 
			glLoadIdentity(); 

			/* Set our viewpoint - the camera */
			gluLookAt( mCamera.mPosition.x, mCamera.mPosition.y, mCamera.mPosition.z,                      // where we are
			           mCamera.mPointOfInterest.x, mCamera.mPointOfInterest.y, mCamera.mPointOfInterest.z, // what we look at
			           mCamera.mUp.x, mCamera.mUp.y, mCamera.mUp.z );                                      // which way is up

			/* Render the Application */
			theApplication.Render();

			/* End OpenGL - swap the frame buffers */
			SwapBuffers( ghdc ); 
		}
    }

	return msg.wParam ;										
}
Пример #6
0
int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	Engine::Init();

	Input input;
	input.Init();

	Window window;
	window.Init(800, 600, "killerg2d");

	ResMgr resmgr;
	resmgr.Init();
	
	FrameRate framerate;
	framerate.Init(600);

	Timer timer;
	timer.Init();

	SpiritAnimate spirit;
	spirit.Init("abc.txt");


	int x = 100, y = 100;
	int model = 0;
	while( !input.IsKeyDown(SDLK_ESCAPE) )
	{
		timer.Update();

		input.Update();

		if( input.IsKeyDown(SDLK_LEFT) )
			x-=1;

		if( input.IsKeyDown(SDLK_RIGHT) )
			x+=1;

		if( input.IsKeyDown(SDLK_UP) )
			y-=1;

		if( input.IsKeyDown(SDLK_DOWN) )
			y+=1;

		if( input.IsKeyDown(SDLK_x) )
			spirit.Play();

		if( input.IsKeyDown(SDLK_y) )
			spirit.Stop();

		spirit.Update(timer.GetIntervalF());

		window.Clear();

		spirit.Draw(&window, x, y);

		window.Flush();

		framerate.WaitFrame();
	}

	timer.Destroy();

	framerate.Destroy();

	resmgr.Destroy();

	window.Destroy();

	input.Destroy();


	Engine::Destroy();


	
}
Пример #7
0
// common run state
void RunState()
{
#if defined(USE_SDL)
	// last ticks
	unsigned int ticks = SDL_GetTicks();
#elif defined(USE_SFML)
	// timer
	sf::Clock timer;

	// start timer
	timer.Reset();
#elif defined(USE_GLFW)
	double prevtime = glfwGetTime();
#endif

	// input logging
	TiXmlDocument inputlog(RECORD_CONFIG.c_str());
	TiXmlElement *inputlogroot;
	TiXmlElement *inputlognext;
	if (playback)
	{
		if (!inputlog.LoadFile())
			DebugPrint("error loading recording file \"%s\": %s\n", RECORD_CONFIG.c_str(), inputlog.ErrorDesc());
		inputlogroot = inputlog.RootElement();
		inputlognext = inputlogroot->FirstChildElement();
	}
	else if (record)
	{
		inputlogroot = inputlog.LinkEndChild(new TiXmlElement("journal"))->ToElement();
		inputlognext = NULL;
	}
	else
	{
		inputlogroot = NULL;
		inputlognext = NULL;
	}

#ifdef GET_PERFORMANCE_DETAILS
	PerfTimer::Init();

	PerfTimer control_timer;
	PerfTimer simulate_timer;
	PerfTimer collide_timer;
	PerfTimer update_timer;
	PerfTimer render_timer;
	PerfTimer overlay_timer;
	PerfTimer display_timer;
	PerfTimer total_timer;

	total_timer.Stamp();
#endif

#ifdef COLLECT_DEBUG_DRAW
	// create a new draw list
	GLuint debugdraw = glGenLists(1);
#endif

	// wait for user exit
	do
	{

#ifdef GET_PERFORMANCE_DETAILS
		PerfTimer::Next();

		control_timer.Clear();
		simulate_timer.Clear();
		collide_timer.Clear();
		update_timer.Clear();
		render_timer.Clear();
		overlay_timer.Clear();
		display_timer.Clear();
		total_timer.Clear();
#endif

		// INPUT PHASE

#if defined(USE_SDL)
		// event handler
		SDL_Event event;

		// process events
		while( SDL_PollEvent( &event ) )
		{
			/* Give the console first dibs on event processing */
			if (OGLCONSOLE_SDLEvent(&event))
				continue;

			switch (event.type)
			{
			case SDL_KEYDOWN:
				input.OnPress( Input::TYPE_KEYBOARD, event.key.which, event.key.keysym.sym );
				switch (event.key.keysym.sym)
				{
				case SDLK_F4:
					if (event.key.keysym.mod & KMOD_ALT)
						setgamestate = STATE_QUIT;
					break;
				case SDLK_RETURN:
					if (event.key.keysym.mod & KMOD_ALT)
					{
						CloseWindow();
						SCREEN_FULLSCREEN = !SCREEN_FULLSCREEN;
						OpenWindow();
					}
					break;
				case SDLK_ESCAPE:
					if (curgamestate == STATE_PLAY)
					{
						if (escape)
							EscapeMenuExit();
						else
							EscapeMenuEnter();
					}
					break;
				case SDLK_PAUSE:
					if (event.key.keysym.mod & KMOD_SHIFT)
					{
						paused = true;
						singlestep = true;
					}
					else
					{
						paused = !paused;
					}

					if (paused)
						Pause();
					else
						Resume();
					break;

				case SDLK_PRINT:
					Screenshot();
					break;
				}
				break;
			case SDL_KEYUP:
				input.OnRelease( Input::TYPE_KEYBOARD, event.key.which, event.key.keysym.sym );
				break;
			case SDL_MOUSEMOTION:
				input.OnAxis( Input::TYPE_MOUSE_AXIS, event.motion.which, 0, float(event.motion.x * 2 - SCREEN_WIDTH) / float(SCREEN_HEIGHT) );
				input.OnAxis( Input::TYPE_MOUSE_AXIS, event.motion.which, 1, float(event.motion.y * 2 - SCREEN_HEIGHT) / float(SCREEN_HEIGHT) );
				input.OnAxis( Input::TYPE_MOUSE_AXIS, event.motion.which, 2, event.motion.xrel / 32.0f );
				input.OnAxis( Input::TYPE_MOUSE_AXIS, event.motion.which, 3, event.motion.yrel / 32.0f );
				break;
			case SDL_MOUSEBUTTONDOWN:
				input.OnPress( Input::TYPE_MOUSE_BUTTON, event.button.which, event.button.button );
				break;
			case SDL_MOUSEBUTTONUP:
				input.OnRelease( Input::TYPE_MOUSE_BUTTON, event.button.which, event.button.button );
				break;
			case SDL_JOYAXISMOTION:
				input.OnAxis( Input::TYPE_JOYSTICK_AXIS, event.jaxis.which, event.jaxis.axis, event.jaxis.value / 32767.0f );
				break;
			case SDL_JOYBUTTONDOWN:
				input.OnPress( Input::TYPE_JOYSTICK_BUTTON, event.jaxis.which, event.jbutton.button );
				break;
			case SDL_JOYBUTTONUP:
				input.OnRelease( Input::TYPE_JOYSTICK_BUTTON, event.jbutton.which, event.jbutton.button );
				break;
			case SDL_QUIT:
				setgamestate = STATE_QUIT;
				break;
			}
		}

		// get loop time in ticks
		unsigned int nextticks = SDL_GetTicks();
		float delta = (nextticks - ticks) / 1000.0f;
		ticks = nextticks;
#elif defined(USE_SFML)
	    sf::Event event;
		while (window.GetEvent(event))
		{
			/* Give the console first dibs on event processing */
			if (OGLCONSOLE_SFMLEvent(&event))
				continue;

			// Some code for stopping application on close or when escape is pressed...
			switch (event.Type)
			{
			case sf::Event::Resized:
				glViewport(0, 0, event.Size.Width, event.Size.Height);
				break;
			case sf::Event::KeyPressed:
				input.OnPress( Input::TYPE_KEYBOARD, 0, event.Key.Code );
				switch(event.Key.Code)
				{
				case sf::Key::F4:
					if (event.Key.Alt)
						setgamestate = STATE_QUIT;
					break;
				case sf::Key::Return:
					if (event.Key.Alt)
					{
						CloseWindow();
						SCREEN_FULLSCREEN = !SCREEN_FULLSCREEN;
						OpenWindow();
					}
					break;
				case sf::Key::Escape:
					if (curgamestate == STATE_PLAY)
					{
						if (escape)
							EscapeMenuExit();
						else
							EscapeMenuEnter();
					}
					break;
				case sf::Key::Pause:
					if (event.Key.Shift)
					{
						paused = true;
						singlestep = true;
					}
					else
					{
						paused = !paused;
					}

					if (paused)
						Pause();
					else
						Resume();
					break;
				}
				break;
			case sf::Event::KeyReleased:
				input.OnRelease( Input::TYPE_KEYBOARD, 0, event.Key.Code );
				break;
			case sf::Event::MouseMoved:
				input.OnAxis( Input::TYPE_MOUSE_AXIS, 0, 0, float(int(event.MouseMove.X) * 2 - SCREEN_WIDTH) / float(SCREEN_HEIGHT) );
				input.OnAxis( Input::TYPE_MOUSE_AXIS, 0, 1, float(int(event.MouseMove.Y) * 2 - SCREEN_HEIGHT) / float(SCREEN_HEIGHT) );
				break;
			case sf::Event::MouseButtonPressed:
				input.OnPress( Input::TYPE_MOUSE_BUTTON, 0, event.MouseButton.Button );
				break;
			case sf::Event::MouseButtonReleased:
				input.OnRelease( Input::TYPE_MOUSE_BUTTON, 0, event.MouseButton.Button );
				break;
			case sf::Event::JoyMoved:
				input.OnAxis( Input::TYPE_JOYSTICK_AXIS, event.JoyMove.JoystickId, event.JoyMove.Axis, event.JoyMove.Position / 100.0f );
				break;
			case sf::Event::JoyButtonPressed:
				input.OnPress( Input::TYPE_JOYSTICK_BUTTON, event.JoyButton.JoystickId, event.JoyButton.Button );
				break;
			case sf::Event::JoyButtonReleased:
				input.OnRelease( Input::TYPE_JOYSTICK_BUTTON, event.JoyButton.JoystickId, event.JoyButton.Button );
				break;
			case sf::Event::Closed:
				setgamestate = STATE_QUIT;
				break;
			}
		}

		// get loop time in ticks
		float delta = timer.GetElapsedTime();
		timer.Reset();
		//ticks += delta;
#elif defined(USE_GLFW)
		if (glfwGetJoystickParam(0, GLFW_PRESENT))
		{
			// get joystick axis positions
			int axiscount = glfwGetJoystickParam(0, GLFW_AXES);
			float *axis = static_cast<float *>(_alloca(axiscount * sizeof(float)));
			axiscount = glfwGetJoystickPos(0, axis, axiscount);
			for (int i = 0; i < axiscount; ++i)
				input.OnAxis(Input::TYPE_JOYSTICK_AXIS, 0, i, axis[i]);

			// get joystick button states
			int buttoncount = glfwGetJoystickParam(0, GLFW_BUTTONS);
			unsigned char *button = static_cast<unsigned char *>(_alloca(buttoncount * sizeof(unsigned char)));
			buttoncount = glfwGetJoystickButtons(0, button, buttoncount);
			for (int i = 0; i < buttoncount; ++i)
				input.OnAxis(Input::TYPE_JOYSTICK_BUTTON, 0, i, button[i]);
		}
		
		double nexttime = glfwGetTime();
		float delta = float(nexttime - prevtime);
		prevtime = nexttime;
#endif

		// clamp ticks to something sensible
		// (while debugging, for example)
		if (delta > 0.1f)
			delta = 0.1f;

		// frame time and turns
		if (singlestep)
		{
			// advance 1/60th of a second
			frame_time = TIME_SCALE / 60.0f;
			frame_turns = frame_time * sim_rate;
		}
		else if (paused || escape)
		{
			// freeze time
			frame_time = 0.0f;
			frame_turns = 0.0f;
		}
		else if (FIXED_STEP)
		{
			// advance one simulation step
			frame_time = TIME_SCALE * sim_step;
			frame_turns = TIME_SCALE;
		}
		else
		{
			// advance by frame time
			frame_time = delta * TIME_SCALE;
			frame_turns = frame_time * sim_rate;
		}

		// turns per motion-blur step
		float step_turns = std::min(TIME_SCALE * MOTIONBLUR_TIME * sim_rate, 1.0f) / MOTIONBLUR_STEPS;

		// advance to beginning of motion blur steps
		sim_fraction += frame_turns;
		sim_fraction -= MOTIONBLUR_STEPS * step_turns;

		// for each motion-blur step
		for (int blur = 0; blur < MOTIONBLUR_STEPS; ++blur)
		{
			// clear the screen
			glClear(
				GL_COLOR_BUFFER_BIT
#ifdef ENABLE_DEPTH_TEST
				| GL_DEPTH_BUFFER_BIT
#endif
				);

			// set projection
			glMatrixMode( GL_PROJECTION );
			glLoadIdentity();
			glFrustum( -0.5*VIEW_SIZE*SCREEN_WIDTH/SCREEN_HEIGHT, 0.5*VIEW_SIZE*SCREEN_WIDTH/SCREEN_HEIGHT, 0.5f*VIEW_SIZE, -0.5f*VIEW_SIZE, 256.0f*1.0f, 256.0f*5.0f );

			// set base modelview matrix
			glMatrixMode( GL_MODELVIEW );
			glLoadIdentity();
			glTranslatef( 0.0f, 0.0f, -256.0f );
			glScalef( -1.0f, -1.0f, -1.0f );

			// advance the sim timer
			sim_fraction += step_turns;

			if (escape)
			{
				input.Update();
				input.Step();
			}
			// while simulation turns to run...
			else while ((singlestep || !paused) && sim_fraction >= 1.0f)
			{
				// deduct a turn
				sim_fraction -= 1.0f;
				
				// advance the turn counter
				++sim_turn;

				// save original fraction
				float save_fraction = sim_fraction;

				// switch fraction to simulation mode
				sim_fraction = 0.0f;

#ifdef COLLECT_DEBUG_DRAW
				// collect any debug draw
				glNewList(debugdraw, GL_COMPILE);
#endif

				// seed the random number generator
				Random::Seed(0x92D68CA2 ^ sim_turn);
				(void)Random::Int();

				// update database
				Database::Update();

				if (curgamestate == STATE_PLAY)
				{
					if (playback)
					{
						// quit if out of turns
						if (!inputlognext)
						{
							setgamestate = STATE_SHELL;
							break;
						}

						// get the next turn value
						int turn = -1;
						inputlognext->QueryIntAttribute("turn", &turn);

						// if the turn matches the simulation turn...
						if ((unsigned int)turn == sim_turn)
						{
							// update the control values
							input.Playback(inputlognext);

							// go to the next entry
							inputlognext = inputlognext->NextSiblingElement();
						}
					}
					else if (record)
					{
						// save original input values
						float prev[Input::NUM_LOGICAL];
						memcpy(prev, input.output, sizeof(prev));

						// update input values
						input.Update();

						// if any controls have changed...
						bool changed = false;
						for (int i = 0; i < Input::NUM_LOGICAL; ++i)
						{
							if (input.output[i] != prev[i])
							{
								changed = true; break;
							}
						}
						if (changed)
						{
							// create an input turn entry
							TiXmlElement item( "input" );
							item.SetAttribute( "turn", sim_turn );

							// add changed control values
							input.Record(&item, prev);

							// add the new input entry
							inputlogroot->InsertEndChild(item);
						}
					}
					else
					{
						// update input values
						input.Update();
					}
				}

				// do any pending turn actions
				DoTurn();


				// CONTROL PHASE

#ifdef GET_PERFORMANCE_DETAILS
				control_timer.Start();
#endif

				// control all entities
				Controller::ControlAll(sim_step);

#ifdef GET_PERFORMANCE_DETAILS
				control_timer.Stop();

				simulate_timer.Start();
#endif

				// SIMULATION PHASE
				// (generate forces)
				Simulatable::SimulateAll(sim_step);

#ifdef GET_PERFORMANCE_DETAILS
				simulate_timer.Stop();

				collide_timer.Start();
#endif

				// COLLISION PHASE
				// (apply forces and update positions)
				Collidable::CollideAll(sim_step);

#ifdef GET_PERFORMANCE_DETAILS
				collide_timer.Stop();

				update_timer.Start();
#endif

				// UPDATE PHASE
				// (use updated positions)
				Updatable::UpdateAll(sim_step);

#ifdef GET_PERFORMANCE_DETAILS
				update_timer.Stop();
#endif

				// step inputs for next turn
				input.Step();

#ifdef COLLECT_DEBUG_DRAW
				// finish the draw list
				glEndList();
#endif
				
				// restore original fraction
				sim_fraction = save_fraction;
			}

			// clear single-step
			singlestep = false;

			// seed the random number generator
			FloatInt floatint;
			floatint.f = sim_fraction;
			Random::Seed(0x92D68CA2 ^ sim_turn ^ floatint.u);
			(void)Random::Int();

#ifdef PRINT_SIMULATION_TIMER
			DebugPrint("delta=%f ticks=%d sim_t=%f\n", delta, ticks, sim_fraction);
#endif

#ifdef GET_PERFORMANCE_DETAILS
			render_timer.Start();
#endif

			// RENDERING PHASE

			// push camera transform
			glPushMatrix();

			// get interpolated track position
			Vector2 viewpos(Lerp(camerapos[0], camerapos[1], sim_fraction));

			// set view position
			glTranslatef( -viewpos.x, -viewpos.y, 0 );

			// calculate view area
			AlignedBox2 view;
			view.min.x = viewpos.x - VIEW_SIZE * 0.5f * SCREEN_WIDTH / SCREEN_HEIGHT;
			view.max.x = viewpos.x + VIEW_SIZE * 0.5f * SCREEN_WIDTH / SCREEN_HEIGHT;
			view.min.y = viewpos.y - VIEW_SIZE * 0.5f;
			view.max.y = viewpos.y + VIEW_SIZE * 0.5f;

			// render all entities
			// (send interpolation ratio and offset from simulation time)
			Renderable::RenderAll(view);

			// reset camera transform
			glPopMatrix();

			// if performing motion blur...
			if (MOTIONBLUR_STEPS > 1)
			{
				// accumulate the image
				glAccum(blur ? GL_ACCUM : GL_LOAD, 1.0f / float(MOTIONBLUR_STEPS));
			}

#ifdef GET_PERFORMANCE_DETAILS
			render_timer.Stop();
#endif
		}

#ifdef GET_PERFORMANCE_DETAILS
		render_timer.Start();
#endif

		// if performing motion blur...
		if (MOTIONBLUR_STEPS > 1)
		{
			// return the accumulated image
			glAccum(GL_RETURN, 1);
		}

		// switch blend mode
		glPushAttrib(GL_COLOR_BUFFER_BIT | GL_TEXTURE_BIT);
		glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

#ifdef GET_PERFORMANCE_DETAILS
		render_timer.Stop();

		overlay_timer.Start();
#endif

#ifdef COLLECT_DEBUG_DRAW
		if (DEBUG_DRAW)
		{
			// push camera transform
			glPushMatrix();

			// get interpolated track position
			Vector2 viewpos(Lerp(camerapos[0], camerapos[1], sim_fraction));

			// set camera to track position
			glTranslatef( -viewpos.x, -viewpos.y, 0 );

			// debug draw
			glCallList(debugdraw);

			// pop camera transform
			glPopMatrix();
		}
#endif

		// push projection transform
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho(0, 640, 480, 0, -1, 1);

		// use 640x480 screen coordinates
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();

		// render all overlays
		Overlay::RenderAll();

#ifdef GET_PERFORMANCE_DETAILS
		overlay_timer.Stop();

		if (!OPENGL_SWAPCONTROL)
		{
			display_timer.Start();

			// wait for rendering to finish
			glFinish();

			display_timer.Stop();
		}

#ifdef DRAW_PERFORMANCE_DETAILS
		if (PROFILER_OUTPUTSCREEN)
		{
			struct BandInfo
			{
				const LONGLONG * time;
				float r;
				float g;
				float b;
				float a;
			};
			static BandInfo band_info[] =
			{
				{ control_timer.mHistory,	1.0f,	0.0f,	0.0f,	0.5f },
				{ simulate_timer.mHistory,	1.0f,	1.0f,	0.0f,	0.5f },
				{ collide_timer.mHistory,	0.0f,	1.0f,	0.0f,	0.5f },
				{ update_timer.mHistory,	0.0f,	0.5f,	1.0f,	0.5f },
				{ render_timer.mHistory,	1.0f,	0.0f,	1.0f,	0.5f },
				{ overlay_timer.mHistory,	1.0f,	0.5f,	0.0f,	0.5f },
				{ display_timer.mHistory,	0.5f,	0.5f,	0.5f,	0.5f },
			};

			// generate y samples
			float sample_y[SDL_arraysize(band_info)+1][PerfTimer::NUM_SAMPLES];
			int index = PerfTimer::mIndex;
			for (int i = 0; i < PerfTimer::NUM_SAMPLES; ++i)
			{
				float y = 480.0f;
				sample_y[0][i] = y;
				for (int band = 0; band < SDL_arraysize(band_info); ++band)
				{
					y -= 60.0f * 480.0f * band_info[band].time[index] / PerfTimer::mFrequency;
					sample_y[band+1][i] = y;
				}
				if (++index >= PerfTimer::NUM_SAMPLES)
					index = 0;
			}

			glBegin(GL_QUADS);
			for (int band = 0; band < SDL_arraysize(band_info); ++band)
			{
				glColor4fv(&band_info[band].r);
				float x = 0;
				float dx = 640.0f / PerfTimer::NUM_SAMPLES;
				for (int i = 0; i < PerfTimer::NUM_SAMPLES; i++)
				{
					glVertex3f(x, sample_y[band][i], 0);
					glVertex3f(x+dx, sample_y[band][i], 0);
					glVertex3f(x+dx, sample_y[band+1][i], 0);
					glVertex3f(x, sample_y[band+1][i], 0);
					x += dx;
				}
			}
			glEnd();
		}
#endif

#ifdef PRINT_PERFORMANCE_DETAILS
		if (PROFILER_OUTPUTPRINT)
		{
			DebugPrint("C=%d S=%d P=%d U=%d R=%d O=%d D=%d\n",
				control_timer.Microseconds(),
				simulate_timer.Microseconds(),
				collide_timer.Microseconds(),
				update_timer.Microseconds(),
				render_timer.Microseconds(),
				overlay_timer.Microseconds(),
				display_timer.Microseconds());
		}
#endif

		// update frame timer
		total_timer.Stamp();

#if defined(PRINT_PERFORMANCE_FRAMERATE) || defined(DRAW_PERFORMANCE_FRAMERATE)
		if (FRAMERATE_OUTPUTSCREEN || FRAMERATE_OUTPUTPRINT)
		{
			// compute minimum, maximum, and average frame times over the past second
			LONGLONG total_min = LLONG_MAX;
			LONGLONG total_max = LLONG_MIN;
			LONGLONG total_sum = 0;
			LONGLONG total_samples = 0;
			int i = PerfTimer::mIndex;
			do
			{
				total_min = std::min(total_min, total_timer.mHistory[i]);
				total_max = std::max(total_max, total_timer.mHistory[i]);
				total_sum += total_timer.mHistory[i];
				++total_samples;
				i = (i > 0) ? i - 1 : PerfTimer::NUM_SAMPLES - 1;
			}
			while (total_sum <= PerfTimer::mFrequency && i != PerfTimer::mIndex && total_samples != PerfTimer::mCount);
			total_sum /= total_samples;

			// compute frame rates
			double rate_max = (double)PerfTimer::mFrequency / total_min;
			double rate_avg = (double)PerfTimer::mFrequency / total_sum;
			double rate_min = (double)PerfTimer::mFrequency / total_max;

#if defined(DRAW_PERFORMANCE_FRAMERATE)
			if (FRAMERATE_OUTPUTSCREEN)
			{
				// draw frame rate indicator
				glEnable(GL_TEXTURE_2D);
				glBindTexture(GL_TEXTURE_2D, OGLCONSOLE_glFontHandle);

				glBegin(GL_QUADS);

				char fps[16];
				sprintf(fps, "%.2f max", rate_max);
				glColor4f(0.5f, 0.5f, 0.5f, 1.0f);
				OGLCONSOLE_DrawString(fps, 640 - 16 - 8 * strlen(fps), 16, 8, -8, 0);
				sprintf(fps, "%.2f avg", rate_avg);
				glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
				OGLCONSOLE_DrawString(fps, 640 - 16 - 8 * strlen(fps), 24, 8, -8, 0);
				sprintf(fps, "%.2f min", rate_min);
				glColor4f(0.5f, 0.5f, 0.5f, 1.0f);
				OGLCONSOLE_DrawString(fps, 640 - 16 - 8 * strlen(fps), 32, 8, -8, 0);

				glEnd();

				glDisable(GL_TEXTURE_2D);
			}
#endif

#if defined(PRINT_PERFORMANCE_FRAMERATE)
			if (FRAMERATE_OUTPUTPRINT)
			{
				DebugPrint("%.2f<%.2f<%.2f\n", rate_min, rate_avg, rate_max);
			}
#endif
		}
#endif
#endif

		// reset camera transform
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glMatrixMode(GL_MODELVIEW);
		glPopMatrix();

		// restore blend mode
		glPopAttrib();

		/* Render our console */
		OGLCONSOLE_Draw();

		// show the back buffer
		Platform::Present();

#if 0
#ifdef GET_PERFORMANCE_DETAILS
		if (OPENGL_SWAPCONTROL)
#endif
		// wait for rendering to finish
		glFinish();
#endif

		// clear device reset flag
		wasreset = false;
	}
	while( setgamestate == curgamestate );

	if (record)
	{
		// save input log
		inputlog.SaveFile();
	}
}
Пример #8
0
int main()
{
	srand(time(0));


	//Window
	sf::VideoMode Res = sf::VideoMode::getDesktopMode();
	sf::RenderWindow window(sf::VideoMode(Res.width, Res.height), "SFML works!", sf::Style::None | sf::Style::Fullscreen);
	//window.setPosition(sf::Vector2i(Res.width * 0.1, Res.height * 0.1));




	//Creating and loading texture
	sf::Texture texture;
	if (!texture.loadFromFile("ptank.png"))
	{
		printf("no texture");
	}

	sf::Texture titleBack;
	if (!titleBack.loadFromFile("howl2.jpg"))
	{
		printf("no texture");
	}

	sf::Texture titleText;
	if (!titleText.loadFromFile("title.png"))
	{
		printf("no texture");
	}


	sf::Sprite sprTitleBack(titleBack);
	sf::Sprite sprTitleText(titleText);

	//Creating Sprite
	sf::Sprite* sprite = new sf::Sprite(texture);
	sprite->setPosition(30, 30);
	sprite->setOrigin(25.0f, 25.0f);
	Tank playerTank;
	playerTank.SetSprite(sprite);
	
	Input input;
	input.AttachTank(&playerTank);

	playerTank.Init();


	//TEST - Circle
	sf::CircleShape circleTest;
	circleTest.setFillColor(sf::Color::Blue);
	circleTest.setPosition(300, 300);
	circleTest.setRadius(30.f);
	sf::FloatRect circleBounds = circleTest.getGlobalBounds();
	sf::RectangleShape circleColSquare(sf::Vector2f(circleBounds.width, circleBounds.height));
	circleColSquare.setPosition(circleBounds.left, circleBounds.top);
	circleColSquare.setOutlineColor(sf::Color::Green);
	circleColSquare.setOutlineThickness(2.0f);
	circleColSquare.setFillColor(sf::Color::Transparent);
	

	//TankBounds - Temp Bounds
	// C style array and memory copying
	// ===more reading in C++ array memory management====
	//int* array = new int[10];
	//int* temp = array;
	//array = new int[20];
	//memcpy(array, temp, sizeof(int) * 10);
	//delete[] temp;
	//
	//int* shortArray = new int[10];
	//int* shortTemp = shortArray;
	//shortArray = new int[5];
	//memcpy(array, temp, sizeof(int) * 5);
	//delete[] shortTemp;


	//Circles - Creation - Number of 
	const int circlecount = 50;
	Tank tanks[circlecount];

	//const int enemyTankCount = 50;
	//Tank** enemyTanks = new Tank*[enemyTankCount];

	//Second star is like Oprah
	//we don't know this is an array
	//stack (1mb)  vs heap
	// learn about this and not use it

	//Green Circle - tanks[i].GetCircle().setFillColor(sf::Color::Green);
	for (int i = 0; i < circlecount; i++)
	{
		//int = 

		sf::Sprite* newSprite = new sf::Sprite(texture);
		newSprite->setColor(sf::Color(255, 128, 128, 255));
		newSprite->setPosition(30, 30);
		newSprite->setOrigin(25.0f, 25.0f);

		int randomX = rand() % window.getSize().x;
		int randomY = rand() % window.getSize().y;

		tanks[i].SetSprite(newSprite);
		tanks[i].SetPosition(sf::Vector2f(randomX, randomY));
		tanks[i].Init();
		//enemyTanks[i] = new Tank();
		//enemyTanks[i]->SetSprite(newSprite);
		//enemyTanks[i]->SetPosition(sf::Vector2f(randomX, randomY));
		//enemyTanks[i]->Init();
	}

	

	enum GState { Title, Main, Pause, GameOver };

	GState gState;
	gState = Title;
	int a = 0;


	//Delta Time (Clock)
	sf::Clock deltaClock;
	sf::Clock titleFadeIn;
	float tfadein = titleFadeIn.getElapsedTime().asSeconds();
	bool fadeT = false;


	//Main Loop
	while (window.isOpen())
	{
		
		while (gState == Title)
		{
		
			//if (tfadein >= 3)
			//{
			//	fadeT = true;
			//}

			if (/*fadeT == true &&*/ tfadein >= 0.01f)
			{
				if (a < 255)
				{
					a += 1;
				}

				titleFadeIn.restart();
			}


			sprTitleText.setColor(sf::Color(255, 255, 255, a));
			
			window.draw(sprTitleBack);
			window.draw(sprTitleText);
			window.display();

			if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Return))
			{
				gState = Main;
			}

		}


		while (gState == Main)
		{

			float dt = deltaClock.restart().asSeconds();
			//Delta time decouples from frame rate

			if (dt > 1.0f / 60.0f)
				//If the next frame is higher than 1 in 60 - the cap stops it from going further e,g window is held
			{
				dt = 1.0f / 60.0f;
			}

			sf::Event event;
			while (window.pollEvent(event))
			{
				if (event.type == sf::Event::Closed)
					window.close();
			}

			//Clear Screen
			window.clear();

			input.Update(dt);

			//Red Circle Movement
			for (int i = 0; i < circlecount; i++)
			{
				sf::Vector2f movelose((rand() % 5) - 2, (rand() % 5) - 2);
				sf::Vector2f currentposition(tanks[i].GetPosition());

				tanks[i].SetPosition((movelose * dt * tanks[i].MoveSpeed()) + currentposition);
			}

			// UPDATE LOOP
			for (int i = 0; i < circlecount; ++i)
			{
				tanks[i].Update(dt);
			}
			playerTank.Update(dt);

			//Draw Loop for red circles
			for (int i = 0; i < circlecount; i++)
			{
				if (tanks[i].GetDrawable() != NULL)
				{
					window.draw(*tanks[i].GetDrawable());
					window.draw(tanks[i].getBounds());
				}
			}


			// Draw player
			//window.draw(*playerTank.GetDrawable());
			//window.draw(playerTank.getBounds());
			playerTank.Draw(&window);
			window.draw(circleTest);
			window.draw(circleColSquare);

			window.display();

			if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Escape))
			{

				window.close();
			}
		}
		//EndMainLoop

	}





	return 0;
}
Пример #9
0
bool Simulation::Run( void ) {
	bool quit = false;
	Input inputs;
	int fpsCount = 0; // for FPS calculations
	int fpsTotal= 0; // for FPS calculations
	Uint32 fpsTS = 0; // timestamp of last FPS printing

	// Grab the camera and give it coordinates
	Camera *camera = Camera::Instance();
	camera->Focus(0, 0);

	// Generate a starfield
	Starfield starfield( OPTION(int, "options/simulation/starfield-density") );

	// Create a spritelist
	SpriteManager sprites;

	Player *player = Player::Instance();

	// Set player model based on simulation xml file settings
	player->SetModel( models->GetModel( playerDefaultModel ) );
	sprites.Add( player->GetSprite() );

	// Focus the camera on the sprite
	camera->Focus( player->GetSprite() );

	// Add the planets
	planets->RegisterAll( &sprites );

	// Start the Lua Universe
	Lua::SetSpriteList( &sprites );
	Lua::Load("Resources/Scripts/universe.lua");

	// Start the Lua Scenarios
	Lua::Run("Start()");

	// Ensure correct drawing order
	sprites.Order();
	
	// Create the hud
	Hud::Hud();

	Hud::Alert( "Captain, we don't have the power! Pow = %d", 3 );

	fpsTS = Timer::GetTicks();
	// main game loop
	while( !quit ) {
		quit = inputs.Update();
		
		if( !paused ) {
			Lua::Update();
			// Update cycle
			starfield.Update();
			camera->Update();
			sprites.Update();
			camera->Update();
			Hud::Update();
			UI::Run(); // runs only a few loops
			
			// Keep this last (I think)
			Timer::Update();
		}

		// Erase cycle
		Video::Erase();
		
		// Draw cycle
		starfield.Draw();
		sprites.Draw();
		Hud::Draw( sprites );
		UI::Draw();
		Video::Update();
		
		// Don't kill the CPU (play nice)
		Timer::Delay();
		
		Coordinate playerPos = player->GetWorldPosition();

		// Counting Frames
		fpsCount++;
		fpsTotal++;

		// Update the fps once per second
		if( (Timer::GetTicks() - fpsTS) >1000 ) { 
			Simulation::currentFPS = static_cast<float>(1000.0 *
					((float)fpsCount / (Timer::GetTicks() - fpsTS)));
			fpsTS = Timer::GetTicks();
			fpsCount = 0;
		}
	}

	Log::Message("Average Framerate: %f Frames/Second", 1000.0 *((float)fpsTotal / Timer::GetTicks() ) );
	return true;
}