tksuoran's picture

Processing Inputs in one thread and doing rendering in another

Is it possible to separate input event processing and rendering into separate threads? How would I do that?


Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
the Fiddler's picture

Yes, this is possible.

In v1.0, input is always handled in the main thread. You can only move your OpenGL calls to a different thread, by calling window.Context.MakeCurrent(null) on the main thread and window.MakeCurrent() on the new thread (where window can be either a GameWindow or a GLControl). Check out the "GameWindow Threaded" sample in the example browser.

In v1.1, you can poll input from any thread using the thread-safe APIs in OpenTK.Input.

tksuoran's picture

Is there example of input polling somewhere?

the Fiddler's picture

Check out the relevant documentation. The "GameWindow States" sample also uses polled input.

The concept is very simple:

  1. poll the device you wish, from any thread
  2. compare the results with the previous ones to see if anything has changed
  3. store the results and wait for next frame

Mouse input, for instance:

using OpenTK.Input;
 
MouseState current, previous;
 
void UpdateMouse()
{
    current = Mouse.GetState();
    if (current != previous)
    {
        // Mouse state has changed
        int xdelta = current.X - previous.X;
        int ydelta = current.Y - previous.Y;
        int zdelta = current.Wheel - previous.Wheel;
    }
    previous = current;
}

Polled input can also handle multiple mice, keyboards, etc: just use GetState(int) to poll a specific device and check the "IsConnected" property before using it.