peekmessage while vs if (main/game loop)

Started by
11 comments, last by vstrakh 7 years, 6 months ago

Imagine you render scene with vsync turned on.
If you go with 'if' implementation, you will process single input event per rendered frame.
But there will be lots of events, especially when mouse moves. If you will process only one event, render frame, wait for 16ms (vsync on), then with simple mouse movement you will create some work for many seconds upfront. Scene update will lag to the point where app will become totally unresponsive.
So you must go with 'while' loop, processing all inputs before you start rendering.


With 'while' it sounds like waiting till a message occurs.


You don't wait for events with PeekMessage(), you would wait with GetMessage().


The if version won't run any update or rendering logic unless peekmessage returns false so it should work properly.
All game and rendering code is inside the else block, it should even be a tiny bit faster since it only has to do the check for VM_QUIT (and not the extra assignment and checks for run like the while version does)
It also has the advantage of exiting almost immediately on a VM_QUIT, the while version will run through one update before exiting.
[size="1"]I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!
Advertisement

From an earlier project:


bool Window::update() {   //flush message queue, return true to continue, false to quit
  MSG msg;
  while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
    if(msg.message == WM_QUIT) { return false; }
  }

  return true;
}

void Game::run() {
  timer.getDT(); //reset timer
  scene->update(0); //hack for setting initial entity positions (arg is DT)
  fadeIn();

  while(scene && window.update()) {
    input.ReadFrame();

    Scene* next = scene->update(timer.getDT());

    if(next == scene.get()) { //draw normally
      gfx.startDraw();
      scene->draw();
      gfx.endDraw();
    }
    else { //changed to new scene, so do fadey stuff
      fadeOut();

      scene.reset(next);
      if(!scene) { break; }
      scene->update(0);

      fadeIn();
    }

  }

  if(scene) { scene.reset(nullptr); } //this was a hack, but I can't remember the specifics
}

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

The if version won't run any update or rendering logic unless peekmessage returns false so it should work properly.

Ah, true. You're right. I've seen so many incorrect implementations, so just seeing 'if' caused immediate reaction.

Broken indentation also doesn't help reading code :)

This topic is closed to new replies.

Advertisement