summaryrefslogtreecommitdiff
path: root/platform/darwin/src/headless_backend_cgl.cpp
blob: 6ad98f43263ef0f8313999d23e4970ec7346ea9b (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <mbgl/gl/headless_backend.hpp>
#include <mbgl/gl/headless_display.hpp>

#include <OpenGL/OpenGL.h>
#include <CoreFoundation/CoreFoundation.h>

#include <string>
#include <stdexcept>

namespace mbgl {

struct CGLImpl : public HeadlessBackend::Impl {
    CGLImpl(CGLContextObj glContext_) : glContext(glContext_) {
    }

    ~CGLImpl() {
        CGLDestroyContext(glContext);
    }

    void activateContext() final {
        CGLError error = CGLSetCurrentContext(glContext);
        if (error != kCGLNoError) {
            throw std::runtime_error(std::string("Switching OpenGL context failed:") +
                                     CGLErrorString(error) + "\n");
        }
    }

    void deactivateContext() final {
        CGLError error = CGLSetCurrentContext(nullptr);
        if (error != kCGLNoError) {
            throw std::runtime_error(std::string("Removing OpenGL context failed:") +
                                     CGLErrorString(error) + "\n");
        }
    }

    CGLContextObj glContext = nullptr;
};

gl::ProcAddress HeadlessBackend::initializeExtension(const char* name) {
    static CFBundleRef framework = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengl"));
    if (!framework) {
        throw std::runtime_error("Failed to load OpenGL framework.");
    }

    CFStringRef str = CFStringCreateWithCString(kCFAllocatorDefault, name, kCFStringEncodingASCII);
    void* symbol = CFBundleGetFunctionPointerForName(framework, str);
    CFRelease(str);

    return reinterpret_cast<gl::ProcAddress>(symbol);
}

bool HeadlessBackend::hasDisplay() {
    if (!display) {
        display.reset(new HeadlessDisplay);
    }
    return bool(display);
}

void HeadlessBackend::createContext() {
    assert(!hasContext());

    CGLContextObj glContext = nullptr;
    CGLError error = CGLCreateContext(display->attribute<CGLPixelFormatObj>(), nullptr, &glContext);
    if (error != kCGLNoError) {
        throw std::runtime_error(std::string("Error creating GL context object:") +
                                 CGLErrorString(error) + "\n");
    }

    error = CGLEnable(glContext, kCGLCEMPEngine);
    if (error != kCGLNoError) {
        throw std::runtime_error(std::string("Error enabling OpenGL multithreading:") +
                                 CGLErrorString(error) + "\n");
    }

    impl.reset(new CGLImpl(glContext));
}

} // namespace mbgl