开发者

Continuously updating an OpenTK GLControl in WindowsFormsHost in WPF - How?

开发者 https://www.devze.com 2023-03-18 17:45 出处:网络
I have开发者_JAVA技巧 an OpenTK GLControl embedden in a WindowsFormsHost in my WPF application. I want to continuously update and render it.

I have开发者_JAVA技巧 an OpenTK GLControl embedden in a WindowsFormsHost in my WPF application. I want to continuously update and render it. In Winforms a solution would be to attach the UpdateAndRender method to the Application.Idle event, but there is no such thing in WPF.

So what would be the best way to do (60FPS) updating of my scene and GLControl ?


You can use a System.Timers.Timer to control how often your render code is called. In your window containing the GLControl-in-WindowsFormsHost, declare a private System.Timers.Timer _timer;, then when you're ready to start the rendering loop, set the timer interval and it's event handler, then start it up, as in the following example:

    private void btnLoadModel_Click(object sender, RoutedEventArgs e)
    {
        LoadModel(); // do whatever you need to do to prepare your scene for rendering
        _timer = new System.Timers.Timer(10.0); // in milliseconds - you might have to play with this value to throttle your framerate depending on how involved your update and render code is
        _timer.Elapsed += TimerElapsed;
        _timer.Start();
    }

    private void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        UpdateModel(); // this is where you'd do whatever you need to do to update your model per frame
        // Invalidate will cause the Paint event on your GLControl to fire
        _glControl.Invalidate(); // _glControl is obviously a private reference to the GLControl
    }

You'll clearly need to add using System.Timers to your usings.


You can use Invalidate() for it. This causes the GLControl to redraw it's content.

If you call it at the end of Paint() you may blocking some UI rendering of the other WPF controls.

WPF provides a per frame render event: CompositionTarget.Rendering. This event is called before WPF wants to render the content. Subscribe from it and call Invalidate:

public YourConstructor()
{
  //...
  CompositionTarget.Rendering += CompositionTarget_Rendering;
}

void CompositionTarget_Rendering(object sender, EventArgs e)
{
  _yourControl.Invalidate();
}

You need to unsubscribe if you don't use it anymore (to avoid memory leaks).

Here is a How to: Render on a Per Frame Interval Using CompositionTarget from MSDN.

I use GLControl with that method and it works fine. I did not checked how much FPS I have but it feels smooth.

You may also have a look on this: Why is Frame Rate in WPF Irregular and Not Limited To Monitor Refresh?

0

精彩评论

暂无评论...
验证码 换一张
取 消