Home > Articles

  • Print
  • + Share This
This chapter is from the book

Developing a Game Engine

You now understand enough about what a game engine needs to accomplish that you can start assembling your own. In this section, you create the game engine that will be used to create all the games throughout the remainder of the book. Not only that, but also you'll be refining and adding cool new features to the game engine as you develop those games. By the end of the book, you'll have a powerful game engine ready to be deployed in your own game projects.

The Game Event Functions

The first place to start in creating a game engine is to create handler functions that correspond to the game events mentioned earlier in the lesson. Following are these functions, which should make some sense to you because they correspond directly to the game events:

BOOL GameInitialize(HINSTANCE hInstance);
void GameStart(HWND hWindow);
void GameEnd();
void GameActivate(HWND hWindow);
void GameDeactivate(HWND hWindow);
void GamePaint(HDC hDC);
void GameCycle();

The first function, GameInitialize(), is probably the only one that needs special explanation simply because of the argument that gets sent into it. I'm referring to the hInstance argument, which is of type HINSTANCE. This is a Win32 data type that refers to an application instance. An application instance is basically a program that has been loaded into memory and that is running in Windows. If you've ever used Alt+Tab to switch between running applications in Windows, you're familiar with different application instances. The HINSTANCE data type is a handle to an application instance, and it is very important because it allows a program to access its resources since they are stored with the application in memory.

The GameEngine Class

The game event handler functions are actually separated from the game engine itself, even though there is a close tie between them. This is necessary because it is organizationally better to place the game engine in its own C++ class. This class is called GameEngine and is shown in Listing 3.1.

NOTE

If you were trying to adhere strictly to object-oriented design principles, you would place the game event handler functions in the GameEngine class as virtual methods to be overridden. However, although that would represent good OOP design, it would also make it a little messier to assemble a game because you would have to derive your own custom game engine class from GameEngine in every game. By using functions for the event handlers, you simplify the coding of games at the expense of breaking an OOP design rule. Such are the trade-offs of game programming.

Listing 3.1 The GameEngine Class Definition Reveals How the Game Engine Is Designed

 1: class GameEngine
 2: {
 3: protected:
 4:  // Member Variables
 5:  static GameEngine* m_pGameEngine;
 6:  HINSTANCE      m_hInstance;
 7:  HWND        m_hWindow;
 8:  TCHAR        m_szWindowClass[32];
 9:  TCHAR        m_szTitle[32];
10:  WORD        m_wIcon, m_wSmallIcon;
11:  int         m_iWidth, m_iHeight;
12:  int         m_iFrameDelay;
13:  BOOL        m_bSleep;
14:
15: public:
16:  // Constructor(s)/Destructor
17:      GameEngine(HINSTANCE hInstance, LPTSTR szWindowClass,
18:       LPTSTR szTitle, WORD wIcon, WORD wSmallIcon, int iWidth = 640,
19:       int iHeight = 480);
20:  virtual ~GameEngine();
21: 
22:  // General Methods
23:  static GameEngine* GetEngine() { return m_pGameEngine; };
24:  BOOL        Initialize(int iCmdShow);
25:  LRESULT       HandleEvent(HWND hWindow, UINT msg, WPARAM wParam,
26:             LPARAM lParam);
27:
28:  // Accessor Methods
29:  HINSTANCE GetInstance() { return m_hInstance; };
30:  HWND   GetWindow() { return m_hWindow; };
31:  void   SetWindow(HWND hWindow) { m_hWindow = hWindow; };
32:  LPTSTR  GetTitle() { return m_szTitle; };
33:  WORD   GetIcon() { return m_wIcon; };
34:  WORD   GetSmallIcon() { return m_wSmallIcon; };
35:  int    GetWidth() { return m_iWidth; };
36:  int    GetHeight() { return m_iHeight; };
37:  int    GetFrameDelay() { return m_iFrameDelay; };
38:  void   SetFrameRate(int iFrameRate) { m_iFrameDelay = 1000 /
39:        iFrameRate; };
40:  BOOL   GetSleep() { return m_bSleep; };
41:  void   SetSleep(BOOL bSleep) { m_bSleep = bSleep; };
42: };

The GameEngine class definition reveals a subtle variable naming convention that wasn't mentioned in the previous lesson. This naming convention involves naming member variables of a class with an initial m_ to indicate that they are class members. Additionally, global variables are named with a leading underscore (_), but no m. This convention is useful because it helps you to immediately distinguish between local variables, member variables, and global variables in a program. The member variables for the GameEngine class all take advantage of this naming convention, which is evident in lines 5 through 13.

The GameEngine class defines a static pointer to itself, m_pGameEngine, which is used for outside access by a game program (line 5). The application instance and main window handles of the game program are stored away in the game engine using the m_hInstance and m_hWindow member variables (lines 6 and 7). The name of the window class and the title of the main game window are stored in the m_szWindowClass and m_szTitle member variables (lines 8 and 9). The numeric IDs of the two program icons for the game are stored in the m_wIcon and m_wSmallIcon members (line 10). The width and height of the game screen are stored in the m_iWidth and m_iHeight members (line 11). It's important to note that this width and height corresponds to the size of the game screen, or play area, not the size of the overall program window, which is larger to accommodate borders, a title bar, menus, and so on. The m_iFrameDelay member variable in line 12 indicates the amount of time between game cycles, in milliseconds. And finally, m_bSleep is a Boolean member variable that indicates whether the game is sleeping (paused).

The GameEngine constructor and destructor are defined after the member variables, as you might expect. The constructor is very important because it accepts arguments that dramatically impact the game being created. More specifically, the GameEngine() constructor accepts an instance handle, window classname, title, icon ID, small icon ID, and width and height (lines 17–19). Notice that the iWidth and iHeight arguments default to values of 640 and 480, respectively, which is a reasonable minimum size for game screens. The ~GameEngine() destructor doesn't do anything, but it's worth defining it in case you need to add some cleanup code to it later (line 20).

I mentioned that the GameEngine class maintains a static pointer to itself. This pointer is accessed from outside the engine using the static GetEngine() method, which is defined in line 23. The Initialize() method is another important general method in the GameEngine class, and its job is to initialize the game program once the engine is created (line 24). The HandleEvent() method is responsible for handling standard Windows events within the game engine, and is a good example of how the game engine hides the details of generic Windows code from game code (lines 25 and 26).

The remaining methods in the GameEngine class are accessor methods used to access member variables; these methods are all used to get and set member variables. The one accessor method to pay special attention to is SetFrameRate(), which sets the frame rate, or number of cycles per second, of the game engine (lines 38 and 39). Because the actual member variable that controls the number of game cycles per second is m_iFrameDelay, which is measured in milliseconds, it's necessary to perform a quick calculation to convert the frame rate in SetFrameRate() to milliseconds.

The source code for the GameEngine class provides implementations for the methods described in the header that you just saw, as well as the standard WinMain() and WndProc() functions that tie into the game engine. The GameEngine source code also initializes the static game engine pointer, like this:

GameEngine *GameEngine::m_pGameEngine = NULL;

Listing 3.2 contains the source code for the game engine's WinMain() function.

Listing 3.2 The WinMain() Function in the Game Engine Makes Calls to Game Engine Functions and Methods, and Provides a Neat Way of Separating Standard Windows Program Code from Game Code

 1: int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
 2:  PSTR szCmdLine, int iCmdShow)
 3: {
 4:  MSG     msg;
 5:  static int iTickTrigger = 0;
 6:  int     iTickCount;
 7:
 8:  if (GameInitialize(hInstance))
 9:  {
10:   // Initialize the game engine
11:   if (!GameEngine::GetEngine()->Initialize(iCmdShow))
12:    return FALSE;
13:
14:   // Enter the main message loop
15:   while (TRUE)
16:   {
17:    if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
18:    {
19:     // Process the message
20:     if (msg.message == WM_QUIT)
21:      break;
22:     TranslateMessage(&msg);
23:     DispatchMessage(&msg);
24:    }
25:    else
26:    {
27:     // Make sure the game engine isn't sleeping
28:     if (!GameEngine::GetEngine()->GetSleep())
29:     {
30:      // Check the tick count to see if a game cycle has elapsed
31:      iTickCount = GetTickCount();
32:      if (iTickCount > iTickTrigger)
33:      {
34:       iTickTrigger = iTickCount +
35:        GameEngine::GetEngine()->GetFrameDelay();
36:       GameCycle();
37:      }
38:     }
39:    }
40:   }
41:   return (int)msg.wParam;
42:  }
43:
44:  // End the game
45:  GameEnd();
46:
47:  return TRUE;
48: }

Although this WinMain() function is similar to the one you saw in the previous lesson, there is an important difference. The difference has to do with the fact that this WinMain() function establishes a game loop that takes care of generating game cycle events at a specified interval. The smallest unit of time measurement in a Windows program is called a tick, which is equivalent to one millisecond, and is useful in performing accurate timing tasks. In this case, WinMain() counts ticks in order to determine when it should notify the game that a new cycle is in order. The iTickTrigger and iTickCount variables are used to establish the game cycle timing in WinMain() (lines 5 and 6) .

The first function called in WinMain() is GameInitialize(), which gives the game a chance to be initialized. Remember that GameInitialize() is a game event function that is provided as part of the game-specific code for the game, and therefore isn't a direct part of the game engine. A method that is part of the game engine is Initialize(), which is called to get the game engine itself initialized in line 11. From there WinMain() enters the main message loop for the game program, part of which is identical to the main message loop you saw in the previous lesson (lines 17—24). The else part of the main message loop is where things get interesting. This part of the loop first checks to make sure that the game isn't sleeping (line 28), and then it uses the frame delay for the game engine to count ticks and determine when to call the GameCycle() function to trigger a game cycle event (line 36). WinMain() finishes up by calling GameEnd() to give the game program a chance to wrap up the game and clean up after itself (line 45).

The other standard Windows function included in the game engine is WndProc(), which is surprisingly simple now that the HandleEvent() method of the GameEngine class is responsible for processing Windows messages:

LRESULT CALLBACK WndProc(HWND hWindow, UINT msg, WPARAM wParam, LPARAM lParam)
{
 // Route all Windows messages to the game engine
 return GameEngine::GetEngine()->HandleEvent(hWindow, msg, wParam, lParam);
}

All WndProc() really does is pass along all messages to HandleEvent(), which might at first seem like a waste of time. However, the idea is to allow a method of the GameEngine class to handle the messages so that they can be processed in a manner that is consistent with the game engine.

Speaking of the GameEngine class, now that you have a feel for the support functions in the game engine, we can move right along and examine specific code in the GameEngine class. Listing 3.3 contains the source code for the GameEngine() constructor and de-structor.

Listing 3.3 The GameEngine::GameEngine() Constructor Takes Care of Initializing Game Engine Member Variables, Whereas the Destructor is Left Empty for Possible Future Use

 1: GameEngine::GameEngine(HINSTANCE hInstance, LPTSTR szWindowClass,
 2:  LPTSTR szTitle, WORD wIcon, WORD wSmallIcon, int iWidth, int iHeight)
 3: {
 4:  // Set the member variables for the game engine
 5:  m_pGameEngine = this;
 6:  m_hInstance = hInstance;
 7:  m_hWindow = NULL;
 8:  if (lstrlen(szWindowClass) > 0)
 9:   lstrcpy(m_szWindowClass, szWindowClass);
10:  if (lstrlen(szTitle) > 0)
11:   lstrcpy(m_szTitle, szTitle);
12:  m_wIcon = wIcon;
13:  m_wSmallIcon = wSmallIcon;
14:  m_iWidth = iWidth;
15:  m_iHeight = iHeight;
16:  m_iFrameDelay = 50;  // 20 FPS default
17:  m_bSleep = TRUE;
18: }
19:
20: GameEngine::~GameEngine()
21: {
22: }

The GameEngine() constructor is relatively straightforward in that it sets all the member variables for the game engine. The only member variable whose setting might seem a little strange at first is m_iFrameDelay, which is set to a default frame delay of 50 milliseconds (line 16). You can determine the number of frames (cycles) per second for the game by dividing 1,000 by the frame delay, which in this case results in 20 frames per second. This is a reasonable default for most games, although specific testing might reveal that it needs to be tweaked up or down.

The Initialize() method in the GameEngine class is used to initialize the game engine. More specifically, the Initialize() method now performs a great deal of the messy Windows setup tasks such as creating a window class for the main game window and then creating a window from the class. Listing 3.4 shows the code for the Initialize() method.

Listing 3.4 The GameEngine::Initialize() Method Handles Some of the Dirty Work That Usually Takes Place in WinMain()

 1: BOOL GameEngine::Initialize(int iCmdShow)
 2: {
 3:  WNDCLASSEX  wndclass;
 4:
 5:  // Create the window class for the main window
 6:  wndclass.cbSize     = sizeof(wndclass);
 7:  wndclass.style     = CS_HREDRAW | CS_VREDRAW;
 8:  wndclass.lpfnWndProc  = WndProc;
 9:  wndclass.cbClsExtra   = 0;
10:  wndclass.cbWndExtra   = 0;
11:  wndclass.hInstance   = m_hInstance;
12:  wndclass.hIcon     = LoadIcon(m_hInstance,
13:   MAKEINTRESOURCE(GetIcon()));
14:  wndclass.hIconSm    = LoadIcon(m_hInstance,
15:   MAKEINTRESOURCE(GetSmallIcon()));
16:  wndclass.hCursor    = LoadCursor(NULL, IDC_ARROW);
17:  wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
18:  wndclass.lpszMenuName  = NULL;
19:  wndclass.lpszClassName = m_szWindowClass;
20:
21:  // Register the window class
22:  if (!RegisterClassEx(&wndclass))
23:   return FALSE;
24:
25:  // Calculate the window size and position based upon the game size
26:  int iWindowWidth = m_iWidth + GetSystemMetrics(SM_CXFIXEDFRAME) * 2,
27:    iWindowHeight = m_iHeight + GetSystemMetrics(SM_CYFIXEDFRAME) * 2 +
28:     GetSystemMetrics(SM_CYCAPTION);
29:  if (wndclass.lpszMenuName != NULL)
30:   iWindowHeight += GetSystemMetrics(SM_CYMENU);
31:  int iXWindowPos = (GetSystemMetrics(SM_CXSCREEN) - iWindowWidth) / 2,
32:    iYWindowPos = (GetSystemMetrics(SM_CYSCREEN) - iWindowHeight) / 2;
33:
34:  // Create the window
35:  m_hWindow = CreateWindow(m_szWindowClass, m_szTitle, WS_POPUPWINDOW |
36:   WS_CAPTION | WS_MINIMIZEBOX, iXWindowPos, iYWindowPos, iWindowWidth,
37:   iWindowHeight, NULL, NULL, m_hInstance, NULL);
38:  if (!m_hWindow)
39:   return FALSE;
40:
41:  // Show and update the window
42:  ShowWindow(m_hWindow, iCmdShow);
43:  UpdateWindow(m_hWindow);
44:
45:  return TRUE;
46: }

This code should look at least vaguely familiar from the Skeleton program example in the previous lesson because it is carried over straight from that program. However, in Skeleton this code appeared in the WinMain() function, whereas here it has been incorporated into the game engine's Initialize() method. The primary change in the code is the determination of the window size, which is calculated based on the size of the client area of the window. The GetSystemMetrics() Win32 function is called to get various standard Window sizes such as the width and height of the window frame (lines 26 and 27), as well as the menu height (line 30). The position of the game window is then calculated so that the game is centered on the screen (lines 31 and 32).

The creation of the main game window in the Initialize() method is slightly different from what you saw in the previous lesson. The styles used to describe the window here are WS_POPUPWINDOW, WS_CAPTION, and WS_MINIMIZEBOX, which results in a different window from the Skeleton program (lines 35 and 36). In this case, the window is not resizable, and it can't be maximized; however, it does have a menu, and it can be minimized.

The Initialize() method is a perfect example of how generic Windows program code has been moved into the game engine. Another example of this approach is the HandleEvent() method, which is shown in Listing 3.5.

Listing 3.5 The GameEngine::HandleEvent() Method Receives and Handles Messages That Are Normally Handled in WndProc()

 1: LRESULT GameEngine::HandleEvent(HWND hWindow, UINT msg, WPARAM wParam,
 2:  LPARAM lParam)
 3: {
 4:  // Route Windows messages to game engine member functions
 5:  switch (msg)
 6:  {
 7:   case WM_CREATE:
 8:    // Set the game window and start the game
 9:    SetWindow(hWindow);
10:    GameStart(hWindow);
11:    return 0;
12:
13:   case WM_ACTIVATE:
14:    // Activate/deactivate the game and update the Sleep status
15:    if (wParam != WA_INACTIVE)
16:    {
17:     GameActivate(hWindow);
18:     SetSleep(FALSE);
19:    }
20:    else
21:    {
22:     GameDeactivate(hWindow);
23:     SetSleep(TRUE);
24:    }
25:    return 0;
26:
27:   case WM_PAINT:
28:    HDC     hDC;
29:    PAINTSTRUCT ps;
30:    hDC = BeginPaint(hWindow, &ps);
31:
32:    // Paint the game
33:    GamePaint(hDC);
34: 
35:    EndPaint(hWindow, &ps);
36:    return 0;
37:
38:   case WM_DESTROY:
39:    // End the game and exit the application
40:    GameEnd();
41:    PostQuitMessage(0);
42:    return 0;
43:  }
44:  return DefWindowProc(hWindow, msg, wParam, lParam);
45: }

The HandleEvent() method looks surprisingly similar to the WndProc() method in the Skeleton program in that it contains a switch statement that picks out Windows messages and responds to them individually. However, the HandleEvent() method goes a few steps further than WndProc() by handling a couple more messages, and also making calls to game engine functions that are specific to each different game. First, the WM_CREATE message is handled, which is sent whenever the main game window is first created (line 7). The handler code for this message sets the window handle in the game engine (line 9), and then calls the GameStart() game event function to get the game initialized (line 10).

The WM_ACTIVATE message is a new one that you haven't really seen, and its job is to inform the game whenever its window is activated or deactivated (line 13). The wParam message parameter is used to determine whether the game window is being activated or deactivated (line 15). If the game window is being activated, the GameActivate() function is called and the game is awoken (lines 17 and 18). Similarly, if the game window is being deactivated, the GameDeactivate() function is called and the game is put to sleep (lines 22 and 23).

The remaining messages in the HandleEvent() method are pretty straightforward in that they primarily call game functions. The WM_PAINT message handler calls the standard Win32 BeginPaint() function (line 30) followed by the GamePaint() function (line 33). The EndPaint() function is then called to finish up the painting process (line 35); you learn a great deal more about BeginPaint() and EndPaint() in the next hour. Finally, the WM_DESTROY handler calls the GameEnd() function and then terminates the whole program (lines 40 and 41).

You've now seen all the code for the game engine, which successfully combines generic Windows code from the Skeleton example with new code that provides a solid framework for games. Let's now take a look at a new and improved Skeleton program that takes advantage of the game engine.

  • + Share This
  • 🔖 Save To Your Account