How do I handle the creation/destruction of many objects in memory effectively? - windows

Im in the process of making a game of my own. One of the goals is to have as many objects within the world as possible. In this game, many objects will need to be created in some unpredictable period of time (like a weapon firing will create an object) and once that projectile hits something, the object will need to be destroyed aswell (and maybe the thing it hits).
So i was wondering what the best way to handle this in memory is. Ive thought about creating a stack or table, and adding the pointers to those objects there, and creating and destroying those objects on demand, however, what if several hundred (or thousand) objects try to be created or destroyed at once between frames? I want to keep a steady and fluid frame rate, and such a surge in system calls would surely slow it down.
So ive thought i could try to keep a number of objects in memory so that i could just copy information into them, and use them without having to request the memory for them on demand. But how much memory should i try to reserve? Or should i not worry about that as long as the users computer has enough (presumably they will be focusing on the game and not running a weather simulation in the background).
What would be the best way of handling this?

Short answer: it depends on the expected lifetime of the objects.
Usually, the methods are combined. An object that is fairly static and is unlikely to be removed or created often (usually, players, levels, certain objects in the levels, etc) are created with the first method you described (a list of objects, an array, a singleton, etc) The exact method depends on the game, and the object being created.
For short term objects, like bullets, particle effects, or in some game, the enemies themselves, something like object pool pattern is usually used. A chunk of memory is reversed at the beginning of the game and reused throughout the course of the game for bullets and pretty particle effects. As for how much memory should I reserve?, the ideal answer is "As little as possible". Unfortunately, it's hard to figure that out sometimes. The best way to figure it out is to take a guess at how many bullets or whatnot you plan on having on screen at any given time, multiply by two (for when you decide that your bullet hell shooter doesn't really work to well with only 50 bullets) and then add a little buffer. To make it easier, store that value in a easily understood #define BULLET_MAX 110 so you can change it when the game is closer to done, and you can reasonably be sure that the value isn't going to fluctuate as much. For extra fun, you can tie the value into a config variable, and have the graphics setting affect it.

In real time games, where fluidity is critical, they often allocate a large chunk of memory in the beginning of the level and avoids any allocation/deallocation in the middle of the game.
You can often design so the game mechanic prevents the game from running out of memory (such as increasing the chance of weapon jamming when the player shoots too much too often).
Ultimately though, test your game in your targeted minimum supported machine, if it's fast enough there then it's fast enough and don't overcomplicate your code for hypothetical situations.

Related

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.

Multiplayer shooter: should projectiles carry the information about damage, or should the damaged entity?

This is a conceptual question, so no code is included.
When making a multiplayer shooter, be it 2D or 3D, where there are projectile-based weapons, should each projectile contain information as to who fired it, and how much damage it should do? Or, should the entity, upon being struck by the projectile, interpret the projectile and deal damage to itself accordingly?
Basically, the question is "where should the information/code about the damage being dealt exist."
Thoughts?
Personally, I think that giving the projectile this damage provides better modularity and makes more sense logically.
Modularity
I used to do M.U.G.E.N, a fighting game engine where individual creators and teams of creators can release either full games or pieces of games. Full games are actually comparatively rare next to individual characters, stages and etc that you could copy into your own folder and have added to your roster. So if any game engine absolutely had to be designed for modularity, this was it.
How did M.U.G.E.N handle the situation? Except in specific circumstances where a particular creator wanted to do something creative or unconventional, damage amount (and a gazillion more pieces of information, like hit sound, how long to stun, what state to enter as a result) are carried by the character that delivers the attack (In a shooter, this would be equivalent to the bullet holding this information). Why?
Well, simply put, there's no way that one character could be defined so that it could tell who hit it and what attack they used when said character and attack hadn't even been made yet. Keep in mind, characters from 1999 and characters from 2016 are able to fight each other without issue. And almost as dauntingly (and more relevant for you), even if a character's creator could somehow precognitively know every character and every attack that would be added, it would take a long time and a lot of code to add a case for all of them.
So let's get back to the idea of a shooter. Consider that you have two kinds of bullets. One is big and deals a lot of damage (we'll call this BigBullet), while the other is small and deals a little damage (We'll call this SmallBullet). Consider also that you have two kinds of targets that these bullets can damage (We'll call them Soldier and Tank). If you store damage information in the target classes (Soldier and Tank), you have to define this information for each type of bullet for each type of target.
That is, Soldier class will have to have logic to determine which type of bullet it is and how much damage it should deal. Tank class will also have to have logic to determine which type of bullet it is and how much damage it should deal. You can reduce the redundancy of this code if you inherit both classes from a common base class, true.
But compare with the alternative. BigBullet and SmallBullet have a public damage field. The Soldier and Tank don't have to care what type of bullet it got hit by; only ask how much damage it should do. So you can remove that code altogether.
And more importantly, this allows the design to be easily expandable. If you later decide you want a new HugeBullet class that deals even more damage, all you need to do is make a new HugeBullet class. You don't have to worry about updating your target entities at all.
Logic
This is more opinional, but let me describe the way I look at it.
Consider the human skull. It is a work of art. It's got joints in it that allow jaw movement. It has holes in all the right places to allow sensory information to enter, and a hole for food. It's designed for durability and observation.
But it's not specifically designed for every single thing that can happen to it. It doesn't have a bullet-deflection property or an axe-survival property. It has properties that contribute to these defenses, but only in the vaguest and most general of terms. Maybe they have a general resistance to piercing, but they don't have a particular resistance to piercing by each individual type of bullet.
Ultimately the driving force behind how much damage it takes lies with the design of the weapon that strikes it. A bullet is designed to cut through flesh and bone. So organizing your code so that the bullet objects carry damage data is a more accurate simulation of reality.
IMHO
Depends entirely on what you consider damage:
Damage potential from the projectile... definitely store in each projectile.
Damage realized upon the target... a counter to add all the damage inflicted on it by the different projectiles.
Information stored on the projectile regarding firing entity is only relevant if the firing entity is to be awarded points for sucessful hits on targets.

How can I avoid decreases in framerate in a game with a lot of instances of an object class?

I'm writing a game that requires a large amount of instances of a "Monster" class that contains very basic data - namely:
Angle of rotation
Damage potential
Max health
Current Health
And that's about it. The game starts out smoothly at 60 fps but once about 50-60 instances are created (and are active at the same time) the game dips to <30 fps. It's frustrating because I don't know how to fix it. For the record, I am removing the monsters from both the array in which they're contained and the scene in an efficient manner (I think).
One way to improve the framerate is to avoid creating and destroying a lot of objects. This can be achieved by pooling the objects. Basically you create the objects you need at the start of the game or level and when one is supposedly destroyed, you hide it and reuse it later.
Depending on the technology you're using (which you haven't specified in your post ^^), there are various ways to implement this.
You can check those links for more info and help:
http://gameprogrammingpatterns.com/object-pool.html
http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/objectpool.html
and/or just google it. The principle is pretty simple and you should be able to use it pretty easily.
Hope this helps ;)
edit: Also, depending on the technology you're using, there might be some better ways to improve framerate. If you could provide the languages / APIs you're currently using, you would probably get more useful help !

Speed of large amount of animated bitmaps in EaselJS

I seem to have a bit of trouble with using a large amount of animated bitmaps (all based on the same spritesheet) when using EaselJS. When I run a couple of these at once on my stage, there is no problem at all, but when running a higher amount of them at the same time (starting at around 30 to 40) whilst moving them around I start to have them "flicker" quite a bit, even at an fps of around 10.
I'm not using any shadows or anything else along those lines. Just using animated bitmaps and moving them around.
Does anyone have any good advice around increasing this performance?
Without seeing your code it's hard to know exactly where the bottleneck is. But here are a few places to start looking (starting with the more trivial fixes):
Make sure you are using a modern browser. In the very least, check across a few other browsers/platforms to see if that has any significant change in performance. From what I understand, EaselJS performance is significantly worse on non-hardware accelerated canvas implementations.
If you can, use createJS's version of TweenJS over other tweening libraries. TweenJS will tie itself to EaselJS's Ticker class, which is more efficient.
Do not call stage.update() unless absolutely necessary. Since stage.update() is such an expensive call, you should be as stingy as possible. In fact, you shouldn't really call it at all if you are using the Ticker to regularly update the stage.
Cache wisely and aggressively. If you have complex static elements on the stage, caching them will save some cycles. However, there is an overhead to caching so save it for containers with a lot of static elements or complexly drawn shapes.
Lower the frequency that EaselJS checks for mouseovers. If you have enabled mouse over on the stage, pass in a lower frequency (documentation). If you don't need it (if you are only listening to clicks), don't enable it at all. Monitoring mouse overs is pretty dang expensive, especially if you have plenty of elements on stage.
Set stage.snapToPixelsEnabled to true. This may or may not help. Theoretically, rendering bitmaps on whole pixels is much more efficient, however this may cause some animations to become jagged and I haven't played around with it enough to know what the other pros and cons are.
I was able to get decent performance with around 600-800 spritesheets at 30FPS and basic tweening using Chrome on a 4 year old iMac (just a quick test).
try using several Stage objects at the same time.

Storing Large 2D Game Worlds

I've been experimenting with different ideas of how to store a 2D game world. I'm interested in hearing techniques of storing large quantities of objects while managing the set that's visible ( lets say 100,000 tiles square ). Obviously the techniques can vary based on how the game renders that space.
Lets assume that we're describing a scrolling 2d game world rather than screen based as you could fairly easily do screen based rendering from such a setup while the converse is a bit more messy.
Looking for language agnostic solutions here so it's more helpful to others.
Edit: I think a good answer here would be a general review of the ideas to consider when thinking about this, as some of the responders have attempted, but also begin to explain how different solutions would apply to those scenarios. It's a somewhat complex question, so I would expect a good answer to reflect that.
Quadtrees are a fairly efficient solution for storing data about a large 2-dimensional world and the objects within it.
You might get some ideas on how to implement this from some spatial data structures like range or kd trees.
However, the answer to this question would vary considerably depending exactly on how your game works.
Are we talking a 2D platformer with 10 enemies onscreen, 20 more offscreen but "active", and an unknown number more "inactive"? If so, you can probably store your whole level as an array of "screens" where you manipulate the ones closest to you.
Or do you mean a true 2D game with lots of up/down movement too? You might have to be a bit more careful here.
The platform is also of some importance. If you're implementing a simple platformer for desktop PCs, you probably wouldn't have to worry about performance as much as you would on an embedded device. This is no excuse to be naive about it, but you might not have to be terribly clever either.
This is a somewhat interesting question I think. Presumably someone smarter than I who has experience with implementing platformers has thought these things out already.
Break the world into smaller areas, and deal with them. Any solution to this problem is going to boil down to this concept (such as quadtrees, mentioned in another answer). The differences will be in how they subdivide the world.
How much data is stored per tile? How fast can players move across the world? What's the behavior of NPCs, etc., that are offscreen? Do they just reset when the player comes back (like old Zelda games)? Do they simply resume where they were? Do they do some kind of catch-up script?
How much different rendering data is going to be needed for different areas?
How much of the world can be seen at one time?
All of these questions are going to immpact your solution, as well as the capabilities of your platform. Coming up with a general answer for these without having a reasonable idea of these parameters is going to be a bit difficult.
Assuming that your game will only update what is visible and some area around what is visible, just break the world in "screens" (a "screen" is a rectangular area on the tilemap that can fill the whole screen). Keep in memory the "screens" around the visible area (and some more if you want to update entities which are close to the character - but there is little reason to update an entity that far away) and have the rest on disk with a cache to avoid loading/unloading of commonly visited areas when you move around. Some setup like:
+---+---+---+---+---+---+---+
|FFF|FFF|FFF|FFF|FFF|FFF|FFF|
+---+---+---+---+---+---+---+
|FFF|NNN|NNN|NNN|NNN|NNN|FFF|
+---+---+---+---+---+---+---+
|FFF|NNN|NNN|NNN|NNN|NNN|FFF|
+---+---+---+---+---+---+---+
|FFF|NNN|NNN|VVV|NNN|NNN|FFF|
+---+---+---+---+---+---+---+
|FFF|NNN|NNN|NNN|NNN|NNN|FFF|
+---+---+---+---+---+---+---+
|FFF|NNN|NNN|NNN|NNN|NNN|FFF|
+---+---+---+---+---+---+---+
|FFF|FFF|FFF|FFF|FFF|FFF|FFF|
+---+---+---+---+---+---+---+
Where "V" part is the "screen" where the center (hero or whatever) is, the "N" parts are those who are nearby and have active (updating) entities, are checked for collisions, etc and "F" parts are far parts which might get updated infrequently and are prone to be "swapped" out (stored to disk). Of course you might want to use more "N" screens than two :-).
Note btw that since 2D games do not usually hold much data instead of saving the far away parts to disk you might want to just keep them in memory compressed.
You probably want to use a single int or byte array that links to block types. If you need more optimization from there, then you'll want to link to more complicated data structures like oct trees from your array. There is a good discussion on a Java game forum here: http://www.javagaming.org/index.php/topic,20505.30.html text
Anything with links becomes very expensive because the pointer takes up something like 8 bytes each, depending upon the language, so depending upon how populated your world is it can get expensive very quickly (8 pointers 8 bytes each is 64 bytes per item, and a byte array is 1 byte per item). So unless 1/64 of your world is empty, a byte array is going to be a much better option. You're also going to need to spend a lot of time iterating down the tree whenever you're doing a lookup for collision or whatever else - a byte array will be an instantaneous lookup.
Hopefully that's detailed enough for you. :-)

Resources