Spawn 2 enemies per second in GLUT - c++

I'm making a game in openGL and I want to spawn 2 enemies per second on the screen. The problem is, I'm calling the spawn function inside idle:
idle
{
// ...
world.spawnEnemy();
}
And then, in the spawnEnemy function:
void World::spawnEnemy()
{
Enemy newEnemy, newEnemy2;
float start;
start = glutGet(GLUT_ELAPSED_TIME);
// 1/2 a second passes
while ( (glutGet(GLUT_ELAPSED_TIME) - start) <= 500 )
{
;
}
// create enemy
newEnemy();
pushToEnemyList(newEnemy);
// another 1/2 second passes
while ( (glutGet(GLUT_ELAPSED_TIME) - start) <= 1000 )
{
;
}
// create enemy
newEnemy2();
pushToEnemyList(newEnemy2);
}
And this is not working, of course. Probably because idle is called everytime and I'm calling a function inside idle that waits for a certain amount of time to pass and then everything starts going wrong. The solution is to do the spawning in the idle function (without calling any function, doing all the logic inside idle), but I don't like this idea. I need to do more things in a certain number of time, for example, my enemies have guns and they will have to shoot n times every second. And if I do all of these directly inside of idle it will become a mess. So, basically, how do I make this work:
idle
{
// ...
world.spawnEnemy();
world.enemyShoot();
// another functionalities that depend on time
}
instead of this:
idle
{
// ...
// logic of spawnEnemy directly here in the idle function
// logic of enemyShoot directly here in the idle function
// logic of another functionalities that depend on time directly here in the idle function
}

There is quite a few ways to do this here the most common:
Measure elapsed time
Simply remember time of last spawn t0 and on each (idle) iteration get current time t. If t0+T<=t then spawn new enemy ans set t0=t. The T is the period of spawning in the same units as the measured time. In your case 500ms.
As mentioned OnIdle Event will take 100% of one CPU core for itself. To remedy this use Sleep(x); where x<<T that will ease up on the CPU load (even Sleep(1); will be a big difference).
To measure time use any OS routine you got available (with high enough accuracy) I am using PerformanceCounter on Windows but there are other alternatives like RDTSC etc ...
Timers
Modern messaging based OS provides timer function which will fire your event periodically (usually with ~1ms accuracy). Just study your API to implement it. Then you just spawn your enemy inside timer event without any other logic or timing code ...
In case you do not have any timers you can fake this by creating thread with code like this inside:
for (;!spawn_exit;)
{
if (spawn_enabled) spawn();
Sleep(T);
}
where volatile bool spawn_enabled=true,spawn_exit=false; are used to control the spawning and stop the thread (before App shutdown) But in this case be careful with multi threaded access in the spawn() function ...

Related

How to call a function every x seconds but be able to do stuff in the meantime

I'm building a tetris game and I need the pieces to fall every x seconds; something like:
while(true){
moveDown();
sleep(x)
}
The problem is, I need to be able to move the pieces left and right in the meantime, i.e., call a function while it's sleeping.
How can I do that in c++?
Both time and key presses can be events which can be used to wait on. On UNIXes you'd use something like poll() with a suitable time for timeout and the input device used to recognize key presses. On other systems there are similar facilities (I'm a UNIX persons and I have never worked on Windows specific stuff although it seems the Windows facilities are actually more flexible). Depending on the result of poll() (timeout or activity on the I/O device in that case) you'd do the appropriate action.
This problem is solvable in multiple ways (another idea that comes to mind is multithreading, but that seems overkill). One approach would be to keep track of the number of "game cycles" and execute some function every n-th cycle like this:
for(int32_t count{1};;count++)
{
if (!count % 5)
{
// do something every 5th cycle
}
// do something every cycle
sleep(x);
}
you can measure how much time has passed since last fall and move piece down after given amount and then reset counter. In pseudo-code it could look like this:
while(true)
{
counter.update();
if(counter.value() == fall_period)
{
move_piece_down();
couter.reset();
}
// rotate pieces
}
If you are using typical implementation of game loop your counter can just accumulate elapsed time since last frame.

C++ How to make precise frame rate limit?

I'm trying to create a game using C++ and I want to create limit for fps but I always get more or less fps than I want. When I look at games that have fps limit it's always precise framerate. Tried using Sleep() std::this_thread::sleep_for(sleep_until). For example Sleep(0.01-deltaTime) to get 100 fps but ended up with +-90fps.
How do these games handle fps so precisely when any sleeping isn't precise?
I know I can use infinite loop that just checks if time passed but it's using full power of CPU but I want to decrease CPU usage by this limit without VSync.
Yes, sleep is usually inaccurate. That is why you sleep for less than the actual time it takes to finish the frame. For example, if you need 5 more milliseconds to finish the frame, then sleep for 4 milliseconds. After the sleep, simply do a spin-lock for the rest of the frame. Something like
float TimeRemaining = NextFrameTime - GetCurrentTime();
Sleep(ConvertToMilliseconds(TimeRemaining) - 1);
while (GetCurrentTime() < NextFrameTime) {};
Edit: as stated in another answer, timeBeginPeriod() should be called to increase the accuracy of Sleep(). Also, from what I've read, Windows will automatically call timeEndPeriod() when your process exits if you don't before then.
You could record the time point when you start, add a fixed duration to it and sleep until the calculated time point occurs at the end (or beginning) of every loop. Example:
#include <chrono>
#include <iostream>
#include <ratio>
#include <thread>
template<std::intmax_t FPS>
class frame_rater {
public:
frame_rater() : // initialize the object keeping the pace
time_between_frames{1}, // std::ratio<1, FPS> seconds
tp{std::chrono::steady_clock::now()}
{}
void sleep() {
// add to time point
tp += time_between_frames;
// and sleep until that time point
std::this_thread::sleep_until(tp);
}
private:
// a duration with a length of 1/FPS seconds
std::chrono::duration<double, std::ratio<1, FPS>> time_between_frames;
// the time point we'll add to in every loop
std::chrono::time_point<std::chrono::steady_clock, decltype(time_between_frames)> tp;
};
// this should print ~10 times per second pretty accurately
int main() {
frame_rater<10> fr; // 10 FPS
while(true) {
std::cout << "Hello world\n";
fr.sleep(); // let it sleep any time remaining
}
}
The accepted answer sounds really bad. It would not be accurate and it would burn the CPU!
Thread.Sleep is not accurate because you have to tell it to be accurate (by default is about 15ms accurate - means that if you tell it to sleep 1ms it could sleep 15ms).
You can do this with Win32 API call to timeBeginPeriod & timeEndPeriod functions.
Check MSDN for more details -> https://learn.microsoft.com/en-us/windows/win32/api/timeapi/nf-timeapi-timebeginperiod
(I would comment on the accepted answer but still not having 50 reputation)
Be very careful when implementing any wait that is based on scheduler sleep.
Most OS schedulers have higher latency turn-around for a wait with no well-defined interval or signal to bring the thread back into the ready-to-run state.
Sleeping isn't inaccurate per-se, you're just approaching the problem all wrong. If you have access to something like DXGI's Waitable Swapchain, you synchronize to the DWM's present queue and get really reliable low-latency timing.
You don't need to busy-wait to get accurate timing, a waitable timer will give you a sync object to reschedule your thread.
Whatever you do, do not use the currently accepted answer in production code. There's an edge case here you WANT TO AVOID, where Sleep (0) does not yield CPU time to higher priority threads. I've seen so many game devs try Sleep (0) and it's going to cause you major problems.
Use a timer.
Some OS's can provide special functions. For example, for Windows you can use SetTimer and handle its WM_TIMER messages.
Then calculate the frequency of the timer. 100 fps means that the timer must fire an event each 0.01 seconds.
At the event handler for this timer-event you can do your rendering.
In case the rendering is slower than the desired frequency then use a syncro flag OpenGL sync and discard the timer-event if the previous rendering is not complete.
You may set a const fps variable to your desired frame rate, then you can update your game if the elapsed time from last update is equal or more than 1 / desired_fps.
This will probably work.
Example:
const /*or constexpr*/ int fps{60};
// then at update loop.
while(running)
{
// update the game timer.
timer->update();
// check for any events.
if(timer->ElapsedTime() >= 1 / fps)
{
// do your updates and THEN renderer.
}
}

Making a specific object pause C++

I am looking at trying to pause something in C++. Specifically a bullet you shoot in a space invaders game. Each time you press the UP key it fires a shot, I have been trying to find a way to pause it for a number of seconds before being able to fire again.
I've tried Sleep(); but it freezes the entire game rather than pauses the ability to press UP again.
Firing code
if (CInput::getInstance()->getIfKeyDownEvent(DIK_UP))
{
g_pGame->AddSprite(new CMissile(m_fX, m_fY+0.5*m_fH, 0.09, 0.9, 2));
}
Try taking the current time and then adding your delay to it. Store that in your shooting object. The next time through your program loop, if the current time is less than the time stored in the object, ignore the UP arrow.
Here are two simple ways to manage this.
When you fire a bullet, take the current system time and add the delay you want to it. If the player attempts to fire again while the current time is less than the variable you set, nothing happens.
Or, when you fire a bullet, set a timer variable to the delay you want. Each update, subtract delta time from the timer. When the timer is <=0, the user can fire.
Typically when you want to deal with real time seconds, you need something called delta time. Due to the inconsistency with frame rates, you need a way to measure real time. Typically you do this by counting the amount of time elapsed between frames. Here's an example of this implementation:
Source
int timeSinceStart = glutGet(GLUT_ELAPSED_TIME);
int oldTimeSinceStart = 0;
while( ... ) // main game loop
{
int timeSinceStart = glutGet(GLUT_ELAPSED_TIME);
int deltaTime = timeSinceStart - oldTimeSinceStart;
oldTimeSinceStart = timeSinceStart;
secondsSinceLastShot += deltaTime;
if (secondsSinceLastShot > shotTimer)
{
canShoot = true;
secondsSinceLastShot = 0;
}
if ( // press space or something )
{
canShoot = false;
// shoot
}
}
Note that this uses GLUT's implementation of a timer, but you need to implement that yourself (probably using clock()).
I've tried Sleep(); but it freezes the entire game rather than pauses the ability to press UP again.
Sleeping will freeze the thread, which is not what you want to do. However, sleep() is typically used in an implementation that contains delta time, usually sleep()ing for the amount of time elapsed between frames. For an example, see Lazy Foo's SDL tutorials
Ignore the fact that I linked to both OpenGL and SDL links, the principle is the same no matter the graphics library used.

C++ waiting a frame before carrying out an action

How would you wait a frame in c++.
I don't want the program to sleep or anything.
It would go soemthing like
Do this in this frame (1)
Continue with rest of program
Do this in the next frame (2)
where action 1 happens only in the first frame and action 2 happens only in the next frame. It would continue like this. 1, 2, 1 again, 2
I have the time between frames, I use c++ and i'm using Visual Studio 2008 to compile.
Edit:
I'm using Opengl my OS is Windows 7.
Frame - http://en.wikipedia.org/wiki/Frame_rate
like each image of the scene printed to the screen over a given time period
I'm making some assumptions here.
Suppose you have a model for which you wish to show the state. You might wish to maximise the CPU time spent evolving the model rather than rendering.
So you fix the target frame rate, at e.g. 25 fps.
Again, assume you have optimised rendering so that it can be done in much less than 0.04 seconds.
So you might want something like (pseudo-code):
Time lastRendertime = now();
while(forever)
{
Time current = now();
if ((current - lastRenderTime > 0.04))
{
renderEverything();
lastRenderTime = current;
}
else
{
evolveModelABit();
}
}
Of course, you probably have an input handler to break the loop. Note that this approach assumes that you do not want the model evolution affected by elapsed real time. If you do, and may games do, then pass in the current time to the evolveModelABit();.
For time functions on Windows, you can use:
LARGE_INTEGER frequency; // ticks per second
LARGE_INTEGER t1; // ticks
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&t1);
Note that this approach is suitable for a scientific type simulation. The model evolution will not depend on the frame rate, rendering etc, and gives the same result very time.
For a game, typically there is a push for maximising the fps. This means that the main loop is of the form:
Time lastRendertime = now();
while(forever)
{
Time current = now();
evolveModelABit(current, lastRenderTime);
renderEverything();
lastRenderTime = current;
}
If V-Sync is enabled, SwapBuffers will block the current thread until the next frame has been shown. So if you create a worker thread, and release a lock, or resume its execution right before the call of SwapBuffers your programm recieves the CPU time it would otherwise yield to the rest of the system during the wait-for-swap block. If the worker thread is manipulating GPU resources, it is a good idea using high resolution/performance counters to determine how much time is left until the swap, minus some margin and use this timing in the worker thread, so that the worker thread puts itself to sleep at about the time the swap happens, so that the GPU will not have to context switch between worker and renderer thread.

C++ Timer control

I want to create a timer so that after completing the time(suppose 10 sec) the control should come out of the function..Please note that am starting the timer inside the function.Code is given below..I want to give certain time limit to that function so that after completing the time the control should come out of the function..I don't want to calculate the time..I want to give my own time so that the function should complete its execution within that time period..suppose if function is waiting for an input then also after completing time limit the control should come out indicating that "time has expired"..once it comes out of the function then it should continue with the next function execution...Is this possible in c++...
Begin();
// here I would like to add timer.
v_CallId = v_CallId1;
call_setup_ind();
call_alert_ind();
dir_read_search_cnf();
dir_save_cnf();
END();
If the code is linear and the functions called cannot be chopped into smaller pieces, your stuck to letting an external process/thread do the timing and abort the worker thread when the timeout is exceeded.
When you can chop the worker into smaller pieces you could do something like this
Timeout.Start(5000);
while ((TimeOut.TimeOut() == false) && (completed == false))
{
completed = WorkToDo()
}
This is a pattern we frequently use in our embbeded application. The timeout class was in house develop. It just reads the tick counter and looks if the time has passed. An framework like QT or MFC should have such a class itself.