在子窗口中实现OpenGL多线程

3
我正在尝试构建一个OpenGL应用程序,即使主窗口被调整大小或移动,它也能够快速响应。我找到的最合理的解决方案是创建一个子窗口和一个消息泵,使用单独的线程来渲染OpenGL。在帧之间可以根据需要调整大小。主要的消息泵和窗口框架在主进程中运行。
它在某种程度上非常有效。窗口可以移动,使用菜单并调整大小,而不影响子窗口的帧率。但是,当调用SwapBuffers()时,一切都崩溃了。
以这种方式运行SwapBuffers()似乎是以软件模式运行的。它不再保持60 FPS以匹配我的显示器的VSync,在窗口大约为100x100时跳入数百个FPS,并在最大化到1920x1080时降至20 FPS。当在单个线程中运行时,一切似乎正常。
有一些问题我已经解决了。例如,当父母和孩子之间需要传递消息时,它会使整个应用程序停顿。覆盖WM_SETCURSOR并设置WS_EX_NOPARENTNOTIFY解决了这些问题。但是,我点击时它仍然偶尔会出现卡顿。
我希望我只是没有做正确的事情,有经验的OpenGL用户可以帮助我。我的初始化或清除可能存在问题,因为即使在关闭它后,它仍会干扰其他在我的PC上运行的OpenGL应用程序。
这是一个简化的测试案例,展示了我正在遇到的问题。它应该能够在任何现代Visual Studio中编译。
#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <wchar.h>

#pragma comment(lib, "opengl32.lib")

typedef signed int s32;
typedef unsigned int u32;
typedef unsigned long long u64;
typedef float f32;
typedef double f64;

bool run = true;

// Window procedure for the main application window
LRESULT CALLBACK AppWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    if (msg == WM_DESTROY && (GetWindowLong(hWnd, GWL_EXSTYLE) & WS_EX_APPWINDOW))
        PostQuitMessage(0);

    return DefWindowProc(hWnd, msg, wParam, lParam);
}

// Window procedure for the OpenGL rendering window
LRESULT CALLBACK RenderWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    if (msg == WM_SETCURSOR)
    {
        SetCursor(LoadCursor(NULL, IDC_CROSS));
        return TRUE;
    }
    if (msg == WM_SIZE)
        glViewport(0, 0, LOWORD(lParam)-2, HIWORD(lParam)-2);

    return AppWindowProc(hWnd, msg, wParam, lParam);
}

int WINAPI ThreadMain(HWND parent)
{
    HINSTANCE hInstance = GetModuleHandle(0);

    // Depending on if this is running as a child or a overlap window, set up the window styles
    UINT ClassStyle, Style, ExStyle;
    if (parent)
    {
        ClassStyle = 0;
        Style = WS_CHILD;
        ExStyle = WS_EX_NOPARENTNOTIFY;
    } else {
        ClassStyle = 0 | CS_VREDRAW | CS_HREDRAW;
        Style = WS_OVERLAPPEDWINDOW;
        ExStyle = WS_EX_APPWINDOW;
    }

    // Create the child window class
    WNDCLASSEX wc = {0};
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = ClassStyle;
    wc.hInstance = hInstance;
    wc.lpfnWndProc = RenderWindowProc;
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wc.hIcon = LoadIcon(0, IDI_APPLICATION);
    wc.hCursor = LoadCursor(0, IDC_ARROW);
    wc.lpszClassName = L"OGLChild";
    ATOM ClassAtom = RegisterClassEx(&wc);

    // Create the child window
    RECT r = {0, 0, 640, 480};
    if (parent)
        GetClientRect(parent, &r);
    HWND WindowHandle = CreateWindowExW(ExStyle, (LPCTSTR)MAKELONG(ClassAtom, 0), 0, Style, 
                                        0, 0, r.right, r.bottom, parent, 0, hInstance, 0);

    // Initialize OpenGL render context
    PIXELFORMATDESCRIPTOR pfd = {0};
    pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.cDepthBits = 16;
    pfd.iLayerType = PFD_MAIN_PLANE;
    HDC DeviceContext = GetDC(WindowHandle);
    int format = ChoosePixelFormat(DeviceContext, &pfd);
    SetPixelFormat(DeviceContext, format, &pfd);
    HGLRC RenderContext = wglCreateContext(DeviceContext);
    wglMakeCurrent(DeviceContext, RenderContext);

    ShowWindow(WindowHandle, SW_SHOW);

    GetClientRect(WindowHandle, &r);
    glViewport(0, 0, r.right, r.bottom);

    // Set up an accurate clock
    u64 start, now, last, frequency;
    QueryPerformanceFrequency((LARGE_INTEGER*)&frequency);
    QueryPerformanceCounter((LARGE_INTEGER*)&now);
    start = last = now;

    u32 frames = 0; // total frames this second
    f64 nextFrameCount = 0; // next FPS update
    f32 left = 0; // line position

    MSG msg;
    while (run)
    {
        while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            if (msg.message == WM_QUIT || msg.message == WM_DESTROY)
                run = false;
        }

        // Update the clock
        QueryPerformanceCounter((LARGE_INTEGER*)&now);
        f64 clock = (f64)(now - start) / frequency;
        f64 delta = (f64)(now - last) / frequency;
        last = now;

        // Render a line moving
        glOrtho(0, 640, 480, 0, -1, 1);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();   
        glColor3f(1.0f, 1.0f, 0.0f);
        left += (f32)(delta * 320.0f);
        if (left > 640.0f)
            left = 0;
        glBegin(GL_LINES);
            glVertex2f(0.0f, 0.0f);
            glVertex2f(left, 480.0f);
        glEnd();
        SwapBuffers(DeviceContext);

        // Resize as necessary
        if (parent)
        {
            RECT pr, cr;
            GetClientRect(parent, &pr);
            GetClientRect(WindowHandle, &cr);
            if (pr.right != cr.right || pr.bottom != cr.bottom)
                MoveWindow(WindowHandle, 0, 0, pr.right, pr.bottom, FALSE);
        }

        // Update FPS counter
        frames++;
        if (clock > nextFrameCount)
        {
            WCHAR title[16] = {0};
            _snwprintf_s(title, 16, 16, L"FPS: %u", frames);
            SetWindowText(parent ? parent : WindowHandle, title);
            nextFrameCount = clock + 1;
            frames = 0;
        }

        Sleep(1);

    }

    // Cleanup OpenGL context
    wglDeleteContext(RenderContext);
    wglMakeCurrent(0,0);
    ReleaseDC(WindowHandle, DeviceContext);

    DestroyWindow(WindowHandle);

    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    int result = MessageBox(0, L"Would you like to run in threaded child mode?", 
                            L"Threaded OpenGL Demo", MB_YESNOCANCEL | MB_ICONQUESTION);
    if (result == IDNO)
        return ThreadMain(0);
    else if (result != IDYES)
        return 0;

    // Create the parent window class
    WNDCLASSEX wc = {0};
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = 0;
    wc.hInstance = hInstance;
    wc.lpfnWndProc = (WNDPROC)AppWindowProc;
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wc.hIcon = LoadIcon(0, IDI_APPLICATION);
    wc.hCursor = LoadCursor(0, IDC_ARROW);
    wc.lpszClassName = L"OGLFrame";
    ATOM ClassAtom = RegisterClassEx(&wc);

    // Create the parent window
    HWND WindowHandle = CreateWindowExW(WS_EX_APPWINDOW, (LPCTSTR)MAKELONG(ClassAtom, 0), 
                                        0, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, 
                                        0, 0, 640, 480, 0, 0, hInstance, 0);

    ShowWindow(WindowHandle, SW_SHOW);

    // Start the child thread
    HANDLE thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadMain, (LPVOID)WindowHandle, 0, 0);

    MSG msg;
    while (run)
    {
        while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            if (msg.message == WM_QUIT)
                run = false;
        }

        Sleep(100);
    }

    DestroyWindow(WindowHandle);

    // Wait for the child thread to finish
    WaitForSingleObject(thread, INFINITE);

    ExitProcess(0);
    return 0;
}

我一直在NVIDIA GeForce 8800 GTX上运行它,但我希望任何解决方案都能在现代卡上同样适用。
我尝试过其他方法,比如在主进程中将线程渲染到窗口中,但在调整大小期间我遇到了伪影甚至出现了几个蓝屏。我的应用程序将是跨平台的,因此DirectX不是一个选择。

1
我刚在ATI 3870HD上测试了你的代码。它始终以大约1000 FPS平稳运行,无论窗口大小如何(我的屏幕最大为1280x1024)。唯一的性能影响是调整窗口大小,但我可以看到这完全没问题。很抱歉我没有真正帮到你。 - Raven
1个回答

2
问题是在Visual Studio中长时间调试OpenGL应用程序会导致OpenGL无法创建上下文。由于我没有捕获任何错误,所以我从未意识到它在没有硬件加速的情况下运行。需要完全重新启动才能恢复,现在已经正常工作。
此外,将泵WinMain替换为以下内容可以修复任何调整大小问题:
MSG msg;
while (GetMessage(&msg, 0, 0, 0) != 0)
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}
run = false;

你没有销毁OpenGL上下文或在应用程序执行之前终止它吗?我以前见过这种行为(在HD2400上),其中系统或驱动程序似乎未能正确清理上下文。 - ssube
@peachykeen: 在清理之前我一直在终止该进程。它需要反复的滥用才会开始出现问题。如果发现newdisp过程,可以重新启动视频驱动程序。 - Josh Brown

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接