• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Martin Barbov

Realtime games. General question

12 posts in this topic

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?

0

Share this post


Link to post
Share on other sites

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:

[code]while(running) {     while(handle_input()) {         move_object();     }     draw(); }[/code]

 

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

[code]  while(running) {     handle_input();     move_object();     draw(); }[/code]

 

[quote]

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

[/quote]

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.

2

Share this post


Link to post
Share on other sites

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

0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

Here's the relevant code:

 

 

 

This updates the screen. 

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();
UpdateScreen();
}

 

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.

0

Share this post


Link to post
Share on other sites
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();

  //If you're concerned about precision:
  //when doing serial scalar operations (multiply and divide)
  //try to do division last to preserve precision for free:
  //(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. ph34r.png
1

Share this post


Link to post
Share on other sites

[quote]

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

[/quote]

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

0

Share this post


Link to post
Share on other sites

As for freezing, can you tell us more about this "freezing"behaviour?

 

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?

0

Share this post


Link to post
Share on other sites

@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 rolleyes.gif  

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. 

0

Share this post


Link to post
Share on other sites

Yeah, typing mistake :p

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?

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0