#include "fps.h"
#include <unistd.h>
#include <GL/glut.h>

void fps_init (fps_t* fps) {
  fps->fpslimit = 100 ;
  fps->timelimit = 1000/fps->fpslimit ;
  fps->lastframetime = 0 ;
  fps->possibleframetime = 1<<30 ;
  fps->realframetime = 1<<30 ;
  fps->sleepstep = 1000 ;
}

double fps_getlimit (fps_t* fps) {
  return fps->fpslimit ;
}

void fps_setlimit (fps_t* fps, double limit) {
  fps->fpslimit = limit ;
  fps->timelimit = 1000/limit ;
}

int fps_getsleepstep (fps_t* fps) {
  return fps->sleepstep ;
}

void fps_setsleepstep (fps_t* fps, int sleepstep) {
  fps->sleepstep = sleepstep ;
}

void fps_oneframe (fps_t* fps) {
#define ELAPSED glutGet(GLUT_ELAPSED_TIME)
  /* compute theoretical max framerate */
  fps->possibleframetime = ELAPSED - fps->lastframetime ;

  if (fps->lastframetime)
    /* wait as long as necessary to limit framerate */
    while ( (ELAPSED-fps->lastframetime) < fps->timelimit ) 
      usleep (fps->sleepstep) ;

  /* compute real framerate */
  fps->realframetime = ELAPSED - fps->lastframetime ;

  fps->lastframetime = ELAPSED ;
}
