• Create Account

## Realtime games. General question

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

12 replies to this topic

### #1Martix91  Members

137
Like
0Likes
Like

Posted 05 January 2013 - 04:47 PM

I started writing my own simple 2D engine in c++ and SDL and everything worked out great until i tried to implement Frame Independent Movement.

I wrote a simple motion function that moves the object with given speed per second((current time - previous move time)/1000 * The Speed). Then I call it it the main loop inside a while. The function itself is buggy but that's not my problem.

The problem is that when i start the program the object do moves and it also moves with close to the desired speed. But only if i feed it inputs. If i stop moving the mouse everything pauses and when I move the mouse again the object continues to move, but without the paused time(meaning it doesn't jump to make up for the lost time).

And that led me to the assumption that I understand nothing about how the program really works. When I create a while(true) and put things in it, how often do these things get called. I always thought they are called as fast as the processor manages to, but it seems I'm wrong.

Is there something more or I just have a nasty bug somewhere and I have to post the code for debugging?

### #2rip-off  Moderators

10730
Like
2Likes
Like

Posted 05 January 2013 - 05:06 PM

My guess is that your program is structured such that the object movement code is only called when there is active input, e.g something like this:

while(running) {
while(handle_input()) {
move_object();
}
draw();
}

If you want the game logic to continue whether there is input or not, your code needs to look like this:


while(running) {
handle_input();
move_object();
draw();
}

And that led me to the assumption that I understand nothing about how the program really works.

Potentially you are confused about how a program is executed. There is a "program counter" that determines which instruction the program is on (generally, each line in your code translates to one or potentially many instructions on the CPU). So while(true) will execute the instructions in its block as fast as possible, but only once the program counter has entered the loop and gets to the given instruction inside. Conditional logic (which includes loop conditions) can cause some of the code inside the loop to not be executed.

So just because you have a move_object() logic in a infinite loop, doesn't mean it is constantly being run.

### #3Martix91  Members

137
Like
0Likes
Like

Posted 05 January 2013 - 05:34 PM

Thank you. I just figured out the problem.

My logic looked like:

while(quit==false)

{

move();

while( SDL_PollEvent( &event ) )

{do a lot of stuff including draw();}//no sleeps here

}

So I'm just stupid. Forgot that the drawing is inside the second loop

There are still a lot of problems though.

I simplified it to

while(quit == false)

{

move();

draw();

}

Now it moves constantly, but way too slow and lags horribly.

Can that be because I have no sleeps in the code

The program takes up to 50% of the processor and less than 20 mb ram

### #4salmjak  Members

102
Like
0Likes
Like

Posted 05 January 2013 - 08:40 PM

Can that be because I have no sleeps in the code
Most probably yes. Most loops while cause a lot of strain on your cpu. (Some infinite loops will cause your computer to freeze completely)
What you could do is to use sleep to adjust movement speed instead of your current system. (I'm not a hundred percent positive on this solution thought)

Edited by salmjak, 05 January 2013 - 08:41 PM.

### #5Khatharr  Members

7737
Like
0Likes
Like

Posted 05 January 2013 - 09:06 PM

Check to make sure you're waiting for vsync when you render. It seems odd that you'd be getting lag from that though...

What's going on in your loop there? What do move() and draw() actually do? (Please use code tags.)
(Some infinite loops will cause your computer to freeze completely)
I doubt he's running in realtime mode. The program should lock up and the get terminated by the OS in that kind of case. Unless there's some mad voodoo happening, which is always a possibility.

What you could do is to use sleep to adjust movement speed instead of your current system. (I'm not a hundred percent positive on this solution thought)

It's better to capture a timestamp for each logical frame and pass that into the logic/simulation. Google 'variable timestep' for more info.
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

### #6Lightness1024  Members

920
Like
0Likes
Like

Posted 05 January 2013 - 10:19 PM

freeze the OS is only possible in kernel mode, whatever the code. be it a system call, a driver routine.. anything that your program may call. but a user space code cannot freeze anything. this is called preemptable execution, OSs has that since the ancient times.

### #7Martix91  Members

137
Like
0Likes
Like

Posted 06 January 2013 - 04:59 AM

Here's the relevant code:

void UpdateScreen()
{
SDL_Surface* frame = SDL_GetVideoSurface();
int i = SDL_Flip(frame);
}

This blits a surface to another surface

void Asset::apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination )
{
//Temporary rectangle to hold the offsets
SDL_Rect offset;

//Get the offsets
offset.x = x;
offset.y = y;

//Blit the surface
SDL_BlitSurface( source, NULL, destination, &offset );
}

This just calls the previous function but uses fewer parameters and is callable from outside the class.

image is a SDL_surface* loaded with an image.

void Asset::apply(int x, int y, SDL_Surface* dscreen)
{
//Apply the background to the screen
apply_surface( x, y, image, dscreen );
}

This uses the previous function to draw the object.

assetx and assety are there if I want to displace the image from the actual game object. They are 0 by default.

void Object::Render()
{
SDL_Surface* screen = SDL_GetVideoSurface();
if(render&&exist)
asset->apply(x+assetx,y+assety,screen);
}


This calculates the coordinates for a move each frame. The angles are way off right now. Probably some int rounding again. Help on this would be appreciated.

int VelocityVector::xMove()
{
double displacement = ((0.0+timy.get_ticks())/(0.0+1000))*speed*cos(double(angle));
return (int)displacement;
}
int VelocityVector::yMove()
{
double displacement = ((0.0+timy.get_ticks())/(0.0+1000))*speed*sin(double(angle));
timy.start();
return (int)displacement;
}


This uses the previous functions to move the object by changing its coordinates.

void Object::move()
{
setX(getX()+velo->xMove());
setY(getY()+velo->yMove());
}

This is the main function. I've commented the event handling loop and left only this one. There are a lot of preloadings before it but they are not looped and I doubt are causing the freezes.

while( quit == false )
{

CLS();//this fills the screen with black
bg.move();
bg.Render();
}

The image is set to move with a speed 1/10 of the whole screen per second but it lags horibly and moves 10 times slower, sometimes freezing for up to 5-10 seconds.

### #8Khatharr  Members

7737
Like
1Likes
Like

Posted 07 January 2013 - 12:48 AM

I suspect that something is going on in the same place where you suspect that something is going on. I will mention in passing that the organization here is a bit choppy. You may want to sit down with a pen and paper and try to rethink how your objects are organized (vectors should not do math, you should do math on them), but I don't think that's what's causing lag here, so let's fix the bug first.

Let's see here...
int VelocityVector::xMove() {
//wow, that's a lot of precision... Is it _really_ necessary to use a double here?
double displacement;

//what's going on here?
displacement = (0.0 + timy.get_ticks());
//and here?
displacement /= (0.0 + 1000);

//assuming 'speed' is some scalar, is its value sane at this point?
displacement *= speed;

//please don't use function-style casts. it frightens the children.
displacement *= cos(double(angle));

return (int)displacement;
}

int VelocityVector::yMove() {
//floats are faster than doubles and I don't reckon we really need super-huge precision here
float displacement = sin(angle);
displacement *= speed;
//hey, are we sure that timy hasn't advanced at all since the time when xMove() was called?
displacement *= timy.get_ticks();

//when doing serial scalar operations (multiply and divide)
//(division reduces precision; multiplication amplifies inaccuracy,
//so put the loss at the end to avoid amplifying it)
//[note - this is not the problem in this case, just general advice]
displacement /= 1000;

///////
timy.start(); //HEY, WHERE'D THIS GUY COME FROM?!?
///////

return (int)displacement;
}
We've got a couple problems. Firstly with that 'timy' fella. (He's always trouble.) From where I'm sitting it looks like any time 'timy' fails to get the necessary number of ticks you'll accomplish no movement whatsoever. Instead of telling 'timy' to 'start' (I'm assuming that means 'restart') every frame you should:
• control 'timy' from outside the move functions
• let 'timy' run continuously without restarting
• at the start of a frame save your existing 'curTime' as 'prevTime', then capture 'timy' into 'curTime'
• pass 'curTime' - 'prevTime' into the move functions to tell them how much time has passed
int curTime;
int prevTime;
int deltaTime;

prevTime = curTime;
curTime = timy.get_ticks();
deltaTime = curTime - prevTime;

float VelocityVector::xMove(int dTime) {
float displacement = cos(angle); //normalized motion
displacement *= speed; //scale for speed
displacement = (displacement * dTime) / 1000; //scale for time delta
return displacement;
}

void Object::move() {
//I get that setXY() may be changing more than one thing,
//but why do you need to call getXY() here instead of
//referring to the members directly?
setX(getX() + velo->xMove(deltaTime));
setY(getY() + velo->yMove(deltaTime));
}
That will correct the skew in your angle because you'll be passing the same time difference to all functions that need it.

But the main concern is that when you use integer coordinates but want higher-than-integer precision you must store the coordinates in the higher precision type and then cast them to lower precision only when you need to. In other words, store x and y as floats and then just cast them as ints when you pass them to a function requiring ints. This way you don't end up with a situation like this where you don't actually move most of the time since 'timy' can't work up enough ticks to move a full pixel-width (since the move functions return int you completely lose that partial movement!).
float x;
float y;

//do all math and adjustment with x and y as floats

//only cast to int at the last possible moment:
SDL_Rect offset = {(int)x, (int)y, 0, 0};
SDL_BlitSurface(source, NULL, destination, &offset);
Always store values in the highest precision they need and then downcast only when needed. This prevents losing precision due to downcasting. Don't think of casting as a conversion. Think of it as a disguise.
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

### #9rip-off  Moderators

10730
Like
0Likes
Like

Posted 07 January 2013 - 04:56 AM

The angles are way off right now. Probably some int rounding again. Help on this would be appreciated.

You're aware that std::sin() and std::cos() take their angle parameters in radians?

### #10rip-off  Moderators

10730
Like
0Likes
Like

Posted 07 January 2013 - 05:18 AM

One thing I noticed is that your revised game loop doesn't appear to be polling for events. On Windows, if you do not promptly consume events, the event queue can fill which will cause your window to freeze. If you never consume events, then eventually Windows will trigger a message box for the user "This application is not responding". Is that the kind of behaviour you are experiencing?

### #11Martix91  Members

137
Like
0Likes
Like

Posted 07 January 2013 - 04:27 PM

@Khatharr

Thank you very much for the input. It seems I'll have to rewrite the motion mechanic and do some time system I currently lack.

@rip-off

I wasn't aware

Thought it was angles. It's ok now

As for the freezing it was just like game lag.The game screen freezes, slowing down the whole system, but not crashing windows or something.

The loop polls for events. I just commented that part for testing purposes.

I did some testing and now it's much better. After I put a SDL_delay(8) in the loop.

### #12rip-off  Moderators

10730
Like
0Likes
Like

Posted 07 January 2013 - 05:11 PM

Thought it was angles.

Radians are angles too! The term you were looking for is probably degrees

### #13Martix91  Members

137
Like
0Likes
Like

Posted 10 January 2013 - 02:47 PM

Yeah, typing mistake

Thanks a lot guys, I made the coordinates into floats and the movement is much smoother now,

Final question, is it normal that the SDL fullscreen is not stretching onto the entire screen but only to its dimensions even if I set them to some known resolution like 1024 x 768 and so on. It works fine only if the resolution matches the monitor resolution but if smaller, it will be centered and surounded by black border. Is there a fix that doesn't require manual stretching of the screen?

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.