1// LAF OS Library
2// Copyright (C) 2022 Igara Studio S.A.
3//
4// This file is released under the terms of the MIT license.
5// Read LICENSE.txt for more information.
6
7#ifndef OS_GL_CONTEXT_GLX_INCLUDED
8#define OS_GL_CONTEXT_GLX_INCLUDED
9#pragma once
10
11#include "os/gl/gl_context.h"
12
13#include <GL/glx.h>
14#include <X11/Xlib.h>
15#undef None
16
17namespace os {
18
19class GLContextGLX : public GLContext {
20public:
21 GLContextGLX(::Display* display, ::Window window)
22 : m_display(display)
23 , m_window(window) {
24 }
25
26 ~GLContextGLX() {
27 destroyGLContext();
28 }
29
30 bool isValid() override {
31 return m_glCtx != nullptr;
32 }
33
34 bool createGLContext() override {
35 GLint attr[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, 0 };
36 XVisualInfo* vi = glXChooseVisual(m_display, 0, attr);
37 if (!vi)
38 return false;
39
40 m_glCtx = glXCreateContext(m_display, vi, nullptr, GL_TRUE);
41 if (!m_glCtx)
42 return false;
43
44 glClearStencil(0);
45 glClearColor(0, 0, 0, 0);
46 glStencilMask(0xffffffff);
47 glClear(GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
48
49 ::Window root;
50 int x, y, w, h;
51 unsigned int border_width, depth;
52 XGetGeometry(m_display, m_window, &root,
53 &x, &y, (unsigned int*)&w, (unsigned int*)&h,
54 &border_width, &depth);
55 glViewport(0, 0, w, h);
56
57 return true;
58 }
59
60 void destroyGLContext() override {
61 if (m_glCtx) {
62 glXDestroyContext(m_display, m_glCtx);
63 m_glCtx = nullptr;
64 }
65 }
66
67 void makeCurrent() override {
68 glXMakeCurrent(m_display, m_window, m_glCtx);
69 }
70
71 void swapBuffers() override {
72 glXSwapBuffers(m_display, m_window);
73 }
74
75private:
76 ::Display* m_display = nullptr;
77 ::Window m_window = 0;
78 GLXContext m_glCtx = nullptr;
79};
80
81} // namespace os
82
83#endif
84