objarni's picture

Platform and frame-rate independent animation


I've come to a point in my Windows.Forms/GLControl game where I want to consider how to measure/control time.

I can't find any examples of how to measure time in the WinForms examples so I ask the
question here:

What is the most popular way of measuring time between Application.Idle events in a Windows.Forms project?

Of course, it has to be platform independent! Otherwise I could just p/invoke windows' builtin QueryPerformanceCounter which I've found good enough so far on the windows platform.

I can see two simple, non-working, solutions:
1. DateTime.Now
2. Timer control

1) My experience of DateTime.Now is that it has big granularity (on the scale of 10 ms, even going BACKWARDS every now and then!) which is not so good for a realtime game.

2) The other method I can think of is using a Timer control, and just assume that whenever the timer.Tick event occur the specified time has passed, something that is not very reliable either in my experience, especially if the ticks-per-second approach 60-100 (typical frame rate of desktops nowadays).

Here is my Application.Idle event handler so far:

void Application_Idle(object sender, EventArgs e)
  double deltaTimeMS = 10; // TODO: better time measurement


Comment viewing options

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

System.Diagnostics.Stopwatch is the way to go. I think Invalidate() allocates memory (for message parameters), so it might be better to call the OnPaint method instead, using EventArgs.Empty as a parameter.

I'll post a more detailed explanation later (out of time right now).

objarni's picture

Thanks! (does it work for mono <1.2.6?)

the Fiddler.'s picture

Yes, it works. I've tested with 1.2.4+, but it should work on earlier versions, too.

Take a look at the implementation in GameWindow.Run (around line 400) to see how it can be used. That implementation is slightly complicated (tries to maintain different update and render framerates), the idea is to set an update period and busy-loop using the stopwatch to monitor when it's time to update.

objarni's picture

This works lika a charm! (hope it will work for mac too.. wonder how they implemented it for linux, rdtsc?)

On a side note, I have not downloaded the source distribution of OpenTK since I don't know how to build it; I simply develop using OpenTK.0.3.13.dll+.xml for intellisense. But of course I can download it and check out how things are implemented..