Friday, June 28, 2013

Integrating AD*

Most of today and much of yesterday was spent integrating AD*. I made many changes to the A* and AD* code such that they would be easily-swappable (though there are still a few #if directives in the code that uses them).

While I have been mostly testing in a constraint-less environment, it does work with static constraints. With dynamic constraints, it will correctly calculate new costs, but it will not specifically re-explore previously-explored nodes whose costs have changed.

Result of updating the plan a few times as the goal moves.
I am currently having some issues with moving the start state, but moving the goal state does work, as seen above.

Thursday, June 27, 2013

Dynamic constraints & replanning

In order to implement dynamic constraints, we needed to be able to change the graph weights immediately when constraints move. Since the multiplier field is always calculated on the fly, this turned out to be very simple. Updating the multiplier field visualization in real-time makes it easy to see these changes.
Of course, it's not animated, but believe me that the bump in the field is moving along with the agent.
However, with a constantly changing graph, the plan must continually be updated. With A*, this means rerunning the full planner constantly, as shown below. This is actually quite fast with a good heuristic, but suffers in this graph due to the fact that the heuristic is several times smaller than the actual result.

(I would have a video here of constant replanning, but it's disabled right now while I work on highways and AD*.)

In the very near future, however, we will be integrating an AD* planner, which will give us the ability to re-plan rapidly and incrementally, allowing for good plans in a real-time situation.

Hybrid ("highway") navigation graph

In this "hybrid"/"highway"/"Eisenhower"/name-subject-to-change navigation graph, we essentially overlay the old, triangulation-based graph onto the new, grid-based graph. We map each node in the tri-based graph to the nearest node in the grid-based graph, then add the appropriate adjacencies, creating "highways" in the new hybridized graph.
Example of the A* planner utilizing highways in a constraint-less system.
Same system without highways.
  • Search without highways: 274 nodes explored, 31 nodes in plan.
  • Search with highways: 130 nodes explored, 15 nodes in plan.
With this graph structure, we hope to be able to improve the performance of the search while losing very little optimality. (In areas where precision is not important, such as far away from constraints, the highways could help shorten the search.)

Planning using A* with a bad estimate does not seem to see much improvement with this graph structure. However, A* with a good estimate (or even a non-admissible estimate; see Weighted A*), the search has a greater tendency to utilize highways. The highways are unfortunately not always effective, as they must be fairly close to the optimal path to be used in the output plan.

(Weighted A*: $f = g + \varepsilon h$. I have set $\varepsilon$ to the "default" multiplier in the multiplier field, which preserves optimality for "avoid" constraints but not for "near" constraints.)

We are also looking at some other ideas, including using a heuristic to ignore the high-density graph when it is not very useful (e.g. when the multiplier field is not very perturbed), but are hoping modifications similar to Weighted A* will provide the results we need (especially once we move over to AD*).

Monday, June 24, 2013

Dense uniform navigation graphs

A meeting today with Alex and Mubbasir led to the idea of giving up on using NavMesh.Triangulate and generating our own dense, uniform navigation graph (using NavMesh.SamplePosition).

The idea is as follows:

  • Define a bounding box in which we want to generate a grid-like graph.
  • For each of many points inside that bounding box, if it is close to the NavMesh, stick it to the ground. If it is not, delete it.
  • Connect these nodes based on adjacency in the grid.
The results look something like this (the tree shown is the graph search):
As usual, the red line is the rough path that was returned by the planner. Much nicer than before.
As it is now, planning takes a few seconds. We discussed some performance ideas in the meeting; the primary idea was to use two levels of navigation mesh detail: use something like the old mesh-based graph for rough planning, and use the new graph when we need detail to deal with constraints, and to perfect/smooth the path.

That said, we might use a graph more like the one Francisco is working on--a quadtree with nodes at the centers of each leaf quad.

Here is the animated result of the plan:

Friday, June 21, 2013

Week of 2013-06-17

Most of this week's work is summarized in the following posts:
I don't have much more to say than that, but here's the last of the things I did this week:

I changed the multiplier field function to be always positive for positive $r$:
$$ M(r) = \frac{\max(0, w)}{k_1} - \frac{w}{k_1 + k_2 r}$$
This means attractors and repellers work correctly at the same time:
Command: to goal, toward long building, away from small building.
I also modified the interface to be a little bit more usable. Instead of pressing arcane sequences of arbitrary keys, the behavior is now defined in the script parameters:
It's designed for this exact case, because I can't very easily add variable numbers of obstacles, but this is what it looks like.

Thursday, June 20, 2013

Visualizing the multiplier field

Okay, the last few posts were pretty dry. Today brings almost-the-beginning-of-summer AND pretty pictures. Hooray!


Multiplier field with one attractor: the ToLeftOf Building constraint
Two attractors: ToLeftOf Building and ToLeftOf Goal
One repeller: To Building (weight = -10)
So what's going on here? For the reasons explained in the previous post, I wanted to model the constraint system after physical potential fields, allowing me to superimpose them nicely. Once I changed the code to allow for multiple constraints, I was able to test this.

For each attractor, there are three ways to change the shape of the dip it makes in the field, which is currently defined as $M(r) = w \left(1 - \frac{1}{k_1 + k_2 r}\right)$. These constants (and their current values) are:

  • $w$ (user defined): The constraint weight affects the depth of a dip.
  • $k_1 = 0.5$: This affects the cutoff of the dip (preventing it from going to infinity). Especially visible at the top of the repeller above.
  • $k_2 = 0.2$: This affects the width of the dip.
And, of course, the path planning works. Sometimes.
Path planning still sometimes gives unexpected results, but I believe this is just due to the low density and bad triangulation of the navigation mesh graph. I may spend a little time in the near future trying to manually subdivide the graph we have now.

Wednesday, June 19, 2013

Constraints as multiplier fields

Now that I've defined the multiplier field, let's look at how we can translate constraints into such fields.

Simple soft constraints
The first system I'll look at is a simple soft constraint I have been working on in code: "Character, Move (NearBackOf Building) To Goal)." We have a single effector, the "Back" annotation on the Building:

The multiplier is defined based on the distance to the closest point on the constraint annotation (as seen in the contour map above):

None of the functions I've tried have shown obvious advantages over others, but see the section on field addition for some considerations.

Other simple soft constraints
Many other soft constraints can be formulated in a similar way:

Multiplier field addition
Since a multiplier field is a simple scalar field, we can also add them together, allowing for multiple constraints as well as using goals as field effectors. (Note that the rule for constant fields, from the previous post, still holds under addition; however, adding a constant to a multiplier field will not result in the same minimized path.)

It should be noted that, when using addition, it is important to consider it when choosing a function $M(d)$ for weighting: if one function chosen rises too quickly, then it will quickly drown out any others, meaning we may want to choose a function that emulates electric/gravitational fields (i.e. $U \propto r^{-1}$).

Inverted constraints
Constraints such as "away from" are simply an inverted "near" constraint. This raises some minor difficulties, but the idea is the same. Since we must avoid negative weights (so that the search algorithm works correctly), it is necessary to, for example, effectively add a constant to the multiplier field. As seen before, this does not maintain the minimized path, but it does provide for some room for smaller multipliers.

Annotations as goals
Another benefit of having the annotations on objects is that it gives us flexibility with goals. Some of the goals listed in the tactical grammar specification are very similar to the constraints: to, near, away, between, behind, inside, outside.

Limitations of annotations
While annotations are a flexible approach, they have some important limitations. In particular, there are a lot of states that are probably much easier to compute on the fly: between, behind (relative to some third party), etc.

Multiplier fields

The next article will outline some possible constraints and how those constraints would be formulated as multiplier fields. But before that: What do I mean by multiplier field? Let $M(\vec x) : \mathbb R^3 \rightarrow \mathbb R$. During a search, we find transitions, such as $(s \rightarrow t)$ in the diagram below.


For each such transition, we calculate a multiplier, which we use to re-weight the original graph, which is based on Euclidean distances. The reasoning behind this is that, for any constant multiplier field $M(\vec x) = m$, the path cost minimization (Dijkstra's or A*) will return the same resulting path. (Note that adding an additional cost to each transition means that replacing a graph edge with two graph edges along the same path changes the total cost for that transition.)

Thus, we model the new cost over a path $P$ as a path integral:
$$C(P) = \int_P {M(\vec x) d \vec x}$$
which, for constant $M$, reduces to $C(P) = m \norm P$, satisfying the condition mentioned above.

Currently, we approximate the multiplier for a single transition $P = (s \rightarrow t)$ by calculating the value of the multiplier field at the midpoint and multiplying it by the length of the transition:
$$C(s \rightarrow t) = M\left(\frac{\vec s + \vec t}{2}\right) \norm{\vec t - \vec s}$$

Tuesday, June 18, 2013

Line integrals & conservative vector fields

This is a short exploration of an idea that has been floating around for a while.

Suppose we model the system as an electrostatic system as follows:

  • The character is a small positive test charge
  • The goal is a negative static charge
  • Constraints are positive or negative charges
This would result in systems that look like this:
http://www.falstad.com/mathphysics.html
The benefit of this is that this creates a conservative vector field--the gradient of a scalar potential field. Minimizing potential in the potential field brings us to the goal, and we can use the search algorithm to find a path that minimizes the path integral of the potential over the path. I don't think this path particularly represents anything physical, but it gives us a nice way to measure path optimality.

Week so far 2013-06-18

Yesterday, I worked on a few of the things from my to-do list.
  • Fixed annotations, by restricting them to BoxColliders and implementing some collision-related methods for BoxColliders only: Contains, MinDistance, and ClosestPoint.
    • I realized today that I should not need to keep annotation lists in the navigation graph.
  • Compute multipliers like before except based on the the distance to the closest point on the annotation.
  • Added text gizmos that allow us to debug using the value of g.
  • Tried (but didn't succeed) at weighting costs based on angle relative to the direction of the constraint.
Today, I've started looking again at the list of constraints. For those that have clear definitions, I believe they should not be very difficult to implement with the cost weighting system. I will need to make some adjustments and possibly give up completely on goal estimates for now (falling back to Dijkstra's and not worrying about A* estimates): As there are some constraints that involve avoiding areas of the graph, it may be much easier if we drop the restriction that the multiplier be greater than 1.

Friday, June 14, 2013

Week of 2013-06-10

The goal this week was to make the planner output a different plan by modifying graph traversal costs; this cost modification is based on spatial relationship to a constraint object. In order to test the cost function without worrying about the A* heuristics, we always estimate the distance to the goal to be h(x) = 0 (thus reducing A* to Dijkstra's).

The results are illustrated in the following images. By multiplying the Euclidean distance by a multiplier (equal to from the graph edge midpoint to the distance to the constraint), we "discourage" the search from going away from the constraint object.

A plan to go straight to the goal.
A plan that is weighted to go near the long object at the bottom.
(Those crazy bubbles are a debugging tool: they scale with the value of g at that point in the search.)
I have noticed one important problem with this simple approach, however: once we want to leave the constraint object and go toward the goal object, the search becomes very slow--since the costs discourage the search from going away from the constraint object, it suddenly gets very slow. I tried defining the multiplier based on distance to both goal and constraint, but I haven't yet found anything that actually works without almost completely ignoring the constraint.

It should also be noted that we are using a very approximate system right now: we simply multiply cost based on distance to the center of the constraint object. In the future, we want it to work based on the distance to the nearest point "on" the object (really, on a collider annotation).

Aside: As it turns out, reducing the accuracy of the mesh (Navigation -> Bake -> Advanced -> Width/Height Inaccuracy %) makes the NavMesh much cleaner around sharp corners (and quicker to bake) while subdividing it much less. For now, this seems to be a more reasonable way to generate meshes.
Inaccuracy 1% (left) and 10% (right)
Unfortunately, the mesh is still messy at 10%.
To do:
  • Get annotations working (by testing against a short vertical ray?)
    • Use annotations to compute multiplier based on distance to closest point on annotation. (Don't use ClosestPointOnBounds--it operates on AABB.)
  • More robust constraint system (with until)?
  • Put text on the bubbles so that we actually know what the g values are.
  • Make an argument that the cost multiplier actually makes sense.
    • Note that it is an increase in cost per distance, rather than a cost per node as with an addend.
  • Revisit the list of constraints and model them in this system.
  • Try a cost weighting system that reduces weights perpendicular to the constraint--this is specific to "near"/"along" constraints, though.

Monday, June 10, 2013

Week of 2013-06-03

Prior to shifting focus this week, I worked on "following" moving objects, improving some behavior with respect to null perimeter waypoints, and handling invalid paths a bit better.

Anyhow, as seen in previous blog posts this week, a lot of things have changed directions. One of the main things is that we've shifted our approach to constraints. Unfortunately, since this new direction requires a lot more lower-level theoretical-ish work, that means there's not a whole lot of cool and interesting things to show off.

So, the plan is now:
  • Use our own A* planner on a graph extracted from Unity's NavMesh.
  • Adjust per-agent graph weights on the fly to reflect the constraints of the command being executed.
  • For dynamic agents, modify the weights of nodes that fall into constraint areas relative to the agent.
  • Initially, start with planning paths to a specific location and focus on implementing constraints.
I accomplished some things this week:
  • Reading Unity's NavMesh and then correctly converting that into a navigation graph for A* (this was difficult because Triangulate returns a mesh that is not fully connected).
  • Examining the usefulness of some things available to me, such as NavMeshLayers, NavMeshAgent.SetLayerCost, and Collider.ClosestPointOnBounds.
  • Adding "NavAnnotations" or "constraint annotation mesh objects" that both split up the Unity-generated NavMesh and allow us to associate graph nodes with constraint areas:
Using these to split up the NavMesh...
Gives us a NavMesh that looks like this.

Here are some things to note for future reference:
  • NavMeshLayers are really only useful to manually split up the NavMesh (and thus make the navigation graph more dense). 
  • SetLayerCost probably won't be useful at all, because we can't have one layer for every possible constraint (every possible pair of object and constraint type) as there are only 32 possible layer flags.
  • We probably want to use ClosestPointOnBounds to figure out which node should be our destination. Choose the path-cost-minimizing destination node amongst the nodes that are "within" the constraint annotation mesh.
  • We may be able to store in graph nodes (at generation time) the constraint annotation mesh objects for each node (thus avoiding searching the graph for the closest nodes, as in the previous bullet point).
  • All of the constraint annotation mesh objects are going into their own layer (NavAnnotations), which means we have the option of searching through them.
The challenges I'm currently anticipating:
  • Figuring out how exactly constraints will work relative to dynamic objects (we can't add nodes to the pre-baked navigation graph).
  • For hard constraints, dealing with the case where a hard constraint is not true at the starting state.
  • Gracefully dealing with any failure case.

Wednesday, June 5, 2013

2013-06-05 Summary

After the meeting today, I tested out the code provided in this forum post, which gives us an (undocumented) way to access the NavMesh's mesh data. To use the data, we need it in the form of a graph with links between edge midpoints (for A*). I implemented the transformation from {vertex list, triangle list} to adjacency list representation of that graph.

To make sure this was working, I also wrote the resulting graph out into an additional mesh:
Sweet deal.
The next thing to look into was NavMeshAgent.SetLayerCost. I created an additional area, with the default cost of 1, for the agents to walk over. At first, they both happily walked across it:
Very synchronous.
But after modifying the layer cost for one agent, one walked around the side:
It works!

2013-06-05 Meeting review & comments

After Norm's email yesterday considering a weighted constraint system, I spent some time working out how to use those ideas. In the image below, I tried to implement each of his example commands in terms of a weighted navigation structure. Some of these involve dynamic constraints, while others are purely static, but I tried to implement everything using as few algorithmic concepts as possible.


This system is largely independent of what I have been working on so far, but is far more robust and optimizable. Today, Alex, Mubbasir, and I had a meeting regarding the direction of the project and the implementation of these ideas.

After some consideration of the technical aspects (using Recast vs. Unity navigation meshes, whether we could read the Unity navigation mesh, etc.), we discussed modifying the navigation mesh to allow us to weight waypoints for a constraint given at runtime.

Ideas:
  • Weight the waypoints in the navigation mesh to implement constraints (not sure if the weights would be in the Unity system or in our own code)
  • Use the A* planner that Francisco is working on
  • Use the weights to encourage the planner to give us the path we want
  • Reject a path if it violates constraints and try again
  • All possible constraints are baked into the navmesh weights
  • Dynamic constraints (e.g. based on moving objects) modify waypoint weights on the fly
What we have discovered so far is as follows:
  • We can access Unity's NavMesh data directly using NavMesh.Triangulate.
  • NavMeshAgent.SetLayerCost probably allows us to set a layer's cost for a single agent.
  • We can cause Unity to break up the NavMesh by putting parts of the terrain on different NavMeshLayers.

Monday, June 3, 2013

Week of 2013-05-27

At my meeting with Alex, Mubbasir, and Norm, we discussed how to begin implementing a subset of the RCTA Tactical Grammar. We determined that it would be very difficult to implement many of the example words defined in the slides, but we set some goals.

In considering certain relatively difficult (but possible/reasonable) commands, we focused on the following:


Verbs:       move
Modes:       quickly, slowly
Constraints: front/back/left/right, near, behind, between, along
Goals:       front/back/left/right, to  , behind, between

(Some of the example words, such as the "along" goal, we ignored because they were not defined in the slides and had no clear definition.)


This week, I focused on implementing the front/back/left/right/to/behind Goals and the "along" Constraint. My initial implementation ignored several parts of the specified grammar for the purpose of prototyping the behavior algorithms (Tue-Fri). I then spent time restructuring it to conform to the grammar and behave more robustly (Sat).


As discussed in our meeting, the "along" constraint was implemented by using a "navigation queue," a structure that assists a GoTo node in following a path continuously without slowing down or stopping. This structure allows an agent to follow a path "along" the side of a structure, "left of" a structure on the way to another goal, and so on.  


A structure is annotated with a perimeter of "navigation waypoints," and is then called "navigable." This annotation allows an agent to know the shape of a path around an object. A NavWaypoint can be tagged with the PerimeterUnnavigable tag to indicate part of the path which is blocked by other structures.


The PerimeterDefinition can also contain a null NavWaypoint, which indicates an edge that cannot be crossed by walking (e.g. between the waypoints along either side of a river). If an attempt is made to cross such an edge, the agent currently moves along the path to one end and stops.


The goal point on an object is also controlled by the navigation waypoints. Some items in the Goal enum specify a cardinal direction with relation to the goal object--using these causes the agent to move to one of those waypoints (still moving "along" another object, if specified).


Further work:

  • Testing interations between goals and constraints
  • Implementing better behavior for the "river" scenario
  • Implementing more goal/constraint prepositions