opengl OpenTK多线程?

093gszye  于 2023-11-18  发布在  其他
关注(0)|答案(2)|浏览(132)

有没有一种方法可以在另一个线程中使用OpenTK/OpenGL绘制到屏幕上?我尝试使用的代码是

GL.Clear(ClearBufferMask.ColorBufferBit);
GL.ClearColor(Color.Black);

GL.Begin(PrimitiveType.Quads);

GL.Color3(Color.FromArgb(255, 0, 0));
GL.Vertex2(-1, 1);
GL.Color3(Color.FromArgb(0, 255, 0));
GL.Vertex2(1, 1);
GL.Color3(Color.FromArgb(0, 0, 255));
GL.Vertex2(1, -1);
GL.Color3(Color.FromArgb(0, 255, 255));
GL.Vertex2(-1, -1f);

GL.End();
SwapBuffers();

字符串
上面的代码在创建GameWindow的同一个线程中工作,但从另一个线程调用时则不工作。

0yycz8jy

0yycz8jy1#

我可以用这段代码交换OpenGL接受的线程

thread = new Thread(() =>
{
    IGraphicsContext context = new GraphicsContext(GraphicsMode.Default, window.WindowInfo);
    context.MakeCurrent(window.WindowInfo);
    //Render code here
}).Start();

字符串

nhjlsmyf

nhjlsmyf2#

下面是一个如何使用IGLFWGraphicsContext MakeNoneCurrent()方法实现这一点的例子。只是要小心,很容易得到忙碌资源异常。也不要忘记在处理游戏窗口之前停止线程。同样可以使用GLControl实现。
Image

using OpenTK.Graphics.OpenGL;
using OpenTK.Mathematics;
using OpenTK.Windowing.Desktop;
using OpenTK.Windowing.GraphicsLibraryFramework;

namespace Display.Presentation.Views;

public class MainWindow : GameWindow
{
    public MainWindow(GameWindowSettings gameWindowSettings, NativeWindowSettings nativeWindowSettings) : base(gameWindowSettings, nativeWindowSettings)
    {
    }

    // Do the setup when OpenTK is fully loaded.
    protected override void OnLoad()
    {
        base.OnLoad();
        this.Context.MakeNoneCurrent(); // Must be called to release thread and make sure you dont call 'Context' on parent thread.

        var windowPrt = this.Context.WindowPtr;
        new Thread(() =>
        {
            unsafe
            {
                var context = new GLFWGraphicsContext((Window*)windowPrt);
                context.MakeCurrent();

                GL.ClearColor(Color.Aqua);
                GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                context.SwapBuffers();
                context.MakeNoneCurrent(); // Very important to release thread.
            }
        }).Start();
    }
}

public class Test2
{
    public Test2()
    {
        var gameWindowSettings = new GameWindowSettings()
        {
            UpdateFrequency = 60
        };

        var nativeWindowSettings = new NativeWindowSettings()
        {
            Size = new Vector2i(800, 600),
            Title = "Game window test title",
        };

        using var game = new MainWindow(gameWindowSettings, nativeWindowSettings);
        game.Run();
    }
}

字符串

相关问题