aboutsummaryrefslogtreecommitdiff
path: root/src/gl.c
blob: c83ab49aeb85aa3786a4886a8c338d2e2449a622 (plain)
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
#include "../include/mgl/gl.h"
#include <dlfcn.h>
/*#include <GL/gl.h>*/
#include <stdio.h>

typedef struct {
    void **func;
    const char *name;
} dlsym_assign;

static void* dlsym_print_fail(void *handle, const char *name) {
    dlerror();
    void *sym = dlsym(handle, name);
    char *err_str = dlerror();

    if(!sym)
        fprintf(stderr, "dlsym(handle, \"%s\") failed, error: %s\n", name, err_str ? err_str : "(null)");

    return sym;
}

int mgl_gl_load(mgl_gl *self) {
    const char *gl_path = "/usr/lib/libOpenGL.so.0";
    self->handle = dlopen(gl_path, RTLD_LAZY);
    if(!self->handle) {
        fprintf(stderr, "dlopen(\"%s\", RTLD_LAZY) failed\n", gl_path);
        return -1;
    }

    const dlsym_assign assign[] = {
        { &self->glViewport, "glViewport" },
        { &self->glClearColor, "glClearColor" },
        { &self->glClear, "glClear" },
        { NULL, NULL }
    };

    for(int i = 0; assign[i].func; ++i) {
        *assign[i].func = dlsym_print_fail(self->handle, assign[i].name);
        if(!assign[i].func) {
            mgl_gl_unload(self);
            return -1;
        }
    }

    return 0;
}

void mgl_gl_unload(mgl_gl *self) {
    if(self->handle) {
        dlclose(self->handle);
        self->handle = NULL;
    }
}