Sign in to follow this  
riruilo

OpenGL Animation in a MFC application and OPENGL (again, sorry)

Recommended Posts

Hi friends! First all, sorry for my english. My questions are about animations in MFC (doc/view arquitecture) and OPENGL. I know there are some articles and threads about this topic, but actually I don´t have clear this subject. My questions is: What is the most correct way to do that? I found these: Overwrite Idle function: There is an article about this in gamedev but I think (it is my opinion, nothing else) this approach is not elegant and intrusive. http://www.gamedev.net/reference/articles/article2204.asp SetTimer: My teacher at university this is horrible and this function has a bad resolution http://www.gamedev.net/community/forums/topic.asp?topic_id=212576 AfxBeginThread, QueryPerformanceCounter... or some While loop... After read some information I will suggest (me) this: (and maybe I´m wrong) Add to my engine a funtion like this: Render(fElapsedTime); So everything will be rendered depending of the value of fElapsedTime. If an animation has a 3 seconds animation, fElapsedTime will be from 0.0 to 3.0 in a variable frame rate (or fixed), but I prefer to draw all frames that my computer can able to do it. So when I will press PLAY, will occur this: starttime=QueryPerformanceCounter; and after this a thread will be launched with this code: while (true) { fElapsedTime=QueryPerformanceCounter-starttime; Render(fElapsedTime); } (Actually, until you press STOP) Is my approach elegant or very difficult? Will I have problems with MFC model? Will I block message waiting line? How can I add this on OnDraw function? or MFC view/doc paradigm. I think with my approach can give me the maximum amount of FPS of my system, not like SetTimer, which give me a constant FPS. Well, I will apreciate all opinions, I would just like to know WHICH is the best and easy way to do it. Thank you very much for your time.

Share this post


Link to post
Share on other sites
Quote:
Original post by riruilo
Overwrite Idle function: There is an article about this in gamedev but I think (it is my opinion, nothing else) this approach is not elegant and intrusive.
http://www.gamedev.net/reference/articles/article2204.asp

Yeah, it is intrusive, and a bit of a hack in truth [grin]

Thing is though, it's a quick and reliable way of continuously updating an MFC application. As you already mention, using a timer is a very poor solution, and just using the OnIdle and OnDraw functions on their own won't give you what you want.

Quote:
Original post by riruilo
After read some information I will suggest (me) this: (and maybe I´m wrong)

Add to my engine a funtion like this:
Render(fElapsedTime);

So everything will be rendered depending of the value of fElapsedTime.
If an animation has a 3 seconds animation, fElapsedTime will be from 0.0 to 3.0 in a variable frame rate (or fixed), but I prefer to draw all frames that my computer can able to do it.
So when I will press PLAY, will occur this:

starttime=QueryPerformanceCounter;
and after this a thread will be launched with this code:

while (true) {
fElapsedTime=QueryPerformanceCounter-starttime;
Render(fElapsedTime);
}

(Actually, until you press STOP)

Is my approach elegant or very difficult? Will I have problems with MFC model? Will I block message waiting line?
How can I add this on OnDraw function? or MFC view/doc paradigm.
I think with my approach can give me the maximum amount of FPS of my system, not like SetTimer, which give me a constant FPS.

The other solution, as you suggest, is to use another thread to control rendering. This is a better (and arguably more elegant) way of doing your rendering, but you need to be aware of all the problems which can occur with a multi-threaded solution, such as the potential for deadlock and mutually-exclusive access to data which is shared among threads.

If you're using a different thread, you won't be blocking the message queue; the parent (main) thread will continue to run after launching the child (rendering) thread.

How you integrate your child (rendering) thread with the rest of your application will vary. If your child (rendering) thread is running continuously calling your Render function as often as it can, you won't actually need to do anything in OnDraw (all of your views will presumably be updated by your Render function). All you'll need to do is update the scene data which is displayed by your Render function (and it's here that problems could occur with both threads trying to read/write to shared data).

To prevent all of your views being updated every cycle by the child thread (which might really slow your app down), you can flag that a view is "dirty" (in need of redrawing) in the OnDraw function, and only redraw views in your Render function which have that dirty flag set. Alternatively, you could give the user the option to specify the update (5fps by default, say). 3ds max allows you to do this; basically, you just lock the frame-rate to the user-specified value (which would be a trivial change to your child thread).

Quote:
Original post by riruilo
Well, I will apreciate all opinions, I would just like to know WHICH is the best and easy way to do it.

The method outlined in my article of overriding the Run and OnIdle functions is a quick and relatively hacky way of getting an MFC application to update continuously. The better solution is to create a child thread which runs continuously, and frees your main thread to run the MFC app.

Quote:
Original post by riruilo
Thank you very much for your time.

You're welcome [smile]

Share this post


Link to post
Share on other sites
Thanks a lot iNsAn1tY.

Right now I´m going to try to implement it using AfxBeginThread. I´m doing a COLLADA loader and I need that for animations.

By the way, is this a proper way to control animations? (time, I mean)

starttime=QueryPerformanceCounter;
and after this a thread will be launched with this code:

while (true) {
fElapsedTime=QueryPerformanceCounter-starttime;
Render(fElapsedTime);
}

Thanks!

Share this post


Link to post
Share on other sites
iNsAn1tY posts a lot of good information. I can't add much but I can tell you the experience I had trying to write an animation viewer with MFC & a render viewport. I've tried all kinds of techniques and the best solution I came up with was using the OnIdle() method. It simplifies the process greatly and isn't really a hack if you stop and think about how MFC applications work. Multi threading was really a hassle and made the application much more complicated than it needed to be.

Most applications are event driven - they wait until they receive a message to perform some task. In an animation viewer it is the same - play this animation, load this animation, start, stop. The only difference is that you want to continue to do something while waiting for messages. MFC provides that mechanism in the idle call. You can make it hacky if you don't code it up to make sense ie OnIdle() { DrawSomething(); }.

In our MFC framework there can be multiple viewports. Some of these are updated always and some of them are not.

Every view is derived from CRenderView. This class, on creation, registers itself with the RenderViewManager. It's automatic in the constructor so client code does not even know it's happenening.

Every application derives not from CWinApp but CRenderApp. This application base class in turn derives from CWinApp. What does it do? It contains the RenderViewManager and overloads OnIdle. Every time OnIdle is called, the time delta is determined and the list of CRenderView classes is iterated over, and the Render function is called with the time delta. We also have a virtual function in CRenderApp called OnFrameUpdate() which also gets the delta. This is called first so that objects are updated before they are rendered. The nice thing about this framework is that people can create MFC render applications without having to worry about the guts of the framework. Additionally, we can switch views between being live updated or not - our CRenderView() overrides the paint message and paints the screen if it is 'dirty update' instead of 'live update' mode. In a quad-view with three wireframe views and one live update view this works really well.

If you are trying to use MFC I would avoid multi-threading it; MFC provides the hooks you need to do the work. You'll be thankful you are working on the application's good points instead of working on critical sections and mutexes.

Share this post


Link to post
Share on other sites
Quote:
Original post by riruilo
By the way, is this a proper way to control animations? (time, I mean)

starttime=QueryPerformanceCounter;
and after this a thread will be launched with this code:

while (true) {
fElapsedTime=QueryPerformanceCounter-starttime;
Render(fElapsedTime);
}

Yeah, that's how performance counters work in outline. You need to divide by the timer frequency, though:


// During initalization...
QueryPerformanceFrequency( reinterpret_cast<LARGE_INTEGER *>( &miTimerFreq ) );
QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER *>( &miStartTime ) );

// When updating...
__int64 liEndTime;
float lfTime;

QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER *>( &liEndTime ) );

lfTime = static_cast<float>( liEndTime - miStartTime ) / static_cast<float>( miTimerFreq );

miStartTime = liEndTime;

return lfTime;


Also, every time your while loop executes, you need a non-blocking rendezvous with the parent thread, so that the parent can stop the child thread when it needs to.

Quote:
Original post by Sphet
Most applications are event driven - they wait until they receive a message to perform some task. In an animation viewer it is the same - play this animation, load this animation, start, stop. The only difference is that you want to continue to do something while waiting for messages. MFC provides that mechanism in the idle call. You can make it hacky if you don't code it up to make sense ie OnIdle() { DrawSomething(); }.

True. This is the rationale the article works to; it's the simple modification of an application from one which is event-driven to on which is both event-driven and updates continuously. Did your animation viewer only use the OnIdle function? I found that I had to override Run as well to get the kind of reliable updating I expected.

Share this post


Link to post
Share on other sites
Hi!

Sorry for this post, but actually I dont know so much threads in MFC.
My first experiment was a failure.

I moved my code from OnDraw to my thread and my screen is black right now (black like my future)

I followed this toturial about MFC threads:
http://www.codeproject.com/threads/memberthread.asp

And I added this code to my thread:

UINT CColladaLoaderView::StartThread (LPVOID param) {
THREADSTRUCT* ts = (THREADSTRUCT*)param;
while (true)
{
ts->_this->Render(ts->_this->m_pDC);
}
return 1;
}



And I add this code after opengl initialization, on OnCreate:
THREADSTRUCT *_param = new THREADSTRUCT;
_param->m_pDC=m_pDC;
_param->_this=this;
AfxBeginThread (StartThread, _param);

But my screen is black.


Any idea? by the way StartThread is a static funtion.



Thank you for your help.

Share this post


Link to post
Share on other sites
Quote:
Original post by iNsAn1tY
True. This is the rationale the article works to; it's the simple modification of an application from one which is event-driven to on which is both event-driven and updates continuously. Did your animation viewer only use the OnIdle function? I found that I had to override Run as well to get the kind of reliable updating I expected.


Only OnIdle I believe - I'll check when I am in the office - I think you just need to make sure your OnIdle() kick returns TRUE - this forces the application to keep firing OnIdle() until you return FALSE or there are messages to handle. Once the messages are handled it goes back to OnIdle() calls. It's in OnIdle() tha the time delta was calculated, so I don't know how widely variable the frame-times slices were but none of our engineers or artists complain about it. Maybe I'll put a profile graph in today to see. I do know that when a menu item is being selected, or a modal loop is entered, the screen no longer refreshes ( OnIdle() not called ) but what I did was make it that if WM_Paint is received and the last-render time is quite old ( > 50ms ) to redraw from the view invalidation - this has the effect of 'time stopping' while modal but still rendering what you need to.

What were you doing in Run()?

I justed checked and there's no call to Run at all.



[Edited by - Sphet on March 5, 2007 11:31:20 AM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Announcements

  • Forum Statistics

    • Total Topics
      628375
    • Total Posts
      2982310
  • Similar Content

    • By test opty
      Hi all,
       
      I'm starting OpenGL using a tut on the Web. But at this point I would like to know the primitives needed for creating a window using OpenGL. So on Windows and using MS VS 2017, what is the simplest code required to render a window with the title of "First Rectangle", please?
       
       
    • By DejayHextrix
      Hi, New here. 
      I need some help. My fiance and I like to play this mobile game online that goes by real time. Her and I are always working but when we have free time we like to play this game. We don't always got time throughout the day to Queue Buildings, troops, Upgrades....etc.... 
      I was told to look into DLL Injection and OpenGL/DirectX Hooking. Is this true? Is this what I need to learn? 
      How do I read the Android files, or modify the files, or get the in-game tags/variables for the game I want? 
      Any assistance on this would be most appreciated. I been everywhere and seems no one knows or is to lazy to help me out. It would be nice to have assistance for once. I don't know what I need to learn. 
      So links of topics I need to learn within the comment section would be SOOOOO.....Helpful. Anything to just get me started. 
      Thanks, 
      Dejay Hextrix 
    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
       
       
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
      Thanks!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
      Thanks.
  • Popular Now