Skip to content

Commit

Permalink
Try to run at a more consistent frame rate
Browse files Browse the repository at this point in the history
Before we were taking however long the simulation took, and then waiting
an additional 0.1s between each frame. Now we only wait the difference
between the simulation time and 0.1s, so we should get a consistent
10fps on machines that can keep up.
  • Loading branch information
cgmb committed Sep 1, 2017
1 parent 41b44cc commit 868c0ff
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
32 changes: 32 additions & 0 deletions main.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <errno.h>
#include <unistd.h>
#include <math.h>
#include <time.h>

#include <algorithm>
#include <random>
Expand Down Expand Up @@ -1148,6 +1149,35 @@ void handle_window_size_changed(int signal) {
u_clear_screen();
}

timespec subtract(const timespec& lhs, const timespec& rhs) {
timespec diff;
diff.tv_sec = lhs.tv_sec - rhs.tv_sec;
diff.tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
if (lhs.tv_nsec < rhs.tv_nsec) {
diff.tv_sec -= 1;
diff.tv_nsec += 1e9;
}
return diff;
}

// wait for up to one second from the given start time
// returns the current time when it exits
timespec wait(long desired_interval_nsec, timespec start) {
timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);

timespec diff = subtract(now, start);
if (diff.tv_sec == 0) {
long wait_for = (desired_interval_nsec - diff.tv_nsec) / 1000;
if (wait_for > 0) {
usleep(wait_for);
clock_gettime(CLOCK_MONOTONIC, &now);
}
}

return now;
}

int main(int argc, char** argv) {
args_t in = parse_args(argc, argv);
g_rainbow_enabled = in.rainbow;
Expand All @@ -1162,8 +1192,10 @@ int main(int argc, char** argv) {
sim_init(in);
draw(&buf);

timespec interval_start;
while (process_keypress()) {
sim_step();
interval_start = wait(1e8, interval_start);
draw(&buf);
}

Expand Down
2 changes: 1 addition & 1 deletion misc/terminal.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ void enable_raw_mode() {
raw.c_cflag |= (CS8);
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 1; // tenths of a second
raw.c_cc[VTIME] = 0; // tenths of a second
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) {
die("failed to enable raw mode");
}
Expand Down

0 comments on commit 868c0ff

Please sign in to comment.