Welcome to MSDN Blogs Sign in | Join | Help

My last post on render loops (hopefully)..

The most common topic on my blog returns again.  This time it will be brief as all I'm going to to do now is show you the render loop the June'05 SDK will be using.  A coworker in another group came up with this markedly simple, yet deceptively effective loop for that groups projects.  I liked it so much, i'm sharing it with everyone else. =)

The basic loop (slightly modified from his original version and the version in the new SDK for ease of reading):

public void MainLoop()
{
        // Hook the application's idle event
        System.Windows.Forms.Application.Idle += new EventHandler(OnApplicationIdle);
        System.Windows.Forms.Application.Run(myForm);
}

private void OnApplicationIdle(object sender, EventArgs e)
{
    while (AppStillIdle)
    {
         // Render a frame during idle time (no messages are waiting)
         UpdateEnvironment();
         Render3DEnvironment();
    }
}

private bool AppStillIdle
{
     get
    {
        NativeMethods.Message msg;
        return !NativeMethods.PeekMessage(out msg, IntPtr.Zero, 0, 0, 0);
     }
}

And the declarations for those two native methods members:

[StructLayout(LayoutKind.Sequential)]
public struct Message
{
    public IntPtr hWnd;
    public WindowMessage msg;
    public IntPtr wParam;
    public IntPtr lParam;
    public uint time;
    public System.Drawing.Point p;
}

[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("User32.dll", CharSet=CharSet.Auto)]
public static extern bool PeekMessage(out Message msg, IntPtr hWnd, uint messageFilterMin, uint messageFilterMax, uint flags);

------

Simple, elegant, effective.  No extra allocations, no extra collections, it just works..  The Idle event fires when there's no messages in the queue, and then the handler keeps looping continuously until a message does appear, in which case it stops..  Once all the messages are handled, the idle event is fired again, and the process starts over.

Published Thursday, May 05, 2005 1:26 PM by tmiller
Filed under:

Comments

Thursday, May 05, 2005 3:13 PM by dwellerville

# Game Loops, Game Physics, and Star Wars spoilers!

Tom Miller finally states the last word on the subject of game loops in Managed DirectX code.  Now...
Friday, May 06, 2005 1:58 PM by Richard

# re: My last post on render loops (hopefully)..

So Tom how does this way of looping compare (fps and memory wise) to the way Rick Hoskinson recently started discussing on his blog. http://blogs.msdn.com/rickhos/archive/2005/04/04/405327.aspx

-Richard
Richard.Parsons (at) gmail.com
Friday, May 06, 2005 6:08 PM by wtf

# re: My last post on render loops (hopefully)..

Why on earth is this page using SSL?
Saturday, May 07, 2005 8:02 PM by Judah Himango

# re: My last post on render loops (hopefully)..

Tom, in your Message struct, what is WindowMessage? Would that be System.Windows.Forms.Message?
Sunday, May 08, 2005 7:45 AM by Seb Nemeth

# re: My last post on render loops (hopefully)..

How does this stand up to supporting rendering to Controls and not just a Form, I wonder..?
Monday, May 09, 2005 12:06 AM by Zman

# re: My last post on render loops (hopefully)..

Added link to 'the saga of the MDX render loop' http://www.thezbuffer.com/articles/185.aspx
Monday, May 09, 2005 2:21 AM by Turon

# re: My last post on render loops (hopefully)..

Hi Tom,

Can't help but notice that your new approach, if i'm not mistaken, is quite similar how GLUT handles the rendering. In GLUT, you need to hook up a callback to the idle event for rendering. Your latest approach is the cleanest so far. KUDOS Tom!

BTW, I have your book "Beginning 3D Game Programming" and it ROCKS!

PS: Sorry about the OpenGL / GLUT post. Since I moved to using C#, I'm now a Managed DirectX fan :P
Monday, May 09, 2005 2:56 AM by Bob the slob

# re: My last post on render loops (hopefully)..

This is bloody brilliant, why didn't I think of this? I have perhaps the most complicated render loop in the history of the universe right now (mind you, it handles switching between windowed/fullscreen, task switching, res changes flawlessly).
Monday, May 09, 2005 5:30 AM by Petey

# re: My last post on render loops (hopefully)..

public WindowMessage msg;

Where does "WindowMessage" come from? I can't seem to find it in any of the namespaces!
Monday, May 09, 2005 11:58 AM by Sivan Segev

# Awesome, but threads are better

I've been tracking the posts regarding render loops, but early on I moved the scene preperation and rendering into a seperate thread. The thread renders to a window or a full screen, at synchronized frame rate or at maximum, with varying "sleep" times. This has worked much better than all proposed "main thread" render loop proposals so far.
Thursday, May 12, 2005 2:49 PM by sapropel

# re: My last post on render loops (hopefully)..


i was going to try it out, but where did you get that WindowMessage enum/struct/class/whatever from? the one inside the Message struct declaration.

thanks []
Thursday, May 12, 2005 7:57 PM by sapropel

# re: My last post on render loops (hopefully)..


also, why the use of SuppressUnmanagedCodeSecurity? theres no need for that (i think).

and where is that CharSet.Auto from? the only one i know is CharacterSet, and it has no .Auto

also, could you post a complete working example please? something really simple like device.Clear(...); device.Present();

i managed to compile it by removing the CharSet=CharSet.Auto and chaging the public WindowMessage msg; Message struct member to public int msg; (since i dont know where that WindowMessage is), but i dont know if it is as good as yours.

again thanks :)
Monday, May 16, 2005 2:32 PM by Deezer

# re: My last post on render loops (hopefully)..

Is there anywhere a newbie can go to view VB.NET solutions to the issues that started this issue applies to VB.NET Managed DirectX coding too?

Everything about Managed DirectX samples and blog chats is infuriatingly C# centric. Am I simply choosing the wrong language if I wish to learn to use Managed DirectX? The utter lack of VB.NET samples even in the DirectX SDK itself, not to mention no talk of how this render loop issue here is implemented in VB.NET, suggests VB.NET is indeed a poor language choice.

Any pointers to a good VB site covering this issue would be very welcome.
Monday, May 16, 2005 10:23 PM by Mort

# re: My last post on render loops (hopefully)..

I hate to sound stupid but what #using' do you need with that.

I copied the code in to a blank project and I get compile errors.

Thanks

Mort.
Monday, May 23, 2005 7:59 AM by T-T

# re: My last post on render loops (hopefully)..

Wassup with all that C# Code?
Forgot about vb have we?
Thursday, May 26, 2005 9:21 AM by akshay

# it has been there for ages

The PeekMessage loop has been in use for ages by game programmers who code in unmanaged DirectX and even OpenGL. What surprises me is that it took such a long before someone was able to figure it out for managed dx!
Monday, May 30, 2005 12:45 PM by Anonymous

# re: My last post on render loops (hopefully)..

I put the using directive System.Runtime.InteropServices and that solved all of the errors except for one that says:

The type or namespace name 'WindowMessage' could not be found (are you missing a using directive or an assembly reference?)

I've looked in the MSDN and all over the web, and I cannot find the namespace it is in. Thank you for your help.
Wednesday, June 01, 2005 2:47 AM by mimfeld

# I guess this works, yet ...

I can only guess this works - since I cannot get it to run. Reason for this being that I - as an average programmer - simply have no idea what namespaces / references to include.

What type is WindowMessage? IntPtr? (I tried looking for WindowMessage in MSDN to no avail).

System.Drawing.NativeMethods seems to be an internal class. Consequently I get compilation errors when trying to compile the code. What am I missing?

Might be I am the only one that plays around with MDX without a complete understanding and knowledge of the .net framework, at least to my very limited mind a complete code sample would be extremely helpful.

Don't get me wrong, I am not critizing here. It's just that I have very limited ressources (both time and brain ;) )
Friday, June 03, 2005 2:47 AM by Akshay

# re: My last post on render loops (hopefully)..

I have made a sample framework app using the loop you have suggested here. It does work better than the original SDK loop. It is located <a href="http://photongl.blogspot.com">here</a>.
Saturday, June 04, 2005 4:44 PM by John

# re: My last post on render loops (hopefully)..

I'm wondering how much of a performance difference will be if I take out the AppStillIdle while loop and just call the update and render methods within OnApplicationIdle.

Tom, do you have any figures on this?
Wednesday, June 08, 2005 3:58 PM by ChrSmith

# Trouble finding WindowMessage struct

That looks great. I am new to DirectX, but I remember back when doing OpenGL that the main render loop was the most difficult part- especially trying to balance always redrawing without overworking the CPU.

Could you provide the source for the C# version of the WindowMessage struct as well? I am having difficulty getting this to compile since I assume that structure is defined else where in your code. (Is it defined somewhere in the managed source for the April MDX SDK update?)

Thanks,
-Chris
Saturday, June 11, 2005 2:50 PM by HopeDagger

# re: My last post on render loops (hopefully)..

Simply put: Yuck. That's not simple nor elegant. :/
Wednesday, June 22, 2005 3:49 AM by Exabyte256

# re: My last post on render loops (hopefully)..

Hrm. The Message struct is already defined by the .NET libraries as:

System.Windows.Forms.Message
Wednesday, February 08, 2006 10:59 AM by corporate samurai

# New Client Code!

I have checked in a new initial version of the Client UI which is based on the OnApplicationIdle style...
Tuesday, May 02, 2006 5:51 PM by Stynet » Remember to Backup Your Work

# Stynet &raquo; Remember to Backup Your Work

Wednesday, November 29, 2006 4:33 PM by The instruction limit » Displayable Profiler

# The instruction limit &raquo; Displayable Profiler

Wednesday, November 29, 2006 4:49 PM by The instruction limit » Samples Rewriting

# The instruction limit &raquo; Samples Rewriting

New Comments to this post are disabled
 
Page view tracker