Datasets:
File size: 2,148 Bytes
987b273 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | #define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <pthread.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "xireun.h"
/* SDL2's presentation functions have a single main-thread contract. */
typedef void (*present_fn)(void *);
static present_fn render_next, gl_next;
static pthread_once_t loaders = PTHREAD_ONCE_INIT;
static _Thread_local struct {
void *chain;
int kind, depth;
int64_t waited;
xr_gate gate;
} thread_state;
static void load_backends(void) {
*(void **)(&render_next) = dlsym(RTLD_NEXT, "SDL_RenderPresent");
*(void **)(&gl_next) = dlsym(RTLD_NEXT, "SDL_GL_SwapWindow");
}
static int64_t now_us(void) {
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts)) return 0;
return (int64_t)ts.tv_sec*1000000 + ts.tv_nsec/1000;
}
static void do_present(present_fn fn, void *object, int kind) {
if (!fn) {
static const char line[] = "Xireun requires the SDL2 shared library in this process.\n";
(void)write(2,line,sizeof(line)-1); abort();
}
if (thread_state.depth) { fn(object); return; }
thread_state.depth++;
if (object != thread_state.chain || kind != thread_state.kind) {
xr_reset(&thread_state.gate);
thread_state.chain = object; thread_state.kind = kind; thread_state.waited = 0;
}
int64_t begin = now_us();
fn(object);
int64_t end = now_us();
int64_t delay = xr_after(&thread_state.gate, begin, end, thread_state.waited);
thread_state.waited = 0;
if (delay > 0) {
int64_t start = now_us(), due = start+delay;
struct timespec t = { (time_t)(due/1000000), (long)(due%1000000)*1000 };
int rc;
do { rc=clock_nanosleep(CLOCK_MONOTONIC,TIMER_ABSTIME,&t,NULL); } while (rc==EINTR);
thread_state.waited=now_us()-start;
if (rc) xr_cool(&thread_state.gate);
}
thread_state.depth--;
}
void SDL_RenderPresent(void *renderer) {
pthread_once(&loaders,load_backends);
do_present(render_next,renderer,1);
}
void SDL_GL_SwapWindow(void *window) {
pthread_once(&loaders,load_backends);
do_present(gl_next,window,2);
}
|