Representing MultiSpatialMap as a MapView
Hello! So I'm writing this unity wrapper for GoRogue. u/Chris3606, thanks for the minimal build, it works great so far.
The map I'm using right now to store GameObjects is a MultiSpatialMap. I'd like to implement pathfinding, but in order to do so I need to access a MapView, but I'm not sure what the right way is to access a MapView from my MultiSpatialMap. Is there a way to do that?
Posted Mar 27, 2019, 10:32 PM UTC
There isn't a built-in class to do this exactly, for a couple reasons - mostly because,
IMapViewis designed to expose a "view" of the map, which is typically not exactly the map itself. For example, theIMapView<bool>that pathing takes represents the map as boolean values telling whether any given location is passable or not for the sake of pathing -- it doesn't particularly matter to the pathfinding algorithm if that data comes from a spatial map, Unity ray-casting, or something else, as long as you implement a map view that tells it how to get the information it needs.GoRogue does provide a number of implementations of
IMapViewto help you out though, that typically make implementation easy. How exactly to implement it, however, will depend on a few specifics of what you're storing. The game objects you are storing in the spatial map -- does the term "game object" refer to theGameObjectclass from GoRogue, or some other custom class? If it's a GoRogueGameObject, then eachGameObjecthas anIsWalkableflag that says whether or not it is a collidable object. In this case, you might consider using aGoRogue.GameFramework.Mapin place of yourMultiSpatialMap, as it implements the map view (and AStar based on thatIsWalkableflag) for you.If you want to keep the spatial map, provided it's a spatial map of GoRogue
GameObjectinstances, you would probably want to create a map view that returnsfalsefor a location if anyGameObjectat that location has itsIsWalkableset tofalse, andtrueotherwise. GoRogue provides theLambdaMapViewclass (which implementsIMapView) that can make this fairly easy -- you can just create a function to check the spatial map at that position, and pass that function to aLambdaMapView:There are some shorter ways to define that function via System.Linq, and/or by passing a lambda function to LambdaMapView if you're familiar with those, but the principle would be the same.
If the objects in your
MultiSpatialMaparen't GoRogueGameObjects, that's absolutely doable too -- I just don't know exactly what the contents of theIsPositionWalkablefunction would be -- it would depend on how you determine whether a position is considered passable or not based on those game objects :DHope that helps -- if not or if you end up with more questions, I'll be around :D
Hey thanks for your quick response. I really appreciate your help with this.
So I'm wondering about the map width and height parameters. I'm trying to decide what the appropriate values to pass for myMapsWidth and myMapsHeight, from the perspective of the intended design of mapview. For a multi spatial map there are no bounds on the positions of the objects (besides the size of an int), and they can also in principle be negative coordinates. So the map itself has no width and height, and it is not clear to me what specifying a width and height corresponds to with respect to the multi spatial map. Will it only consider coordinates from x=[0, width] and y=[0, height]? Is there a way to center this rect so that it includes negative coordinates? I am also uncertain about if the map width and map height need to represent the full extent of the map, or can correspond to some subset of the map, for instance as a way of bounding how far afield the pathfinder searches. It seems like this would be the intended functionality of the viewport, but I am uncertain how to take a viewport of the multi spatial map.
My current strategy is something like the following:
Now we have something like a viewport for the spatial map. However it feels to me that you've put so much nice work into the polymorphism of your code that I shouldn't be reinventing functionality in this way. Do you have any thoughts? It seems to me that the natural thing to do is to have a constructor for the viewport that takes the spatial map as input. Or else a new class which extends from viewport and does this. Maybe I will write something like that.
One thing that might be useful is if the spatialmap stored the lower left and upper right occupied coordinates, and dynamically updated that information when modified, since then they wouldn't need to be searched for. Better yet, if the spatial map stored a rectangle.
I hope you don't mind my interrogations, I am mostly just trying to document my confusions and thoughts, since I imagine it could be useful for your development process.
No problem, I'm glad I'm able to help :D
I think some of the confusion on this is due to some differences in the way GoRogue uses the term "position", vs Unity. GoRogue, for the most part, "thinks" in grid squares when it talks about maps -- eg, thinks in terms of map "tiles".
Coordand some other data structures don't restrict themselves to only this definition --Coorditself can represent any integral position, whether that be pixel coordinates, grid coordinates, or otherwise. Similarly, although spatial maps make more sense conceptually when you think of them as representing items and associating those items with their map-grid coordinates, they don't enforce some of the invariants you might expect there -- they do allow negative coordinates, for instance. This is largely because spatial maps are really just data structures that happen to be useful for representing elements of maps. There's a lot of ways to do that, though -- you could have one spatial map that represents the entire map like you currently have, certainly. -- Or, you might decide for a particular use case to break it down into chunks, with one multi spatial map per chunk (in which case the coordinates in the spatial map might be chunk-relative, not map-relative), or you might in some cases not use spatial maps at all -- it depends on the specific situation of what you're implementing and the tools you have available. In short, spatial maps are at their core data structures (that can be useful for maps), not an abstraction of the map itself, so it doesn't enforce the same invariants about what "position" means, like map view does.Generally, though, when a GoRogue algorithm wants to interact with a map (eg, a map view), it considers that map as having grid coordinates that are in range
([0, width], [0, height]), as you noted in your post, and this is indeed the subset of coordinates that must be represented by a map view. The reasoning behind this generally relates to the idea that, when you consider a map outside of any specific graphics/pre-built game engine, this definition of position (eg. defining it by grid squares) is the only one that makes sense in all environments. For instance, consider three game/graphics engines -- MonoGame, Unity, and BearLib terminal emulator. MonoGame works in pixel coordinates -- so you have to perform the(mapPosition.X * textureWidth) + (mapPosition.Y + textureHeight)type math for most of what you do in a grid-like game. BearLib, on the other hand, is a terminal emulator, so it thinks of positions as character locations on the screen, so effectively what already amounts to map grid positions. Unity is somewhere in between because it generally thinks of positions as scene coordinates -- if you define the pixels per unit on your textures in the correct manner, one map grid square might equate to one scene distance unit. If you import the textures differently, it might not and might require similar translation math to the MonoGame example. Also, unlike the first two, unity's scene coordinates can go negative. Since these definitions vary widely, and I wanted GoRogue to be able to support all of them, GoRogue simply "thinks" about maps in terms of map grid squares from 0 to end of map dimension, and leaves it to the user to do translation between whatever graphics library/game you are using it with as necessary.In summary yes,
IMapViewsupports only coordinates in range([0, width], [0, height]), so you'll need to perform some translation if you choose to allow negative scene coordinates and/or negative coordinates in your spatial map. The differentiation between spatial map and map view (data structure vs. map abstraction) is why I don't define a direct translation between the two (a constructor like you had mentioned) -- if I define it so it makes sense for one of the potential use cases I mentioned, then it doesn't make sense for some of the other toolset use cases mentioned.As for how to define the translation in your case, the method you have could potentially work -- I myself typically took the easy way out when I dealt with Unity, and made sure the map started at scene coordinates (0, 0) and set the pixels per unit such that one scene unit = one grid unit, so no translation was necessary. Another solution would have been to deal with the positions relative to a parent object that could be positioned freely in the scene, so the relative positions similarly align with the grid. Yet another option is to have both the spatial map and the map view deal in grid coordinates, and perform the offset translation as items are added/moved around.
The bounds-tracking idea for spatial maps is an interesting concept -- however, it may have some run-time implications, as when an item on the edge of the map is moved or removed, it becomes somewhat challenging to efficiently find the new bound on that side of the map (you potentially have to search all objects in the spatial map, in the worst case). GoRogue typically assumes maps are static-sized (meaning, the size might be determined by dynamically but isn't modified after its determined), as this is nearly necessary for traditional RL map generation and some other concepts. That doesn't mean all the algorithms require it, but just that generally that was the use case in mind. That much said, spatial maps to do provide
ItemAddedandItemRemovedevents, so it wouldn't be too hard to create a bolt-on component that tracks that bounds data based on those events -- and that could potentially be added to GoRogue.As for your question about viewports -- this is definitely something that GoRogue implements for you, via its map view system. If you define a map view that does represent the whole map based on your spatial map, you can then define a
GoRogue.MapViews.Viewportas you suspected, based on that map view. It does what the name implies -- takes an existing map view, and represents a subset of that map view, as a map view. Something like:The above implementation does have a downside -- the coordinates you pass to
ShortestPathneed to then be relative to themapView, notfullMap. This wouldn't be the case with something like goal maps where you don't provide coordinates to it in that way, and if you needed to do this with A*, you should be able create a wrapper function that calls an Viewport function to do the coordinate translation. There might be some room in GoRogue for making this slightly more direct, though --I'll create an issue for itI have created an issue for it on the GitHub repo and can experiment at some point, and feel free to add any input to that issue you want to.Truthfully though, this isn't something I could see you needing to do for performance reasons with A* -- A* is generally so fast even on a big map (500x500 grid squares or more) that it's not necessary. It might still have its uses from a mechanical standpoint, though, and absolutely has some great uses when paired with goal maps or even FOV when you have a bunch of objects all calculating their own FOVs.
I don't mind the input at all -- its definately useful all around. And if you disagree with the design behind something (whether it's something I mentioned or otherwise), feel free to bring it up, by all means -- discussions about it are how the library gets better :D. I hope this answers your current question -- either way, you know where to find me :D
Thanks for your help. I've got a bit of a pathfinding demo working in unity now. Here's the project in case you're interested https://www.dropbox.com/s/er5tpx1n6wr7nx5/GoRogueUnityDemo.unitypackage?dl=0 I'm still new to exporting unity packages, so let me know if it doesn't work.
I ended up writing a MultiSpatialMapView class which stores a rectangle as the view, and has some helper functions to convert from the spatial map coordinates to the view coordinates.
One thing that struck me is the following. As you explained, A* is in the coordinates of the Mapview, not the underlying SpatialMap data structure. So when A* returned a path, it was in those coordinates. I wanted to shift those coordinates, to put it back in the coordinates of the underlying data structure, but I could not manipulate the path in this way, nor could I construct my own path, with offset coordinates. So I ended up writing a wrapper class called OffsetPath, which just stores and offset and adds it on the fly. This seems like something that could come up often, given your comments about Viewports. I wonder if it would be useful to include an offset parameter in the A* shortest path routine, or else a built in way to add an offset to a Path object.
Playing with the pathfinding, its much faster than my original code :D, although it's not clear to me exactly why. I'm starting to suspect it was because I had originally used a bad hash function for my dicitonary data structure. Two thing's I've noticed. The first is that when the pathfinding target is inaccessible, the pathfinding routine struggles. This is not surprising, but I've been trying to think about the right way to address it. The second is that when the target is far away, the pathfinding also struggles, this is also not surprising, but this happens even when there's a clear line of sight. I remembered reading something about this, where if you add a tiebreaking clause in the pathfinder it can dramatically improve the performance, and dug up this comment on the rot.js project: https://github.com/ondras/rot.js/pull/91
One last thing. Is there a performance reason you use a boolean map for pathfinding instead of a float map? With a float map one could have paths which are passable but undesirable.Is it straightforward to make these minimal builds for unity myself? I wouldn't mind trying some modifications to the source and adding them to my build.
(I should add that right now the pathfinders are pathfinding every update, which is obviously a bad idea. But for the purposes of testing its a good way to see the performance.)
Hm. I'm curious as to why pathfinding is struggling at all -- how big are your maps, and how many paths are you calculating, if you don't mind me asking? In my performance tests, I'm able to crank out multiple paths completely across a 500x500 open map without falling below a time that would break 60FPS. That much said, it is slower than I remember it being (just ran those tests), so I will check to see if something got broken somewhere along the line.
An offset to path may be included in the eventual solution to the viewport problem I put in the github issue I linked in my last post -- it could definitely be useful, I agree :D.
If the target is inaccessible, it will indeed struggle, only because to verify that there is no path, it basically has to hit a wall in every direction (which means it practically becomes Dijkstra's algorithm on an open map in the worst case). Particularly on a map that is mostly open until very close to the target, this is expected and unfortunately unpreventable if the target location is truly inaccessible.
Regarding the tie-breaking aspect, unless either I broke something in a GoRogue update, or some assumptions I made about the priority queue implementation it uses are no longer valid (which I will be checking), GoRogue already implements this. In the AStar source file, the neighbor function it uses returns the directions in order of the one that leads most directly to the end path first. Like I said, I'll be double checking to make sure some assumptions have not broken down, as this would absolutely cause slower behavior. You might try having AStar calculate its path using Distance.EUCLIDEAN instead, which may illustrate if the tie-breaking has broken down.
The reason for the boolean map is indeed performance related. GoRogue implements the common use of weights (euclidean distance) via the distance calculation you pass it, however there are absolutely other uses for weights. I didn't want to implement them in the existing AStar algorithm because it does have a significant impact on performance (floating point operations are significantly more expensive than boolean checks, and are not as cache-friendly), however I have planned to implement a version of AStar that supports these weights.
The minimal builds are unfortunately not as easy as they should be currently. The only thing not in the minimal build that is in the regular release is some implicit conversions/interoperability operators for MonoGame primitives that correspond to some GoRogue types (Coord and Point, etc). When GoRogue is deployed via nuget, it is done in such a way that these operators do not create a required dependency on monogame, however when the DLL is manually added to a Unity project, the compiler isn't apparently smart enough to resolve these properly. Thus, the minimal builds are exactly GoRogue with all the MonoGame interoperability operators commented out (which you currently have to do by hand). I will be automating this in the somewhat near future, though, as knowing this now I intend to release these builds with every GoRogue release, so it will after I'm done be as simple as changing a preprocessor flag in the csproj.
Regarding the performance difference between your AStar and GoRogues -- my best guess, to be honest, is the priority queue implementation GoRogue uses, which is very highly optimized -- using a efficient heap-based priority queue implementation can make a huge difference in the algorithm in general :D
EDIT:
Another possibility might be the source of the data -- I don't know how you were storing items on the map prior to MultiSpatialMap, but spatial maps are designed to be significantly more efficient than implementations like a simple list of items, for operations like getting items at the location (which is something that AStar does frequently). That much said, MultiSpatialMap may also be part of the problem if your pathing is significantly slower than it should be based on the benchmarks I listed -- if you're using a spatial map to store terrain (wall, floor, etc -- stuff where each location has exactly one piece of terrain), you may get some speed improvements by pulling those specific objects out into an ArrayMap or a 2d array, and using the spatial map for the others. Spatial maps excel at instances where the items are sparse -- eg, when there are fewer items than there are map squares. While asymptotically, spatial map performs the same way as a 2D array in cases where the map is dense, in practice the constants are higher, and thus spatial map will be slower at getting the item at a location than an ArrayMap or 2D array is when there are items at every location.
Regarding how to handle the pathing slowness in practice -- you definitely won't need to path in the Update loop, so depending on what level of performance you mean by "struggling", it may not be a practical issue. In all honesty, particularly when you are pathing across a huge map, you might not even want to path every turn, instead just calculate a path then follow that path without calculating a new one for several turns, or some such. This may alleviate some of the stress you will find on a larger map.
After a quick look, I am seeing some evidence that the tiebreaking in GoRogue's AStar may not be correct,at least as of 2.1.0. It may not be today, but I'll investigate this further, and post if I come up with anything that affects performance. Thanks!