如何正确地使用 GLFW 进行上下文共享?

How to properly do Context Sharing with GLFW?

我想做的是,如果我用新的 window 替换 window,这可能会发生,因为用户切换屏幕或切换从全屏到 windowed,或出于任何其他原因。

到目前为止我的代码如下所示:

"Context.h"

struct window_deleter {
    void operator()(GLFWwindow * window) const;
};

class context {
    std::unique_ptr<GLFWwindow, window_deleter> window;
public:
    context(int width, int height, const char * s, GLFWmonitor * monitor, GLFWwindow * old_window, bool borderless);
    GLFWwindow * get_window() const;
    void make_current() const;
};

"Context.cpp"

context::context(int width, int height, const char * s, GLFWmonitor * monitor, GLFWwindow * old_window, bool borderless) {
    if (!glfwInit()) throw std::runtime_error("Unable to Initialize GLFW");
    if (borderless) glfwWindowHint(GLFW_DECORATED, 0);
    else glfwWindowHint(GLFW_DECORATED, 1);
    window.reset(glfwCreateWindow(width, height, s, monitor, old_window));
    if (!window) throw std::runtime_error("Unable to Create Window");
    make_current();
}

GLFWwindow * context::get_window() const {
    return window.get();
}

void context::make_current() const {
    glfwMakeContextCurrent(window.get());
}

"WindowManager.h"

#include "Context.h"
class window_style;
/* window_style is basically a really fancy "enum class", and I don't 
 * believe its implementation or interface are relevant to this project.
 * I'll add it if knowing how it works is super critical.
 */

class window_manager {
    context c_context;
    uint32_t c_width, c_height;
    std::string c_title;
    window_style c_style;
    std::function<bool()> close_test;
    std::function<void()> poll_task;
public:
    static GLFWmonitor * get_monitor(window_style style);
    window_manager(uint32_t width, uint32_t height, std::string const& title, window_style style);
    context & get_context();
    const context & get_context() const;
    bool resize(uint32_t width, uint32_t height, std::string const& title, window_style style);
    std::function<bool()> get_default_close_test();
    void set_close_test(std::function<bool()> const& test);
    std::function<void()> get_default_poll_task();
    void set_poll_task(std::function<void()> const& task);

    void poll_loop();
};

"WindowManager.cpp"

GLFWmonitor * window_manager::get_monitor(window_style style) {
    if (style.type != window_style::style_type::fullscreen) return nullptr;
    if (!glfwInit()) throw std::runtime_error("Unable to initialize GLFW");
    int count;
    GLFWmonitor ** monitors = glfwGetMonitors(&count);
    if (style.monitor_number >= uint32_t(count)) throw invalid_monitor_exception{};
    return monitors[style.monitor_number];
}

std::function<bool()> window_manager::get_default_close_test() {
    return [&] {return glfwWindowShouldClose(c_context.get_window()) != 0; };
}

window_manager::window_manager(uint32_t width, uint32_t height, std::string const& title, window_style style) :
c_context(int(width), int(height), title.c_str(), get_monitor(style), nullptr, style.type == window_style::style_type::borderless),
    c_width(width), c_height(height), c_title(title), c_style(style), close_test(get_default_close_test()), poll_task(get_default_poll_task()) {
}
context & window_manager::get_context() {
    return c_context;
}
const context & window_manager::get_context() const {
    return c_context;
}

bool window_manager::resize(uint32_t width, uint32_t height, std::string const& title, window_style style) {
    if (width == c_width && height == c_height && title == c_title && style == c_style) return false;
    c_width = width;
    c_height = height;
    c_title = title;
    c_style = style;
    c_context = context(int(width), int(height), title.c_str(), get_monitor(style), get_context().get_window(), style.type == window_style::style_type::borderless);
    return true;
}

void window_manager::set_close_test(std::function<bool()> const& test) {
    close_test = test;
}

std::function<void()> window_manager::get_default_poll_task() {
    return [&] {glfwSwapBuffers(c_context.get_window()); };
}

void window_manager::set_poll_task(std::function<void()> const& task) {
    poll_task = task;
}

void window_manager::poll_loop() {
    while (!close_test()) {
        glfwPollEvents();
        poll_task();
    }
}

"Main.cpp"

int main() {
    try {
        glfwInit();
        const GLFWvidmode * vid_mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
        gl_backend::window_manager window(vid_mode->width, vid_mode->height, "First test of the window manager", gl_backend::window_style::fullscreen(0));
        glfwSetKeyCallback(window.get_context().get_window(), [](GLFWwindow * window, int, int, int, int) {glfwSetWindowShouldClose(window, 1); });
        glbinding::Binding::initialize();
        //Anything with a "glresource" prefix is basically just a std::shared_ptr<GLuint> 
        //with some extra deletion code added.
        glresource::vertex_array vao;
        glresource::buffer square;
        float data[] = {
            -.5f, -.5f,
            .5f, -.5f,
            .5f, .5f,
            -.5f, .5f
        };
        gl::glBindVertexArray(*vao);
        gl::glBindBuffer(gl::GL_ARRAY_BUFFER, *square);
        gl::glBufferData(gl::GL_ARRAY_BUFFER, sizeof(data), data, gl::GL_STATIC_DRAW);
        gl::glEnableVertexAttribArray(0);
        gl::glVertexAttribPointer(0, 2, gl::GL_FLOAT, false, 2 * sizeof(float), nullptr);

        std::string vert_src =
            "#version 430\n"
            "layout(location = 0) in vec2 vertices;"
            "void main() {"
            "gl_Position = vec4(vertices, 0, 1);"
            "}";

        std::string frag_src =
            "#version 430\n"
            "uniform vec4 square_color;"
            "out vec4 fragment_color;"
            "void main() {"
            "fragment_color = square_color;"
            "}";
        glresource::shader vert(gl::GL_VERTEX_SHADER, vert_src);
        glresource::shader frag(gl::GL_FRAGMENT_SHADER, frag_src);
        glresource::program program({ vert, frag });
        window.set_poll_task([&] {
            gl::glUseProgram(*program);
            gl::glBindVertexArray(*vao);
            glm::vec4 color{ (glm::sin(float(glfwGetTime())) + 1) / 2, 0.f, 0.5f, 1.f };
            gl::glUniform4fv(gl::glGetUniformLocation(*program, "square_color"), 1, glm::value_ptr(color));
            gl::glDrawArrays(gl::GL_QUADS, 0, 4);
            glfwSwapBuffers(window.get_context().get_window());
        });
        window.poll_loop();
        window.resize(vid_mode->width, vid_mode->height, "Second test of the window manager", gl_backend::window_style::fullscreen(1));
        glfwSetKeyCallback(window.get_context().get_window(), [](GLFWwindow * window, int, int, int, int) {glfwSetWindowShouldClose(window, 1); });
        window.poll_loop();
    }
    catch (std::exception const& e) {
        std::cerr << e.what() << std::endl;
        std::ofstream error_log("error.log");
        error_log << e.what() << std::endl;
        system("pause");
    }
    return 0;
}

因此当前版本的代码应该执行以下操作

  1. 在主显示器上显示全屏 window
  2. 在此显示器上,显示一个 "square"(矩形,真的....)随着时间的推移在品红色和蓝色之间过渡,同时背景在品红色和绿色之间过渡。
  3. 当用户按下一个键时,使用第一个 window 的上下文在第二个监视器上创建一个新的全屏 window 以提供给 GLFW 的 window 创建,并销毁原始 window(按此顺序)
  4. 在这一秒显示相同的矩形window
  5. 继续定期转换背景
  6. 当用户再次按下一个键时,销毁第二个window并退出程序。

在这些步骤中,第 4 步根本不起作用,第 3 步部分起作用:window 确实创建了,但默认情况下不显示,用户必须调用它通过任务栏。所有其他步骤都按预期工作,包括 windows.

上的过渡背景

所以我的假设是上下文之间的对象共享出了问题;具体来说,我正在创建的第二个上下文似乎没有接收到第一个上下文创建的对象。我犯了明显的逻辑错误吗?我是否应该做其他事情来确保上下文共享按预期工作?有没有可能只是 GLFW 中的一个错误?

So my assumption is that something is going wrong with respect to the object sharing between contexts; specifically, it doesn't appear that the second context I'm creating is receiving the objects created by the first context. Is there an obvious logic error I'm making?

是的,你的前提是错误的。共享的 OpenGL 上下文不会共享整个状态,只是 "big" 个实际保存用户特定数据(如 VBO、纹理、着色器和程序、渲染缓冲区等)的对象,而不是仅引用它们的对象 -诸如 VAO、FBO 等状态容器从不共享。

Should I be doing something else to ensure that context sharing works as intended?

好吧,如果你真的想走那条路,你必须重新构建所有那些状态容器,还要恢复全局状态(所有那些 glEnables,深度缓冲区设置,混合状态, 大量其他东西)你的原始上下文。

但是,我发现你的整个概念在这里都值得怀疑。从全屏到 windowed 或同一 GPU 上的不同显示器时,您不需要销毁 window,并且 GLFW 通过 glfwSetWindowMonitor().[=14= 直接支持它]

即使您 重新创建一个window,这并不意味着您必须重新创建 GL 上下文。 GLFW API 在这方面可能会施加一些限制,但基本概念是不同的。您基本上可以使旧上下文在新 window 中成为当前上下文,然后就完成了。 GLFW 只是将 Window 和 Context 不可分割地联系在一起,这是一种不幸的抽象。

然而,我能想象的唯一需要重新创建 window 的场景是不同的屏幕由不同的 GPU 驱动——但 GL 上下文共享在不同的 GL 实现中不起作用,所以即使在那种情况下,您也必须重建整个上下文状态。