# How to aquire relevant data without iterating through vector containing all the data to verify if it's releva.. just read my thread.

This topic is 1775 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Why hello there! How nice of you to come by. Have a seat.

My game is 2D-topdown and made in C++. Zeldaish. Love that game. ANYHO, I am trying to figure out how to make a vector contain only relevant Units. You might wanna skip this part and answer my question at once. No f*** you, read my wall of text. I'll try to explain with collisiondetection as example (have in mind this issue is not collision-specific, that's not what I am getting at..). I want to check if any Unit has collided with another Unit. I currently achieve this by doing this:

1. Create a vector which contain all Units.

2. Iterate through it so that all Units have checked collision with each other only once.

Now what if I have 30 Units in my world? If all 30 are to compare with each other only once, we got a total of 435 collisionchecks per frame, y = (x2 - x) / 2. This is inefficient. If there is 40 we get 780 collision checks.. It scales terribly. For some calculations the terrible scale isn't to much of an issue since the operation isn't complicated, but overall this will slow down my game if I don't come up with another way of comparing objects.

Instead I figured I'd like to create a member vector of relevant entities within the Unit - not a vector containing all Entities. This would greatly reduce the need of collisionchecks. Relevant entities would be entities that are close to the unit. I can take advantage of indexing, storing pointers to all Units in a 2-dimensional array that would represent and be identical to my 2-dimensional worldmap-array. Then it would be easy to grab some pointers to relevant, physically close, Units via indexing by coordinates and push them into a member vector of the Unit. Now this vector only contains other Units that is physically close to my unit and the result is that each unit only need to check collision with at most 4-5 Units, instead of all present Units.

In theory this would work out, assuming that creating the index isn't more inefficient than iterating through the vector of all Units (or items, or enemies or whatever object I have to access), but creating the index and maintaining it with moving objects etc is always slower when I try to implement it.

This issue persists with all kind of stuff within my game - not only collisiondetection. I actually got to write this thread since I'm currently at making Items storable within an inventory. When the Unit, my character, should pick up an item that is in front of him I only iterate through a vector of all items and check which one are within range. It'd be unealistic if my character could pick up an item from 100 meters. Well Slenderman has long arms, but this guy is more of a Gnome Urist McTransracialGnome. Same issue here - I want a vector that consists of relevant objects, not all of them. When combating enemies I iterate through a vector containing all enemies to check if the spoon sword hit any, instead of iterating through a vector containing all enemies that are likely to get hit. It's oblivious! Perhaps I shouldn't even iterate through a vector?

If you still haven't grasped my issue I'll make a final try: In Mount&Blade there is lots of players. When I shoot an arrow I can't imagine it iterates through all players every single frame and check if the arrow has collided with any of them? Surely there must be a more efficient way?! What way would that be? What alternatives to that way is there? Any design-pattern I should look into? (I did read GoF: Design Patterns but I grasped approx 10% of it the English language is inferior and nothing could be explained properly. Perhaps anyone have a Swedish translation of it?)

Seriously now, thanks for reading and I'd be REALLY happy if someone could point me in a good direction !

##### Share on other sites

You can divide your space into non-overlapping regions and update object region when it moves. You can quickly get regions in specified radius with all the objects in them.

http://en.wikipedia.org/wiki/Space_partitioning

Edited by Nercury

##### Share on other sites

What you're looking for is a partitioning system like a quadtree. Essentially, your map will be broken up into sections, and each section will have a vector that contains all the objects in that section. Collision checks will only occur between objects within a given section. Of course, since these objects can move freely around the map, you'll need to implement a way to remove and insert an object into a vector as it moves from one section to another. You'll also have to deal with what happens if an object is in two sections at once. If you look up "quadtree collision detection" I'm sure you'll find far more detailed explanations of how to implement this system.

Edited by Ludus

##### Share on other sites

I'm just going to say: One of the reasons you're not getting posts is your attitude. No one wants to help someone who starts out with:

No F**k you read my post

Or someone who says this (to a largely english speaking crowd):

The English language is inferior and nothing could be explained properly.

Because they couldn't grasp design patterns. You're essentially saying: "I read an advanced book I wasn't ready for, and now I'll blame my misunderstanding on how terrible English is."

##### Share on other sites

I'm just going to say: One of the reasons you're not getting posts is your attitude.

I'm sure it's all in good humour ;)

##### Share on other sites

As for both Space-partitioning and Quadtrees, they seem very much indeed to be the answer to my question! I'll definitely look into it further. If anyone have any other suggestion how to solve the issue I'd be glad to hear more.

And about the inapt try to put a smile on your faces humour, it was purely for the sake of merriment and I didn't mean to offend anyone :).

##### Share on other sites

As a note, I do agree that the "attitude" given is a touch iffy, if you read it literally.  A little hint you were having fun would have been good though, such as adding a:

Anyway, yes an SAS is what you are likely looking for.  I replied to something very similar to this a couple days ago in a different thread, though it turned out the problem wasn't actually an issue that SAS would have solved.  First off: SAS=spacial awareness system.  The idea being something which leverages various bits of cohesive information in such a way that it keeps the problem of knowing what other objects are in a range from being O(n^2), or just about the worst possible performance you can imagine.  The topic was at http://www.gamedev.net/topic/639587-ai-speedups-for-running-game-in-accelerated-time/ where I also suggest an SAS system.  (And also the link to http://codesuppository.blogspot.com/2008/03/spatial-awareness-system.html as a starting point for research.)  I also posted a video later which was an example of 2k objects running around using something which requires constant knowledge of who is within some "x" range.

When you get into selection of an SAS solution, there are several trade offs to keep in mind.  I'll make a little list (Please note: I'm just high leveling all of this, you want to complain about my overview, I'll bury you in lots of research and real world usage.. :)):

1.  Quad/oct tree versions.  You have to figure out an appropriate bounds for the world and then figure out a division level which is appropriate.  If you get any of this wrong, performance can quickly go O(n^2) on enough objects to kill your performance.  Or, you are going to be hit with a second order O(n^2) checking surrounding nodes for possible "in range" checks.  These are probably among the easiest solutions but they are touchy based on fixed values.  I really hate the quad/oct tree versions of SAS due to the "tweaky" bits required.

2.  KDtree.  I like the idea, especially for free form "query" of localized items.  Unfortunately rebuilding the tree is expensive and if you have a lot of movement going on, the constant rebuilds kill performance.  I believe this could eventually be the best solution but it takes a hell of a lot of work to deal with partial rebuilds dynamically and all the implementations I've seen mostly just remove an item from the tree and put it in a global "check me list" after movement, until that list gets too big, then it just rebuilds the entire kd-tree.  Partial rebuilds are possible, they are just difficult to implement.  I've not tried this myself, my favored solution is easier.

3.  Sphere tree.  Another one I like, unfortunately it's basically a KDtree without the easy to define bounding divisions.  The KDtree is better if you put in the time to do partial tree rebuilds.  (I.e. super spheres are your primary axis', just harder to define in terms of the math.)  Though, the more I think about it, the same optimizations could be applied and a sqrt is not that horrible for a more distributed structure.

4.  My personal favorite, though probably the most difficult to implement (without considering the kd-tree with sub-tree recomputes and all that I suggested) is the sweep and prune solution.  It maintains the most linear performance over all variations of problems of all the solutions without being unreasonably complicated to implement.  Per frame it is slightly more expensive, but that is trivial (for my uses) since it doesn't have multi-ms spikes when a group of objects cross from one quad/oct to another, and of course if I end up with hundreds of objects in a small space I don't get O(n^2) issues with those objects because sweep/prune works on the continuous float space and only makes changes as required.

There are other options, this is not an exhaustive list.  I'm just posting the most likely ones you will see if you do searches and my thoughts on them.  If you can get away with quad/oct tree, use it, it's very easy to implement and performance is exceptional with proper values, unless you really push on it with lots of objects per node.

##### Share on other sites
5. Possibly the most straightforward of all, a spatial hash table. Find the grid coordinates of an object by dividing its world coordinates by the grid size. Take a hash of the grid coordinates and use that to look up in a table. The grid size should be larger than the object size, otherwise objects will need to be inserted into many cells (normally four would be the limit). The table size should be larger than the number of objects. You can support infinite worlds (or at least, avoid the hassle of setting the bounds) and searches are constant time.

##### Share on other sites

I agree it's in good humor, however the point is the same: Just ask your question. Spending extra lines making jokes doesn't make it any easier for us to figure out what's going on. I left the thread after the second joke, because it made the problem harder to understand. Sorry if I offended you, just trying to give advice :)!

Cheers :)!