Lecture 6

51
Obstacle Avoidance Lecture 6 Pathfinding Thanks, Obama! Funnel Algorithm Platformer 3

description

Lecture 6. Obstacle Avoidance. Thanks, Obama!. Funnel Algorithm. Platformer 3. Pathfinding. Pathfinding. Pathfinding is the most common primitive used in game AI A path is a list of instructions for getting from one location to another - PowerPoint PPT Presentation

Transcript of Lecture 6

Obstacle AvoidanceLecture 6PathfindingThanks, Obama!Funnel AlgorithmPlatformer 31PathfindingPathfinding is the most common primitive used in game AIA path is a list of instructions for getting from one location to anotherNot just locations: instructions could include jump or climb ladderA hard problem!Bad path planning breaks the immersive experienceMany games get it wrong3D world representationNeed an efficient encoding of relevant information in the worldNavigable spaceImportant locations (health, safety, bases, mission objective)Field-based approachesPotential fieldsGraph-based approachesWaypointsNavigation meshesPathfinding with potential fieldsPotential field: a region of potential valuesUsually a 2D grid in gamesGood paths can be found by hill climbingThe potential at a location represents how desirable it is for the entity to be thereObstacles have low potentialDesirable places have high potential4Potential fields: algorithm detailsOn startupGenerate potential fields for static objectsPeriodically (~5 times a second)Generate potential fields for dynamic objectsSum static and dynamic potential fields to get the final potential fieldEach tick (~60 times a second)Pathfinding entities move towards direction of greatest potential increase (hill climbing)Choosing a potential functionPotential function for a single entityUsually defined radiallyNon-radially symmetric ones useful tooExample: cone of negative values ahead of player to encourage enemies to stay out of viewExample potential functions (radial):Choosing a potential functionPotential functions don't need linear falloffLinear falloff leads to a targetRise then fall leads ranged units to a safe distance awayPathfinding with Potential FieldsMultiple ways of combining potentialsMaximum sometimes works better than sumSumming creates false desirable spot for ranged unitsMaximum correctly identifies desirable areas for ranged unitsPros and cons of potential fieldsAdvantagesAble to represent fully dynamic worldHill climbing doesn't need to generate and store the entire pathNaturally handles moving obstacles (crowds)Can be efficiently implemented on the GPUDrawbacksTuning parameters can be trickyHill climbing can get stuck in local maximaLocal maximumGlobal maximumAgentAvoiding local maximaAgents drop negative-potential "pheromone trail"Bulge behind them pushes them forwardDoesn't prevent agents from turning around in cornersStill doesn't avoid all local maximaPotential fields are better suited for dynamic worlds with large open areasClassical graph-based pathfinding works better for complex terrain with lots of concave areasReconsidering potential fieldsNot actually used in many real gamesWe couldn't find any commercial releases that use themBut there are at least custom Starcraft bots that doInstead, most games use graph-based path planningGraph-based path planningWorld is represented as a graphNodes represent open spaceEdges represent ways to travel between nodesUse graph search algorithms to find pathsTwo common typesWaypoint graphsNavigation meshesWaypoint graphsRepresents a fixed set of paths through the worldNodes are waypointsEdges represent a path between adjacent nodes

Disadvantages of waypoint graphsOptimal path is likely not in the graph Paths will zig-zag to destinationGood paths require huge numbers of waypoints and/or connections, which can be expensiveNo model of space in between waypointsNo way of going around dynamic objects without recomputing the graphAwkward to handle entities with different radiiHave to turn off certain edges and add more waypointsNavigation meshesConvex polygons as navigable spaceNodes are polygonsEdges show which polygons share a sideAdvantages of navigation meshesMore efficient and compact representationEquivalent waypoint graph would have many more nodes and would take longer to traverseModels entire navigable spaceCan plan path from anywhere inside nav meshPaths can be planned around dynamic obstaclesZig-zagging can be avoidedNaturally handles entities of different radiiDon't go through edges less than 2 * radius longLeave at least a distance of radius when moving around nav mesh verticesNavigation meshesDifferent from collision meshOnly contains walkable facesStairs become a single, rectangular polygonPolygons are usually smaller to account for player radiusNavigation meshesAnnotate special regionsCan have regions for jumping across, falling down, crouching behind, climbing up, ...Regions are usually computed automaticallyFind CorridorNavigation loopProcess for robust path navigation on a navigation mesh:Find sequence of polygons (corridor) using graph algorithmFind corner using string pulling (funnel algorithm)Steer using smoothingActually move/collide entityGraph searchFirst step in finding a pathGraph search problem statementGiven starting point A, target point B and a nav meshGenerate a list of nav mesh nodes from A to B (called a corridor)Simplest approach: Breadth-first searchKeep searching until target point is reachedEach edge has equal weightMost common approach: A-starVariable edge weights (mud or steep surfaces may have higher cost)Uses a heuristic to arrive at an answer fasterPath generation: problem statementGiven a list of polygons (output of a graph search)The light polygonsConstruct the shortest path for the agentWhere a path is a sequence of connected segmentsThe path must lie entirely in the list of polygons

Path generation: first attemptCan we just connect polygon centers?No: the path might not even be within the polygonsPolygons convexity only tells us that any 2 points in a single polygon can be connected with a segment

Path generation: second attemptCan we just connect centers of polygon sides?This always produces a valid path (within the polygons)But not always the optimal path (zig-zagging)This is just a waypoint graph!

Path generation: third attemptThe Funnel algorithm finds the optimal pathHugs cornersIs like pulling a string that connects A and B until it is taut

Obstacle AvoidanceLecture 6PathfindingSimple StupidTM!Funnel AlgorithmPlatformer 325FunnelFunnel algorithmTraverses through a list of polygons connected by shared edges (portals)Keeps track of the leftmost and rightmost sides of the "funnel" along the wayAlternates updating the left and right sides, making the funnel narrower and narrowerAdd a new point to the path when they crossFunnel AlgorithmFunnel AlgorithmStartApex point = start of pathLeft and right points = left and right vertices of first portalStepAdvance to the next portalTry to move left point to left vertex of next portalIf inside the funnel, narrow the funnel (C-D in previous slide)If past the right side of the funnel, turn a corner (E-G in previous slide)Add right point to pathSet apex point to right pointRestart at portal where right point came fromTry to move right point to right vertex of next portalSimilar to left pointEdge casesZero-length funnel side (portals that share a vertex)Always use left*0.99+right*0.01 for the left and left*0.01+right*0.99 for the right (shrinks portal slightly)End iteration of the funnel algorithmEnd point is portal of size 0, need to check for potential restart like other portals29Funnel algorithm exampleRestart search from here (apex)Don't restart search from any of these points30Obstacle AvoidanceLecture 6PathfindingWatch out for that tree!Funnel AlgorithmPlatformer 331SteeringThere are many different ways for an entity to move towards a pointMoving in straight lines towards each destination gives a robotic lookMany alternatives exist: which to use depends on the desired behaviorSeek, arrive, wander, pursue, etc.Steering behaviors may be influenced by a groupQueue, flock, etc.Steering example: arrivalWhen approaching the end of a path, we may want to naturally slow to a haltArrival applies a deceleration force as the entity approaches its destinationMoving and CollidingIf there are no collisions, moving and colliding is as simple as using the destination and steering to moveCollisions can cause a variety of issuesMay need to re-plan path if a collision is impeding movementCan detect getting stuck if the entity stays in roughly the same spot for a few secondsObstacle avoidanceStatic obstacles can be avoided by generating the right navigation meshDynamic obstacles are trickierBaseline approach for dynamic obstaclesUse raycast or sweep test to determine if in obstacle is in the wayApply steering force away from obstacleAdjust force based on distance to obstacleDynamic obstacle avoidanceIf we consider each obstacle individually, this is purely local avoidanceCan easily get stuck in local minimaRemember, this step is added on top of global path planningWe need an approach between purely local and global for handling temporary obstaclesWill not perfectly handle all casesOnly perfect solution is to adjust navigation meshExample approach: "Very Temporary Obstacle Avoidance" by Mikko MononenVery Temporary Obstacle AvoidanceFor the obstacle blocking the pathCalculate tangent pointsChoose tangent that generates a shorter path from the start position to the goal through the tangentCluster overlapping objects into one objectVery Temporary Obstacle AvoidanceHandling multiple obstaclesCheck for obstacles on newly chosen pathIterate until path is clearMight take many iterations to convergeOnly run 2-4 iterations, usually good enoughVery Temporary Obstacle AvoidanceHandling objects along wallsCheck for intersections along navigation mesh boundaryIf one is hit, exclude that pathVery Temporary Obstacle Avoidance

RobustnessCan't find path from off the navigation meshClamp agents inside boundary of navigation meshSpecial-case climbing up ledgesCrowds can't all follow the same pathDon't precompute the path, assume it's wrongUse a more loose structure of path (polygons)Just navigate to the next cornerUse local object avoidance to handle crowdsCase study: Recast and DetourOpen source middlewareRecast: navigation mesh constructionDetour: movement over a navigation meshDeveloped by Mikko Mononen (lead AI on Crysis)Widely used in AAA gamesKillzone 3BulletstormHalo ReachCase study: Recast and DetourRecast: navigation mesh generationStart with arbitrary meshDivide world into tilesVoxelize a tile at a timeExtract layered heightfield from voxelsExtract walkable polygons from heightfieldMust have minimum clearanceMerge small bumps in terrain and steps on stairs togetherShrink polygons away from edge to account for radius of agentDetour: navigation mesh pathfinding

Case study: Recast and Detour

ReferencesRecast and Detourhttp://code.google.com/p/recastnavigation/Funnel algorithmhttp://digestingduck.blogspot.com/2010/03/simple-stupid-funnel-algorithm.htmlObstacle avoidancehttp://digestingduck.blogspot.com/2011/02/very-temporary-obstacle-avoidance.htmlPotential fieldshttp://aigamedev.com/open/tutorials/potential-fields/Obstacle AvoidanceLecture 6PathfindingBetter than Apple Maps!Funnel AlgorithmPlatformer 346Platformer: week 3Load a pre-made navigation meshGenerate graph from triangle adjacencyFind a set of nodes using breadth-first searchOr A*, though this is optionalGenerate a path using the funnel algorithmPretend polygons are 2D in the horizontal planeCollision response will handle the vertical positionLocal obstacle avoidance is not requiredPlatformer: week 3In your handin:Navigation mesh is visualizedPath is visualized from player to a target positionTarget position can be set to the player's current position by pressing a keyIn week 4, you will create at least one enemy that uses pathfindingSo starting thinking about that, too...C++ tip of the weekReference typesLike pointers, but cant be reassignedBetter than value types (no copying)Better than pointers (safer, more limited)Good for knows-about relationships, especially back-referencesSyntax:World& w = player.getWorld();49References exampleclass Player {// doesnt own, knows aboutWorld &w;

Player(World &w) : w(w){// modification is okw.clearEntities();}

World &getWorld() {return w;}

void setWorld(World &w2) {// BAD copies w2 into w1!w = w2;}}// Good for helper functionsvoid clamp(Vector3 &v, const Vector3 &min, const Vector3 &max){for (int i=0; i < 3; ++i) {v[i] = fmax(min[i], fmin(max[i], v[i]));}}

// Good for out parametersbool raycast(float &outT, Vector3 &outP, const World &world, const Ray &ray){// ...}50Weeklies!