prosperon/source/engine/timer.c

84 lines
1.5 KiB
C
Raw Normal View History

2022-06-21 12:48:19 -05:00
#include "timer.h"
#include <GLFW/glfw3.h>
#include <stdlib.h>
2022-08-22 08:55:54 -05:00
#include "vec.h"
2022-06-21 12:48:19 -05:00
static double time;
2022-08-22 08:55:54 -05:00
struct vec timers;
2022-06-21 12:48:19 -05:00
void timer_init() {
time = glfwGetTime();
2022-08-22 08:55:54 -05:00
timers = vec_init(sizeof(struct timer), 10);
}
void check_timer(struct timer *t)
{
if (!t->on)
return;
if (time >= t->fire_time) {
t->cb(t->data);
if (t->repeat) {
t->fire_time = time + t->interval;
return;
}
t->on = 0;
return;
}
2022-06-21 12:48:19 -05:00
}
2022-08-22 08:55:54 -05:00
void timer_update(double s) {
time = s;
vec_walk(&timers, check_timer);
}
struct timer *timer_make(double interval, void (*callback)(void *param), void *param) {
struct timer *new = calloc(sizeof(*new),1);
new->remain_time = interval;
new->interval = interval;
new->cb = callback;
new->data = param;
new->repeat = 1;
2022-06-21 12:48:19 -05:00
2022-08-22 08:55:54 -05:00
timer_start(new);
struct timer *nn = vec_add(&timers, new);
free(new);
nn->timerid = timers.len-1;
return nn;
2022-06-21 12:48:19 -05:00
}
2022-06-30 10:31:23 -05:00
void timer_pause(struct timer *t) {
2022-08-22 08:55:54 -05:00
t->on = 0;
2022-06-30 10:31:23 -05:00
2022-08-22 08:55:54 -05:00
t->remain_time = t->fire_time - time;
2022-06-30 10:31:23 -05:00
}
2022-08-22 08:55:54 -05:00
void timer_stop(struct timer *t) {
t->on = 0;
t->remain_time = t->interval;
}
2022-06-30 10:31:23 -05:00
2022-08-22 08:55:54 -05:00
void timer_start(struct timer *t) {
t->on = 1;
t->fire_time = time + t->remain_time;
2022-06-30 10:31:23 -05:00
}
2022-06-21 12:48:19 -05:00
void timer_remove(struct timer *t) {
2022-08-22 08:55:54 -05:00
vec_delete(&timers, t->timerid);
}
void timer_settime(struct timer *t, double interval) {
double elapsed = time - (t->fire_time - t->interval);
t->interval = interval;
t->remain_time = time + t->interval - elapsed;
}