304 7. The Game Loop and Real-Time Simulation
Real-time 3D computer graphics are implemented in an entirely diff erent
way. As the camera moves about in a 3D scene, the entire contents of the screen
or window change continually, so the concept of invalid rectangles no longer
applies. Instead, an illusion of motion and interactivity is produced in much
the same way that a movie produces it—by presenting the viewer with a se-
ries of still images in rapid succession.
Obviously, producing a rapid succession of still images on-screen requires
a loop. In a real-time rendering application, this is sometimes known as the
render loop. At its simplest, a rendering loop is structured as follows:
while (!quit)
{
// Update the camera transform based on interactive
// inputs or by following a predefined path.
updateCamera();
// Update positions, orientations and any other
// relevant visual state of any dynamic elements
// in the scene.
updateSceneElements();
// Render a still frame into an off-screen frame
// buffer known as the "back buffer".
renderScene();
// Swap the back buffer with the front buffer, making
// the most-recently-rendered image visible
// on-screen. (Or, in windowed mode, copy (blit) the
// back buffer’s contents to the front buffer.
swapBuffers();
}
7.2 The Game Loop
A game is composed of many interacting subsystems, including device I/O,
rendering, animation, collision detection and resolution, optional rigid body
dynamics simulation, multiplayer networking, audio, and the list goes on.
Most game engine subsystems require periodic servicing while the game is
running. However, the rate at which these subsystems need to be serviced var-
ies from subsystem to subsystem. Animation typically needs to be updated
at a rate of 30 or 60 Hz, in synchronization with the rendering subsystem.
However, a dynamics simulation may actually require more frequent updates