How Ruby arrays behave internally when deleting an element? - ruby

I am designing a game in Ruby in order to learn the language and my game needs to be in a constant cycle of deleting items from an array and adding them to another one, than deleting from the other one and readding to the first one.
I want to know what happens internally when I call Array.delete(). I'd rather use a linked list for my game since deleting from and adding to a linked list is way more efficient than on an array. However, Array is the only data structure I've come accross in Ruby so far. Is it really the only one available?
edit: It's a basic shoot'em up game where the enemy ships can shoot bullets at the player. In order to avoid having to allocate a new bullet every time an enemy fires at the player, I allocate a lot of bullets before the game starts. When an enemy shoots, he picks a bullet from the list of available bullets and puts it in the list of "active" bullets. The class responsible for drawing the bullets on the screen only draws those bullets in the list of acitve bullets. When a bullet leaves the screen, it goes back to the list of available bullets. That's where all the shuffling comes from...

It's easy to implement a linked list in Ruby, but the one time I actually did it, performance was exactly the same as using an Array. The better algorithm in Ruby was exactly balanced by the speed of the internal C code.
Now, I wasn't trying to delete things in the middle of my Array.
For your case, I think it's safe to say if the arrays are short, then the algorithm doesn't matter and you will be fine using the built-in Array class. If the array is long, then no doubt some sort of map could be constructed whereby deleting things from the middle of the Array would not require repacking the array and its quadratic time complexity.
Really, you should first implement your game in the simple and direct way. You shouldn't stir in complexity in the beginning without even knowing what it buys, if anything. Who knows, you may even find that some other part of the game uses more time.
And should you find that indeed you are bogged down with Array deletions, the next step is to add a map or perhaps, yes, a linked list or tree implemented in Ruby. And if that isn't fast enough, with your encapsulated Ruby solution and a set of tests, you would be in a good position to write a C extension, and you would know almost exactly the benefit.

Use Hash. It is more efficient than Array.

Related

Understanding thread-safety

Let use as example standard Binary Search Tree, its nodes having an encapsulated value and pointers to the left and right children and its parent. Its primary methods are addNode(), removeNode() and searchNode().
I want to understand how to make my data structure safe. I however do not know much about thread-safety and want to ask if what I am thinking is correct or not.
My first problem is one of decision: what I want to happen when I have concurrent methods? Let us say I am using my BST to manage a map in a game: the position of the character of a player is represented by an array of doubles, I store the player's positions in my BST in lexicographic order. One player destroyed a target (and his thread want to remove it from my map), but another player is initiating an attack and needs a list of all possible targets inside a certain distance from him, including the target just removed (and his thread want to execute a search that will include the target). How I manage the situation? What about other situations?
My second problem, (I think) my biggest, is one of actuation: how I make happen what I want to happen. I read about things like atomic-operations, linearity, obstruction-free, lock-free, wait-free. I never found out in a single place a simple definition for each, the advantages of that strategy, the disadvantages. What are those things? What am I doing if I am locking the nodes, or if i am locking the pointers to other nodes, or the values encapsulates in the node?
Am I understanding correctly the problematics of thread-safety? Do you have suggestions on problems I should think about, or on written papers and pdfs I should read in order to better understand the problems and their many solutions?

Avoiding nested for loops in 2D game engine

I am creating a 2D game.
There are many objects, each has a width, a height, and X and Y coordinates.
Each object is stored in an array of it's class:
the player
allies
enemies
obstacles
power ups
bullets shot by the enemies
bullets shot by the player & allies
To make the game work, I need to obviously detect if two elements occupy the same space (let's call it "collission") , so that
the player can collect power ups
nobody can pass through obstacles
the allies can shoot the enemies
the enemies can shoot the allies
friendly fire can be either enabled or disabled
this needs to be checked every frame, 60 times per second.
What I have been doing so far, is loop through each class, and then loop over each class that it can interact with.
For example:
foreach (ally_bullets)
{
foreach (enemies)
{
if ( collision detected between enemy and bullet )
{
remove the bullet and the enemy
}
}
}
It makes sense and it works, but it's very resource intensive as the game gets more complex. The more elements there are, the longer this nested for loop takes to render, ultimately reducing the frame rate. Even if I am trying to run as few loops as possible.
What's a better way of solving this then nested for loops?
A common solution is to use Polymorphism, in which you have a base class (in this case Object) which gets inherited by other classes (such as Player, Bullet, Enemy, etc). Instead of each of these having an individual array, you would have a single array (or typically more appropriate, a vector). Now you just loop through that one array having each Object do their updates, and have their updates checked against every Object in the array.
This 'vector-wise' updating is usually setup as a Messaging System. Now whenever an inherited Object receives a message (such as 'hit by bullet'), that object checks if it cares about that message. If so, accept the message, else ignore it.
This is (in my opinion) the better way to handle what you are trying to accomplish, which I believe is what you were asking.
If you are still using arrays for this, I am going to assume you are still fairly new to programming, and I am going to suggest sticking with what you have now. It will absolutely work (providing you know how to finish your project), and when you finish this and start to learn something more advanced you will see both the shortcomings of the way you are doing it, and the benefits of it).
If you do see some lag arise, it will likely be from your drawing methods long before this kind of interactivity checking becomes a bottleneck.
Either way you go, collision detection itself and rendering are going to be the main areas your cpu will be eaten up, providing your arrays stay within reasonable ranges.
Edit:
Another thing that will help you should you pursue the topics I mentioned is the Observer Pattern, also known as the Listener Pattern.

Data structure for storing entities in game

I have a tiled map which is made of chunks and each chunk is a rectangle of tiles. Now I want to add entities to this(each entity stand on a specific tile), and every loop all the entities should call their update() function, so I wanted to ask for a suggestion: what data structure should I use for saving their locations?
I don't know yet what kind of methods I'll have, but I'll probably need a method that gets all the entities from a specific area(maybe a point) for drawing for example. This is a critic question because there maybe a huge map like 100x100 chunks where each chunk is 30x20 tiles so it will be 3000x2000 tiles, and lots of entities for example 1000, so if I'll save it in a list it will be very slow to search for an entities O(n) and if every entities make a search it will take O(n^2).
Right now I have a couple of solutions but they are all problematic:
kd-tree(for 2d) - since each loop all the entities can change their locations, the complexity of updating them will be the same as rebuilding the whole tree each loop O(nlogn).
each chunk will save the entities that belong to it - my best solution so far, easy updating, but the complexity is higher then in the kd-tree.
So does anybody have a suggestion for this problem?
A dictionary that maps tile (position) towards a list of all entities on that tile. All entities should have a position property and an event notifying when it changes, so that the dictionary can be updated at each movement.
(There should be no list for the tiles without entities. The list should be created when an entitiy moves to that position, and removed when the last entity leaves the position.)
This might be a crude suggestion, and I'm sure it can be improved, but here's a thought:
First, store your positions in such a way that you can access them in constant time given a specific object. For instance, if you want to access them directly through your entities, you can store the position structs in a list/vector and give each entity a pointer/reference to its position.
Second, store an entity pointer/reference or GUID in the same struct as the entity position, so you can identify an entity based on a position object. (There is probably a better way I'm not thinking of right now though.)
Third, utilize some of the principles of sweep and prune/sort and sweep (common in 3D games): Keep two sorted position lists/vectors, one sorted in the x direction and the other sorted in the y direction. One can hold the actual position objects, and the other can hold pointers/references. These lists can take advantage of temporal coherence, so the cost of keeping them sorted shouldn't be too high, unless there's a lot of fast and chaotic movement.
An advantage of this setup is that it's really easy to figure out where every object is relative to each other. Want to know how many objects are within 10 squares of Billy the Elf in either direction? Check Billy's position and iterate forward/backward through both lists until you reach an entity more than 10 squares away in each direction.
If you're interested in the concept, look up sort and sweep (also known as sweep and prune). You'd only be using the first half of the algorithm, but it's used for broad-phase collision detection in practically every major 3D physics engine, so you know that it has to be fast in general. ;) There's a lot of information floating around about it, so you'll probably find much more sophisticated implementation ideas floating around too. (For instance, I don't like the indirection involved in storing a sorted list of pointers/references to position structs; working with the actual structs is more cache-efficient, but then you need to update the position in two places if you want to exploit temporal coherency with persistent arrays. Someone else may have thought of a more clever design that's escaping me right now.)
EDIT: I'd comment on Erik H's idea, but my rep isn't high enough. I just wanted to say that his idea sounds very well suited to your game, especially if you will have a lot of entities tightly packed on the same tile or in a small neighborhood. If I were you, I'd probably try it before the sweep and prune idea. However, it should be accompanied with a well-planned memory management strategy: If you have a dictionary of tile locations that naively map to vectors of entities, you're going to have a lot of memory being allocated and freed when entities move from one tile to another. Instead, you'll want to implement his idea as something more like a dictionary/linked list combo:
The dictionary keys would be tile positions, and the dictionary would return a single pointer to a linked list node. This node would be part of a linked list of all entities on the same tile. Whenever an entity moves from one tile to another, it will be removed from its current linked list and added to the new one. If an entity moves to an empty tile, it will be in a linked list all on its own, and it should be added to the dictionary. When the last entity moves from a tile, the entry for that tile should be removed from the dictionary. This will allow you to move around entities without continual dynamic allocation/deallocation, since you're just updating pointers (and the dictionary will probably be pretty memory efficient).
Note that you don't have to store full-blown entities in the linked lists, either; you can easily create your linked list out of lightweight objects (containing a pointer or GUID to the actual entity).

Proper Data Structure Choice for Collision System

I am looking to implement a 2D top-down collision system, and was hoping for some input as to the likely performance between a few different ideas. For reference I expect the number of moving collision objects to be in the dozens, and the static collision objects to be in the hundreds.
The first idea is border-line brute force (or maybe not so border-line). I would store two lists of collision objects in a collision system. One list would be dynamic objects, the other would include both dynamic and static objects (each dynamic would be in both lists). Each frame I would loop through the dynamic list and pass each object the larger list, so it could find anything it may run into. This will involve a lot of unnecessary calculations for any reasonably sized loaded area but I am using it as a sort of baseline because it would be very easy to implement.
The second idea is to have a single list of all collision objects, and a 2D array of either ints or floats representing the loaded area. Each element in the array would represent a physical location, and each object would have a size value. Each time an object moved, it would subtract its size value from its old location and add it to its new location. The objects would have to access elements in the array before they moved to make sure there was room in their new location, but that would be fairly simple to do. Besides the fact that I have a very public, very large array, I think it would perform fairly well. I could also implement with a boolean array, simply storing if a location is full or not, but I don't see any advantage to this over the numeric storage.
The third I idea I had was less well formed. A month or two ago I read about a two dimensional, rectangle based data structure (may have been a tree, i don't remember) that would be able to keep elements sorted by position. Then I would only have to pass the dynamic objects their small neighborhood of objects for update. I was wondering if anyone had any idea what this data structure might be, so I could look more into it, and if so, how the per-frame sorting of it would affect performance relative to the other methods.
Really I am just looking for ideas on how these would perform, and any pitfalls I am likely overlooking in any of these. I am not so much worried about the actual detection, as the most efficient way to make the objects talk to one another.
You're not talking about a lot of objects in this case. Honestly, you could probably brute force it and probably be fine for your application, even in mobile game development. With that in mind, I'd recommend you keep it simple but throw a bit of optimization on top for gravy. Spatial hashing with a reasonable cell size is the way I'd go here -- relatively reasonable memory use, decent speedup, and not that bad as far as complexity of implementation goes. More on that in a moment!
You haven't said what the representation of your objects is, but in any case you're likely going to end up with a typical "broad phase" and "narrow phase" (like a physics engine) -- the "broad phase" consisting of a false-positives "what could be intersecting?" query and the "narrow phase" brute forcing out the resulting potential intersections. Unless you're using things like binary space partitioning trees for polygonal shapes, you're not going to end up with a one-phase solution.
As mentioned above, for the broad phase I'd use spatial hashing. Basically, you establish a grid and mark down what's in touch with each grid. (It doesn't have to be perfect -- it could be what axis-aligned bounding boxes are in each grid, even.) Then, later you go through the relevant cells of the grid and check if everything in each relevant cell is actually intersecting with anything else in the cell.
Trick is, instead of having an array, either have a hash table for every cell grid. That way you're only taking up space for grids that actually have something in them. (This is not a substitution for badly sized grids -- you want your grid to be coarse enough to not have an object in a ridiculous amount of cells because that takes memory, but you want it to be fine enough to not have all objects in a few cells because that doesn't save much time.) Chances are by visual inspection, you'll be able to figure out what a good grid size is.
One additional step to spatial hashing... if you want to save memory, throw away the indices that you'd normally verify in a hash table. False positives only cost CPU time, and if you're hashing correctly, it's not going to turn out to be much, but it can save you a lot of memory.
So:
When you update objects, update which grids they're probably in. (Again, it's good enough to just use a bounding box -- e.g. a square or rectangle around the object.) Add the object to the hash table for each cell it's in. (E.g. If you're in cell 5,4, that hashes to the 17th entry of the hash table. Add it to that entry of the hash table and throw away the 5,4 data.) Then, to test collisions, go through the relevant cells in the hash table (e.g. the entire screen's worth of cells if that's what you're interested in) and see what objects inside of each cell collide with other objects inside of each cell.
Compared to the solutions above:
Note brute forcing, takes less time.
This has some commonality with the "2D array" method mentioned because, after all, we're imposing a "grid" (or 2D array) over the represented space, however we're doing it in a way less prone to accuracy errors (since it's only used for a broad-phase that is conservative). Additionally, the memory requirements are lessened by the zealous data reduction in hash tables.
kd, sphere, X, BSP, R, and other "TLA"-trees are almost always quite nontrivial to implement correctly and test and, even after all that effort, can end up being much slower that you'd expect. You don't need that sort of complexity for a few hundreds of objects normally.
Implementation note:
Each node in the spatial hash table will ultimately be a linked list. I recommend writing your own linked list with careful allocations. Each node need take up more than 8 bytes (if you're using C/C++) and should a pooled allocation scheme so you're almost never allocating or freeing memory. Relying on the built-in allocator will likely cripple performance.
First thing, I am but a noob, I am working my way through the 3dbuzz xna extreme 101 videos, and we are just now covering a system that uses static lists of each different type of object, when updating an object you only check against the list/s of things it is supposed to collide with.
So you only check enemy collisions against the player or the players bullets, not other enemys etc.
So there is a static list of each type of game object, then each gamenode has its own collision list(edit:a list of nodes) , that are only the types it can hit.
sorry if its not clear what i mean, i'm still finding my feet

Is there some standard functionality in XNA to efficiently implement a 2D Camera on a large world

I am making a 2d space game with many moving objects. I have already implemented a camera that can move around and draw the objects within the view. The problem now is that I have to check for every object wether it is within the rectangle of my view before I draw it (O(n) operations where n is the number of objects in my world). I would like a more efficient way to acquire all the objects within the view so I only have to draw them.
I know a bunch of data structures that can achieve a O(log n + k) query time for a two dimensional range query, where k is the amount of objects within the range. The problem is that all the objects are constantly moving. The update time on most of the data structures is O(log n) as well. This is pretty bad because almost all objects are moving so all will have to be updated resulting in O(n log n) operations. With my current implementation (everything is just stored in a list), the update time takes O(n) operations to update everything.
I am thinking that this problem must have been solved already, but I couldn't really find a solution that specifically considers my options. Most 2D camera examples just do it the way I am currently doing.
So my question basically consists out of two things:
Is there a more efficient way to do this than my current one (in general)?
Is there a more efficient way to do this than my current one (in XNA)?
On one hand I am thinking, O(n) + O(n) is better than O(log n) + O(n log n), but on the other hand I know that in many games they use all these data structures like BSPs etc. So I feel like I am missing some piece of the puzzle.
PS: I am a bit confused whether I should post this on Stack Overflow, the Game Developers stack exchange or the Computer Science Theory stack exchange...... So please excuse me if it's a bit out of scope.
My first question would be: are you really going to have a world with a million (or even a billion!) objects?
This is a performance optimisation, so here's what I would do:
First of all: nothing. Just draw everything and update everything every frame, using a big list. Suitable for tens of objects.
If that is too slow, I would do some basic culling as I iterated the list. So for each object - if it is off-screen, don't draw it. If it is "unimportant" (eg: a particle system, other kinds of animation, etc) don't update it while off-screen either. Suitable for hundreds of objects.
(You need to be able to get an object's position and bounding box, and check compare it with the screen's rectangle.)
And finally, if that is too slow, I would implement a bucketed data structure (constant update time, constant query time). In this case a 2D grid of lists that covers your world space. Suitable for thousands of objects.
If that ends up taking up too much memory - if your world is crazy-large and sparse - I would start looking into quadtrees, perhaps. And remember that you don't have to update the space-partitioning structure every time you update an object - only when an object's position changes significantly!
Remember the idiom: Do The Simplest Thing That Could Possibly Work. Implement the simple case, and then actually see if your game is running slowly with a real-world number of objects, before you go implementing something complicated.
You mean to say, you check every object that you wish to put on to screen & take action against whether or not it is inside the specified screen area???
XNA takes care of handling objects which are out of screen (by not drawing of course) automatically, You simply specify the coordinates... Or did I misunderstand you question??
EDIT
Why not use a container sprite, draw everything you want inside it & then draw that single main sprite onto the screen? Calling draw on that single sprite won't really involve drawing of those parts which are outside.

Resources