Wednesday, September 8, 2010

VBlank

Start at the Beginning
Table of Contents

The other advantage of double buffering is that it prevents what's called 'tearing'. Back in the day, everyone used CRT (cathode ray tube) monitors instead of the LCDs we use today. Inside these monitors was an electron gun that would light up pixels by running an electron beam down the screen extremely quickly. Once it reached the bottom, it'd move back up to the top before drawing the next frame. The time the electron gun takes to move back up to the top is called the vertical blank period or vblank.

If we start drawing a new frame to the screen while the monitor is in the middle of drawing, half the screen will be the previous frame, and the other half will be the next frame. If things are moving quickly, this creates a weird visual effect called "tearing". If we wait until the monitor is in vsync before drawing our frame, we can avoid this entirely - as long as the drawing takes less time than the vblank. Without double buffering, it might not if we're drawing a particularly complex scene and waiting until vsync before we start. If, instead, we draw away on our back buffer, the quick copy operation is all we have to do in vblank, and that's almost guaranteed to finish in time.

Even though LCD monitors don't quite work this way, this approach is still required. LCD pixels never have to be refreshed, but the monitor queries the VGA for the current contents of the graphics array every so often and only redraws the actual physical screen then. If we're in the middle of drawing when that happens, we'll get tearing.

On a VGA card, vblank occurs 70 times per second. Thus, waiting for vblank also gives us a way to prevent our game from running too fast - but it does limit us to 70fps. This makes our lives easier in a lot of ways, but it is limited. Eventually we'll learn ways around this.

Here's the function we'll use to wait for vblank:

(click here for vblank.c)

No comments:

Post a Comment