AI for Games, Third Edition Ian Millington

AI for Games, Third Edition Ian Millington
Item# 000

Description

CHAPTER 2 GAME AI

BEFORE going into detail with particular techniques and algorithms, it is worth spending a little time thinking about what we need from our game’s AI. This chapter looks at the high-level issues around game AI: what kinds of approaches work, what they need to take account of, and how they can all be put together.

2.1 THE COMPLEXITY FALLACY

It is a common mistake to think that the more complex the AI in a game, the better the characters will look to the player. Creating good AI is all about matching the requirements of the game to the right behaviors and the right algorithms to produce them. There is a bewildering array of techniques in this book, and the right one isn’t always the most obvious choice.

Countless examples of difficult to implement, complex AI have resulted in poor, or even stupid looking behavior. Equally, a very simple technique can be perfect, when used well.

2.1.1 WHEN SIMPLE THINGS LOOK GOOD

In the last chapter I mentioned Pac-Man [140], one of the first games with any form of character AI. The AI has three states: one normal state when the player is collecting pips; a second state when the player has eaten the power-up and is out for revenge; and a final state that triggers at timed intervals, to have the ghosts back off a little.

In all three states, each of the four ghosts has a target. It moves in a straight line until it reaches a junction, then chooses whichever route is closest to the direction of its target. It doesn’t attempt to plan the entire route, or even check its target can be reached, it just moves toward it. In their chasing state, when hunting the player, each ghost has its own simple snippet of code to choose a target. Blinky (the red ghost) always targets the player position. Pinky (the pink one, obviously) targets a square four spaces in front of the player, even if that is inside or on the other side of a wall. Inky (light blue) uses a modified offset of its own and the player’s position. Clyde (orange) targets the player if they are far away, or the corner of the board if close. All these targeting routines can be implemented in a line or two of code.

This is about as simple as you can imagine an AI for a moving character. Any simpler and the ghosts would be either very predictable (if they always homed in) or purely random. On their own, the ghosts strategy can be easily predicted; their AI does not pose a challenge. But together, the different behaviors of each ghost are enough to make a significant opposing force—so much so that the AI to this day gets flattering comments. For example, this comment recently appeared on a website: “To give the game some tension, some clever AI was programmed into the game. The ghosts would group up, attack the player, then disperse. Each ghost had its own AI.”

Other players have reported strategies among the ghosts: “The four of them are programmed to set a trap, with Blinky leading the player into an ambush where the other three lie in wait.”

A simple AI, done well, can appear to a player to be much more intelligent than it is.

The same thing has been reported by many other developers on own their games. As an extreme example: a few years ago Chris Kingsley of Rebellion mentioned an unpublished Nintendo Game Boy title in which particular enemy characters simply home in on the player, but for variation, sidestep at random intervals as they move forward. Players reported that these characters ‘anticipated’ their firing patterns and dodged out of the way.

The AI wasn’t anticipating anything, and only managed to dodge by coincidence some of the time. But a timely sidestep at a crucial moment stayed in the player’s mind and shaped their perception of the AI.

2.1.2 WHEN COMPLEX THINGS LOOK BAD

Of course, the opposite thing can easily happen. A game that I looked forward to immensely was Herdy Gerdy [97], one of the launch games Sony used to tout the new gameplay possibilities of the ‘emotion engine’ chip in their PlayStation 2 hardware. The game is a herding game. An ecosystem of characters is present in the game level. The player has to herd individuals of different species into their corresponding pens. Herding had been used before and has since as a component of a bigger game, but in Herdy Gerdy it constituted all of the gameplay. There is a section on AI for this kind of game in Chapter 15.

Unfortunately, the characters’ movement AI was not quite up to the challenge of its rich level design. It was easy to get them caught on the scenery, and their collision detection could leave them stuck in irretrievable places. This would be frustrating (though not uncommon) in any game. But it interacted with the herding AI in a way that made some characters appear unexpectedly unintelligent. Reviews were mixed, and sales lackluster.

Unlike Herdy Gerdy, Black & White [131] achieved significant sales success. But at places it also suffered from great AI looking bad. The game involves teaching a character what to do by a combination of example and feedback. When people first play through the game, they often end up inadvertently teaching the creature bad habits, and in the worst cases it may become unable to carry out even the most basic actions. By paying more attention to how the creature’s AI works, players are able to manipulate it better, but the illusion of teaching a real creature can be gone.

Most of the complex things I’ve seen that looked bad never made it to the final game. It is a perennial temptation for developers to use the latest techniques and the most hyped algorithms to implement their character AI. Late in development, when a learning AI still can’t learn how to steer a car around a track without driving off at every corner, simpler algorithms come to the rescue and make it into the game’s release.

Knowing when to be complex and when to stay simple is the most difficult element of the game AI programmer’s art. The best AI programmers are those who can use a very simple technique to give the illusion of complexity.

This is easier when there is a tight feedback loop between implementation and game design. A slight modification to the requirements can mean a better AI technique can be used, which leads to a better game. Sometimes this means making the required behavior simpler, to make it much more robust. Unfortunately, with the large team sizes on mass-market PC and console games, it is difficult for a programmer to have much influence. Indie and mobile games, whose teams are much smaller, though not as small as they were a few years ago, still have more opportunity.

2.1.3 THE PERCEPTION WINDOW

Unless your AI is controlling an ever-present sidekick or a one-on-one enemy, chances are your player will only come across a character for a short time.

This can be a significantly short time for disposable guards whose life purpose is to be shot. More difficult enemies can be on-screen for a few minutes as their downfall is plotted and executed.

When we seek to understand someone in real life, we naturally put ourselves into their shoes. We look at their surroundings, the information they are gleaning from their environment, and the actions they are carrying out. The same happens with game characters. A guard standing in a dark room hears a noise: “I’d flick the light switch,” we think. If the guard doesn’t do that, we might assume they are stupid.

If we only catch a glimpse of someone for a short while, we don’t have enough time to understand their situation. If we see a guard who has heard a noise suddenly turn away and move slowly in the opposite direction, we assume the AI is faulty. The guard should have moved across the room toward the noise. If we observed them for longer to see the guard head over to a light switch by the exit, their action would be understandable. Then again, the guard might not flick on the light switch after all, and we might take that as a sign of poor implementation. But the guard may know that the light is inoperable, or they may have been waiting for a colleague to slip some cigarettes under the door and thought the noise was a predefined signal. If we knew all that, we’d know the action was intelligent after all.

This no-win situation is the perception window. You need to make sure that a character’s AI matches its purpose in the game and the attention it will get from the player. Adding more AI to incidental characters might endear you to the rare gamer who spends hours analyzing each level, checking for curious behavior or bugs, but everyone else (including the publisher and the press) may think your programming was sloppy.

2.1.4 CHANGES OF BEHAVIOR

The perception window isn’t only about time. Think about the ghosts in Pac-Man again. They might not give the impression of sentience, but they don’t do anything out of place. This is because they rarely change behavior (the most noticeable is their transformation when the player eats a power-up).

Whenever a character in a game changes behavior, the change is far more conspicuous than the behavior itself. In the same way, when a character’s behavior should obviously change and doesn’t, it draws attention. If two guards are standing talking to each other and you shoot one down, the other guard shouldn’t carry on the conversation!

A change in behavior almost always occurs when the player is nearby or has been spotted. This is the same in platform games as it is in real-time strategy. A good solution is to keep only two behaviors for incidental characters—a normal action and a player-spotted action.

2.2 THE KIND OF AI IN GAMES

Games have always come under criticism for being poorly programmed, in a software engineering sense: they use tricks, arcane optimizations, and unproven technologies to get extra speed or neat effects. Though game engines may be reused, gameplay code usually isn’t (or at least isn’t written with that in mind) and strong time pressures mean programmers often do whatever they need to get the game done. Game AI is no different.

There is a big gulf between what qualifies as AI in games (i.e. what is the responsibility of an AI programmer) and what the rest of the programming industry or academia considers to be AI.

In my experience, AI for a game is equal parts hacking (ad hoc solutions and neat effects), heuristics (rules of thumb that only work in most, but not all, cases), and algorithms (the “proper” stuff). Most of this book is aimed at the last group, because those are the techniques we can generalize, examine analytically, use in multiple games, and build into an AI engine.

But ad hoc solutions and heuristics are just as important and can breathe as much life into characters as the most complicated algorithm.

2.2.1 HACKS

There’s a saying that goes “If it looks like a fish and swims like a fish, it’s probably a fish.” We understand a behavior by replicating it to a sufficient accuracy.

As a psychological approach it has some pedigree (it is related to the behaviorist school of psychology) but has been largely superseded. This fall from fashion has influenced psychological approaches to AI, as well. At one point it was quite acceptable to learn about human intelligence by making a machine to replicate it, but now that is considered poor science. And with good reason; after all, building a machine to play skillful Chess involves algorithms that evaluate millions of board positions. Human beings are simply not capable of this.

On the other hand, as AI engineers, we are not paid to be interested in the nature of reality or mind; we want characters that look right. In most cases, this means starting from human behaviors and trying to work out the easiest way to implement them in software.

Good AI in games usually works in this direction. Developers rarely build a great new algorithm and then ask themselves, “so what can I do with this?” Instead, you start with a design for a character and apply the most relevant tool to get the result.

This means that what qualifies as game AI may be unrecognizable as an AI technique. A simple random number generator applied judiciously can produce a lot of of believability. Generating a random number isn’t an AI technique as such. In most languages there are builtin functions to get a random number, so there is certainly no point giving an algorithm for it! But it can work in a surprising number of situations.

Another good example of creative AI development is The Sims [136]. While there are reasonably complicated things going on under the surface, a lot of the character behavior is communicated with animation. Remove the character animation, and the AI would look far less impressive. In Star Wars: Episode 1 – Racer [133], characters who are annoyed gave a little sideswipe to other characters. Quake II [123] introduced the “gesture” command, now used in a vast range of first person games, where characters (and players) can flip their enemy off. All these require no significant AI infrastructure. They don’t need complicated cognitive models, learning, or neural networks. They just need a few lines of code that schedule an animation at the appropriate time.

Always be on the lookout for simple things that can give the illusion of intelligence. If you want engaging emotional characters, is it possible to add a couple of emotion animations (a frustrated rub of the temple, perhaps, or a stamp of the foot) to your game? Triggering these in the right place is much easier than trying to represent the character’s emotional state through their actions. Do you have a portfolio of behaviors that the character will choose from? Will the choice involve complex weighing of many factors? If so, it might be worth trying a version of the AI that picks a behavior purely at random (maybe with different probabilities for each behavior). You might be able to tell the difference, but your customers may not; so try it out before you code the complex version.

2.2.2 HEURISTICS

A heuristic is a rule of thumb, an approximate solution that might work in many situations but is unlikely to work in all.

Human beings use heuristics all the time. We don’t try to work out all the consequences of our actions. Instead, we rely on general principles that we’ve found to work in the past (or that we have been taught or even brainwashed with, equally). It might range from something as simple as “if you lose something then retrace your steps to look for it” to heuristics that govern our life choices, such as “never trust a used-car salesman.”

Heuristics have been codified and incorporated into some of the algorithms in this book, and saying “heuristic” to an AI programmer often conjures up images of pathfinding or goal- oriented behaviors. Beyond these, many of the techniques in this book rely on heuristics that may not always be explicit. There is a trade-off between speed and accuracy in areas such as decision making, movement, and tactical thinking (including board game AI). When accuracy is sacrificed, it is usually by replacing search for a correct answer with a heuristic.

A wide range of heuristics can be applied to general AI problems that don’t require a particular algorithm.

In our perennial Pac-Man example, the ghosts move by taking the route at a junction that leads toward their current target. They don’t attempt to calculate the best route: either the shortest or fastest. That might be quite complex and involve turning back on oneself, and it might be ultimately redundant as the position of the player continues to change. But the rule of thumb (move in the current direction of the target) works most of the time and provides sufficient competence for the player to understand that the ghosts aren’t purely random in their motion.

In Warcraft [85] (and many other RTS games that followed) there is a heuristic that moves a character forward slightly so they can engage an enemy standing a fraction beyond the character’s reach. While this worked in most cases, it wasn’t always the best option. Many players got frustrated as comprehensive defensive structures went walkabout when enemies came close. Later, RTS games allowed the player to choose whether this behavior was switched on or not.

In many strategic games, including board games, different units or pieces are given a single numeric value to represent how “good” they are. In Chess, pawns are often given one point, bishops and knights three, rooks five, and the queen eight. This is a heuristic; it replaces complex calculations about the capabilities of a unit with a single number. And the number can be defined by the programmer in advance. The AI can work out which side is ahead simply by adding the numbers. In an RTS it can find the best value offensive unit to build by comparing the number with the cost. A lot of useful effects can be achieved just by manipulating the number.

There isn’t an algorithm or a technique for this. And you won’t find it in published AI research. But it is the bread and butter of an AI programmer’s job.

Common Heuristics

A handful of heuristics appear over and over. They are good starting points when initially tackling a problem.

Most Constrained

Given the current state of the world, one item in a set needs to be chosen. The item chosen should be the one that would be an option for the fewest number of states.

For example, a squad of characters engages a group of enemies. One of the enemies is wearing a type of armor that only one rifle can penetrate. One squad member has this rifle. When they select who to attack, the most constrained heuristic comes into play; only one squad member can attack this enemy, so that is the action that they should take. Even if their weapon would be more powerful against different enemy, their squad mates should handle the others.

Do the Most Difficult Thing First

The hardest thing to do often has implications for lots of other actions. It is better to do this first, rather than find that the easy stuff goes well but is ultimately wasted.

For example, an army has two squads with empty slots. The computer schedules the creation of five Orc warriors and a huge Stone Troll. It wants to end up with balanced squads. How should it assign the units to squads? The Stone Troll requires the most slots, so is the hardest to assign. It should be placed first.

If the Orcs were assigned first, they would be balanced between the two squads, leaving room for half a Troll in each squad, but nowhere for the Troll to go.

Try the Most Promising Thing First

If there are a number of options open to the AI, it is often possible to give each one a really rough-and-ready score. Even if this score is dramatically inaccurate, trying the options in decreasing score order will provide better performance than trying things purely at random.

2.2.3 ALGORITHMS

And so we come to the final third of the AI programmer’s job: building algorithms to support interesting character behavior. Hacks and heuristics will get you a long way, but relying on them solely means you’ll have to constantly reinvent the wheel. General bits of AI, such as movement, decision making, and tactical thinking all benefit from tried and tested methods that can be endlessly reused.

This book is about these kinds of technique, and the next few chapters introduces a large number of them. Just remember that for every situation where a complex algorithm is the best way to go, there are likely to be several more where a simpler hack or heuristic will get the job done.

2.3 SPEED AND MEMORY CONSTRAINTS

The biggest constraint on the AI developer’s job is the physical limitations of the machine. Game AI doesn’t have the luxury of days of processing time and terabytes of memory. We don’t even have the luxury of using all the processor and memory of the computer the game is running on. Other tasks need space and time, such as graphics, sound, networking, and input. In teams where different groups of developers have to work on their specialties in parallel, a speed and memory budget will be set.

One of the reasons AI techniques from academia or commercial research don’t achieve widespread use is their processing time or memory requirements. An algorithm that might be compelling in a simple demo can slow a production game to a standstill.

This section looks at low-level hardware issues related to the design and construction of AI code. Most of what is contained here is general advice for all game code. If you’re up to date with current game programming issues and just want to get to the AI, you can safely skip this section.

2.3.1 PROCESSOR ISSUES

The most obvious limitation on the efficiency of a game is the speed of the processor on which it is running. Originally all the games machines had a single main processor, which was also responsible for graphics. Most game hardware now has several CPUs (several processing cores on the same piece of silicon, usually), and dedicated GPUs for processing graphics.

As a general rule, CPUs are faster and more flexible, where a GPU is more parallel. When the task can be split up into many simple subtasks, all running at the same time, the tens up to thousands of processing cores on a GPU can be orders of magnitude faster than the same task running sequentially on the CPU.

Graphics card drivers used to have ‘fixed function’ pipelines, where the graphics code was built into the driver, and could only be tweaked within narrow parameters. It was impossible to do very much other than graphics on the graphics card. Now drivers support technologies such as Vulkan, DirectX 11, CUDA, and OpenCL, which allow general-purpose code to be executed on the GPU. As a result, more functionality has been moved to the GPU, freeing up more processing power on the CPU.

The share of the processing time dedicated to AI has grown in fits and starts over the last two decades. In some cases now making up most of the CPU load, with some AI running on the GPU. Along with the increase in processor speeds, this is obviously good news for AI developers wanting to apply more complicated algorithms, particularly to decision making and strategizing. But, while incremental improvements in processor time help unlock new techniques, they don’t solve the underlying problem. Many AI algorithms take a long time to run. A comprehensive pathfinding system can take tens of milliseconds to run per character. Clearly, in an RTS with 1000 characters, there is no chance of running each frame.

Complex AI that does work in games needs to be split into bite-size components that can be distributed over multiple frames. The chapter on resource management shows how to accomplish this. Applying these techniques to many long running AI algorithms can bring them into the realm of practicality.

Low-Level Concerns

One large change in the industry in the last 10 years has been the move away from C++ having a hegemony over game programming. Now, character behavior, game logic, and AI is often written in higher-level languages such as C#, Swift, Java, or even scripting languages. This is significant because these languages provide the programmer less ability to micromanage the performance characteristics of their code. There are AI programmers still working in C++, who still need a good knowledge of the ‘bare metal’ performance characteristics of the processors, but in my recent experience such programmers tend to be low-level specialists working on AI engines: portfolios of functionality designed to be reused in multiple games.

In the first and second edition of this book, I described three low-level issues in detail: SIMD, superscalar architectures, and virtual functions. In this edition I will describe them only briefly. For reasons I will describe below, in my own professional practice, I haven’t been directly concerned with any of these for several years.

SIMD (single instruction, multiple data) are a set of registers on modern hardware large enough to fit several floating point numbers. Mathematical operators can be applied to these registers, which has the effect of running the same code against multiple pieces of data in parallel. This can dramatically speed up some code, particularly geometric reasoning. Although CPUs have dedicated registers for SIMD, they provide the best speed up on code that tends to suit the GPU. Optimizing for SIMD on the CPU is often redundant, when the code can be moved onto the GPU.

Superscalar CPUs have several execution paths active at the same time. Code is split among the parts to execute in parallel and the results are then recombined into the final result. When the result of one pipeline depends on another, this can involve either waiting, or guessing what the result might be and redoing the work if it proves to be wrong (known as branch prediction). In the last decade, multi-core CPUs, where several independent CPUs allow different threads to run in parallel, have become almost ubiquitous. Although each core may still be superscalar, this is now largely treated as a behind-the-scenes detail, irrelevant to AI programmers. Better speed ups can be attained by concentrating on making AI code parallelizable, rather than worrying about the details of branch prediction.

AI code can take advantage of this parallelism by either running AI for different characters in different threads, or by running all AI in a different thread to other game systems. These threads will then be executed in parallel on different cores, when available. Multiple threads doing the same thing (such as one character running its AI in each thread) is often more performant, as it is easier to make sure all processors are being used to the same capacity, and more flexible, as it scales without rebalancing to hardware with a different number of cores.

When AI routinely had to be careful of every single CPU cycle used, it was common to avoid virtual classes in C++, with their virtual function call overhead. This meant avoiding object-oriented polymorphism, whenever possible. A virtual function call stores the memory location in which the function is implemented in a variable (in a structure called a function table, or vtable). Calling a function therefore involves looking up the variable at runtime, and then looking up the location that variable specifies. Though this extra look-up uses a trivial amount of time, it could interact significantly with the branch predictor and processor cache. For this reason virtual functions, and hence polymorphism, had a bad reputation. A reputation that has largely faded in the past 10 years. The code in this book has always been written in a polymorphic style. Now, game engines such as Unity, Unreal, Lumberyard, and Godot assume that game logic will be polymorphic.

2.3.2 MEMORY CONCERNS

Most AI algorithms do not require a large amount of RAM, often just a few, up to tens of megabytes. This small storage requirement, easily achievable on modest mobile devices, is ample for heavyweight algorithms such as terrain analysis and pathfinding. Massively multi-player online games (MMOGs) typically require much more storage for their larger worlds, but are run on server farms where sufficient memory can be installed (even then, we are only talking gigabytes of RAM, rarely more). Huge worlds are usually sharded into separate sections, or else characters are limited to certain areas, further reducing the AI memory requirements.

So it is not the amount of memory which is usually the limiting factor, but the way it is used. Allocation, and cache coherence are both memory concerns that affect performance. They can both influence the implementation of an AI algorithm.

Allocation and Garbage Collection

Allocation is the process of asking for memory in which to place data. When that memory is no longer needed it is said to be freed or deallocated. Allocation and deallocation are relatively fast, as long as memory is available.

Low-level languages such as C require the programmer to free memory manually. Languages such as C++ and Swift, when memory is allocated for a particular object, provide ‘reference counting.’ This stores the number of places that know about the existence of the object. When the object is no longer referenced, the counter drops to 0, and the memory is freed. Unfortunately, both these approaches can mean that memory that should be freed is never freed. Either the programmer forgets to free manually, or there is a circular set of references, such that their counters never drop to 0. Many higher-level languages implement sophisticated algorithms to collect this ‘garbage’, i.e., free memory that is no longer useful. Unfortunately garbage collection can be expensive. In languages such as C#, particularly in the mono runtime that runs the Unity game engine, garbage collection can be slow enough to delay a rendering frame, causing a visual stutter. This is unacceptable to most developers.

As a result, implementing AI algorithms for higher-level languages often involves trying not to allocate and deallocate objects while a level is running. The data required for the entire level is reserved when the level begins, and only released when the level ends. Several of the algorithms in this book assume that new objects can be created at any time, and will be left to disappear when no longer needed. On a platform with time-consuming garbage collection, it may be important to modify these implementations. For example: several of the pathfinding algorithms (in Chapter 4) create and store data for each location in the map, when that location is first considered. When the path is complete, none of the intermediate location data are needed. A garbage-collection-friendly implementation might create a single pathfinding object, containing data for every location in the map. That same object is called whenever pathfinding is required, and it uses the preallocated location data it needs and ignores the rest. On its own, this implementation will be a little more complicated, and could be considerably more complex if multiple characters who need pathfinding must queue to use the one pathfinding object. To avoid complicating the underlying algorithm this book presents them in their simplest form: without regard for allocation.

Cache

Memory size alone isn’t the only limitation on memory use. The time it takes to access memory from the RAM and prepare it for use by the processor is significantly longer than the time it takes for the processor to perform its operations. If processors had to rely on the main RAM, they’d be constantly stalled waiting for data.

All modern processors use at least one level of cache: a copy of the RAM held in the processor that can be very quickly manipulated. Cache is typically fetched in pages; a whole section of main memory is streamed to the processor. It can then be manipulated at will. When the processor has done its work, the cached memory is sent back to the main memory. The processor typically cannot work on the main memory: all the memory it needs must be on cache. An operating system may add additional complexity to this, as a memory request may have to pass through an operating system routine that translates the request into a request for real or virtual memory. This can introduce further constraints, as two bits of physical memory with a similar mapped address might not be available at the same time (called an aliasing failure).

Multiple levels of cache work the same way as a single cache. A large amount of memory is fetched to the lowest level cache, a subset of that is fetched to each higher level cache, and the processor only ever works on the highest level.

If an algorithm uses data spread around memory, then it is unlikely that the right memory will be in the cache from moment to moment. These cache misses are costly in time. The processor has to fetch a whole new chunk of memory into the cache for one or two instructions, then it has to stream it all back out and request another block. A good profiling system will show when cache misses are happening. In my experience, even in languages that don’t give you control over memory layout, dramatic speed ups can be achieved by making sure that all the data needed for one algorithm are kept in the same place, in the same few objects.

In this book, for ease of understanding, I’ve used an object-oriented style to lay out the data. All the data for a particular game object are kept together. This may not be the most cache-efficient solution. In a game with 1000 characters, it may be better to keep all their positions together in an array, so algorithms that make calculations based on location don’t need to constantly jump around memory. As with all optimizations, profiling is everything, but a general level of efficiency can be gained by programming with data coherence in mind.

2.3.3 PLATFORMS

With the centralization of the industry around a few game engines, platform differences have less of an impact on AI design than they used to. Graphics programmers may still have to worry about console versus mobile, for example. But AI programming tends to be more general. In this section I will consider each of the major platforms for games, highlighting any issues specific to AI code.

PC

PCs can be the most powerful games machines, with hard-core gamers buying high-end expensive hardware. But they can be frustrating for developers because of their lack of consistency. Where a console has fixed hardware (or at least relatively few variations), there is a bewildering array of different configurations for PCs. There is a vast difference between a machine with a pair of top of the range video cards, SSD drives and fast memory, and a budget PC with integrated graphics.

Things are easier than they were: low-level developers rely on application programming interfaces (APIs) such as Vulkan and DirectX to insulate them from most hardware specifics, but the game still needs to detect feature support and speed and adjust accordingly. Developers working in an engine such as Unity and Unreal have it even easier, but may still need to use the built-in feature detection to ensure their game runs well on all systems.

Working with PCs involves building software that can scale from a casual gamer’s limited system to the hard-core fan’s up-to-date hardware. For graphics, this scaling can be reasonably modular; for example, for low-specification machines we switch off advanced rendering features. A simpler shadow algorithm might be used, or physically based shaders might be replaced by simple texture mapping. A change in graphics sophistication usually doesn’t change gameplay.

AI is different. If the AI gets less time to work, how should it respond? It can try to perform less work. This is effectively the same as having more stupid AI, and can affect the difficulty level of the game. It is probably not acceptable to have your game be easier on lower specification machines. Similarly, if we try to perform the same amount of work, it might take longer. This can mean a lower frame rate, or it can mean more frames between characters making decisions. Slow-to-react characters are also often easier to play against and can cause the same problems with QA.

The solution used by most developers is to target AI at the lowest common denominator: the minimum specification machine listed in the technical design document. The AI time doesn’t scale at all with the capabilities of the machine. Faster machines simply use proportionally less of their processing budget on AI.

There are many games, however, where scalable AI is feasible. Many games use AI to control ambient characters: pedestrians walking along the sidewalk, members of the crowd cheering a race, or flocks of birds swarming in the sky. This kind of AI is freely scalable: more characters can be used when the processor time is available. Chapter 10 covers some techniques for level of detail AI that can cope with this scalability.

Console

Consoles can be simpler to work with than a PC. You know exactly the machine you are targeting, and you can usually see code in operation on your target machine. There is no future proofing for new hardware or ever-changing versions of APIs to worry about.

Developers working with next-generation technology often don’t have the exact specs of the final machine or a reliable hardware platform (initial development kits are often little more than a dedicated emulator), but most console development has a fairly fixed target.

The technical requirements checklist (TRC) process, by which a console manufacturer places minimum standards on the operation of a game, serves to fix things like frame rates (although different territories may vary—PAL and NTSC, for example). This means that AI budgets can be locked down in terms of a fixed number of milliseconds. In turn, this makes it much easier to work out what algorithms can be used and to have a fixed target for optimization (provided that the budget isn’t slashed at the last milestone to make way for the latest graphics technique used in a competitor’s game).

The same game engines used for PC development target consoles, making cross-platform development much easier than it has been in the past. Fortunately few AI developers creating games are now working with the low-level details of a particular console. Almost all the lowlevel code is handled by engines or middleware.

Mobile

Apple launched the iPhone in 2007, ushering in a revolution in gaming as big as anything since the home consoles of the 80s. When the first edition of this book was released, in 2006, mobile gaming consisted of dedicated handheld consoles like the PlayStation Portable (PSP) and Nintendo’s GameBoy advance. Now almost 100% of the market is for phones and tablets.

There are two platforms in the space: Apple, with its iOS devices (iPhone, iPad, iPod Touch), and Android. Until recently these were very different, and required games to be coded for each individually. Although both can use low-level languages such as C and C++, for higher-level languages Apple encourages the use of Swift (it formerly used Objective-C), and Android Java (or languages that compile into Java bytecode, such as Kotlin).

Both the major game engines by market share (Unreal and Unity), as well as many smaller competitors (e.g. Godot) support mobile platforms with the same game code, making platform-specific implementation unnecessary. There has been a big shift toward mobile developers working in a cross-platform way, using these tools. Factoring in the Steam platform as a viable marketplace for mobile games running on PC, I think there is no doubt this trend will soon become almost ubiquitous.

Smartphones capable of running games are powerful machines, comparable to last generation consoles, and PCs 5-10 old. There is no longer any practical difference between the kinds of AI that can be run on a PC or console and those that can be run on mobile. Phones may require simpler graphics or smaller crowd sizes, but in terms of algorithms, the same things now apply.

Virtual and Augmented Reality

At the time of writing, in early 2019, virtual and augmented reality are both extremely hyped, and a tiny proportion of the games market. The technology and the market is in rapid flux, and beyond generalities, very little that could be said now would be true in two years.

Virtual reality (VR) attempts to immerse the player in the game world by providing a stereoscopic 3D point of view. Depending on the hardware, a player’s motion may also be detected and incorporated as movement in the game. VR requires separate views of the scene to be rendered for each eye, and to avoid motion sickness, higher frame rates are typically targeted (90fps, for example).

Up to this point most virtual reality devices have been displays tethered to an existing games machine, such as a PC (Oculus Rift and Vive), a console (PlayStation VR), or a phone (Gear VR). At the time of writing, companies are beginning to release standalone VR Products, based on mobile processors, with approximately similar performance to high-end phones.

Augmented reality (AR) uses semitransparent displays to add computer-generated elements to the real world. Although Microsoft released a development kit in early 2016, a consumer version has not yet followed. Magic Leap released their product in 2018, but saw limited demand. Augmented reality may also refer to games that use a mobile phone camera, and add computer-generated elements to the captured images. In that sense, Pokémon Go [150], for example, is considered an augmented reality game, but does not require specialist hardware.

While the visual presentation of VR games may be unconventional, the game logic rarely is. Most commercial game engines support VR, AR on mobile via camera, and are positioned to offer hardware AR support, when products are announced. VR and AR games are similar enough in design not to need unusual AI algorithms. It remains to be seen whether these platforms open new design possibilities. It also remains to be seen whether these platforms become a significant part of the industry.

2.4 THE AI ENGINE

When I started in the industry, a game was mostly built from scratch. Some bits of code were dragged from previous projects, and some bits were reworked and reused, but most were new. A handful of companies used the same basic code to write multiple games, as long as the games were a similar style and genre. LucasArts’ SCUMM engine, for example, was a gradually evolving game engine used to power many point-and-click adventure games.

Since then, game engines have become ubiquitous, a consistent technical platform on which multiple games are built. Low-level routines (like talking to the operating system, loading textures, model file formats, and so on) are shared among all titles, a set of tools are available for a broad range of games (e.g. 2D graphics, 3D graphics, networking), and finally interfaces are provided to add game-specific code on top. Originally these engines belonged to individual companies, but over time only the very largest companies could afford to keep their engines up-to-date. It is now common for large developers to license commercial engines.

The way AI is developed has changed, also. Initially, the AI was written for each game and sometimes for each character. Now there is an increasing tendency to have general AI routines, either built into the game engine, available to license as commercial add-ons, or created and reused in-house by a developer. This allows individual characters to be designed by level editors, game designers, or technical artists. The engine structure is fixed, and the AI for each character combines the components in an appropriate way. The algorithms described in this book are exposed to non-specialists through graphical front-ends. Dragging boxes and lines allows anyone to create a finite state machine (Section 5.3) or behavior tree (Section 5.4), for example.

So, building a game engine involves building AI tools that can be easily reused, combined, and applied in interesting ways. To support this, we need an AI structure that makes sense over multiple genres.

2.4.1 STRUCTURE OF AN AI ENGINE

In my experience, there are a few basic facilities that need to be in place for a general AI system. They conform to the model of AI given in Figure 2.1.

First, we must have some kind of infrastructure in two categories: a general mechanism for managing AI behaviors (deciding which behavior gets to run when, and so on) and a world interfacing system for getting information into the AI. Every AI algorithm needs to honor these mechanisms.

Second, we must have a means to turn whatever the AI wants to do into action on-screen. This consists of standard interfaces to a movement and an animation controller, which can turn requests such as “pull lever 1” or “walk stealthily to position x, y” into action.

Third, a standard behavior structure must serve as a liaison between the two. It is almost guaranteed that you will need to write one or two AI algorithms for each new game. Having all AI conform to the same structure helps this immensely. New code can be in development while the game is running, and the new AI can simply replace placeholder behaviors when it is ready.

Image

Figure 2.1: The AI model

All this needs to be thought out in advance. The structure needs to be in place before you get well into your AI coding. Part III of this book discusses support technologies, which are the first thing to implement in an AI engine. The individual techniques can then slot in.

Game engines do some of this for you, but not all. Each engine has its own mechanism to make sure your code is run, often in the form of base classes that you should derive from. But you may need to provide more fine-grained control: not every character needs its AI run in every frame. They also provide standard mechanisms for scheduling animations, but less often character movement. And they may provide basic tools for working out which character knows what (such as a built-in line of sight or sight cone check), but will need custom implementations for anything more complex. Unless you intend to use very simple techniques, you will need to create some infrastructure, and possibly some tools in the editor to support it.

I’m not going to emphasize this structure throughout the book. There are techniques that I will cover that can work on their own, and all the algorithms are fairly independent. For a demo, or a simple game, it might be sufficient to just use the technique. But a good AI structure helps promote reuse, and reduces debugging and development time.

2.4.2 TOOL CONCERNS

The complete AI engine will have a central pool of AI algorithms that can be applied to many characters. The definition for a particular character’s AI will therefore consist of data (which may include scripts in some scripting language), rather than compiled code. The data specifies how a character is put together: what techniques will be used and how those techniques are parameterized and combined.

This data needs to come from somewhere. Data can be manually created, but this is no better than writing the AI by hand each time. Flexible tools ensure that the artists and designers can create the content in an easy way, while allowing the content to be inserted into the game without manual help. These are usually created as custom modes in the game engine editor: a tool for setting up character decision making rules, or an overlay onto the level used to mark tactical locations or places to avoid.

The need to expose search tools has its own effect on the choice of AI techniques. It is easy to set up behaviors that always act the same way. Steering behaviors (covered in Chapter 3) are a good example: they tend to be very simple, they are easily parameterized (with the physical capabilities of a character), and they do not change from character to character.

It is more difficult to use behaviors that have lots of conditions, where the character needs to evaluate special cases. Many of those covered in Chapter 5 operate this way. Those based on a tree (decision trees, behavior trees) are easier to represent visually. A rule-based system, on the other hand, needs to have complicated matching rules defined. When these are supported in a tool they typically look like program code, because a programming language is the most natural way to express them.

2.4.3 PUTTING IT ALL TOGETHER

The final structure of the AI engine might look something like Figure 2.2. Data are created in a tool (the modeling or level editor), which is then packaged for use in the game. When a level is loaded, the game AI behaviors are created from level data and registered with the AI engine. During gameplay, the main game code calls the AI engine which updates the behaviors, getting information from the world interface and finally applying their output to the game data.

The particular techniques used depend heavily on the genre of the game being developed. We’ll see a wide range of techniques for many different genres in this book. As you develop your game AI, you’ll need to take a mix and match approach to get the behaviors you are looking for. The final part of the book gives some hints on this; it looks at how the AI for games in the major genres are put together piece by piece.

Image

Figure 2.2: AI schematic