Reader small image

You're reading from  The Android Game Developer???s Handbook

Product typeBook
Published inAug 2016
Reading LevelBeginner
PublisherPackt
ISBN-139781785885860
Edition1st Edition
Languages
Right arrow
Author (1)
Avisekhar Roy
Avisekhar Roy
author image
Avisekhar Roy

Avisekhar Roy is a B.Tech engineer in computer science. He has had a passion for coding since his school days. However, he had no plans to become a game programmer. His fate landed him in the gaming industry in 2010. Since then, he fell in love with game development. Avisekhar has worked in many formats of game development environment, ranging from small companies and individual studios to corporate companies and full-scale game development studios. He recently started his own gaming start-up in 2016 and is currently working on games for the mobile platform. Avisekhar has also worked with some big companies, such as Reliance Games in India, as well as a small-scale studio called Nautilus Mobile. He is now trying to acquire a position in the gaming industry for his own venture, Funboat Games.
Read more about Avisekhar Roy

Right arrow

Chapter 5. Understanding the Game Loop and Frame Rate

The game loop is the operational body of a game, and the frame rate is the consequence. A game cannot be made without a defined game loop, and the performance cannot be judged without measuring the frame rate.

These two aspects of game development are common throughout any game development project. However, the scalability and nature of the game loop vary across different devices, and there might be different scales to measure frame rates across different platforms.

For native development, the game loop is created and maintained by developers only. However, in most game engines, the loop is already defined with all the necessary controls and scope.

We will have a detailed look at these two most important parts of game development through the following topics:

  • Introduction to the game loop

  • Creating a sample game loop using the Android SDK

  • Game life cycle

  • Game update and user interface

  • Interrupt handling

  • General idea of a game state machine

  • The FPS...

Introduction to the game loop


The game loop is the core cycle in which user input, game update, and rendering are executed sequentially. This loop ideally runs once per frame. So, the game loop is the most important part of running a game with frame rate control.

A typical game loop has three steps:

  1. User input

  2. Game update

  3. Rendering

    A simple game loop

User input

This section checks the UI system of the game for any external input that has been given to the game. It sets the required changes to be made in the game for the next update. On a different hardware platform, this portion of the game loop varies the most. It is always a best practice to create common functionality for different input types to make a standard.

The input system is not considered as part of the game loop; however, user-given input detection is part of the game loop. This system continuously monitors the input system, whether an event has occurred or not.

A user can trigger any event at any point of time during gameplay when an...

Creating a sample game loop using the Android SDK


Android SDK development starts with an activity, and the game runs on single or multiple views. Most of the time, it is considered to have a single view to run gameplay.

Unfortunately, the Android SDK does not provide a predefined game loop. However, the loop can be created in many ways, but the basic mechanism remains the same.

In the Android SDK library, the View class contains an abstract method OnDraw() in which every possible rendering call is queued. This method is called upon any change in the drawing, which invalidates the previous rendering pipeline.

The logic is as follows:

Let's have a look at a basic game loop created with Android View. Here, a custom view is extended from the Android View:

/*Sample Loop created within OnDraw()on Canvas 
* This loop works with 2D android game development
*/
@Override
public void onDraw(Canvas canvas)
{
  //If the game loop is active then only update and render
  if(gameRunning)
  {
    //update game...

Game life cycle


The Android game life cycle is almost similar to any other application's life cycle, other than the game loop mechanism. Mostly, the application state changes with external interference. States can be manipulated otherwise, where games have algorithms or artificial intelligence that is capable of interfering with the main game cycle.

An Android game is initialized with an activity. The onCreate() method is used for initialization. Then, the game thread starts and enters the game loop. The game loop can then be interrupted by an external interrupt.

In the case of game development, it is always a good practice to save the current game state and pause the loop and threads properly. On resuming the game, it should be easy to return to the last state.

Game update and user interface


We have already covered a few update and interface mechanisms previously. A running game state can be changed by user input or internal AI algorithms:

Mostly, game update is called once per frame or once after a fixed time interval. Either way, an algorithm does its job to change the game state. You have learned about user input queues. On each game loop cycle, the input queues are being checked.

For example, a mobile game loop with a touch interface works as follows:

/* import proper view and implement touch listener */
public class MyGameView extends View implements View.OnTouchListener
/* declare game state */
private MyGameState gameState;
/* set listener */
public MyGameView (Context context)
{
  super(context);
  setOnTouchListener(this);
  setFocusableInTouchMode(true);
  gameState = new MyGameState();
}

/* override onTouch() and call state update on individual touch events */
@Override
public boolean onTouch(View v, MotionEvent event) 
{
  if(event.getAction...

Interrupt handling


The game loop is a continuous process. Whenever an interrupt occurs, it is necessary to pause every running thread and save the current state of the game to ensure that it resumes properly.

In Android, any interrupt triggers from onPause():

@Override
protected void onPause() 
{
  super.onPause();
  // pause and save game loop here
}
// When control is given back to application, then onResume() is // called.
@Override
protected void onResume() 
{
  super.onResume();
  //resume the game loop here
}

Now, we need to change the class where the actual game loop is running.

First, declare a Boolean to indicate whether the game is paused or not. Then, put a check in the game loop. After that, create a static method to deal with this variable:

private static boolean gamePaused = false;
@Override
public void onDraw(Canvas canvas)
{
  if(gameRunning && ! gamePaused)
  {
    MainGameUpdate();
    RenderFrame(canvas);
    
    invalidate();
  }
  else if(! gamePaused)
  {
    /...

General idea of a game state machine


A game state machine runs within the update cycle of the game loop. A game state machine is the mechanism of binding all the game states together. In old techniques, this was a typical linear control flow. However, in modern development processes, it can be parallel control running in multiple threads. In the old architecture of game development, it was encouraged to have only one game thread. Developers used to avoid parallel processing as it was vulnerable to game loop and timer management. However, even in modern development, many developers still prefer to use a single thread for game development whenever possible. With the help of various tools and advanced scripting language, most game developers now use a virtual parallel processing system.

One of the processes of a simple game state machine is to create a common state interface and override it for each game state. In this way, it becomes easy to manage the state inside the game loop.

Let's see a...

The FPS system


In the case of game development and gaming industry, FPS matters a lot. The game quality measurement depends heavily on the FPS count. In simple words, the higher the FPS of the game, the better. The FPS of a game is dependent on the processing time for instructions and rendering.

It takes some time to execute the game loop once. Let's have a look at a sample implementation of FPS management inside a game loop:

long startTime;
long endTime;
public final int TARGET_FPS = 60;

@Override
public void onDraw(Canvas canvas)
{
  if(isRunning)
  {
    startTime = System.currentTimeMillis();
    //update and paint in game cycle
    MainGameUpdate();

    //set rendering pipeline for updated game state
    RenderFrame(canvas);

    endTime = System.currentTimeMillis();
    long delta = endTime - startTime;
    long interval = (1000 - delta)/TARGET_FPS;
      
    try
    {
      Thread.sleep(interval);
    }
    catch(Exception ex)
    {}
    invalidate();
  }
}

In the preceding example...

Hardware dependency


We have discussed earlier that hardware configuration plays a major role in the FPS system. If the hardware is not capable of running a certain set of instructions with a certain frequency, then it is not possible for any developer to run a game on the target FPS.

Let's list the tasks that take most of the processing time for a game:

  • Display or rendering

  • Memory load/unload operations

  • Logical operations

Display or rendering

Display processing depends mostly on the graphics processor and what all needs to be displayed. When it comes to interaction with the hardware, the process becomes slow. Rendering each and every pixel with shader manipulation and mapping takes time.

There were times when running a game with a frame rate of 12 was difficult. However, in the modern world, a superb display quality game needs to be run on a frame rate of 60. It is only a matter of hardware quality.

A large display requires a good amount of cache memory. So, for example, hardware with a large and...

Balance between performance and memory


As you learned earlier, memory operation takes a lot time. However, developers always have a limited memory. So, it is extremely necessary to have a balance between performance and memory.

Loading or unloading any asset from ROM to RAM takes time, so it is recommended that you do not do such operations for games that depend on FPS. This operation affects FPS significantly.

Suppose a game requires a lot of assets while running one game state and the target device has a limited heap available. In such a case, the developer should group assets. Small assets can be loaded in the game running the state only in required cases.

Sometimes, many developers preload all the assets and use it from cache. This approach makes the gameplay smoother and faster. However, loading assets in a cache that is not required for that particular game state may crash the game if an interrupt occurs. The Android OS is fully authorized to clear memory occupied by inactive or minimized...

Controlling FPS


We have already seen some ways of defining the FPS system. We have already discussed the major drawback of the system as well. So, we can manipulate the game loop according to the real-time FPS generated in the current game loop cycle:

long startTime;
long endTime;
public static in ACTUAL_FPS = 0;

@Override
public void onDraw(Canvas canvas)
{
  if(isRunning)
  {
    startTime = System.currentTimeMillis();
    //update and paint in game cycle
    MainGameUpdate();

    //set rendering pipeline for updated game state
    RenderFrame(canvas);

    endTime = System.currentTimeMillis();
    long delta = endTime - startTime;
    ACTUAL_FPS = 1000 / delta;
    invalidate();
  }
}

Now, let's have a look at the hybrid FPS system where we cap the maximum FPS to 60. Otherwise, the game can be manipulated through actual FPS:

long startTime;
long endTime;
public final int TARGET_FPS = 60;
public static int ACTUAL_FPS = 0;

@Override
public void onDraw(Canvas canvas)
{
  if(isRunning)
 ...

Summary


The game loop is mainly a logical approach for game development. In many cases, developers do not opt for such a mechanism. Some games may be typically interactive and have no algorithm that runs continuously. In such cases, the game loop may not be needed. Game states can be updated as per input given to the gaming system.

However, an exception cannot be an example. That is why it is an industrial approach to follow a game loop to maintain a development standard irrespective of game design.

You learned about the game loop and game state management here. Developers are free to invent and execute game loops in different ways. There are many game engines that have different ways to control game loop and manage game states. The idea and concept of game loop and state management may change as per the game requirement.

However, developers should always keep in mind that the technique they are using should not affect the game performance and FPS. Besides that, developers need to maintain...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
The Android Game Developer???s Handbook
Published in: Aug 2016Publisher: PacktISBN-13: 9781785885860
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Avisekhar Roy

Avisekhar Roy is a B.Tech engineer in computer science. He has had a passion for coding since his school days. However, he had no plans to become a game programmer. His fate landed him in the gaming industry in 2010. Since then, he fell in love with game development. Avisekhar has worked in many formats of game development environment, ranging from small companies and individual studios to corporate companies and full-scale game development studios. He recently started his own gaming start-up in 2016 and is currently working on games for the mobile platform. Avisekhar has also worked with some big companies, such as Reliance Games in India, as well as a small-scale studio called Nautilus Mobile. He is now trying to acquire a position in the gaming industry for his own venture, Funboat Games.
Read more about Avisekhar Roy