Download - (Original)Terrain Analysis in Computer Games

Transcript
Page 1: (Original)Terrain Analysis in Computer Games

TERRAIN ANALYSIS IN COMPUTER GAMES

Coord. Prof. Dr. Lect. Vlad Radulescu

Asavei Florin, ISS1Cristian Catalin Mihai, ISS2

1

Page 2: (Original)Terrain Analysis in Computer Games

Summary

Introduction … … … … … … … … … … … … ... 31. Terrain representation … … … … … … … … … … … … ... 4

1.1. Tiles … … … … … … … … … … … … ... 41.2. Quadtrees … … … … … … … … … … … … ... 51.3. Waypoints … … … … … … … … … … … … ... 6

2. Pathfinding algorithms … … … … … … … … … … … … ... 72.1. Trial and Error … … … … … … … … … … … … ... 72.2. Contour Tracing … … … … … … … … … … … … ... 82.3. Collision Avoidance Tracks … … … … … … … … … … … … ... 92.4. Waypoint Pathfinding … … … … … … … … … … … … ... 9

3. Real Pathfinding … … … … … … … … … … … … ... 113.1. Breadth-First Search … … … … … … … … … … … … ... 12

3.2. Bidirectional Breadth-First Search … … … … … … … … … … … … ... 123.3. Depth-First Search … … … … … … … … … … … … ... 133.4. A* … … … … … … … … … … … … ... 133.5. Quadtree Search … … … … … … … … … … … … ... 16

4. Dynamic Caching for Path Planning … … … … … … … … … … … … ... 175. Dynamic Terrain Analysis … … … … … … … … … … … … ... 186. Influence Mapping … … … … … … … … … … … … ... 19References … … … … … … … … … … … … ... 22

2

Page 3: (Original)Terrain Analysis in Computer Games

Introduction

The purpose of this work is to illustrate the importance of terrain analysis in computer games. There are a number of methods employed in order to perform such analysis or a combination of them. Each of them are particularly suitable for a certain kind of game, or where a certain genre characteristic is more predominant.

Terrain analysis has a direct impact over the way that CPU AI is taking action, the decisions that the AI part of the game takes are based mostly on the data regarding the game environment. The entire game environment, no matter the complexity form or shape, has some notion of a terrain. Every active or inactive part of the environment, including the player controlled objects, and the computer controlled ones, are subject to a relative position on the terrain, and to one another.

Knowing were is some object in the environment or at what position from a different object it is placed influences the way the game it is played, that kind of knowledge it is achieved trough terrain analysis.

Another part that has a direct connection with terrain analysis is influence mapping, knowing which areas from the game environment to avoid or to pass trough, to find a weak spot in someones defense, or to know the vantage points, such as high ground for a certain type of playing units or the areas that contain a certain amount of a certain resource.

Terrain analysis is influenced by the type of the terrain that it is applied upon, aspects like material and height are influencing the computation of an alternative route to some destination, or taking the decision to attack someone or not to.

Path finding is directly connected to terrain analysis because computations regarding the path to follow towards a certain destination and the cost implied in order to achieve that spot are used in influence mapping, also, influence mapping can alter the path that a unit can take, for example if an area on the map has a high rate of conflict, a worker unit, that has no attack ability will avoid that area, taking a longer and safer path.

These are some of the situations and notions that will be explained in the following sections, and also ways to implement them, compromises that were needed to be made in real games to balance the performance and fun factors.

The main thing is that there is no AI without terrain analysis, these two are tightly connected since the AI part cannot take any decisions if it is not aware about the surrounding environment. Terrain analysis does that for the AI, and figuring out “where you are” in the game takes a lot of computation time because of calculations has to be made at every iteration, because parts of the game can move or be altered, position of some objects can change (opponent players for example), path obstruction, or creation of some new access routes just to name a few.

This paper uses fragments from the works listed under the bibliography, the purpose was to gather all of the scattered information into one place and structure it in order to give the potential reader a kick start overview over what terrain analysis involves. There was no intention to break the intellectual property of any of the sources used here, it's just an academic research paper that tries to shed some light into the more difficult and challenging aspects of game programming.

3

Page 4: (Original)Terrain Analysis in Computer Games

1. Terrain representation

When talking about terrain analysis firstly we must consider the ways in which the terrain is represented. There are more approaches to this problem although any combination of them can be used.

The approach in which the terrain is represented must allow the appliance of path finding algorithms, and the ability to create areas or better said mark some portions of the terrain.

When referring to the terrain it is usually aliased with the term of a map, this is not a comprehensive term, since the map is a representation of an terrain, and the terrain has multiple particularities such as composition, humidity, height, etc. opposed to a map that in the classic term is nothing more than a piece of paper. Since we are talking about a game world and not about the real world, we can consider the map and the terrain one and the same thing, since both in computer games are a representation of the game space, the differences between the notions, if applicable will be pointed out where necessary.

The main logic structures used to give meaning to some regions of the game map, on which a path finding algorithm can be successfully applied are tiles, quad trees and way points.

1.1. Tiles

A tile-based video game is a type of video or computer game where the playing area consists of small rectangular, square, or hexagonal graphic images, referred to as tiles. The complete set of tiles available for use in a playing area is called a tileset. Tiles are laid out adjacent to one another in a grid; usually, some tiles are allowed to overlap, for example, when a tile representing a unit is overlaid onto a tile representing terrain. Tile-based games usually simulate a top-down or "2.5D" view of the playing area, and are almost always two-dimensional.

Tile-based games are not a distinct game genre; rather, the term refers to the technology a game engine uses for its visual representation.

The map is probably the single most important data structure in a game of this type. The map serves as the central repository of nearly all game data and is the primary source of information used by the game logic. The various units, "fog of war", unit AI, and so on, all rely extensively on the map.

The most basic structure of the map is the map cell. A map cell is simply a single map location. The information you store in a map cell depends on the game you're creating, but there are a few common elements. Such common elements include an indicator of the type of map cell (for instance, the terrain), the structure (or structure segment) built on the cell, and a pointer to the first mobile unit on the map.

Once you have your map cell defined, you have to decide how you want to structure the entire map. Here we have to refer back to your game design concept and how you want the finished game to look. There are 3 primary "looks" that are popular: straight overhead, angled isometric, and layered isometric.

The straight overhead map and angled isometric map have the simplest possible scenario: a two-

4

Page 5: (Original)Terrain Analysis in Computer Games

dimensional array of map cells. The layered isometric map can also use a two-dimensional array, but there are several complexities. The biggest difference concerns adjacencies in the map.

Layered isometric maps, however, are significantly more complex. This is because, while the map is still a two dimensional array, the adjacencies work differently because of their on-screen representation. How adjacency is calculated varies according to whether the map cell is on an even-numbered row or an odd-numered row.

1.2. Quadtrees

A quadtree is a tree data structure in which each internal node has exactly four children. Quadtrees are most often used to partition a two dimensional space by recursively subdividing it into four quadrants or regions. The regions may be square or rectangular, or may have arbitrary shapes.

All forms of Quadtrees share some common features:

• They decompose space into adaptable cells ;

• Each cell (or bucket) has a maximum capacity. When maximum capacity is reached, the bucket splits ;

• The tree directory follows the spatial decomposition of the Quadtree.

Quadtrees may be classified according to the type of data they represent, including areas, points, lines and curves. Quadtrees may also be classified by whether the shape of the tree is independent of the order data is processed.

The region quadtree represents a partition of space in two dimensions by decomposing the region into four equal quadrants, subquadrants, and so on with each leaf node containing data corresponding to a specific subregion. Each node in the tree either has exactly four children, or has no children (a leaf node). The region quadtree is not strictly a 'tree' - as the positions of subdivisions are independent of the data. They are more precisely called 'tries'.

5

Isometric grid adjacencies

Page 6: (Original)Terrain Analysis in Computer Games

The point quadtree is an adaptation of a binary tree used to represent two dimensional point data. It shares the features of all quadtrees but is a true tree as the center of a subdivision is always on a point. The tree shape depends on the order data is processed.

Edge quadtree are specifically used to store lines rather than points. Curves are approximated by subdividing cells to a very fine resolution. This can result in extremely unbalanced trees which may defeat the purpose of indexing.

1.3. Waypoints

Any of the form of representation presented earlier can be a fundament for this one. This is nothing more than an augmentation of the above by annotating the terrain with hand-selected places that movable entities can be in. Adjacency relationships between waypoints indicate ways to move from one to the other (including travel time). Additional annotations can be used to indicate other properties:

• whether line-of-sight exists between two waypoints;• part of a room or a base or some interesting location;• environment conditions, such as light/dark, types of movement required.

The tradeoffs are that you can analyze to derive many useful tactical properties and generally must be entered by hand. With the usage of waypoints you can easily find vantage points closer to you such as high ground, rich resource terrain, choke points, best places that you can use to perform a sneak attack against you enemy, etc. Finding that king points it is easy and fast since they are already introduced or precomputed, before the game even started.

6

Example: The best sniper posts in a waypoint representation

Page 7: (Original)Terrain Analysis in Computer Games

2. Pathfinding algorithms

Pathfinding involves solving a planning problem with agents seeking optimal paths from a start state to a goal state. The pathfinding process involves utilizing the full state space information available to agents to find the least expensive route to the goal. However most solutions to the pathfinding problem have solely focused on using graph based terrain representations and graph search algorithms to obtain a path.

Pathfinding in the context of video games concerns the way in which a moving entity finds a path around an obstacle; the most frequent context is real-time strategy games (in which the player directs units around a play area containing obstacles), but forms of this are found in most modern video games. Pathfinding has grown in importance as games and their environments have become more complex.

Real-time strategy games typically contain large areas of open terrain which is often relatively simple to route across, although it is common for more than one unit to travel simultaneously; this creates a need for different, and often significantly more complex algorithms to avoid traffic jams at choke-points in terrain, or when units come into contact with each other. In strategy games the map is normally divided into tiles, which act as nodes in the pathfinding algorithm.

More open endedly structured genres such as first-person shooters often have more enclosed (or a mixture of open and enclosed) areas that are not as simply divided into nodes, which has given rise to the use of navigation meshes. These are constructed by placing nodes in the game world that store details of which nodes are accessible from it.

2.1. Trial and Error

In the simplest terms, pathfinding is the computation and execution of a path from point p1 to goal p2. If there are no obstacles, the simple AI technique of vectoring toward the goal position will suffice. However, if there are obstacles, obstacle avoidance will have to come into play.

For simple obstacles that aren't large and are mostly convex, you can usually get away with an

7

Page 8: (Original)Terrain Analysis in Computer Games

algorithm that, when the object hits an obstacle, backs it up, turns it right or left 45-90 degrees, and then moves it forward again for some fixed amount. When the object has moved that distance, the AI retargets the goal, turns the object toward it, and tries again.

Although this algorithm surely isn't as robust as you'd like, it works because there's a randomness in the avoidance algorithm. It turns randomly each way to try again, so sooner or later the object will find its way around the obstacle.

2.2. Contour Tracing

Another method of obstacle avoidance is contour tracing. Basically, this algorithm traces the contour of the object that's blocking the object's path. You can implement this by following the outline of the obstacle and periodically testing if a line from your current position to the goal intersects the obstacle anymore. If not, you're clear; otherwise, continue tracing.

8

The "Bump-n-Grind" object avoidance algorithm

Page 9: (Original)Terrain Analysis in Computer Games

This works, but it looks a little stupid because the algorithm traces around things instead of going through the obvious shortest path. But it works. So what you might do is use the trial-and-error method first, and if that fails after a certain period of time, switch to the contour tracing algorithm and get out.

2.3. Collision Avoidance Tracks

In this technique, you create virtual tracks around objects, consisting of a series of points or vectors that trace out a fairly intelligent path. The path can be computed algorithmically using a shortest-path algorithm (which we will get to later) or manually created by you or your game designers with a tool.

Around each large obstacle you create is an invisible track that only the pathfinding bot AI can see. When a bot wants to get around an object, it asks for the nearest avoidance path for that obstacle and then takes it. This ensures that the pathfinder will always know how to get around obstacles. Of course, you might want to have more than one avoidance path for each obstacle or add some tracing "noise" so the bots don't all follow the path perfectly.

2.4. Waypoint Pathfinding

Let's say that you have a really complicated world and there are all kinds of obstacles. Sure, you could make a creature with enough intelligence to navigate itself around everything and get to a goal, but is all that necessary? No! You can set up a network of paths that connect all points of interest in the game via a connected network of nodes. Each node represents a waypoint, or point of interest, and the edges in the network represent the vector direction and length to get to other nodes in the network.

For example, let's say that you have a plan running and you need to move a bot from its current

9

Page 10: (Original)Terrain Analysis in Computer Games

location over the bridge and into the city. Doesn't that sound like a lot of drama? But if you have a network of paths and you can find a path that goes to the city via the bridge, all you have to do is follow it! The bot is guaranteed to get there and avoid all obstacles.

To follow the path, you have a few things to consider. First, you have to get to the first node of the path or a node along it. This can be a problem. Assuming that there are sufficient path entry points on the game grid, you can assume that one of the nodes from a desired path is within range. Therefore, you want to find the node that is closest and vector toward it. During this initial path alignment, you may have to avoid obstacles to get there! Once you're at the starting node or a node on the interior of the path, you're ready to go.

There are problems with having paths. First, finding a path to follow might be as difficult as trying to get from point to point! This is an issue, of course, but with the proper network data structure, you can ensure that for any given game cell, a game object needs to travel less than 100 units or so to pick up a path. Granted, the data structure representing the path network will be complex because some links may be used by other paths, but this is more of a data structure problem and depends on how you want to do it. You may simply have 1,000 different paths that don't reuse waypoints even if they're the same for many paths.

Or you might use a connected graph that reuses waypoints, but has logic and data links to follow a path and won't switch tracks. This can be accomplished with clever pointer arithmetic and logic to select the correct links that make up a specific path.

10

A pathfinding network with a path highlighted

Page 11: (Original)Terrain Analysis in Computer Games

A good example of using paths is in racing games. Imagine that you want to have a number of cars on a racetrack, and you want them to drive around the track while avoiding the player and looking somewhat intelligent. This is a good place for paths.

What you might do is create, say, eight or 16 different paths that follow the road. Each of the paths might be equidistant or have slightly different properties, like "tight and short" or "long and wide." Each AI car starts off on a different path, and as the game runs, it follows the path by vectoring toward it. If a car gets in a crash, it picks up on the next nearest path, and so on.

In addition, if a car's AI wants to change lanes to a more aggressive path, it does so. This helps you because you don't have to worry about keeping the cars from bunching up as much, and you don't have to make them steer as much because they're on paths. Controlling their speed and braking time will be more than enough to make them seem real.

3. Real Pathfinding

Real pathfinding; in other words, using computer science algorithms to find paths from p1 to p2. There are a number of algorithms that can do this. The problem is that none of them are for real-time and thus don't lend themselves to games easily. However, you can use them in real-time if you employ some tricks, and of course you can use them to compute paths for you.

All of the algorithms work on graph-like structures, which are representations of your game universe that consist of nodes, along with edges made up of nodes that can be reached from any particular node. There's usually a cost associated with each edge.

In any case, once you've come up with a way to represent the game world that is graph-like, you can run the algorithm(s) on the problem of finding a short path, or the shortest path, from p1 to p2 that avoids obstacles. Obstacles aren't allowed in the graph, so they can't possibly be part of the path.

11

Page 12: (Original)Terrain Analysis in Computer Games

3.1. Breadth-First Search

This search fans out in all directions at the same time, visiting each node one unit away, then two units away, then three units away, and so on, a growing circle. It's crude because it doesn't focus on the actual direction of the goal.

3.2. Bidirectional Breadth-First Search

The bidirectional breadth-first search is similar to the breadth-first search, except that two different searches are started: one at the start and one at the goal. When they overlap, the shortest path is computed.

12

Page 13: (Original)Terrain Analysis in Computer Games

3.3. Depth-First Search

This is the converse of the breadth-first search. The depth-first search searches one direction all the way until it runs out of space or finds the goal. Then it searches the next direction, and so on. The problem with depth-first is that it needs a stopping limit that says, "If the goal is 100 units away and you've already tried a path that has a cost 1000, it's time to try another path."

3.4. A*

Dijkstra's search stems from the same algorithm used to find the minimum spanning tree of a graph. At each iteration, the algorithm determines what the shortest path to the next point is and then works on it rather than shooting out blindly in a random direction.

The A* search (pronounced A-star) is similar to Dijkstra's search, except that it uses a heuristic that not only looks at the cost from the start to the current node, but also makes an estimate to the goal from the current node, even though it hasn't visited the nodes along the way.

Let’s assume that we have someone who wants to get from point A to point B. Let’s assume that a wall separates the two points. This is illustrated below, with green being the starting point A, and red being the ending point B, and the blue filled squares being the wall in between.

13

Page 14: (Original)Terrain Analysis in Computer Games

Once we have simplified our search area into a manageable number of nodes, as we have done with the grid layout above, the next step is to conduct a search to find the shortest path. We do this by starting at point A, checking the adjacent squares, and generally searching outward until we find our target.

We begin the search by doing the following:

1. Begin at the starting point A and add it to an “open list” of squares to be considered. The open list is kind of like a shopping list. Right now there is just one item on the list, but we will have more later. It contains squares that might fall along the path you want to take, but maybe not. Basically, this is a list of squares that need to be checked out.

2. Look at all the reachable or walkable squares adjacent to the starting point, ignoring squares with walls, water, or other illegal terrain. Add them to the open list, too. For each of these squares, save point A as its “parent square”.

3. Drop the starting square A from your open list, and add it to a “closed list” of squares.

The key to determining which squares to use when figuring out the path is the following equation:

F = G + H

where

• G = the movement cost to move from the starting point A to a given square on the grid, following the path generated to get there.

• H = the estimated movement cost to move from that given square on the grid to the final destination, point B. This is often referred to as the heuristic, which can be a bit confusing. The reason why it is called that is because it is a guess. We really don’t know the actual distance until we find the path, because all sorts of things can be in the way (walls, water, etc.).

To continue the search, we simply choose the lowest F score square from all those that are on the open list. We then do the following with the selected square:

4) Drop it from the open list and add it to the closed list.

5) Check all of the adjacent squares. Ignoring those that are on the closed list or unwalkable (terrain with walls, water, or other illegal terrain), add squares to the open list if they are not on the open list already. Make the selected square the “parent” of the new squares.

6) If an adjacent square is already on the open list, check to see if this path to that square is a better one. In other words, check to see if the G score for that square is lower if we use the current square to get there. If not, don’t do anything. On the other hand, if the G cost of the new path is lower, change the parent of the adjacent square to the selected square (in the diagram above, change the direction of the pointer to point at the selected square). Finally, recalculate both the F and G scores of that square.

We repeat this process until we add the target square to the closed list.

So how do we determine the path? Simple, just start at the red target square, and work backwards moving from one square to its parent, following the arrows. This will eventually take you back to the starting square, and that’s your path. It should look like the following illustration. Moving from the starting square A to the destination square B is simply a matter of moving from the center of each square (the node) to the center of the next square on the path, until you reach the target.

14

Page 15: (Original)Terrain Analysis in Computer Games

IDA* is a variant of the A* search algorithm which uses iterative deepening to keep the memory usage lower than in A*. It is an informed search based on the idea of the uninformed iterative deepening depth-first search.

Iterative deepening depth-first search (IDDFS) is a state space search strategy in which a depth-limited search is run repeatedly, increasing the depth limit with each iteration until it reaches d, the depth of the shallowest goal state. On each iteration, IDDFS visits the nodes in the search tree in the same order as depth-first search, but the cumulative order in which nodes are first visited, assuming no pruning, is effectively breadth-first.

The main difference to IDDFS is that it uses the f-costs (g + h) as the next limit and not just an iterated depth.

15

Page 16: (Original)Terrain Analysis in Computer Games

3.5. Quadtree Search

The map is subdivided into 4 squares. Each square that contains an obstacle is subdivided again. The process is repeated recursively until the area of a square reaches a specified minimum. The advantage of this approach is that large unobstructed areas are represented as a single node. The disadvantage is that the quality of the path is reduced. Compare the nodes expanded versus path quality in Figures 1 to 4. The start and goal points are green and red, respectively. The start and end graph nodes are also green and red. The explored nodes (closed list) are indicated in purple and the fringe nodes (open list) are in cyan.

Note that in the quadtree approach, the path is constructed from quad center to quad center. For large quads, this can dramatically affect the path quality. To overcome this limitation yet attempt to retain, to a degree, the reduced search space advantage, another approach is framed quadtrees.

In this approach, high resolution cells adjoin the boundaries of the quads. Paths passing through a quad travel from boundary to boundary, crossing at a high resolution cell rather than going center to centre.

One further approach is to partition the terrain into convex polygons covering regions of uniform terrain.

16

Page 17: (Original)Terrain Analysis in Computer Games

An advantage of this representation is that because the polygons are convex and uniform cost, the locally minimal path traversing the covered region is a straight line. Since this line is guaranteed to remain in the confines of the polygon, its cost is simply its Euclidean length times the region cost. In all the representations discussed here, the ultimate result is a graph to be searched using the A* algorithm which relies on a given cost function and heuristic cost estimator. One possibility for improvement is to provide a means to take advantage of geometric properties of the underlying world directly, rather than indirectly through search.

4. Dynamic Caching for Path Planning

The industry standard for low level path planning is to use A* or Iterative Deepening IDA* search over embedded map information, such as a node network). Heavy precomputation is often done, storing connection lists in large databases in order to make queries as fast as possible at runtime. There are two distinct disadvantages to this approach. First, it uses large amounts of memory storing entries that might not ever be used. Second, it precludes the ability to have a dynamic environment; an environment that changes during the course of the game.

Dynamic map information is one of the major challenges in implementing deformable terrain features in games today. If the environment changes the entire precomputed cache must be recomputed. This performance hit is unacceptable in most cases and the end result is that dynamic environments are avoided altogether. This presents a limitation to game and level design.

Dynamic caching, such as is used in processors and web caching systems, would solve these problems. Simply enough, the cache would start out empty and as valid paths are found they would be entered into the cache. The cache size could be limited and seldom used entries thrown out if it grew too big.

A search algorithm would check the cache each iteration looking for a hit. If a hit is found the cache will serve up the answer and search will halt. If the cache misses the search continues normally. There are two types of redundancy that caches can take advantage of, temporal redundancies and spatial redundancies. Both can apply to search algorithms. Often agents are moving in packs and these packs are often given orders to move to the same location. This is temporal redundancy; many of the same queries are being requested in a very short amount of time. Caches satisfy this inherently, if a matching copy is found then it is served up and in most cases only the first searcher must incur the cost.

Spatial redundancy is more complicated and we will have to sacrifice some optimality to take advantage of it. First, we can check the cache for hits not only on the initial call but also within the search algorithm.

For example a cache check could be performed whenever a node was popped off of the open queue in A*. This does, however, affect the optimality of the algorithm. A second way to take advantage of spatial redundancy would be to store not only the beginning and end of a valid search into a cache entry but also a number of nearby nodes linked off of them. This would allow a search that encountered any one of these intermediate nodes to finish at that point and use the cached solution. Depending on when in the A* algorithm the cache was checked this approach may result in a nonoptimal path.

There are interesting research challenges involved in exploring the trade off between speed and memory involved in different cache sizes and caching different numbers of intermediate points. There are also interesting challenges in determining when optimality should be traded for efficiency. How does dynamic caching solve the problem of dynamically changing environments? The simple and most

17

Page 18: (Original)Terrain Analysis in Computer Games

straightforward solution would be to invalidate the entire cache whenever a node or link is added or removed. Also, due to a dynamic cache’s smaller size an algorithm to check through the cache and detect entries that would be affected would be more plausible than it would be for precomputed caches. Dynamic caching presents benefits as well as sacrifices over fully precomputed solutions.

As discussed, it provides the ability to handle dynamic networks while precomputing fails to do so. It also can provide speed savings in comparison to systems that are doing no caching at all. However it will not be able to match the runtime speed of precomputation. Dynamic caching, with the right parameters, looks to be a good middle ground for performance vs. flexibility in path planning.

5. Dynamic Terrain Analysis

As AI characters lack vision capabilities in a game environment, there is a need to provide spatial awareness to them by using terrain analysis. The most common approach to terrain analysis in games is to manually annotate the terrain with hints to the AI system about the tactical suitability of the various locations for both attacks and defenses. Some of the location hints provided to the AI system include cover locations arrayed along walls and other barriers, exit references for each door into and out of a room, scramble positions that indicate where to run to when fired upon, and fixed networks for obstacle avoidance.

This approach is an extremely tedious process requiring the game level designer to manually identify location hints and individually placing them on the game’s map structure. While this works for small maps, this quickly becomes tedious for larger terrains.

While AI annotations on the terrain provide the advantage of minimizing runtime computations, they remain valid only if the NPC movement and the terrain changes are constrained. It fails to consider the dynamic aspects of the terrain like vehicles, obstacles like barrels, bridges which can be blown apart, minefields which can go off during the game execution. It also fails to consider the locations of enemy forces, their line-of-sight visibility and lines of fire. Force-based terrain analysis is a very challenging problem because of the mobility of the forces, which could often invalidate the pre-computed analysis results.

Influence mapping techniques remain another popular way to provide dynamic terrain information to game AI. But, they provide only a crude way to assess dynamic terrain and have scalability limitations caused by heuristics overload when too many influences affect a map.

One desirable characteristic of a dynamic terrain analysis solution would be to use the static analysis results as much as possible and minimally modify them to accommodate the game dynamics. One way to achieve this ideal would be to develop representations and access methods for the terrain which would accommodate partial patching of analysis results. We would also want to filter the changes in the game world to the suitable granularity corresponding to our game AI’s reaction times.

18

Page 19: (Original)Terrain Analysis in Computer Games

6. Influence Mapping

Influence mapping is a common terrain analysis tool. Influence maps are 2D arrays that represent some area of the terrain. The influence map is initialized to an initial value and then attracting and detracting influences are applied to the map based on some game-specific heuristics. A quick example would be a gather site placement. The influence map would “solve” the case of determining whether to place the gather site by a single resource or a group of the same resources because the group would have attracted the gather site to it by a repeated attractor operation on the same area in the influence map (thus raising that area’s value). After the influencing was complete, the gather site placement would look at the map and find the most attractive area to place the site.

Influence maps work well on 2D maps and can be abstracted into 3D influence volumes. Influence maps are still a fairly brute-force approach, though, and can end up being fairly slow as a result. Influence maps are also subject to heuristic overload if too many attracting and detracting influences are used. Imagine a case where an attractor ups the value of a cell in the map and then a detractor knocks it right back down to its original value. In one sense, that’s what you’d like to happen because the tile is both good and bad, but you also lose the fact that it’s good and bad because it looks like any other tile that hasn’t been attracted or detracted at all. Sometimes this is okay, but there are times when it’s not. There are a variety of ways to work around this, but the best is to keep the number of influences during any one influence mapping operation down to a fairly low number.

Area decomposition is a newer component of the terrain analysis toolbox (at least as far as RTS games go). When humans look at an RTS map, it’s very natural to break that down into areas such as “My Town”, “Good spot to put walls”, “Good spot to put a tower”, etc. CP AIs would really like to have that ability as well. Areas are the way to do it. When a map is fully processed into areas, the CP AI can assign units to a given area for logical lookup later as part of a location-based knowledge base. The CP AI can also track how valuable an area is based on the number of resources in it or how many other areas it is connected to. In addition to mimicking human map analysis, areas are excellent at abstracting large areas of the map into easily usable chunks.

Areas can be difficult to keep updated in a game with dynamic terrain. But, with intelligent notifications and good code to split and merge areas, this problem can be mitigated quite a bit. With the addition of connectivity, the area system becomes a powerful way to enable quick and accurate high-level pathfinding. This is useful to simulation in general and also to the CP AIs. The CP AI can use that high level pathfinding for canPath checks and to make strategic choices about where an enemy attack route is likely to be or where to wall off all access to the CP’s town.

On higher difficulty levels, we could precalculate an influence map that detracted from previous attack routes and all known enemy buildings in a region. The canPath check would then try to get the units to the target without walking through those detracted areas.

Influence mapping still plays a part in any terrain analysis. It’s a simple algorithm that everyone quickly understands and can apply. Given its tile/cell basis, though, it can eat a lot of memory. If there are only a few factors with a small dynamic range, you can save some space by implementing a bit storage mechanism where multiple tiles are bit shifted into the same space that one tile used to take. Practically, most single layer uses will want at least 16 levels of range, so you can only pack two cells into a BYTE. Nevertheless, halving your influence map memory usage is still useful. As the size of the range is decreased, though, the risk of heuristic overload increases.

19

Page 20: (Original)Terrain Analysis in Computer Games

Saving memory is a very useful thing with influence maps. If enough memory is saved, you could consider keeping a persistent influence map in the terrain. As resources were consumed, you would remove their influence. As buildings were built, they would add influence (depending on what was tracked). This reduces the costly CPU usage of recreating the influence maps each time they are needed.

Using a tile-based solution, it makes sense to have some area decomposition system that maps one tile to one area. Extending that philosophy, we end up with any point in the terrain being in one and only one area. This allows unambiguous lookups such as “Which area is this unit in?” to be done. The CP AI can then store that area identifier off for use in the expert system or track statistics associated with the area in its knowledge base. Those statistics range from simply asking how many units are in a given area to sophisticated evaluations such as how much offensive power is in a specific area. It is possible to ask these same questions with overlapping areas, but it’s considerably harder to push that data up to something like the expert system that controls the CP behavior.

The areas are delineated by actual terrain passability (e.g. villagers cannot walk on lava), the slope of the terrain (e.g. villagers cannot walk up more than a 50° slope), and any additional logical area distinction (e.g. anything within 50 meters of a player’s starting position is part of that player’s town). Together all of these conditions make up the area creation conditions. Depending on the game’s particular need, different sets of areas can be generated for different creation condition sets (e.g. land vs. air units) or the area sets can carry on/off bits for passability by a given unit type (e.g. land and sea units can share the same areas, but land units cannot walk on water and sea units cannot sail on land).

Just before the game starts, the entire map is processed. The initial goal is to break the map up into simple, roughly convex tile areas. These are the tile subareas. Once every tile is assigned to a subarea, the subareas are processed to create the larger areas. This process allows us to be accurate, but ignore inconsequential areas such as a small lake in the middle of a player’s town. The areas are subject to game specific constraints (e.g. each player’s town should be 250 meters in usable surface area). While not immediately obvious, the subarea process gives us a couple of very useful advantages:

· Consistent generation criteria. Subareas are roughly convex and areas are made up of subareas. Assuming we bound the subareas to a reasonable, consistent size, this allows us to just change the area criteria (in case 250 meters really needs to be 400 meters) without changing our low level processing. It’s much easier to do a greedy grab on subareas until some area goal is met than to continually tweak the low level decomposition heuristics.

· We actually need subarea accuracy. A twisty forest passage may be a hundred meters long, but if it’s made up of five subareas, then we already have our several usable wall endpoints determined for us. We can simply take the subarea boundaries and use those as wall locations to block that passage. Conveniently, that paradigm extends to every situation all the way to an all-grass map that’s decomposed into small subareas; walling off in that type of situation can still be accomplished by the same method as the twisty forest map.

So, with our map completely decomposed into nicely defined areas, we’re all set until something changes the map. At that point, we need to dynamically analyze the change(s) and alter the areas accordingly. The basic process for this is pretty straightforward:

· Using the knowledge of what the change is (e.g. an earthquake creates an impassable seam in the terrain of a certain size), we rip through the area system and remove all of the tiles that could possibly be affected.

· The full subarea decomposition pass is run on the removed tiles. If possible, outside information about the surrounding areas and the terrain change are used (e.g. the line of impassability the

20

Page 21: (Original)Terrain Analysis in Computer Games

earthquake creates is a good area boundary). Time slicing the terrain analysis comes in very handy here in case this is a slow process.

· Once those subareas are created, the greedy algorithm is run starting with the existing areas that bound the affected area. This will tend to push the subareas into existing areas. Generally, this is a good thing unless the earthquake stretches across the entire map.

· All systems that have referenced the areas and subareas that were removed or altered get notifications to reset their data. This is much easier if the areas keep reference counts and identifiers to be able to directly notify the systems in question.

21

Page 22: (Original)Terrain Analysis in Computer Games

References

• Terrain Analysis in Realtime Strategy Games Dave C. Pottinger, Ensemble Studios;• Dynamic Path Planning and Terrain Analysis for Games Paul Brobst, Ramesh Saran, Michael

van Lent, University of Southern California Institute for Creative Technologies;• Pathfinding in Open Terrain S. D. Goodwin, S. Menon, R. G. Price Centre for Interactive

Digital Entertainment Research School of Computer Science, University of Windsor Windsor, Ontario, Canada;

• Terrain Analysis in Strategy Games CS 395GAI Spring, 2005, Nortwestern University;• http://www.yaldex.com/games-programming/0672323699_toc.html , Game Programming

Gurus;

• http://www.policyalmanac.org/games/aStarTutorial.htm , A* Pathfinding for Beginners, By Patrick Lester;

• http://en.wikipedia.org/wiki/IDA *;• http://intelligence.worldofcomputing.net/ai-search/iterative-deepening-a-star.html ;• http://www.ai-blog.net/ ;• http://en.wikipedia.org/wiki/Pathfinding ;• http://en.wikipedia.org/wiki/Quadtree ;• http://en.wikipedia.org/wiki/Video_game_genres ;• http://www.gamedev.net/ .

22