367e283686d5690451ecc6ff0dc9800f3683909f
[demo] / src / opengl / opengl.cc
1 #include <GL/glew.h>
2 #include <stdio.h>
3
4 #include "gfxapi.h"
5 #include "opengl/opengl.h"
6
7 extern GLFWwindow *win;
8 extern int win_h;
9 extern int win_w;
10
11 static void clear(float r, float g, float b);
12 static void viewport(int x, int y, int width, int height);
13 static void zbuffer(bool enable);
14 static void cull_face(Gfx_cull_face cf);
15
16 bool init_opengl()
17 {
18         if(!glfwInit()) {
19                 fprintf(stderr, "Failed to initialize GLFW.\n");
20                 return false;
21         }
22
23         glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
24         glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
25         glfwWindowHint(GLFW_SRGB_CAPABLE, GLFW_TRUE);
26
27         if(!(win = glfwCreateWindow(win_w, win_h, "glcow", 0, 0))) {
28                 fprintf(stderr, "Failed to create window.\n");
29                 return false;
30         }
31         glfwMakeContextCurrent(win);
32
33         glewInit();
34
35         glEnable(GL_DEPTH_TEST);
36         glEnable(GL_CULL_FACE);
37         glEnable(GL_FRAMEBUFFER_SRGB); // linear colorspace
38
39         gfx_clear = clear;
40         gfx_viewport = viewport;
41         gfx_zbuffer = zbuffer;
42         gfx_cull_face = cull_face;
43
44         return true;
45 }
46
47 void cleanup_opengl()
48 {
49         if(win) {
50                 glfwDestroyWindow(win);
51         }
52         glfwTerminate();
53 }
54
55 static void clear(float r, float g, float b)
56 {
57         glClearColor(r, g, b, 1.0);
58         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
59 }
60
61 static void viewport(int x, int y, int width, int height)
62 {
63         glViewport(x, y, width, height);
64 }
65
66 static void zbuffer(bool enable)
67 {
68         if(enable)
69                 glEnable(GL_DEPTH_TEST);
70         else
71                 glDisable(GL_DEPTH_TEST);
72 }
73
74 static void cull_face(Gfx_cull_face cf)
75 {
76         switch(cf) {
77         case GFX_CULL_NONE:
78                 glDisable(GL_CULL_FACE);
79                 break;
80         case GFX_CULL_FRONT:
81                 glEnable(GL_CULL_FACE);
82                 glCullFace(GL_FRONT);
83                 break;
84         case GFX_CULL_BACK:
85                 glEnable(GL_CULL_FACE);
86                 glCullFace(GL_BACK);
87                 break;
88         }
89 }