[SDL] Framerate independence?

James Barrett xucaen at gmail.com
Sat Feb 17 15:45:32 PST 2007


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

After reading this thread, I wanted to try writing my own timer class.
It's a quick example based on the articles I read. I think I have the
basic concept down. If anyone would care to give some feedback on my
example I'd appreciate it.

Jim


sdl_timer.h
- ----------------------
#ifndef  _sdl_timer_H
#define  _sdl_timer_H
#include <SDL/SDL.h>

#define DEFAULT_STEP_TIME = 50

class sdl_timer
{
public:
    sdl_timer(Uint32 stepTime);
    ~sdl_timer();

    void start();
    void stop();
    //returns delta time
    Uint32 delay();
    Uint32 timeLeft();

public://accessor methods
inline Uint32 getCurrentTime(){return current_time;};
inline Uint32 getNextTime(){return next_time;};
   
private:
    Uint32 current_time;
    Uint32 next_time;
    Uint32 step_time;
};


#endif    /* _sdl_timer_H */


- ----------------------
sdl_timer.cc
- ----------------------
#include "sdl_timer.h"


sdl_timer::sdl_timer(Uint32 stepTime)
:  current_time(0),
next_time(0),
step_time(stepTime) {
}

sdl_timer::~sdl_timer() {
}


void sdl_timer::start() {
    this->current_time = SDL_GetTicks();
}

void sdl_timer::stop() {
    this->current_time = 0;
}

Uint32 sdl_timer::delay() {
    Uint32 delay_time = this->timeLeft();
    if(delay_time) {
        SDL_Delay(delay_time);
    }
    return delay_time;
}

Uint32 sdl_timer::timeLeft() {
    //current_time = SDL_GetTicks();
    if ( next_time <= current_time ) {
        next_time = current_time+step_time;
        return(0);
    }
    return(next_time-current_time);
}


- ----------------------
testTimer.cc
- ----------------------
#include "sdl_timer.h"
#include <SDL/SDL.h>
#include <cstdlib>
#include <iostream>
void print_timer(sdl_timer& timer);
bool game_loop(sdl_timer& timer);

int main(int argc, char** argv) {
    sdl_timer timer(60);
    for(int x=0;x<10;++x){//ten loops
        while(!game_loop(timer));
    }
    return (EXIT_SUCCESS);
}

bool game_loop(sdl_timer& timer) {
    bool done = false;
    timer.start();
   
    print_timer(timer);
   
    for(int x=0;x<1000;++x)  for(int y=0;y<10000;++y);//waste time,
simulate a game
    Uint32 delta = timer.delay();
    if(delta){
        std::cout << "DELAY CALLED: " << delta << std::endl;
        done = true;
    }
    return done;
}

void print_timer(sdl_timer& timer) {
    std::cout << "************************************"     << std::endl;
    std::cout << "current time: " << timer.getCurrentTime() << std::endl;
    std::cout << "next time: " << timer.getNextTime()       << std::endl;
    std::cout << "************************************"     << std::endl;
   
}


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)

iD8DBQFF15ObQuDJiZ/QrH0RAus3AJ9XNQUtwW4/3BE4dH2Fu37ucnrPzQCgm6iG
HDqhYuyY3pSe5DFvZlKGd+E=
=rBi6
-----END PGP SIGNATURE-----



More information about the SDL mailing list