草庐IT

c++ - 子窗口中的多线程 OpenGL

coder 2024-06-05 原文

我正在尝试构建一个即使在调整主窗口大小或移动时也能响应的 OpenGL 应用程序。我发现的最合乎逻辑的解决方案是在呈现 OpenGL 的单独线程中创建一个子窗口和一个消息泵。它可以根据需要在帧之间调整自身大小。主要消息泵和窗口框架在主进程中运行。

它在某种程度上非常有效。可以移动窗口、使用菜单和调整大小,而不会影响子窗口的帧速率。 SwapBuffers() 是一切分崩离析的地方。

SwapBuffers() 以这种方式运行时,似乎是在软件模式下运行。它不再保持在 60 FPS 以匹配我的显示器的 VSync,当窗口约为 100x100 时它会跳到数百,而当最大化到 1920x1080 时它会下降到 20 FPS。在单线程中运行时,一切似乎都很正常。

我解决了一些问题。就像当消息需要在 parent 和 child 之间传递时,它会拖延整个应用程序。覆盖 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 不是一个选项。

最佳答案

事实证明,在 Visual Studio 中长时间调试 OpenGL 应用程序会导致 OpenGL 开始无法创建上下文。因为我没有捕获任何错误,所以我从来没有意识到它在没有硬件加速的情况下运行。它需要完全重启才能恢复,现在工作正常。

此外,用这个替换泵 WinMain 可以解决任何调整大小的问题:

MSG msg;
while (GetMessage(&msg, 0, 0, 0) != 0)
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}
run = false;

关于c++ - 子窗口中的多线程 OpenGL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5521131/

有关c++ - 子窗口中的多线程 OpenGL的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  3. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  4. ruby - 如何让Ruby捕获线程中的语法错误 - 2

    我正在尝试使用ruby​​编写一个双线程客户端,一个线程从套接字读取数据并将其打印出来,另一个线程读取本地数据并将其发送到远程服务器。我发现的问题是Ruby似乎无法捕获线程内的错误,这是一个示例:#!/usr/bin/rubyThread.new{loop{$stdout.puts"hi"abc.putsefsleep1}}loop{sleep1}显然,如果我在线程外键入abc.putsef,代码将永远不会运行,因为Ruby将报告“undefinedvariableabc”。但是,如果它在一个线程内,则没有错误报告。我的问题是,如何让Ruby捕获这样的错误?或者至少,报告线程中的错误?

  5. ruby - 如何在 ruby​​ 中运行后台线程? - 2

    我是ruby​​的新手,我认为重新构建一个我用C#编写的简单聊天程序是个好主意。我正在使用Ruby2.0.0MRI(Matz的Ruby实现)。问题是我想在服务器运行时为简单的服务器命令提供I/O。这是从示例中获取的服务器。我添加了使用gets()获取输入的命令方法。我希望此方法在后台作为线程运行,但该线程正在阻塞另一个线程。require'socket'#Getsocketsfromstdlibserver=TCPServer.open(2000)#Sockettolistenonport2000defcommandsx=1whilex==1exitProgram=gets.chomp

  6. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  7. ruby - Rails 开发服务器、PDFKit 和多线程 - 2

    我有一个使用PDFKit呈现网页的pdf版本的Rails应用程序。我使用Thin作为开发服务器。问题是当我处于开发模式时。当我使用“bundleexecrailss”启动我的服务器并尝试呈现任何PDF时,整个过程会陷入僵局,因为当您呈现PDF时,会向服务器请求一些额外的资源,如图像和css,看起来只有一个线程.如何配置Rails开发服务器以运行多个工作线程?非常感谢。 最佳答案 我找到的最简单的解决方案是unicorn.geminstallunicorn创建一个unicorn.conf:worker_processes3然后使用它:

  8. arrays - Ruby 数组 += vs 推送 - 2

    我有一个数组数组,想将元素附加到子数组。+=做我想做的,但我想了解为什么push不做。我期望的行为(并与+=一起工作):b=Array.new(3,[])b[0]+=["apple"]b[1]+=["orange"]b[2]+=["frog"]b=>[["苹果"],["橙子"],["Frog"]]通过推送,我将推送的元素附加到每个子数组(为什么?):a=Array.new(3,[])a[0].push("apple")a[1].push("orange")a[2].push("frog")a=>[[“苹果”、“橙子”、“Frog”]、[“苹果”、“橙子”、“Frog”]、[“苹果”、“

  9. += 的 Ruby 方法 - 2

    有没有办法让Ruby能够做这样的事情?classPlane@moved=0@x=0defx+=(v)#thisiserror@x+=v@moved+=1enddefto_s"moved#{@moved}times,currentxis#{@x}"endendplane=Plane.newplane.x+=5plane.x+=10putsplane.to_s#moved2times,currentxis15 最佳答案 您不能在Ruby中覆盖复合赋值运算符。任务在内部处理。您应该覆盖+,而不是+=。plane.a+=b与plane.a=

  10. ruby - Ruby 1.9.1 中的 native 线程,对我有什么好处? - 2

    所以,Ruby1.9.1现在是declaredstable.Rails应该与它一起工作,并且正在慢慢地将gem移植到它。它具有native线程和全局解释器锁(GIL)。自从GIL到位后,原生线程是否比1.9.1中的绿色线程有任何优势? 最佳答案 1.9中的线程是原生的,但它们被“放慢了速度”,一次只允许一个线程运行。这是因为如果线程真的并行运行,它会混淆现有代码。优点:IO现在在线程中是异步的。如果一个线程阻塞在IO上,那么另一个线程将继续执行直到IO完成。C扩展可以使用真正的线程。缺点:任何非线程安全的C扩展都可能存在使用Thre

随机推荐